abidibo.net

Development of a preview functionality with canvas

canvas javascript mootools

Do you remember the last post about canvas dealing with undo and redo functionality?

Now we'll see how to add a preview functionality, that is I want to see my straight line, or my circle, while keeping pressed the left mouse button and moving the pointer to change the shape size.

The first, bad, idea

Initially I thought that the way was to store the portion of canvas interested by the modification and restore it in the next mousemove call, so that the mousemove function has to respect the following flow:

  • restore the previous saved state
  • save the state of the portion of the canvas that now will be drawed
  • draw the new state

Such flow works, but doesn't work well. The point here is that such workflow is extremely heavy, too heavy for a mousemove event which is called with an high frequency.

The solution

So how we can do it? Well, there is a sort of trick, what we have to do is:

  • Create a temporary canvas and place it exactly over the permanent one
  • Draw all previews (and clear previous frames) over the temporary canvas (attach mousemove, click.., events to the temporary canvas)
  • Copy the temporary canvas image over the permanent one when the preview ends (when the user clicks to actually draw the shape)

Why the temporary canvas?

Essentially because we can restore the previous state inside the mousemove function by clearing all the canvas entirely! Such operation is far more light than storing portions of canvas and calculate the portion's coordinates.

We can clear the entire canvas without problems because hopefully we have 1 preview at a time.

I've written a mootools class to draw a sort of time chart representing the variation of a generic quantity, you may find it in one of my gists, and here I post a working jsfiddle example

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured