How to Create a Responsive Canvas Element

2022-05-12
By: O. Wolfson

To create a responsive canvas. We wrap the canvas element with a parent element that is responsive. Then set the canvas’ style attribute’s width and height to 100%. The pixel density / resolution of drawings are set by the canvas element’s global width and height attributes. The browser calculates global attributes separate from the style attribute’s properties.

JavaScript
<div id="container" >
     <div id="responsive-frame">
         <canvas id="canvas"></canvas>
     </div>
</div>

The resolution of the canvas is set to 1000 pixels. This resolution determines the pixel density of the drawings within the responsive frame.

JavaScript
const resolution = 1000;
const ratio = 1

const canvas = document.getElementById('canvas')
const ctx = canvas.getContext("2d");

canvas.setAttribute('width', resolution * ratio)
canvas.setAttribute('height', resolution)

canvas.style.setProperty('width', '100%')
canvas.style.setProperty('height', '100%')

Finally, note that you can set display: block; on the canvas element’s style attribute. Otherwise the canvas will be an inline element and will have a baseline, which creates extra space under the canvas.