Development of a preview functionality with canvas
You can also be interested in:
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
Your Smartwatch Loves Tasker!
Your Smartwatch Loves Tasker!
Featured
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May