【问题标题】:Using fillrect on multiple canvas在多个画布上使用 fillrect
【发布时间】:2015-09-06 01:23:54
【问题描述】:


我正在使用两个在位置上彼此分离的画布元素,并且我正在尝试使用 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);
}

【问题讨论】:

  • 尝试为每个画布分配不同的 ID,然后使用document.getElementById("cavas1");

标签: javascript css html canvas


【解决方案1】:

它正在工作,您正在从画布上绘制第二个矩形。从(0,0) 开始,而不是(200,0)

//canvas2
ctx2.fillStyle = "red";
ctx2.fillRect(0,0,150,150);

下面是一个示例 sn-p:

// 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);
<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>

【讨论】:

  • 我错过了谢谢,我想给我更多的咖啡。
  • @holmberd。请单击绿色复选标记以接受 Spencer Wieczorek 的正确答案。这样一来,您已解决的问题就会从要求答案列表中删除。谢谢!
  • @markE 我做到了,但显然就在他编辑他的答案之前,现在一切都修复了。谢谢你告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 2019-02-03
相关资源
最近更新 更多