【问题标题】:Scaling HTML5 canvas width preserving w/h aspect ratio缩放 HTML5 画布宽度保留 w/h 纵横比
【发布时间】:2012-05-31 18:47:25
【问题描述】:

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

【问题讨论】:

  • 计算新的宽度和高度并通过 jquery/javascript 应用它们。有大量关于如何计算尺寸保持比例的信息。你自己尝试过什么吗?可能是您遇到问题的一些代码?

标签: javascript html5-canvas aspect-ratio


【解决方案1】:
 ctx.canvas.width = window.innerWidth;

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

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

【讨论】:

    【解决方案2】:

    首先将画布的宽度设置为 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 吗?
    • 是的,我忘了放#canvas
    • 这会导致内容模糊。您需要按照其他答案状态来操作画布上下文。
    • 您应该设置画布元素的高度/宽度属性而不是 CSS 属性并重绘画布。
    • 如何在响应式画布上缩放图像?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        试试这个

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

        【讨论】:

        • 这不会设置比例,它只是将画布大小设置为窗口宽度和窗口高度。
        猜你喜欢
        • 2013-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-08
        • 2016-04-01
        • 2016-05-18
        • 2013-08-07
        • 1970-01-01
        相关资源
        最近更新 更多