0

I am beginning to explore HTML canvas element by creating a simple drawing program:

  • When I move my mouse on the canvas, I want a line to be drawn between (0,0) and my mouse coordinates. I only want to render one line at any given time.
  • To ensure that only one line is displayed, on mouse move, I clear the context and draw a new line from (0,0) to mouse (x,y).
  • The above is not the same as 'free-form' or 'pencil' drawing tool, but a crude form of 'line' tool.

Inside the mouse move event handler, I first do this:

context.clearRect(0, 0, canvas.width, canvas.height);

and then do this:

context.moveTo(0, 0);
context.lineTo(mousePos.x, mousePos.y);
context.stroke();

The problem is, the canvas is not clearing and all lines previously drawn are still shown.

The full code is here: https://jsfiddle.net/csenthiltech/7ozsnhoy/

I tried going through the source code of simple drawing programs online and found they too followed a similar approach. But I am not able to get it working. Here are some questions I went through about this topic:

What am I missing here?

Community
  • 1
  • 1

1 Answers1

1

I found an answer here

The reason is that if you do not call context.beginPath() & context.closePath(), stroke() will draw all the previously stored commands.

context.beginPath();
context.moveTo(0, 0);
context.lineTo(mousePos.x, mousePos.y);
context.clearRect(0, 0, canvas.width, canvas.height);
context.stroke();

Jsfiddle here

derp
  • 2,300
  • 13
  • 20