Wednesday, September 5, 2012

Draw Something JS - Part #1

This is my first post, so please be gentle with your comments :) 
Today, You are going to see the power of HTML5 and Javascript and I’m going to show you, step by step, how to create the Great DrawSomething application in Javascript.

DrawSomething JS

Ready?!?! so lets go.

The first thing we’re going to learn is how to draw inside your browser:

HTML5 has a new element called Canvas, to add a canvas inside your html, you just need to copy this code inside the html page:

<canvas id=”board” class=”board” ></canvas>

To draw inside this canvas with the mouse, we need to listen to three mouse events:
  • mousedown - to start drawing the line
  • mousemove - to continue drawing the line
  • mouseup - to stop drawing the line
var board = document.getElementById(“board”);
Here are the methods implementation:
var startPaintWithMouse = function(event) {
    brushCtx = board.getContext(‘2d’); // get the context of the canvas
    brushCtx.lineWidth = lineWidth; // set line width from variable
    brushCtx.strokeStyle = color; // set line color from variable
    brushCtx.moveTo(event.offsetX,event.offsetY); // start drawing from this point
var movePaintWithMouse = function(event) {
    if (mouseState == 1) {
        brushCtx = board.getContext(‘2d’);
        brushCtx.lineTo(event.offsetX,event.offsetY); // go to this point and draw
        brushCtx.stroke(); // stroke the line
var stopPaintWithMouseUp = function(evet) {
    mouseState = 0; // set mouse state to 0 to stop the draw

Now, just add the buttons that change the line width and color and start to draw inside the html5 canvas element.
In the next post, We will learn how to record the user movements and to play it, just like the DrawSomething app.


  1. That is a good thing. I hope I could use it freely, nevertheless, its modifications are too complicated to me.

  2. Each element is important in this structure of the code. We need to draw the clean lines to create the desired application.