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

在openGL或者webGL用要想實(shí)現(xiàn)多彩絢麗的效果,必須要使用到shader著色器。著色器需要使用GLSL語言來編寫,專業(yè)性很強(qiáng)門檻也比較高。我們可以通過內(nèi)部挖潛來達(dá)到同樣的目的。

在Threejs的文檔中我們可以看到,[CanvasTexture](https://threejs.org/docs/index.html#api/zh/textures/CanvasTexture通過這項(xiàng)技術(shù)我們可以把一個(gè)canvas當(dāng)作texture來使用。下面我將實(shí)現(xiàn)一個(gè)有漸變效果的planning線來作為實(shí)例講解。

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面板中可以看到兩個(gè)兩個(gè)canvas實(shí)例:


MacHi 2019-09-24 14-21-35.png

結(jié)語

通過內(nèi)部挖潛使用canvasTexture我們實(shí)現(xiàn)了需要用shader才能實(shí)現(xiàn)的效果,發(fā)散一下思維,很多的高級效果也可以使用這一方式來實(shí)現(xiàn)。


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容