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
| var VSHADER_SOURCE = ` attribute vec4 a_Position; void main(){ gl_Position = a_Position; gl_PointSize = 10.0; } `;
var FSHADER_SOURCE = ` precision mediump float; uniform vec4 u_FragColor; void main(){ gl_FragColor = u_FragColor; } `; function main() { let canvas = document.getElementById('webgl'); let gl = getWebGLContext(canvas); if (!gl) { console.log('获取上下文失败'); return; } if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) { console.log('着色器初始化失败'); return; } let a_Position = gl.getAttribLocation(gl.program, 'a_Position'); let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor'); if (a_Position < 0 || u_FragColor ) { console.log('获取变量存储位置失败'); return; }
canvas.onmousedown = function (ev) { click(ev, gl, canvas, a_Position, u_FragColor); }
gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT);
}
let gl_points = []; let gl_colors = []; function click(ev,gl,canvas,a_Position,u_FragColor) { let x = ev.clientX; let y = ev.clientY; let rect = ev.target.getBoundingClientRect(); x = (x - rect.left - canvas.width / 2) / (canvas.width / 2); y = (rect.top + canvas.height / 2 - y) / (canvas.height / 2); gl_points.push([x, y]); gl_colors.push([ Math.random().toFixed(1), Math.random().toFixed(1), Math.random().toFixed(1), 1.0, ]); gl.clear(gl.COLOR_BUFFER_BIT); gl_points.forEach((point, index) => { gl.vertexAttrib2f(a_Position, point[0], point[1]); gl.uniform4f( u_FragColor, gl_colors[index][0], gl_colors[index][1], gl_colors[index][2], gl_colors[index][3] ) gl.drawArrays(gl.POINTS, 0, 1); }) }
|