HTML5 canvas width scaling with w / h ratio

I have a canvas element with dimensions of 979X482px, and I would like it to stretch to fit the width of any browser window, keeping the aspect ratio of width / height 1 to 1, I want the height to scale relative to the width of the canvas. Any suggestions on how to do this using javascript / jQuery?

+8
javascript html5-canvas aspect-ratio
source share
5 answers

First you set the canvas width to 100%

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

then update its height base in width

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

2.031 = 979/482

But you should not attach to $ (window) .resize, as I ... this is bad behavior

+5
source share
  ctx.canvas.width = window.innerWidth; ctx.canvas.height = 3*window.innerWidth/4; 

or some variation of this. ctx is the context. An if statement may be required for edge cases!

+9
source share

All the previous answers are great, but they will not scale all the images drawn on the canvas in proportion to the new canvas size. If you use kinetics, I made a function here = http://www.andy-howard.com/how-to-resize-kinetic-canvas-and-maintain-the-aspect-ratio/

+1
source share

I played with this for a while. The concept revolves around knowing the width of the canvas. You also need to make sure that all of your canvas assets also use browser-based calculations for publishing. I registered my code, hope this helps,

 <body> // in style make your canvas 100% width and hight, this will not flex for all browsers sizes. <style> canvas{ width: 100%; height:100%; position: relative; } </style> <canvas id="myCanvas"></canvas> <script> // here we are just getting the canvas and asigning it the to the vairable context var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // no we get with of content and asign the same hight as the with. this gives up aspect ration 1:1. context.canvas.width = window.innerWidth; context.canvas.height = window.innerWidth; // If you want aspect ration 4:3 uncomment the line below. //context.canvas.height = window.innerWidth; </script> </body> 
0
source share

try it

 $('#canvas').css('width', $(window).width()); $('#canvas').css('height', $(window).height()); 
-2
source share

All Articles