English 中文(简体)
缩放 HTML5 画布宽度保持 w/h 宽度宽度
原标题:Scaling HTML5 canvas width preserving w/h aspect ratio

我有979X482px的画布元素,我想让它伸展到任何特定浏览器窗口的宽度, 保持宽度/ 高1比宽度/ 高1比, 我想要相对于画布宽度的高度与大小。 任何建议, 如何使用 javascript/ jQuery 来做到这一点吗?

最佳回答

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

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

然后在宽度上更新它的高度基数

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

2.031 = 979/482

但你不应该附着于$( 窗口) 。 像我这样大小的大小... 这是不好的行为

问题回答
 ctx.canvas.width = window.innerWidth;

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

上下文为 ctx 。 如果有必要的话, 边缘情况说明!

这个概念围绕了解画布的宽度。 您也需要确保您所有的画布资产 也使用计算方法 来在浏览器上发布信息。 我记录了我的代码, 我希望它有用,

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




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签