1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| const vs = ` precision mediump float;
attribute vec2 vertPosition; attribute vec3 vertColor; varying vec3 fragColor;
void main() { gl_Position = vec4(vertPosition, 0.0, 1.0); fragColor = vertColor; } `
const fs = ` precision mediump float;
varying vec3 fragColor; void main() { gl_FragColor = vec4(fragColor, 1.0); } `
const triangleVertices = [ 0.0, 0.5, 1.0, 1.0, 0.0, -0.5, -0.5, 0.7, 0.0, 1.0, 0.5, -0.5, 0.1, 1.0, 0.6 ];
Page({ onLoad() { const query = wx.createSelectorQuery() query.select('#myCanvas').node().exec((res) => { const canvas = res[0].node this._render(canvas) }) },
_render(canvas) { const gl = canvas.getContext('webgl') if (!gl) { console.error('gl init failed', gl) return } gl.viewport(0, 0, 300, 300) const vertShader = gl.createShader(gl.VERTEX_SHADER) gl.shaderSource(vertShader, vs) gl.compileShader(vertShader)
const fragShader = gl.createShader(gl.FRAGMENT_SHADER) gl.shaderSource(fragShader, fs) gl.compileShader(fragShader)
const prog = gl.createProgram() gl.attachShader(prog, vertShader) gl.attachShader(prog, fragShader) gl.deleteShader(vertShader) gl.deleteShader(fragShader) gl.linkProgram(prog) gl.useProgram(prog)
const draw = () => { const triangleVertexBufferObject = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexBufferObject) gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVertices), gl.STATIC_DRAW)
const positionAttribLocation = gl.getAttribLocation(prog, 'vertPosition') const colorAttribLocation = gl.getAttribLocation(prog, 'vertColor') gl.vertexAttribPointer( positionAttribLocation, 2, gl.FLOAT, gl.FALSE, 5 * Float32Array.BYTES_PER_ELEMENT, 0 ) gl.vertexAttribPointer( colorAttribLocation, 3, gl.FLOAT, gl.FALSE, 5 * Float32Array.BYTES_PER_ELEMENT, 2 * Float32Array.BYTES_PER_ELEMENT )
gl.enableVertexAttribArray(positionAttribLocation) gl.enableVertexAttribArray(colorAttribLocation) gl.drawArrays(gl.TRIANGLES, 0, 3) canvas.requestAnimationFrame(draw) }
canvas.requestAnimationFrame(draw) } })
|