缩放HTML5画布宽度,保持w / h宽高比

时间:2012-05-25 07:19:10

标签: javascript html5-canvas aspect-ratio

我有一个尺寸为979X482px的画布元素,我想让它伸展以适应任何给定浏览器窗口的宽度,保持宽高/高度1的宽高比为1,我希望高度相对于到画布的宽度。有关如何使用javascript / jQuery执行此操作的任何建议吗?

5 个答案:

答案 0 :(得分:10)

 ctx.canvas.width = window.innerWidth;

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

或其中的一些变体。 ctx是上下文。边缘情况的if语句可能是必要的!

答案 1 :(得分:3)

首先,您将画布的宽度设置为100%

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

然后根据宽度

更新其高度
$(window).resize(function(){
   $('#canvas').height($('#canvas').width() / 2.031);
});

2.031 = 979/482

但是你不应该像我一样附上$(window).resize ......这是一种不好的行为

答案 2 :(得分:1)

之前的所有答案都很棒,但它们不会按照新的画布大小按比例缩放画布上绘制的所有图像。如果你正在使用kinetic,我在这里做了一个函数= http://www.andy-howard.com/how-to-resize-kinetic-canvas-and-maintain-the-aspect-ratio/

答案 3 :(得分:0)

我自己一直在玩这个。这个概念围绕着了解画布的宽度。您还需要确保所有画布资源也使用计算来依赖于浏览器进行发布。我记录了我的代码,希望它有所帮助,

<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>

答案 4 :(得分:-3)

试试这个

$('#canvas').css('width', $(window).width());
$('#canvas').css('height', $(window).height());
相关问题