HTML 5 Animated Dot To Dot Canvas
An animated dot to dot image triggered by the mouse’s distance from an element, all using HTML 5’s canvas feature.
This showcase is part tutorial part tech demo. HTML 5 introduced an awesome new feature called the canvas. It can be used to do low level drawing and animations with its JavaScript API, and gives you much more power than using JavaScript alone.
Check out the end product below - an animated dot to dot that changes when you mouse over an element on screen:
The Code
The full code sample can be found below. It’s licensed under the MIT license so feel free to grab it, change it, republish it, whatever!
… Wut?
Phew! That was long… Most of it is fairly well documented but here’s a quick rundown of what the script actually does:
- Defines the Coordinate object that represents coordinates on the canvas itself
- Defines the Circle object which defines a point plotted on the canvas that will be linked together with lines to create the actual image
- Define a Canvas object and various helper methods that gets the data for the image, draws on the canvas, and updates everything each frame
When the page has finished loading the script does the following:
- Sets all the configuration options for the canvas animation
- Creates a Canvas object
- Starts the whole animation by calling the init function
- The Canvas then gets the following JSON via an Ajax request:
This JSON data represents the coordinates for each part of the image we want to draw. They were generated using our Image Coordinate Tool.
Bare in mind that while comments in JSON are not strictly allowed, the script uses a jQuery extension called JSON.minify to strip them. Without the comments the JSON file would be impossible to understand.
The init function then calls the draw function at intervals defined by the framerate in the configuration options.
The draw function checks how far away the mouse is from the “trigger element” and changes the Circles coordinates accordingly, then redraws them all.
Customising the Script
The script wasn’t designed to be customised but it shouldn’t be too difficult to get it working on your installation. Changing the image however is super easy, just use our Image Coordinate Tool to trace a new image and save the output into a file, then set the path in the script accordingly.
Enjoy!