简体   繁体   中英

Scale HTML5 Canvas to div width and height

In my application i have div that styled with twitter bootstrap like this :

<div class="col-md-12">
    <canvas id="canvas"></canvas>
</div>

the canvas is placeholder of some large images.i need a way to scale image to width and height of this div or if not exactly scale to width and height of div , scale must create a very small scroll bar for div. the div has overflow:scroll style.

Get the width and height of the div using JavaScript and then set the canvas height and width with these values.

For instance:

var canvas = document.getElementsByTagName('canvas')[0];
var divHeight = document.getElementById('yourDiv').clientHeight;
var divWidth = document.getElementById('yourDiv').clientWidth;

canvas.height = divHeight;
canvas.width = divWidth;

You could add this to a resize event handler so when the div height/width scales it invokes the above code.

If you'd like a non-javascript answer, you can make this happen in CSS:

.col-md-12{
  position:relative; //make sure this is part of your col-md style
}

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

I'm assuming that there is styling that is setting the height of your .col-md-12 div elsewhere.

As you're using bootstrap, you can do it with jquery:

var $canvas = $("#canvas");
var $parent = $canvas.parent();
$canvas.width($parent.width());
$canvas.height($parent.height());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM