How to make canvas responsive

Gislef picture Gislef · Jan 13, 2016 · Viewed 100.8k times · Source

I use bootstrap. I want the user to be able to choose the canvas size while keeping the design screen responsive within the div.

<div class="row">
  <div class="col-xs-2 col-sm-2" id="border">content left</div>
  <div class="col-xs-6 col-sm-6" id="border">
    Width <input type="number" class="form-control"><br>
  Height <input type="number" class="form-control"><br>
  canvas
  <canvas id="canvas" width="500" height="300">  
  </canvas>

  </div>
  <div class="col-xs-2 col-sm-2" id="border">content right</div>

How can I limit the size of the canvas to the size of the div?

I do not know if it will be necessary to use JavaScript.


Edit

It should be taken into account that the width and height values are entered by the user and the canvas must be in div proportional in size

https://jsfiddle.net/1a11p3ng/2/

Answer

Faheel picture Faheel · Mar 28, 2018

You can have a responsive canvas in 3 short and simple steps:

  1. Remove the width and height attributes from your <canvas>.

    <canvas id="responsive-canvas"></canvas>
    
  2. Using CSS, set the width of your canvas to 100%.

    #responsive-canvas {
      width: 100%;
    }
    
  3. Using JavaScript, set the height to some ratio of the width.

    var canvas = document.getElementById('responsive-canvas');
    var heightRatio = 1.5;
    canvas.height = canvas.width * heightRatio;