画布尺寸 [英] Dimensions of a canvas

查看:135
本文介绍了画布尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了这篇很棒的博客文章,其中解释了如何调整画布大小以适合任何屏幕 http://www.html5rocks.com/zh-cn/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/ 我实现了它,并且它的大小无可挑剔,但是我遇到这个问题,当画布太少时,我的对象会出现在屏幕外。

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.

例如,对于我的游戏,如果我定义了一个尺寸为480,高度为1024的世界将元素放在x轴上大约400,但当前使用的显示为360px宽,则画布将具有正确的宽高比 0.46875 ,但对象不会是

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.

要解决此问题,我想我需要定义绝对世界尺寸和屏幕尺寸之间的比率,并在计算对象位置时乘以该比率,但是我的问题是-是否在

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?

推荐答案

画布本身和canvas元素都具有宽度和高度。如果它们不同,画布的内容将自动缩放以适合该元素。因此,可以的,您可以将画布定义为所需的尺寸,然后定义可缩放的元素。当然,所有内容都会缩放,并且如果宽高比不同,您的形状就会变形。

Both the canvas itself and the canvas element have a width and height. 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.

例如:这是一块300x300的画布,尺寸仅为150x300。当我在其中绘制一个圆时,您可以看到缩放比例:

For example: Here's a canvas that's 300x300, within a canvas element that's only 150x300. 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>

这篇关于画布尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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