Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling HTML5 canvas width preserving w/h aspect ratio

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?

like image 978
dcd0181 Avatar asked May 25 '12 07:05

dcd0181


People also ask

How can an HTML5 canvas size be changed so that it fits the entire window?

Width and height of canvas is set to 100%. Position is absolute and top, left, right, and bottom are “0” in order make the canvas fit the window. Also, the body elements fill the window by assigning their height and width value to 100%.

How do I make my canvas fit the screen in HTML?

Set the Size with CSSto set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.


1 Answers

First you set the width of canvas to 100%

$('#canvas').css('width', '100%');

then update its height base on its width

$(window).resize(function(){
   $('#canvas').height($('#canvas').width() / 2.031);
});

2.031 = 979/482

But you should not attach to $(window).resize like me... it's a bad behavior

like image 131
James Avatar answered Nov 07 '22 07:11

James