clearRect函数不会清除画布 [英] clearRect function doesn't clear the canvas

查看:1228
本文介绍了clearRect函数不会清除画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在body onmousemove函数上使用这个javaScript:

I'm using this javaScript on the body onmousemove function:

function lineDraw() {
    //Get the context and the canvas:
    var canvas=document.getElementById("myCanvas");
    var context=canvas.getContext("2d");
    //Clear the last canvas
    context.clearRect(0, 0, canvas.width,canvas.height);
    //Draw the line:
    context.moveTo(0,0);
    context.lineTo(event.clientX,event.clientY);
    context.stroke();

}

每次移动鼠标都应该清除画布周围,​​并画一条新线,但它不能正常工作。
我试图在不使用jQuery,鼠标监听器或类似工具的情况下解决它。

It's supposed to clear the canvas each time I move the mouse around, and draw a new line, but it isn't working properly. I'm trying to solve it without using jQuery, mouse listeners or similar.

以下是代码:

http://jsfiddle.net/7vx2z/

推荐答案

您应该使用 beginPath()。就是这样。

You should use "beginPath()". That is it.

function lineDraw() {   
    var canvas=document.getElementById("myCanvas");
    var context=canvas.getContext("2d");
    context.clearRect(0, 0, context.width,context.height);
    context.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<
    context.moveTo(0,0);
    context.lineTo(event.clientX,event.clientY);
    context.stroke();
}

这篇关于clearRect函数不会清除画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆