| 2022-05-12

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.

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

    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%')
    
    JavaScript

    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.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.