Setting pixel colors on a WebGL canvas typically involves the following steps:
1. Create and Set Up the Canvas
First, create a <canvas> element and get its WebGL context.
html<canvas id="webglCanvas"></canvas> <script> var canvas = document.getElementById('webglCanvas'); var gl = canvas.getContext('webgl'); if (!gl) { console.error('WebGL not supported in this browser.'); } </script>
2. Define Vertex Data
Define the vertices for the shape you want to render. For simplicity, we'll draw a single point.
javascriptvar vertices = new Float32Array([ 0.0, 0.0 ]);
3. Create Vertex Buffer
Upload the vertex data to the GPU buffer.
javascriptvar vertexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
4. Create Vertex and Fragment Shaders
The vertex shader sets the vertex positions, while the fragment shader sets the pixel colors.
javascriptvar vertexShaderCode = `\nattribute vec2 position;\nvoid main() {\n gl_Position = vec4(position, 0.0, 1.0);\n gl_PointSize = 10.0;\n}`;\nvar vertexShader = gl.createShader(gl.VERTEX_SHADER);\ngl.shaderSource(vertexShader, vertexShaderCode);\ngl.compileShader(vertexShader); var fragmentShaderCode = `\nprecision mediump float;\nvoid main() {\n gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // red\n}`;\nvar fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\ngl.shaderSource(fragmentShader, fragmentShaderCode);\ngl.compileShader(fragmentShader);
5. Create and Link Shader Program
Link the vertex and fragment shaders into a shader program and use it.
javascriptvar shaderProgram = gl.createProgram();\ngl.attachShader(shaderProgram, vertexShader);\ngl.attachShader(shaderProgram, fragmentShader);\ngl.linkProgram(shaderProgram);\ngl.useProgram(shaderProgram);
6. Associate Vertex Data with Shader Attributes
Bind the vertex data from the buffer to the attributes in the vertex shader.
javascriptvar positionAttributeLocation = gl.getAttribLocation(shaderProgram, 'position');\ngl.enableVertexAttribArray(positionAttributeLocation);\ngl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);\ngl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);
7. Draw
Finally, draw the pixels on the canvas using the drawing command.
javascriptgl.clearColor(0.0, 0.0, 0.0, 1.0); // black background\ngl.clear(gl.COLOR_BUFFER_BIT);\ngl.drawArrays(gl.POINTS, 0, 1);
By following these steps, you will render a red point at the center of the WebGL canvas. Each step is essential to ensure WebGL correctly sets and displays the pixel colors.