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?
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?
Share Improve this question edited Apr 27, 2024 at 11:28 Alexander Farber 23k78 gold badges257 silver badges441 bronze badges asked Dec 14, 2010 at 15:19 clampclamp 34k75 gold badges207 silver badges305 bronze badges3 Answers
Reset to default 19If 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.
Nowadays you have css property object-fit:contain
. No additional calculation is required while using it. This way the canvas keeps it's aspect ratio while filling 100% of width or height and keep a margin for the other (red area in the snippet):
canvas1 = document.getElementById('canvas1')
const ctx = canvas1.getContext("2d");
ctx.beginPath();
ctx.rect(0, 0, 20, 20);
ctx.fill();
ctx.strokeStyle="#00ff00"
ctx.rect(0, 0, 20, 20)
ctx.stroke()
<div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color:red">
<canvas id="canvas1" width="20" height="20" style="width:100%; height: 100%; object-fit: contain"></canvas>
</div>
While trying to resize your browser window you will notice the canvas is always fully displayed while keeping it's aspect ratio.