画布的尺寸

Dimensions of a canvas

本文关键字:      更新时间:2023-09-26

我发现了一篇非常棒的博客文章,它解释了如何调整画布大小以适应任何屏幕http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/我实现了它,它完美地调整了它的大小,但我遇到了这样的问题,即当画布太小时,我的对象会出现在屏幕外。

例如,对于我的游戏,我定义了一个维度为宽480和高1024的世界,如果我在x轴上放置一个元素,大约为400,但当前使用的显示器是360像素宽,那么画布将具有正确的宽高比0.46875,但对象将不可见。

为了解决这个问题,我想我需要定义一个绝对世界维度和屏幕维度之间的比率,并在计算对象的位置时乘以它,但我的问题是,画布有办法自动做到这一点吗?

画布本身和画布元素都有宽度和高度。如果它们不相同,画布的内容会自动缩放以适应元素。所以,是的,你可以将画布定义为你想要的大小,并定义元素使其缩放。当然,所有东西都会缩放,如果纵横比不同,你的形状就会失真。

canvas元素内画布的宽度和高度由canvas元素的widthheight属性控制。(它们分别默认为300和150。)

画布元素的宽度和高度由CSS控制;它们默认为画布的widthheight,但您可以使用CSS覆盖它。

例如:这是一个300x300的画布(多亏了CSS),在一个只有300x150的画布元素中(因为这些是canvas元素的默认宽度和高度)。当我在里面画一个圆圈时,你可以看到缩放的效果——它变成了椭圆形:

// Get the canvas element
const canvas = document.getElementById("clock");
// Get the 2D rendering context for it
const context = canvas.getContext("2d");
// Show the canvas's dimensions (NOT the dimensions of the element)
document.getElementById("dimensions").innerHTML = canvas.width + "x" + canvas.height;
// Draw a circle -- it comes out oval because of scaling
const path = new Path2D();
path.arc(75, 75, 50, 0, Math.PI * 2, true);
context.fillStyle = context.strokeStyle = "blue";
context.fill(path);
canvas#clock {
    width: 300px;
    height: 300px;
    background: #1E1E1E;
}
<canvas id="clock"></canvas>
<div id="dimensions"></div>

这里有一个例子,画布及其容器的宽度和高度相同,因此没有缩放;代码完全相同,只是我在canvas HTML:中添加了width="300" height="300"

// Get the canvas element
const canvas = document.getElementById("clock");
// Get the 2D rendering context for it
const context = canvas.getContext("2d");
// Show the canvas's dimensions (NOT the dimensions of the element)
document.getElementById("dimensions").innerHTML = canvas.width + "x" + canvas.height;
// Draw a circle
const path = new Path2D();
path.arc(75, 75, 50, 0, Math.PI * 2, true);
context.fillStyle = context.strokeStyle = "blue";
context.fill(path);
canvas#clock {
    /* We could comment out the width and height properties
       since they'll default to the values from the attributes
    */
    width: 300px;
    height: 300px;
    background: #1E1E1E;
}
<canvas id="clock" width="300" height="300"></canvas>
<div id="dimensions"></div>

如果您确保元素及其画布的纵横比相同,则自动缩放非常方便。如果不直接设置画布元素的大小,在大多数浏览器上,由于widthheight属性,它将默认为画布的纵横比。从MDN对aspect-ratio的报道来看:

浏览器添加了一个内部aspect-ratio属性,该属性适用于被替换的元素以及接受widthheight属性的其他相关元素。这显示在浏览器的内部UA样式表中。

在Firefox中,内部样式表规则如下:

img, input[type="image"], video, embed, iframe, marquee, object, table {
  aspect-ratio: attr(width) / attr(height);
}
相关文章:
  • 没有找到相关文章