Threejs in autonomy driving - advanced effects can be written without shader s

In order to achieve colorful effects in openGL or webGL, shader s must be used. Shaders need to be written in GLSL language, which is very professional and has a high threshold. We can achieve the same goal by tapping potential internally.

As we can see in the documentation of Threejs, CanvasTexture With this technology, we can use a canvas as a texture. Next, I will implement a planning line with gradient effect as an example.

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} =;
        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;

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


        this.path = mesh;

In safari's canvas panel, you can see two canvas instances:


Through the use of canvas texture, we have realized the effect that can only be realized by using shader. Let's spread our thinking. Many advanced effects can also be realized by using this method.

Keywords: Javascript github

Added by djtozz on Thu, 17 Oct 2019 18:56:20 +0300