How to make canvas responsive

CssHtmlCanvasResponsive Design

Css Problem Overview


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/

Css Solutions


Solution 1 - Css

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;
    

Solution 2 - Css

To change width is not that hard. Just remove the width attribute from the tag and add width: 100%; in the css for #canvas

#canvas{
  border: solid 1px blue;  
  width: 100%;
}

Changing height is a bit harder: you need javascript. I have used jQuery because i'm more comfortable with.

you need to remove the height attribute from the canvas tag and add this script:

  <script>
  function resize(){	
    $("#canvas").outerHeight($(window).height()-$("#canvas").offset().top- Math.abs($("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
  }
  $(document).ready(function(){
  	resize();
    $(window).on("resize", function(){         				
    	resize();
    });
  });
  </script>

You can see this fiddle: https://jsfiddle.net/1a11p3ng/3/

EDIT:

To answer your second question. You need javascript

  1. First of all i changed your #border id into a class since ids must be unique for an element inside an html page (you can't have 2 tags with the same id)

    .border{ border: solid 1px black; }

    #canvas{ border: solid 1px blue;
    width: 100%; }

  2. Changed your HTML to add ids where needed, two inputs and a button to set the values

    content left
    Width
    Height
    canvas

    content right

  3. Set the canvas height and width so that it fits inside the container

    $("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));

  4. Set the values of the width and height forms

    $("#h-input").val($("#canvas").outerHeight()); $("#w-input").val($("#canvas").outerWidth());

  5. Finally, whenever you click on the button you set the canvas width and height to the values set. If the width value is bigger than the container's width then it will resize the canvas to the container's width instead (otherwise it will break your layout)

     $("#set-size").click(function(){
     	$("#canvas").outerHeight($("#h-input").val());
         $("#canvas").outerWidth(Math.min($("#w-input").val(), $("#main-content").width()));
     });
    

See a full example here https://jsfiddle.net/1a11p3ng/7/

UPDATE 2:

To have full control over the width you can use this:

<div class="container-fluid">
<div class="row">
  <div class="col-xs-2 border">content left</div>
  <div class="col-xs-8 border" id="main-content">
    <div class="row">
      <div class="col-xs-6">
        Width <input id="w-input" type="number" class="form-control">
      </div>
      <div class="col-xs-6">
        Height <input id="h-input" type="number" class="form-control">
      </div>
      <div class="col-xs-12 text-right" style="padding: 3px;">
        <button id="set-size" class="btn btn-primary">Set</button>
      </div> 
    </div>
      canvas
    <canvas id="canvas">

    </canvas>
  
  </div>
  <div class="col-xs-2 border">content right</div>
</div>
</div>
  <script>
   $(document).ready(function(){
   	$("#canvas").outerHeight($(window).height()-$("#canvas").offset().top-Math.abs( $("#canvas").outerHeight(true) - $("#canvas").outerHeight()));
  	$("#h-input").val($("#canvas").outerHeight());
  	$("#w-input").val($("#canvas").outerWidth());
    $("#set-size").click(function(){
    	$("#canvas").outerHeight($("#h-input").val());
      $("#main-content").width($("#w-input").val());
      $("#canvas").outerWidth($("#main-content").width());
    });
   });
  </script>

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

the content left and content right columns will move above and belove the central div if the width is too high, but this can't be helped if you are using bootstrap. This is not, however, what responsive means. a truly responsive site will adapt its size to the user screen to keep the layout as you have intended without any external input, letting the user set any size which may break your layout does not mean making a responsive site.

Solution 3 - Css

The object-fit CSS property sets how the content of a replaced element, such as an img or video, should be resized to fit its container.

Magically, object fit also works on a canvas element. No JavaScript needed, and the canvas doesn't stretch, automatically fills to proportion.

canvas {
    width: 100%;
    object-fit: contain;
}

Solution 4 - Css

<div class="outer">
 <canvas id="canvas"></canvas>
</div>    

.outer {
 position: relative;
 width: 100%;
 padding-bottom: 100%;
}

#canvas {
 position: absolute;
 width: 100%;
 height: 100%;
}

Solution 5 - Css

extending accepted answer with jquery

what if you want to add more canvas?, this jquery.each answer it

responsiveCanvas(); //first init
$(window).resize(function(){
  responsiveCanvas(); //every resizing
  stage.update(); //update the canvas, stage is object of easeljs
  
});
function responsiveCanvas(target){
  $(canvas).each(function(e){
    
    var parentWidth = $(this).parent().outerWidth();
    var parentHeight =  $(this).parent().outerHeight();
    $(this).attr('width', parentWidth);
    $(this).attr('height', parentHeight);
    console.log(parentWidth);
  })
  
}

it will do all the job for you

why we dont set the width or the height via css or style? because it will stretch your canvas instead of make it into expecting size

Solution 6 - Css

this seems to be working :

#canvas{
  border: solid 1px blue; 
  width:100%;
}

Solution 7 - Css

There's a better way to do this in modern browsers using the vh and vw units.

vh is the viewport height.

So you can try something like this:

<style>
canvas {
  border: solid 2px purple;
  background-color: green;
  width: 100%;
  height: 80vh;
}
</style>

This will distort the aspect ration.

You can keep the aspect ratio by using the same unit for each. Here's an example with a 2:1 aspect ratio:

<style>
canvas {
  width: 40vh;
  height: 80vh;
}
</style>

Solution 8 - Css

try using max-width: 100%; on your canvas.

canvas {
  max-width: 100%;
}

Solution 9 - Css

Hi I know this post has been going on for a while, but I had a very similar problem with my canvas. like mentioned as the viewport gets resized and so does the elements within the window. This can be done using css, however it doesnt quite apply to the elements within the canvas. Now if your canvas context is 2D this is the solution that works for me... This can be used as a method.

class ParentObject{
 constructor()
        /**
        * @this this._width - Private width variable that would store the size of the window width
        */
        this._width = Number();
       
        /**
         * @this this._height - Private Height variable that would store the height of the window
         */
        this._height= Number();
        
        /**
         * Calls the getCanvasDimensions method
         */
        this.getCanvasDimensions();
       
        //Getting the Width and Height as soon as the Window loads
        window.addEventListener('load',()=>{
            this.getCanvasDimensions()
        })
       
        //As the window is resized we are getting the new Canvas Dimensions
        window.addEventListener('resize',()=>{
            this.getCanvasDimensions();

getCanvasDimensions() {
        // Width is determined by the css value for the viewport width this is then respected by the device pixel ratio. This is then used to set the canvas.width value
        this._width = Math.round((Number(getComputedStyle(canvas).getPropertyValue('width').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
        //Setting the canvas width 
        canvas.width = this._width
        
        // height is determined by the css value for the viewport height this is then respected by the device pixel ratio. This is then used to set the canvas.height value
        this._height = Math.round((Number(getComputedStyle(canvas).getPropertyValue('height').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
        //Setting the canvas height
        canvas.height = this._height
        
    }
get width(){
        //This sets the width to the private _width value
        return this._width
        
    }
get height(){
        //This sets the height to the private _height value
        return this._height
    }

As a function on the global scope:

let width,height
function responsiveCanvas(){
   let w = Math.round((Number(getComputedStyle(canvas).getPropertyValue('width').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
 width = canvas.height = w;

let h  = Math.round((Number(getComputedStyle(canvas).getPropertyValue('height').slice(0,-2))/devicePixelRatio) * devicePixelRatio);
height = canvas.height = h;
}
window.addEventListener('load',responsiveCanvas)
window.addEventListener('resize',responsiveCanvas)

Then just use the width and height variables to reference the sizes. Anyways I hope that this helps someone out.

Solution 10 - Css

One of the best possible way to do this without even using JavaScript is to just put that canvas inside a div tag and then display block (Note: width:100%; height:100%; is completely optional).

Run the snippet below to see how it works.....

<div class="container">
  <!-- width and height are set just to show you it actually works-->
  <canvas id="canvas" width=864 height=480></canvas>
</div>

.container {
  display: block;
  margin: auto;
  height: auto;
}

#canvas {
  width: 100%;
  height: 100%;
  border: 1px solid black;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGislefView Question on Stackoverflow
Solution 1 - CssFaheelView Answer on Stackoverflow
Solution 2 - CssvalepuView Answer on Stackoverflow
Solution 3 - CssnicklundyView Answer on Stackoverflow
Solution 4 - CssMichael Sherris CaleyView Answer on Stackoverflow
Solution 5 - Cssdavid valentinoView Answer on Stackoverflow
Solution 6 - CssTheGrumView Answer on Stackoverflow
Solution 7 - CssMichael ColeView Answer on Stackoverflow
Solution 8 - CssSanusi hassanView Answer on Stackoverflow
Solution 9 - CssDr GaudView Answer on Stackoverflow
Solution 10 - CssanzeqarView Answer on Stackoverflow