简体   繁体   中英

scaling a canvas element and keeping the aspect ratio

i have a simple html5 page with a canvas element at a certain size. now i want that the canvas element always scales with the available size from the page but still keeps a certain aspect ratio.

also how can i get the current scale factor of the canvas element in javascript code?

thanks!

If w is your width and h your height. w/h is your ratio.

Now your page width is bigger or smaller. Let's say your new width name is newW. And you are searching newH.

To keep your ratio just do the math : newH = newW / (w/h);

To get your width and height just use a document.getElementById("canvas").width/height

This should work

canvas {
 outline: 0px;
 position: absolute;
 left: 0px;
 top: 0px;
 width: 100%;
 height: auto;
}

The key thing here is that the height automatically adjusts to whatever aspect ratio the canvas element is in.

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