保持宽高比例的情况下缩放HTML5画布的宽度

13

我有一个尺寸为979X482像素的画布元素,我希望它可以自适应任何给定浏览器窗口的宽度,并保持宽高比例为1:1,我希望画布的高度相对于宽度进行缩放。 有什么建议可以用javascript / jQuery实现这个功能吗?


1
计算新的宽度和高度,并通过jquery/javascript应用它们。关于如何保持比例计算尺寸的信息有很多。你自己试过什么吗?你遇到了一些问题的代码吗? - Yoshi
这个回答是否解决了你的问题?使用CSS保持div的宽高比 - TylerH
5个回答

15
 ctx.canvas.width = window.innerWidth;

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

或者类似的变体。 ctx 是上下文。对于边缘情况可能需要一个 if 语句!


8

首先,您需要将画布的宽度设置为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
是的,我忘记放 #canvas 了。 - James
这将导致内容变模糊。你需要像其他答案所述一样操作画布上下文。 - cyberwombat
1
你应该设置画布元素的高度/宽度属性,而不是CSS属性,并重新绘制画布。 - hobberwickey
在响应式画布上缩放图像怎么样? - oldboy

1

我自己也玩了一会儿这个。这个概念围绕着知道画布的宽度展开。您还需要确保所有画布资产也使用计算来依赖于浏览器的发布。我记录了我的代码,希望能帮到您,

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

画布样式是让我解决问题的关键。谢谢你。 - CYoung

0

-5

试试这个

$('#canvas').css('width', $(window).width());
$('#canvas').css('height', $(window).height());

1
这并不设置比例,它只是将画布大小设置为窗口的宽度和高度。 - shadryck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接