将HTML画布缩放为浏览器窗口大小,但不会在画布中缩放元素 [英] Scale HTML canvas to browser window size but don't scale elements within the canvas

查看:1065
本文介绍了将HTML画布缩放为浏览器窗口大小,但不会在画布中缩放元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以缩放HTML画布到浏览器窗口的宽度/高度,但不缩放其中的内容?假设我正在创建小行星,并且想要使用整个浏览器窗口,但是当我调整窗口大小时,不希望岩石和船舶向上/向下。

Is there a way to scale your HTML canvas to the browser window width/height but not scale the contents within it? Say I was creating Asteroids and want to use the entire browser window but don't want the rocks and ship to scale up/down when I resize the window.

推荐答案


  1. 不要使用CSS来缩放画布。

  1. Do not use CSS to scale your canvas. That will scale the pixels in the canvas up/down.

而是观察 resize 事件在适当的元素(例如窗口)上,然后适当地更改画布的 .width .height 属性JavaScript。这将更改您要绘制的像素数。

Instead, watch for a resize event on an appropriate element (e.g. the window) and then change the .width and .height properties of the canvas appropriately in JavaScript. This will change how many pixels you are drawing with.

继续使用您始终使用的固定大小的绘图命令。对象将在屏幕上保持相同的像素大小。

Continue to use the same fixed-size drawing commands you always use. Object will stay that same pixel size on screen.

要使您的内容居中在屏幕上,您可能希望将0,0作为在调整大小后,使用 translate()即可。例如:

To keep your contents centered on the screen, you may want to treat 0,0 as the center of the canvas by using translate() on the context right after you resize it. For example:

var ctx = document.querySelector('#mycanvas').getContext('2d');
window.addEventListener('resize',function(){
  var width  = calculateDesiredWidth();  // your code here
  var height = calculateDesiredHeight(); // your code here
  ctx.canvas.width  = width;
  ctx.canvas.height = height;
  ctx.translate(width/2,height/2); // now 0,0 is the center of the canvas.
},false);


这篇关于将HTML画布缩放为浏览器窗口大小,但不会在画布中缩放元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆