THREEJS实现给定宽度的虚线

220 阅读1分钟

在 Three.js 中,直接设置线条宽度可能会比较复杂,因为 WebGL 本身对线宽支持有限。大多数情况下,WebGL 只支持 1 像素的线宽。在一些高性能的应用中,你可能需要使用其他方法来模拟线条的宽度,如使用带有宽度的网格(如平面几何体)来代替线条,但是实现起来比较复杂且性能方面欠佳。
好在Three.js在其扩展库中提供了Line2的物体,可以用来创建带宽度、虚线的线条。这是更高级的方式,适合需要高性能渲染的场景。

    import { Line2 } from 'three/examples/jsm/lines/Line2'
    import { LineGeometry } from 'three/examples/jsm/lines/LineGeometry'
    import { LineMaterial } from 'three/examples/jsm/lines/LineMaterial'
    
    const getDashedWidthLine({pointArr,dashSize,gapSize,width=1,dashed=false}){
        const geometry = new LineGeometry();
        geometry.setPositions(pointArr);
        const material = new LineMaterial({ 
            color: 0xffffff, 
            linewidth: width,
            dashed,//开启是否为虚线
            dashSize, // 设置虚线长度
            gapSize, // 设置虚线间隔
         });
        // LineMaterial类的构造函数值
         // parameters = {
         //  color: <hex>,
         //  linewidth: <float>,
         //  dashed: <boolean>,
         //  dashScale: <float>,
         //  dashSize: <float>,
         //  dashOffset: <float>,
         //  gapSize: <float>,
         //  resolution: <Vector2>, // to be set by renderer
         // }
        material.resolution.set(window.innerWidth, window.innerHeight);//设置分辨率
        const line = new Line2(geometry, material);
        line.computeLineDistances();
        return line
    }
    //测试
    const pointArr = [
         -100, 0, 0,
        -100, 100, 0,
        0, 0, 0,
        100, 100, 0,
        100, 0, 0
    ]
    getDashedWidthLine({pointArr,dashSize:3,gapSize:1,width:5,dashed:true})