Scaling HTML5 canvas width preserving w/h aspect ratio

dcd0181 picture dcd0181 · May 25, 2012 · Viewed 32.6k times · Source

I have a canvas element with dimensions of 979X482px and I'd like to have it stretch to fit the width of any given browser window, keeping the aspect ratio of width/hight 1 to 1, I want the height to scale relative to width of the canvas. Any suggestions as how to go about doing this with javascript/jQuery?

Answer

user1422770 picture user1422770 · May 30, 2012
 ctx.canvas.width = window.innerWidth;

 ctx.canvas.height = 3*window.innerWidth/4;

or some variation of that. ctx is the context. An if statement for edge cases might be necessary!