Threejs in autonomous driving -(4)不會shader也能寫出高級效果

在openGL或者webGL用要想實現多彩絢麗的效果,必須要使用到shader着色器。着色器需要使用GLSL語言來編寫,專業性很強門檻也比較高。我們可以通過內部挖潛來達到同樣的目的。

在Threejs的文檔中我們可以看到,CanvasTexture通過這項技術我們可以把一個canvas當作texture來使用。下面我將實現一個有漸變效果的planning線來作爲實例講解。

MacHi 2019-09-24 14-15-26.png


import {MeshLine, MeshLineMaterial} from 'three.meshline';

getMaterial(width) {
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        let colorStop = [
            [0, 'rgba(48,95,255, 1)'],
            [1, 'rgba(40,64,134, 0)']
        ];

        let h = 64;
        let w = 128;

        canvas.width = w;
        canvas.height = h;
        ctx.lineWidth = width;

        let gradient = ctx.createLinearGradient(0, 0, w, 0);

        colorStop.forEach(([position, color]) => gradient.addColorStop(position, color));

        ctx.strokeStyle = gradient;
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, w, h);
        ctx.shadowBlur = 40;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.shadowColor = '#00ff00';

        let texture = new THREE.Texture(canvas);

        texture.needsUpdate = true;

        let {far, near} = this.camera;
        let material = new MeshLineMaterial({
            useMap: true,
            map: texture,
            lineWidth: width,
            transparent: true,
            side: THREE.FrontSide,
            depthTest: true,
            opacity: .89
        });

        return material;
    }

draw(point) {
        let geometry = new THREE.Geometry();
        let line = new MeshLine();

        geometry.vertices = point;
        line.setGeometry(geometry);

        let mesh = new THREE.Mesh(line.geometry, this.material);

        mesh.position.setZ(.2);

        this.path = mesh;
        this.scene.add(this.path);
}

在safari的canvas面板中可以看到兩個兩個canvas實例:
MacHi 2019-09-24 14-21-35.png

結語

通過內部挖潛使用canvasTexture我們實現了需要用shader才能實現的效果,發散一下思維,很多的高級效果也可以使用這一方式來實現。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章