[css] How to make canvas responsive

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/

This question is related to css html canvas responsive-design

The answer is


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;
}

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>

this seems to be working :

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

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;
    

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.


<div class="outer">
 <canvas id="canvas"></canvas>
</div>    
.outer {
 position: relative;
 width: 100%;
 padding-bottom: 100%;
}

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

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


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

canvas {
  max-width: 100%;
}

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to canvas

How to make canvas responsive How to fill the whole canvas with specific color? Use HTML5 to resize an image before upload Convert canvas to PDF Scaling an image to fit on canvas Split string in JavaScript and detect line break Get distance between two points in canvas canvas.toDataURL() SecurityError Converting Chart.js canvas chart to image using .toDataUrl() results in blank image Chart.js canvas resize

Examples related to responsive-design

How to make flutter app responsive according to different screen size? Bootstrap 4: responsive sidebar menu to top navbar How to make canvas responsive Putting -moz-available and -webkit-fill-available in one width (css property) Bootstrap 3 - Responsive mp4-video Change hover color on a button with Bootstrap customization iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions? Bootstrap full responsive navbar with logo or brand name text Bootstrap 3 truncate long text inside rows of a table in a responsive way Responsive Bootstrap Jumbotron Background Image