Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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.

Post a Comment for "Scaling A Canvas Element And Keeping The Aspect Ratio"