3

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!

clamp
  • 33,000
  • 75
  • 203
  • 299

2 Answers2

18

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

Tim
  • 1,938
  • 1
  • 13
  • 20
1

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.

10 Replies
  • 426
  • 9
  • 25