在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)。
- 我的blog: neverland.github.io
- 我的email enix@foxmail.com