我有一个尺寸为979X482像素的画布元素,我希望它可以自适应任何给定浏览器窗口的宽度,并保持宽高比例为1:1,我希望画布的高度相对于宽度进行缩放。 有什么建议可以用javascript / jQuery实现这个功能吗?
我有一个尺寸为979X482像素的画布元素,我希望它可以自适应任何给定浏览器窗口的宽度,并保持宽高比例为1:1,我希望画布的高度相对于宽度进行缩放。 有什么建议可以用javascript / jQuery实现这个功能吗?
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = 3*window.innerWidth/4;
或者类似的变体。 ctx
是上下文。对于边缘情况可能需要一个 if 语句!
首先,您需要将画布的宽度设置为100%。
$('#canvas').css('width', '100%');
然后根据宽度更新其高度。
$(window).resize(function(){
$('#canvas').height($('#canvas').width() / 2.031);
});
2.031 = 979/482
但是你不应该像我一样绑定 $(window).resize...这是一种不好的行为。
$('#canvas').height($('canvas').width() / 2.031);
应该改为 $('#canvas').height($('#canvas').width() / 2.031);
,注意ID是否正确? - dcd0181我自己也玩了一会儿这个。这个概念围绕着知道画布的宽度展开。您还需要确保所有画布资产也使用计算来依赖于浏览器的发布。我记录了我的代码,希望能帮到您,
<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 = 3 * window.innerWidth / 4;
</script>
</body>
所有之前的答案都很好,但它们不能按比例缩放画布上绘制的所有图像以适应新的画布大小。如果您正在使用Kinetic,我在这里制作了一个函数= http://www.andy-howard.com/how-to-resize-kinetic-canvas-and-maintain-the-aspect-ratio/
试试这个
$('#canvas').css('width', $(window).width());
$('#canvas').css('height', $(window).height());