12

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

4

5 回答 5

13
 ctx.canvas.width = window.innerWidth;

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

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

于 2012-05-30T04:28:17.533 回答
6

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

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

然后根据其宽度更新其高度

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

2.031 = 979/482

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

于 2012-05-25T07:34:12.327 回答
1

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

于 2014-05-13T06:35:15.693 回答
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 = 3 * window.innerWidth / 4;
  </script>
</body>
于 2018-01-27T13:52:44.643 回答
-3

试试这个

$('#canvas').css('width', $(window).width());
$('#canvas').css('height', $(window).height());
于 2012-05-25T07:45:07.717 回答