我使用了两个相互分离的画布元素,我尝试使用fillRect,使用 fillRect 绘制两个不同颜色的画布元素。问题是只有一个画布使用 fillRect 填充(即。"蓝色"在下面的代码示例中)。我可以使用css style = background-color 以不同颜色获取它们,但我更感兴趣的是为什么我 fillRect 不能为我工作在这种情况下。
感谢您的帮助。
这是我的HTML代码
<body style="position:relative">
<div id='c1' style="position:absolute; top:0px; left:0px; z-index:1">
<canvas id='canvas1' width='150' height='150'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div id='c2'style="position:absolute; top:0px; left:200px; z-index:2">
<canvas id='canvas2' width='150' height='150'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</form>
以下是脚本标记内的JavaScript代码:
window.onload = function () {
// get all canvas elements
var canvasList = document.getElementsByTagName("canvas");
var ctx = canvasList[0].getContext("2d");
var ctx2 = canvasList[1].getContext("2d");
//canvas1
ctx.fillStyle = "blue";
ctx.fillRect(0,0,150,150);
//canvas2
ctx2.fillStyle = "red";
ctx2.fillRect(200,0,150,150);
}
答案 0 :(得分:1)
它正在工作,你正在从画布上绘制第二个矩形。从(0,0)
开始,而不是(200,0)
:
//canvas2
ctx2.fillStyle = "red";
ctx2.fillRect(0,0,150,150);
以下是一个示例代码段:
// get all canvas elements
var canvasList = document.getElementsByTagName("canvas");
var ctx = canvasList[0].getContext("2d");
var ctx2 = canvasList[1].getContext("2d");
//canvas1
ctx.fillStyle = "blue";
ctx.fillRect(0,0,150,150);
//canvas2
ctx2.fillStyle = "red";
ctx2.fillRect(0,0,150,150);
&#13;
<div id='c1' style="position:absolute; top:0px; left:0px; z-index:1">
<canvas id='canvas1' width='150' height='150'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
<div id='c2'style="position:absolute; top:0px; left:200px; z-index:2">
<canvas id='canvas2' width='150' height='150'>
Your browser does not support HTML5 Canvas.
</canvas>
</div>
&#13;