Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearRect function doesn't clear the canvas

I'm using this script 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(); } 

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.

Here is a demo: https://jsfiddle.net/0y4wf31k/

like image 270
Juan C. Roldán Avatar asked Nov 17 '12 23:11

Juan C. Roldán


People also ask

How do I clear my canvas screen?

To clear the Canvas, you can use the clearRect() method. This method performs pretty well than others for clearing the canvas (such as resetting the width/height, destroying the canvas element and then recreating it, etc..) const context = canvas. getContext('2d'); context.

How do you clear canvas and redraw?

We can clear the canvas easily with the clearRect method, which is part of the canvas context object. to draw something and add a click listener to the button to clear the canvas when we click the button. We call getContext to get the context object.

What does the clearRect method perform?

The clearRect() method sets the pixels in a rectangular area to transparent black ( rgba(0,0,0,0) ). The rectangle's top-left corner is at (x, y) , and its size is specified by width and height .

Is clearRect faster than fillRect?

clearRect() is optimized while fillRect() is bound to compositing/blending rules (Porter-Duff) so the former is faster.


1 Answers

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(); } 
like image 179
aviomaksim Avatar answered Sep 19 '22 20:09

aviomaksim