Saturday, March 1, 2014

Draw a Line Using HTML Canvas Element

By searching about how to draw a line/pixel in a web brower using the pointer mouse, I found that there is a HTML5 element called canvas, which allow us to render 2D shapes in the browser. In this entry we are going to implement this HTML5 element and JavaScript code to make a small box where we can paint something using the mouse as it would be a pencil.

First of all, let's include the canvas element with some basic information:



To paint the line/pixel everytime that we pass the mouse over the box, use onmousemove event of the canvas. We will make a call to a JS method from the onmousemove to run all the logic.

Let us call this method MainEvent. We need to know the position of the mouse in connection with the screen and also identify if the user has clicked the mouse, for this we will need the object MouseEvent that is passed from the canvas element through the onmousemove event with the word 'event'.

So, our canvas and JS function would looks like this:



Now, let's go to the JS side. We will put our logic in a new JS function called draw_signature that will receive the event sent from onmousemove, so it should be called from mainEvent.

First thing we would need to know is the coordinates of the mouse; It could be read from the properties event pageX and pageY. However that's not enough, since the canvas is not draw exactly in the left/top on page, is needed to read the offsetLeft/offsetTop from the canvas object:


To draw the line/pixel over the canvas, call getContext() method passing the value "2d" to get the object to start drawing. Use this new object to draw a small line with methods moveTo() and lineTo(), that receive the X and Y coordinates where should be draw the line. We would draw a line from the captured position to the same position plus one:


That's it. we can see the serie of dots forming a line by clicking and moving the mouse over the box.
DEMO: Click to see the demo

NOTES:

  • Tested in Chrome Version 33.0.1750.117 m
  • Found there is a very powerfull library to make things like this called svg-edit svg-edit
  • There is an improved version in Improved Version - DEMO