KITASENJU DESIGN BLOG

memo, html, javascript, unity

threejsでsvg

import * as THREE from 'three';
import { MeshBasicMaterial, BoxGeometry, Object3D, Shape, Vector3 } from 'three';
import { SVGLoader } from 'three/examples/jsm/loaders/SVGLoader';


export class MySVGLoader extends Object3D{

    loader  :SVGLoader;
    shapes   :Shape[][]
    callback :()=>void;
    points   :THREE.Vector3[] = [];

    constructor(){
        super();
    }

    init(url:string,callback:()=>void){

        this.callback = callback;
        this.shapes = [];
        this.loader = new SVGLoader();
        this.loader.load( url, ( data )=>{

            console.log("onload")
             const paths = data.paths;
             //console.log(paths);
 
             for ( let i = 0; i < paths.length; i ++ ) {
 
                const path = paths[ i ];
 
                const shapes = SVGLoader.createShapes( path );
                this.shapes.push(shapes);

                 for ( let j = 0; j < shapes.length; j ++ ) {
 
                     const shape = shapes[ j ]; 
                     let m = new MeshBasicMaterial({
                         color:0xff0000,
                         wireframe:true
                     });
                     const geometry = new THREE.ShapeGeometry( shape );
                     const mesh = new THREE.Mesh( geometry, m );
                     
                     //this.add(mesh);
 
                 }
 
             }
             
             this.getAllPoints();
             this.callback();
        });

       

    }


    getRandomPoint():THREE.Vector3{

        return this.points[Math.floor(Math.random()*this.points.length)];

    }


    getAllPoints(){

        this.points = [];
        for(let i=0;i<this.shapes.length;i++){

            let shape = this.shapes[i];
            for(let j=0;j<shape.length;j++){

                let pts = shape[j].getSpacedPoints(50);

                let geo = new BoxGeometry(4,4,4);
                let mat = new MeshBasicMaterial({color:0xff0000})

                for(let k=0;k<pts.length;k++){
                    let m = new THREE.Mesh(geo,mat);
                    m.position.set(
                        pts[k].x,
                        -pts[k].y,
                        0
                    )
                    this.add(m);
                    this.points.push(new Vector3(
                        pts[k].x,
                        -pts[k].y,
                        0
                    ));
                }



            }

        }


    }


}
"FOOTER"