Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I scale an HTML5 canvas to the size of the container wrapping it? [duplicate]

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.

like image 558
Ryan Avatar asked Aug 31 '25 20:08

Ryan


1 Answers

Here's a basic implementation that maintains aspect ratio: http://jsfiddle.net/wtVX2/1/

function resizeCanvas(){
    var con = document.getElementById("container"),
        canvas = document.getElementById("canvas"),
        aspect = canvas.height/canvas.width,    
        width = con.offsetWidth,
        height = con.offsetHeight;

    canvas.width = width;
    canvas.height = Math.round(width * aspect);
}

Note it is only fluid horizontally.

The jQuery would be:

function resizeCanvas(){
    var con = $("#container"),
        canvas = $("#canvas")[0],
        aspect = canvas.height/canvas.width,
        width = con.width(),
        height = con.height();

    canvas.width = width;
    canvas.height = Math.round(width * aspect);
}

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.

like image 66
Shmiddty Avatar answered Sep 03 '25 10:09

Shmiddty