JSFiddle - React, Tailwind, and code Playground
by mortac8
HTML
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<canvas></canvas>
CSS
canvas {
border: 1px solid black;
background: red;
}
JavaScript
function main() {
let myCanvas = document.querySelector('canvas');
let gl = myCanvas.getContext('webgl2');
if (!gl) {
return alert('need WebGL2');
}
const vs = `#version 300 es
void main() {
gl_PointSize = 300.0;
gl_Position = vec4(0, 0, 0, 1);
}
`;
const fs = `#version 300 es
precision highp float;
precision highp int;
precision highp isampler2D;
// our texture
uniform isampler2D u_image;
out vec4 color;
void main() {
ivec4 intColor = texture(u_image, gl_PointCoord.xy);
color = vec4(vec3(intColor.rrr) / 10000.0, 1);
}
`;
const program = twgl.createProgram(gl, [vs, fs]);
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(
gl.TEXTURE_2D,
0, // mip level
gl.R16I, // internal format
10, // width
1, // height
0, // border
gl.RED_INTEGER, // source format
gl.SHORT, // source type
new Int16Array([
1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000
]));
// can't filter integer textures
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.useProgram(program);
// no need to set any attributes or
// uniforms as we're not using attributes
// and uniforms default to zero so will use
// texture unit zero
gl.drawArrays(gl.POINTS, 0, 1);
let result = new Uint16Array(myCanvas.width*myCanvas.height*4);
gl.readPixels(0, 0, myCanvas.width, myCanvas.height, gl.RGBA, gl.UNSIGNED_SHORT, result);
console.log(result);
}
main();