Oliver Wolfson
ServicesProjectsContact

Development Services

SaaS apps · AI systems · MVP builds · Technical consulting

Services·Blog
© 2025 O. Wolf. All rights reserved.
webdevelopmentjavascript
How to Create a Responsive Canvas Element
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.
May 12, 2022•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.

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

Component "IFrame" is not available. Please define it in the MDX components.

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

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.

Tags
#canvas#html