Canvas size and WebGL
This WebGL example explores the effect of setting (or not setting) the canvas size to its element size inCSS pixels, as it appears in the browser window.
In this article
Effect of canvas size on rendering with WebGL
Withscissor() andclear() we can demonstrate how the WebGL drawing buffer is affected by the size of the canvas.
The size of the first canvas is set to the styledElement size, determined byCSS. This is done by assigning thewidth andheight properties of the canvas to the values of theclientWidth andclientHeight properties, respectively.
In contrast, no such assignment is done for the second canvas. The internalwidth andheight properties of the canvas remain at default values, which are different than the actual size of the canvasElement in the browser window.
The effect is clearly visible when usingscissor() andclear() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position.
<p>Compare the two canvases.</p><canvas>Your browser does not seem to support HTML canvas.</canvas><canvas>Your browser does not seem to support HTML canvas.</canvas>body { text-align: center;}canvas { display: inline-block; width: 120px; height: 80px; margin: auto; padding: 0; border: none; background-color: black;}const [firstCanvas, secondCanvas] = document.getElementsByTagName("canvas");firstCanvas.width = firstCanvas.clientWidth;firstCanvas.height = firstCanvas.clientHeight;[firstCanvas, secondCanvas].forEach((canvas) => { const gl = canvas.getContext("webgl"); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.enable(gl.SCISSOR_TEST); gl.scissor(30, 10, 60, 60); gl.clearColor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT);});The source code of this example is also available onGitHub.