使用WebGL绘制每个点都有不同颜色的二维点数组可以通过以下步骤实现:
points
是一个包含点的位置数据的二维数组。points[i].color
是一个包含RGBA颜色值的数组,表示第i个点的颜色。完整的示例代码如下:
<!DOCTYPE html>
<html>
<head>
<title>WebGL Example</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const gl = canvas.getContext('webgl');
const vertexShaderSource = `
attribute vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0, 1);
}
`;
const fragmentShaderSource = `
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
const points = [
{ position: [0, 0], color: [1, 0, 0, 1] },
{ position: [0.5, 0.5], color: [0, 1, 0, 1] },
{ position: [-0.5, 0.5], color: [0, 0, 1, 1] }
];
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(points.flatMap(p => p.position)), gl.STATIC_DRAW);
const positionAttributeLocation = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);
const colorUniformLocation = gl.getUniformLocation(program, 'u_color');
for (let i = 0; i < points.length; i++) {
gl.uniform4fv(colorUniformLocation, points[i].color);
gl.drawArrays(gl.POINTS, i, 1);
}
</script>
</body>
</html>
这样,就可以使用WebGL绘制每个点都有不同颜色的二维点数组了。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云