猿问

clearRect函数不会清除画布

我在body onmousemove函数上使用此脚本:


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,鼠标侦听器或类似工具来解决它。


这是一个演示:https : //jsfiddle.net/0y4wf31k/


守着星空守着你
浏览 1539回答 3
3回答

德玛西亚99

您应该使用“ beginPath() ”。这就对了。function lineDraw() {&nbsp; &nbsp;&nbsp; &nbsp; var canvas=document.getElementById("myCanvas");&nbsp; &nbsp; var context=canvas.getContext("2d");&nbsp; &nbsp; context.clearRect(0, 0, context.width,context.height);&nbsp; &nbsp; context.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<&nbsp; &nbsp; context.moveTo(0,0);&nbsp; &nbsp; context.lineTo(event.clientX,event.clientY);&nbsp; &nbsp; context.stroke();}

呼啦一阵风

尝试context.canvas.width = context.canvas.width:function lineDraw() {&nbsp; &nbsp;&nbsp; &nbsp; var canvas=document.getElementById("myCanvas");&nbsp; &nbsp; var context=canvas.getContext("2d");&nbsp; &nbsp; //context.clearRect(0, 0, context.width,context.height);&nbsp; &nbsp; context.canvas.width = context.canvas.width;&nbsp; &nbsp; context.moveTo(0,0);&nbsp; &nbsp; context.lineTo(event.clientX,event.clientY);&nbsp; &nbsp; context.stroke();}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答