【发布时间】:2017-04-11 19:59:13
【问题描述】:
我有一个包含 <canvas> 元素的 WWWeb 页面。目标是在下部画布中绘制持久的东西,并在上部画布中反复绘制、清除和重绘。根据 w3.org 和 this StackOverflow article (How do I make a transparent canvas in html5?),画布元素默认是透明的。我看到的是,它们不仅不透明,而且通过z-index 覆盖也不起作用。这是页面代码的“香草”版本(完整并用于生成图像):
<html>
<head>
<title>Canvas Stack</title>
<script>
function doStuff() {
drawStuff(document.getElementById("lowerCanvas"), 0, 1);
drawStuff(document.getElementById("upperCanvas"), 1, 0);
}
function drawStuff(cvs, p0X, p1X) {
var ctx = cvs.getContext("2d");
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.strokeStyle = cvs.style.color;
ctx.beginPath();
ctx.moveTo(p0X * cvs.width, 0);
ctx.lineTo(p1X * cvs.width, cvs.height);
ctx.stroke();
}
</script>
</head>
<body onload="doStuff();" style="border:solid;">
<canvas id="lowerCanvas" style="color:red;height:200px;left:0;position:inherit;top:0;width:300px;z-index:0;" />
<canvas id="upperCanvas" style="color:blue;height:200px;left:0;position:inherit;top:0;width:300px;z-index:1;" />
</body>
</html>
结果如下:
如果我交换画布元素的顺序
<canvas id="upperCanvas" style="color:blue;height:200px;left:0;position:inherit;top:0;width:300px;z-index:1;" />
<canvas id="lowerCanvas" style="color:red;height:200px;left:0;position:inherit;top:0;width:300px;z-index:0;" />
结果是
似乎z-index 已被忽略,并且声明的顺序具有优先性。
我想要的是
(合成图像)
在 Windows 10 下的 Chrome、Edge、Firefox 和 Internet Explorer 中的行为是相同的。这让我确信我只是遗漏了一些细节而不是遇到异常。但是,由于我的头撞到墙上,我的前额变得扁平,非常感谢这里的一些指导。
谢谢大家!
一些注释(也许不相关;也许不):
-
style="position:absolute;...(没有left和top条目)似乎与style="left:0;position:absolute;top:0;... - 以类似的方式,
style="position:inherit;... 可能是必要的,如果画布要驻留在表的<td>中,并且<td>不是<tr>中的第一个。
【问题讨论】:
标签: javascript html canvas z-index transparency