clearRect function doesn't clear the canvas

喜你入骨 提交于 2019-11-26 13:47:15
aviomaksim

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();
}

Be advised that ctx.clearRect() does not work properly on Google Chrome. I spent hours trying to solve a related problem, only to find that on Chrome, instead of filling the rectangle with rgba(0, 0, 0, 0), it actually fills the rectangle with rgba(0, 0, 0, 1) instead!

Consequently, in order to have the rectangle filled properly with the required transparent black pixels, you need, on Chrome, to do this instead:

ctx.fillStyle = "rgba(0, 0, 0, 0)";
ctx.fillRect(left, top, width, height);

This should, of course, work on all browsers providing proper support for the HTML5 Canvas object.

Try with context.canvas.width = context.canvas.width:

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

Demo HERE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!