Skip to content
Advertisement

How to keep drawing on canvas when scrolling?

I’m wanting to implement canvas as background for my website so users can use their cursors to paint on the webpage like this codepen: https://codepen.io/cocotx/pen/PoGRdxQ?editors=1010 (this is an example code from http://www.dgp.toronto.edu/~clwen/test/canvas-paint-tutorial/)

JavaScript

The problem is that the cursor stops painting when I scroll until I move my mouse again. Any idea on how to keep cursor painting even when I scroll?

Thanks in advance! Much appreciated!

Advertisement

Answer

You will have to store the last mouse event and fire a new fake one in the scroll event.

Luckily, the MouseEvent constructor accepts an mouseEventInit object on which we can set the clientX and clientY values of our new event, so we just need to store these values from the previous event and dispatch it in the scroll event.

Now, I couldn’t help but rewrite almost everything from your code.
It had a lot of checks for old browsers (like very old ones which should never face the web again anyway), you may want to add it again if you wish.
It wasn’t clearing the context, meaning that every time it drew a new line, it also did draw again the previous lines over themselves, leading in fatter lines, with a lot of noise at the beginning, and smoother lines at the end.
This could be fixed in many ways, the less intrusive one was to just clear the context at each frame. To get the relative mouse position, it now uses the clientX and clientY properties of the event.

And the rest of the changes is commented in the snippet.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement