全屏画布
画布显示尺寸
画布是大小方面的一个特例。它的分辨率定义了它包含的像素数,它的显示大小定义了它在页面上占据的像素数。
画布显示大小通过其样式属性设置。
canvas.style.width = "100%"; // does not change the resolution
canvas.style.height = "100%";
画布分辨率
要设置分辨率,请设置画布的宽度和高度属性。
canvas.width = 1000; // if the style width and height not set then
canvas height = 800; // the computed style will match. If not
// then setting the resolution will
// not effect display size (in most cases.)
注意,画布尺寸样式属性需要单位类型 '%'、'px'、...,而画布尺寸属性则不需要,并且如果您使用这些值,则会假定这些值是像素 ('px")只需将它们设置为数字即可。
由于尺寸错误导致质量低下。
如果您只设置样式 width 和 height,您最终会将默认画布分辨率拉伸 300 x 150 像素,并且由于双线性过滤,结果图像会变得模糊。
默认画布分辨率和仅样式大小的示例。
var ctx = myCan.getContext("2d");
ctx.font = "18px arial";
ctx.textAlign = "center";
ctx.fillText("Low res & blury",myCan.width/2,myCan.height/2);
ctx.font = "12px arial";
ctx.fillText("Canvas resolution default " + myCan.width + "px by " + myCan.height + "px",myCan.width/2,myCan.height/2 + 18);
html, body {
min-height: 100%;
}
canvas {
width : 100%;
height : 100%;
background:#aaa;
}
<canvas id="myCan"></canvas>
全屏(页面)画布
要在显示尺寸和分辨率上正确调整画布的大小(两者都应该匹配以获得最佳结果(而不是拉伸),最好通过 javascript 完成。
如果我正在制作全屏画布,我更喜欢通过绝对定位来定位它。
canvas.style.position = "absolute"
canvas.style.top = "0px";
canvas.style.left = "0px";
而且我不会通过设置样式宽度和高度来设置画布显示尺寸,一旦我设置了画布分辨率,我就允许浏览器为我计算它
示例使用 javascript 正确设置全屏画布。
myCan.style.position = "absolute"
myCan.style.top = "0px";
myCan.style.left = "0px";
// when page has loaded size the canvas resolution to fit the display
myCan.width = window.innerWidth;
myCan.height = window.innerHeight;
var ctx = myCan.getContext("2d");
ctx.font = "18px arial";
ctx.textAlign = "center";
ctx.fillText("Canvas resolution matches page resolution",myCan.width/2,myCan.height/2);
ctx.font = "12px arial";
ctx.fillText("Canvas resolution " + myCan.width + "px by " + myCan.height + "px",myCan.width/2,myCan.height/2 + 18);
ctx.textAlign = "right";
ctx.fillText("Resize by clicking [full page]",myCan.width -10,20);
// resize function
function resizeCan(){
myCan.width = window.innerWidth;
myCan.height = window.innerHeight;
ctx.font = "18px arial";
ctx.textAlign = "center";
ctx.fillText("Resized canvas resolution matches page resolution",myCan.width/2,myCan.height/2);
ctx.font = "12px arial";
ctx.fillText("Canvas resolution " + myCan.width + "px by " + myCan.height + "px",myCan.width/2,myCan.height/2 + 18);
}
window.addEventListener("resize",resizeCan);
html, body {
min-height: 100%;
}
canvas {
background:#aaa;
}
<canvas id="myCan"></canvas>
注意,当页面调整大小时,您需要通过监听窗口调整大小来调整画布大小。上面的示例将为您做到这一点。