作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
类似于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%:
如果您删除 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/
我是一名优秀的程序员,十分优秀!