lineto相对于窗口绘制而不是画布

时间:2014-05-29 21:57:32

标签: javascript html5 canvas

我正在尝试在Canvas上使用绘图功能,我很想知道是否有人可以提出解决方案,因为我是新手;)

我的主要html页面在图层中设置了几个画布,以便我可以操纵和擦除每个画面而不会干扰其他画面。我有这样的事情:

<div>
<canvas id="myCanvas" width="450" height="450" style="border:1px solid #d3d3d3;"></canvas>
<canvas id="layer1" width="450" height="450" style="position: absolute; left:0; top:0; z-index:1;"></canvas>
<canvas id="layer2" width="450" height="450" style="position: absolute; left:0; top:0; z-index:2;"></canvas>
<canvas id="layer3" width="450" height="450" style="position: absolute; left:0; top:0; z-index:3;"></canvas>
<canvas id="layer4" width="450" height="450" style="position: absolute; left:0; top:0; z-index:4;"></canvas>
</div>

在一些Javascript中,我正在操纵这些画布,例如:

c1=document.getElementById("layer1");
ctx1=c1.getContext("2d");
ctx1.beginPath();
ctx1.moveTo(this.xcoord, this.ycoord);
ctx1.lineTo(newx, newy);
ctx1.stroke();

现在这个有效;它在屏幕上绘制线条毫无问题,除了它们没有在画布上绘制,它们是相对于主浏览器窗口绘制的(我的画布不是在屏幕的左上角,而是由于文字和其他图形)。 任何人都可以建议我做错了吗?

1 个答案:

答案 0 :(得分:0)

它对浏览器是实际的,因为你告诉它是相对于浏览器的。您需要使包装元素的位置相对。

<强> CSS:

div.wrapper { position:relative;}
div.wrapper canvas { position : absolute; }

<强> HTML:

<div class="wrapper">
    <canvas id="myCanvas" width="450" height="450" style="border:1px solid #d3d3d3;"></canvas>
    <canvas id="layer1" width="450" height="450" style="z-index:1;background-color: red"></canvas>
    <canvas id="layer2" width="450" height="450" style="z-index:2;background-color:yellow;"></canvas>
</div>

<强>的jsfiddle:

http://jsfiddle.net/X8BCp/1/