我希望使完成的 Canvas 项目可调整大小。我读过的一些网站建议使用 CSS 来重新设计样式,但我也看到人们说永远不要这样做,因为它会通过拉伸(stretch)东西来模糊文本。但是,如果您只是在 JavaScript 中告诉 Canvas 调整大小,则不需要重做下面示例中的填充文本吗?
var canvas = document.getElementById("example");
var ctx = canvas.getContext('2d');
var cornerRadius = 10;
function drawMe() {
ctx.fillStyle = "red";
ctx.strokeStyle = "red";
ctx.lineJoin = "round";
ctx.lineWidth = cornerRadius;
ctx.strokeRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius, 406-cornerRadius);
ctx.fillRect(5+(cornerRadius/2), 23+(cornerRadius/2), 155-cornerRadius, 406-cornerRadius);
ctx.font = '16pt Arial';
ctx.fillStyle = 'white';
ctx.textAlign="start";
ctx.fillText('Text', 8, 70);
ctx.fillText('Text', 8, 128);
}
function redraw() {
ctx.strokeStyle = 'blue';
ctx.lineWidth = '5';
ctx.strokeRect(0, 0, window.innerWidth, window.innerHeight);
drawMe();
}
window.onload = function () {
redraw();
};
项目示例。
Canvas 在 html 中设置为 1280 x 800。
编辑后包括 https://jsfiddle.net/o1rkg1tf/
最佳答案
为了使 Canvas 元素可调整大小,您需要处理窗口调整大小事件。 之后,您需要将 Canvas 的宽度和高度设置为窗口大小值。 最后,在 Canvas 元素中使用相对值、主宽度和高度值的百分比。
以下是您的示例的更新: https://jsfiddle.net/abelflopes/o1rkg1tf/5/
var wH = window.innerHeight;
var wW = window.innerWidth;
...
function drawMe() {
canvas.height = wH;
canvas.width = wW;
...
}
window.addEventListener("resize", function () {
wH = window.innerHeight;
wW = window.innerWidth;
drawMe();
redraw();
});
希望我说得足够清楚,可以帮助您。
关于Javascript、Canvas 和调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43155446/