JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<div>
<p>
WebGL Canvas
</p>
<!--Set the canvas height and width in the element's attribute-->
<canvas id="canvas" height='300' width='400'></canvas>
<p>
HTML5 Canvas (Expected output)
</p>
<canvas id="html5Canvas" height='300' width='400'></canvas>
</div>
CSS
div {
background-color: purple;
background-image: linear-gradient(45deg, rgba(255, 255, 255, 1) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 1) 50%, rgba(255, 255, 255, 1) 75%, transparent 75%, transparent);
background-size: 50px 50px;
min-height: 600px;
padding: 50px;
}
canvas {
border: 3px solid red;
/* Set the dimension of the canvas in CSS */
height: 300px;
width: 400px;
}
p {
color: red;
font-family: "Arial";
font-weight: "Bold";
font-size: 2em;
background: white;
}
JavaScript
function drawHtml5() {
var html5 = document.getElementById("html5Canvas").getContext("2d");
// Set the dimension of the canvas in JS.
html5.width = 400;
html5.height = 300;
html5.fillStyle = "rgba(255,0,0,0.5)";
html5.fillRect(100,75,200,150);
html5.fillStyle = "rgba(0,255,0,0.5)";
html5.fillRect(135,100,200,150);
html5.fillStyle = "rgba(0,0,255,0.5)";
html5.fillRect(50,125,200,150);
}
function drawWebGL() {
/* Set premulipliedAlpha to 'true' */
var gl = document.getElementById("canvas").getContext("webgl", {
premultipliedAlpha: true,
});
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.disable(gl.DEPTH_TEST);
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
indices = [3,2,1,3,1,0];
// Create an empty buffer object to store vertex buffer
var vertex_buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// Create an empty buffer object to store Index buffer
var Index_Buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
/*====================== Shaders =======================*/
// Vertex shader source code
var vertCode =
'attribute vec3 coordinates;' +
'uniform vec4 translation;'+
'void main(void) {' +
' gl_Position = vec4(coordinates, 1) + translation;' +
'}';
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
...