gpt4 book ai didi

css - 如何让 Canvas 占用 100% 的剩余空间?

转载 作者:太空狗 更新时间:2023-10-29 13:46:31 26 4
gpt4 key购买 nike

类似于i want a div to take 100% height , 100% 宽度, 或两者兼而有之。我希望 Canvas 具有 100% 的宽度和 100% 的高度:

( Link to JsFiddle for your perusal )

标记:

<div id="canvasContainer">
<canvas id="myCanvas"></canvas>
</div>

CSS:

html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
margin: 0;
}
#canvasContainer {
width: 100%;
height: 100%;
background-color: green;
}
#myCanvas {
width: 100%;
height: 100%;
}

Javascript:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(canvas.width, canvas.height);
ctx.stroke();

ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(canvas.width, 0);
ctx.lineTo(0, canvas.height);
ctx.stroke();

这导致某些东西占用浏览器窗口的 100%:

enter image description here

如果您删除 Canvas,它会正常工作:

enter image description here

缺点是我没有Canvas

最佳答案

调整 Canvas 元素的大小

如果您使用 CSS 拉伸(stretch) Canvas ,您会将默认尺寸为 300x150 像素的劣质 Canvas 拉伸(stretch)到整个屏幕 - 假设您有一张该尺寸的图像并且您对其执行了相同的操作 - 看起来会很糟糕。

Canvas 内容不能使用 CSS 拉伸(stretch)(它以这种方式充当图像)。您需要明确设置 Canvas 的像素大小。

这意味着您需要获取父容器的大小并将其设置为 Canvas 上的像素值:

首先,要摆脱滚动条等。调整您拥有的 CSS:

body, html {
width: 100%;
height: 100%;
margin: 0;
padding:0;
overflow:hidden;
}

现在修改这条规则:

#myCanvas {
background-color: green;
position:fixed;
left:0;
top:0;
}

现在将您的标记减少到仅此(如果您希望 Canvas 覆盖整个屏幕,您不需要窗口以外的容器):

<canvas id="myCanvas"></canvas>

现在我们可以计算大小了:

var canvas;

window.onload = window.onresize = function() {

canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}

就是这样。

Working demo (调整窗口大小以查看)。

关于css - 如何让 Canvas 占用 100% 的剩余空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com