Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - 调整HTML5画布大小以适合窗口(Resize HTML5 canvas to fit window)

How can I automatically scale the HTML5 <canvas> element to fit the page?

(如何自动缩放HTML5 <canvas>元素以适合页面?)

For example, I can get a <div> to scale by setting the height and width properties to 100%, but a <canvas> won't scale, will it?

(例如,我可以通过将heightwidth属性设置为100%来缩放<div> ,但是<canvas>不会缩放,是吗?)

  ask by devyn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe I have found an elegant solution to this:

(我相信我找到了一个优雅的解决方案:)

JavaScript

(JavaScript的)

/* important! for alignment, you should make things
 * relative to the canvas' current width/height.
 */
function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

CSS

(CSS)

html, body {
  width:  100%;
  height: 100%;
  margin: 0;
}

Hasn't had any large negative performance impact for me, so far.

(到目前为止,对我没有任何大的负面影响。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...