为什么上下文描边在画布上重画了旧的图形 [英] Why context stroke redraws the old drawing on canvas
本文介绍了为什么上下文描边在画布上重画了旧的图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中,当按下两个按钮时在画布上绘制了两条不同的线,我该如何使第二个按钮清除旧线并绘制另一条线呢?
Having the following example where on a canvas are drew two different lines when pressing two buttons, how can I make the second button clear the old line and draw another?
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>
<button onclick="draw()">first</button>
<button onclick="draw2()">second</button>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = "red";
function draw(){
ctx.moveTo(0,0);
ctx.lineTo(100,200);
ctx.stroke();
}
function draw2(){
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(100,0);
ctx.lineTo(0,200);
ctx.stroke();
}
</script>
我正在使用 clearRect
函数清除画布,但是当在第二个图形上调用stroke时,第一个图形将被重画.
I am using clearRect
function, to clear the canvas, but when stroke is called on the second drawing, the first one is redrawn.
推荐答案
您必须调用 .beginPath()
来清除当前路径并开始新的路径.就您而言,您似乎可以在两个函数中的每个函数的开头执行该操作.
You have to call .beginPath()
to clear out the current path and start a new one. In your case, it looks like you can do that at the beginning of each of your two functions.
这篇关于为什么上下文描边在画布上重画了旧的图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文