效果
image.png
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600" style="border: 1px solid #ff0000;"></canvas>
<script>
let canvas = document.getElementById('canvas');
let gl = canvas.getContext('webgl');
// 顶点着色器
let VSHADER_SOURCE =
"attribute vec4 a_Position;\n"+
"void main(){\n"+
"gl_Position = a_Position;\n"+
"gl_PointSize = 10.0;\n"+
"}\n";
// 片元着色器
let FSHADER_SOURCE =
"precision mediump float;\n"+
"uniform vec4 u_FragColor;\n"+
"void main(){\n"+
"gl_FragColor = u_FragColor;\n"+
"}\n";
// 初始化着色器
function initShaders(gl, vSource, fSource){
let vShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vShader, vSource);
gl.compileShader(vShader);
let fShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fShader, fSource);
gl.compileShader(fShader);
let program = gl.createProgram();
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
gl.useProgram(program);
gl.program = program;
}
initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);
let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
let g_points = [];
let g_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 = (canvas.height/2 - (y-rect.top)) / (canvas.height/2)
g_points.push([x, y]);
if(x >= 0.0 && y>= 0.0){
g_colors.push([1.0, 0.0, 0.0, 1.0]);
}else if(x <= 0.0 && y>= 0.0){
g_colors.push([1.0, 1.0, 0.0, 1.0]);
}else if(x <= 0.0 && y<= 0.0){
g_colors.push([0.0, 1.0, 0.0, 1.0]);
}else{
g_colors.push([0.0, 0.0, 1.0, 1.0]);
}
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
for(let i=0,len=g_points.length; i<len; i++){
gl.vertexAttrib2f(a_Position, g_points[i][0], g_points[i][1]);
gl.uniform4f(u_FragColor, g_colors[i][0], g_colors[i][1], g_colors[i][2], g_colors[i][3]);
gl.drawArrays(gl.POINTS, 0, 1);
}
}
canvas.onclick = 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);
</script>
</body>
</html>
网友评论