3

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.

Ryan
  • 199
  • 2
  • 7
  • 19

1 Answers1

5

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.

Shmiddty
  • 13,847
  • 1
  • 35
  • 52
  • This is exactly what I wanted, going to try to get it working now. Cheers mate. – Ryan Oct 03 '12 at 21:07
  • With jQuery, the code becomes simpler, but that tag wasn't there when I wrote this. :P – Shmiddty Oct 03 '12 at 21:12
  • Do you mind providing it done with Jquery? – Ryan Oct 03 '12 at 21:39
  • @Ryan It's more or less the same, except instead of using `offsetWidth` we can use jQuery's `width` or `outerWidth` which is consistent across different browsers. – Shmiddty Oct 03 '12 at 21:46