KITASENJU DESIGN BLOG

memo, html, javascript, unity

SVGのストロークを扱うclass

https://kitasenjudesign.hatenablog.com/?page=1725178084を使って


import { SVGStroke } from "./SVGStroke";

export class SVGStrokes{

    public static SVG_P:string = '<?xml version="1.0" encoding="UTF-8"?><svg id="_レイヤー_1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 122.3555 159.5796"><defs><style>.cls-1{fill:#e71f19;stroke:#040000;stroke-miterlimit:10;}</style></defs><path class="cls-1" d="M67.0952,102.0596h-33.6743v57.02H.5V.5h69.0693c15.9229,0,28.6177,4.0879,38.085,12.2646,9.4678,8.1763,14.2012,20.8359,14.2012,37.9771,0,18.7197-4.7334,31.9526-14.2012,39.6987-9.4673,7.7461-22.9878,11.6191-40.5591,11.6191Z"/><path class="cls-1" d="M82.5874,69.0312c4.3032-3.8008,6.4551-9.8257,6.4551-18.0742s-2.1704-14.1289-6.5088-17.644c-4.3408-3.5132-10.4189-5.2715-18.2358-5.2715h-30.877v46.6919h30.877c7.8169,0,13.9136-1.8999,18.2896-5.7021Z"/></svg>';
    public static SVG_O:string = "";
    public static SVG_L:string = "";

    private strokes:SVGStroke[] = [];

    constructor(svgText:string){

        const parser = new DOMParser();
        const svgDoc = parser.parseFromString(svgText, 'image/svg+xml');
  
        const svgElement = svgDoc.querySelector('svg');
        //document.body.appendChild(svgElement); // SVGをDOMに追加
  
        const viewBox = svgElement.getAttribute('viewBox');
        console.log(viewBox); // 例: "0 0 100 100"
        const [minX, minY, width, height] = viewBox.split(' ').map(Number);

        //console.log('min-x:', minX);
        //console.log('min-y:', minY);
        //console.log('width:', width);
        //console.log('height:', height);

        var paths = svgElement.querySelectorAll('path');

        paths.forEach((path) => {
            
            let p =new SVGStroke(
                path as SVGPathElement,
                width,
                height
            );
            this.strokes.push(p);

            console.log(p.getPoints())
        });
  
    }

    getStrokes():{x:number,y:number}[][]{

        let list = [];
        for(let i=0;i<this.strokes.length;i++){
            list.push(this.strokes[i].getPoints());
        }

        return list;
    }

}

export class SVGStroke{

    path : SVGPathElement;
    points:{x:number,y:number}[] = [];

    constructor(path:SVGPathElement,w:number,h:number){

        this.path = path;    
        console.log(this.path.getTotalLength());

        this.points = [];

        let num = 10;
        for(let i=0;i<num;i++){
            
            let points = this.path.getPointAtLength(i/num*this.path.getTotalLength());
            this.points[i] = {
                x:points.x,
                y:points.y
            };
            
        }
        //this.path.getTotalLength();
        //this.path.getPointAtLength(0);
    }

    public getPoints():{x:number,y:number}[]{
        return this.points;
    }

}

"FOOTER"