Currently I have an HTML5 canvas that is a fixed size, something like this:
<div class="container">
<canvas id="example" width="350" height="250"></canvas>
</div>
However I want to be able to scale the canvas so that it is the same size as the container around it, obviously it still has to keep the same aspect ratio. I also want it to be fluid so that if a user resizes the browser then the canvas will scale with the fluid container.
So for example if my container was set to a width of 500px then the width of the canvas would scale to the same size. Eg:
<div class="container" style="width:500px;">
<canvas id="example"></canvas>
</div>
For example the canvas would get a width of 500px to match the container and the height would automatically be set to 357px which keeps the same aspect ratio.
I believe this could be achieved with some javascript, I just do not know how to do it …
I hope I have provided enough info for someone to help me. Would appreciate it if someone could whip up a jsfiddle and provide some example code of it working if possible.
Thanks.
Here’s a basic implementation that maintains aspect ratio: http://jsfiddle.net/wtVX2/1/
Note it is only fluid horizontally.
The jQuery would be:
Note that I’m still setting the width and height of canvas the same way. If we set the width/height with CSS, it will stretch/squash the drawing of the pixels, and you’ll get fuzzy drawings.