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/
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.
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.
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 .
clearRect() is optimized while fillRect() is bound to compositing/blending rules (Porter-Duff) so the former is faster.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With