我会持续更新关于wegl的编程指南中的代码。
git代码地址 sogooday
当前的代码不会使用书中的缩写,每一步都是会展开写。希望能给后来学习的一些帮助
在上一节的代码中是使用一个固定的颜色进行绘制?clickPint.js?
本节中我们将使用随机的颜色进行绘制点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
<button id='clearBtn'>画布清除点</button>
<script>
let canvas = document.getElementById('canvas');
canvas.width = 400;
canvas.height = 400;
let gl = canvas.getContext('webgl');
let vertexShaderSource = `
//定義頂點變量
attribute vec4 a_Postion;
void main(){
gl_Position = a_Postion;
//定义当前坐标点中点绘制的大小
gl_PointSize = 10.0;
}
`
let fragmentShaderSource = `
precision mediump float;
//定义当前定点的颜色色值
uniform vec4 u_FragColor;
void main(){
gl_FragColor = u_FragColor;
}
`
//顶点着色器
let vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
//片元着色器
let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader)
//创建程序片段
let program = gl.createProgram()
gl.attachShader(program, vertexShader)
gl.attachShader((program), fragmentShader)
gl.linkProgram(program);
//使用当前的程序片段
gl.useProgram(program);
//点的坐标
let a_Position = gl.getAttribLocation(program, 'a_Postion')
//点颜色的变量
let u_FragColor = gl.getUniformLocation(program, 'u_FragColor')
console.log('u_FragColor:', u_FragColor)
//将点击过的所有坐标点记录下来
let pointList = []
//设置清除背景色
gl.clearColor(0.0, 0.0, 0.0, 1.0)
//使用上述颜色清除canvas的画面
gl.clear(gl.COLOR_BUFFER_BIT)
canvas.onmousedown = function (params) {
//获取点击鼠标的坐标点
let { clientX, clientY } = params;
let color = randomColor()
console.log('color:', color)
//将鼠标的坐标获取到 并转化为 -1 到 1之间
pointList.push({
x: clientX / canvas.offsetWidth * 2 - 1,
y: (clientY / canvas.offsetWidth * 2 - 1) * -1,
//将当前点的色值储存起来
color: color
})
//清除背景色
gl.clear(gl.COLOR_BUFFER_BIT)
//将顶端一口气全部绘制出来
for (let index = 0; index < pointList.length; index++) {
const { x, y, color } = pointList[index];
console.log(color)
gl.vertexAttrib3f(a_Position, x, y, 0.0)
gl.uniform4f(u_FragColor, color.r, color.b, color.g, color.a)
gl.drawArrays(gl.POINTS, 0, 1)
}
}
let nodeBtn = document.getElementById('clearBtn');
nodeBtn.addEventListener('click', () => {
pointList = []
gl.clear(gl.COLOR_BUFFER_BIT)
})
//获取颜色的色值
function randomColor() {
return {
r: Math.random(),
g: Math.random(),
b: Math.random(),
a: 1
};
}
</script>
</body>
</html>
|