{
const canvas = DOM.canvas(256, 256)
const gl = canvas.getContext('webgl2')
if (!gl) {
return html`<strong style="color:red">Sorry, WebGL2 is not supported in this browser.</strong><br /><a href="https://get.webgl.org/get-a-webgl-implementation/">Learn how to get a WebGL2 implementation →</a>`
}
const vertexShaderSource = `#version 300 es
uniform float u_PointSize;
in vec2 a_Position;
in vec4 a_Color;
out vec4 v_Color;
void main() {
v_Color = a_Color;
gl_Position = vec4(a_Position, 0, 1);
gl_PointSize = u_PointSize;
}`
const vs = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vs, vertexShaderSource)
gl.compileShader(vs)
const fragmentShaderSource = `#version 300 es
precision highp float;
in vec4 v_Color;
out vec4 color;
void main() {
color = v_Color;
}`
const fs = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fs, fragmentShaderSource)
gl.compileShader(fs)
const prog = gl.createProgram()
gl.attachShader(prog, vs)
gl.attachShader(prog, fs)
gl.linkProgram(prog)
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
console.error('prog info-log:', gl.getProgramInfoLog(prog))
console.error('vert info-log: ', gl.getShaderInfoLog(vs))
console.error('frag info-log: ', gl.getShaderInfoLog(fs))
}
// Use the program
gl.useProgram(prog)
// Get uniform location
const u_PointSize = gl.getUniformLocation(prog, 'u_PointSize')
// Set uniform value
gl.uniform1f(u_PointSize, 50)
// Get attribute locations
const a_PositionIndex = gl.getAttribLocation(prog, 'a_Position')
const a_ColorIndex = gl.getAttribLocation(prog, 'a_Color')
// Set up attribute buffers
const a_PositionBuffer = gl.createBuffer()
const a_ColorBuffer = gl.createBuffer()
// Set up a vertex array object
// This tells WebGL how to iterate your attribute buffers
const vao = gl.createVertexArray()
gl.bindVertexArray(vao)
// Pull 2 floats at a time out of the position buffer
gl.bindBuffer(gl.ARRAY_BUFFER, a_PositionBuffer)
gl.enableVertexAttribArray(a_PositionIndex)
gl.vertexAttribPointer(a_PositionIndex, 2, gl.FLOAT, false, 0, 0)
// Pull 4 floats at a time out of the color buffer
gl.bindBuffer(gl.ARRAY_BUFFER, a_ColorBuffer)
gl.enableVertexAttribArray(a_ColorIndex)
gl.vertexAttribPointer(a_ColorIndex, 4, gl.FLOAT, false, 0, 0)
// Add some points to the position buffer
const positions = new Float32Array([
-1.0, 1.0, // top-left
1.0, 1.0, // top-right
1.0, -1.0, // bottom-right
-1.0, -1.0, // bottom-left
])
gl.bindBuffer(gl.ARRAY_BUFFER, a_PositionBuffer)
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW)
// Add some points to the color buffer
const colors = new Float32Array([
1.0, 0.0, 0.0, 1.0, // red
0.0, 1.0, 0.0, 1.0, // green
0.0, 0.0, 1.0, 1.0, // blue
1.0, 1.0, 0.0, 1.0, // yellow
])
gl.bindBuffer(gl.ARRAY_BUFFER, a_ColorBuffer)
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW)
// Draw the point
gl.clearColor(0, 0, 0, 1)
gl.clear(gl.COLOR_BUFFER_BIT)
gl.drawArrays(gl.POINTS, 0, positions.length / 2) // draw all 4 points
return canvas
}