简体   繁体   English

画布尺寸

[英]Dimensions of a canvas

I found this pretty awesome blog post that explains how to resize a canvas to fit any screen http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/ I implemented it and it is sizing it flawlessly but I get this problem that my objects appear off screen when the canvas is too little. 我发现这则很棒的博客文章解释了如何调整画布的大小以适合任何屏幕http://www.html5rocks.com/zh-CN/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/我实现了完美地调整它的大小,但是当画布太小时,我的对象出现在屏幕外,这是我遇到的问题。

For example for my game I define a world with dimensions width 480 and height 1024, if I put an element on x axis at about 400 but the display that is currently used is 360px wide then the canvas would have correct ratio of width to height 0.46875 but the object will not be visible. 例如,对于我的游戏,我定义了一个尺寸为宽度480和高度1024的世界,如果我在x轴上将元素放置在大约400处,但当前使用的显示为360px宽,则画布将具有正确的宽高比0.46875但该对象将不可见。

To solve this problem I suppose I need to define a ratio between the absolute world dimensions and the screen dimensions and multiply by that when I'm calculating the object's position, however my question is - is there a way for the canvas to do that automatically? 为了解决这个问题,我想我需要在绝对世界尺寸和屏幕尺寸之间定义一个比率,并在计算对象位置时乘以该比率,但是我的问题是-画布是否可以自动执行此操作?

Both the canvas itself and the canvas element have a width and height. 画布本身和canvas元素都具有宽度和高度。 If they're not the same, the content of the canvas is automatically scaled to fit the element. 如果它们不相同,则画布的内容将自动缩放以适合该元素。 So yes, you could define your canvas to be the size you want, and define the element such that it scales. 因此,可以的,您可以将画布定义为所需的大小,然后定义可缩放的元素。 Naturally, though, everything scales, and if the aspect ratio is different, your shapes get distorted. 当然, 一切都会缩放,如果宽高比不同,则形状会变形。

For example: Here's a canvas that's 300x300, within a canvas element that's only 150x300. 例如:这是一个300x300的画布,在只有150x300的canvas元素内。 You can see the scaling when I draw a circle in it: 当我在其中画一个圆时,您可以看到缩放比例:

 var canvas = document.getElementById("clock"); var context = canvas.getContext("2d"); document.getElementById("status").innerHTML = canvas.height; console.log(canvas.height); var ctx = canvas.getContext('2d'); var path = new Path2D(); path.arc(75, 75, 50, 0, Math.PI * 2, true); ctx.fillStyle = ctx.strokeStyle = "blue"; ctx.fill(path); 
 canvas#clock { width: 300px; height: 300px; border: #D50003 1px solid; background: #1E1E1E; } 
 <canvas id="clock"></canvas> <div id="status"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM