Scaling HTML5 canvas width preserving w/h aspect ratio

醉酒当歌 提交于 2019-11-30 19:28:32
Trinh Hoang Nhu

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

 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!

All the previous answers are great, but they won't scale all the images drawn on the canvas proportionally with the new canvas size. If you're using kinetic, I've made a function here = http://www.andy-howard.com/how-to-resize-kinetic-canvas-and-maintain-the-aspect-ratio/

I was playing around with this for a while myself. The concept revolves around knowing the width of the canvas. You also need to make sure all your canvas assets also use calculations to for posting dependent on the browser with. I documented my code, I hope it 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>

Try this

$('#canvas').css('width', $(window).width());
$('#canvas').css('height', $(window).height());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!