I have a need for a web based drawing tool, much like Microsoft Paint – just a simple canvas that allows me to draw on it. I’ve searched around a bit and have found that the majority of the tools are Flash based and the ones that are not are lacking in one way or another.
So I decided to create a simple, purely web based drawing tool. This works in all browsers and even works on my iPad (although I have to click each square to form the drawing on the iPad since dragging simply moves the screen). The canvas, with a drawing, is shown in Figure 1.
Here’s how to use it:
// Creates the canvas - just make sure you have a DIV with an id of "drawingArea" // The last parameter of false allows editing - set to true for read only // Note that these are squares - actual square size is set via CSS var myCanvas = new Canvas("drawingArea", 60, 40, false); // This will change the drawing colors myCanvas.setFillColor("#CCCCCC"); // #000 by default myCanvas.setEraseColor("#555555"); // #FFF by default // This will resize the canvas, preserving what portions of the drawing it can myCanvas.resize(100, 10); // 100 wide by 10 high // This will save the contents of the canvas down to a JSON string var myData = myCanvas.save(); // This will load a drawing from a JSON string myCanvas.load(myData);
You can view a working demo here.
You can find the JS file here:
Note that you’ll also need the JSON2 JS file as well:
An improvement idea:
When mouse moves fast, lines have gaps in them. It would be pretty easy to write an algorithm that figures out empty squares between two points and fills them in. Alternatively, it wouldn’t be too difficult to handle this without tables by tracking the mouse location within the DIV then drawing points/lines.
Feel free to use this as you see fit. I just ask that you:
- Leave the copyright information at the top of the JS file in place.
- Don’t sell the code or any product that has this code as the core feature without my consent.