Web Info and IT Lessons Blog...

Tuesday 21 July 2015

Drawing on html5 canvas

The previous lesson of Html5 Canvas Series was about filling an html5 canvas with colors and in this lesson we will learn to draw on html5 canvas.

Drawing on html5 canvas

Demo: Drawing on html5 canvas



Html Code:


<canvas id="paint" width="600" height="350" onmousedown="fill(event);" 
onmouseup="stop();" onmousemove="drawonmove(event);">
</canvas>

In the above html code onmousemove, onmouseup and onmousemove events are bind to the html5 canvas. Javascript fill() function is called when someone clicks on the canvas. Inside the fill() function, the first thing we do is enable drawing on canvas by setting the drawing variable (draw = 1) and then we draw a small black circle on the html5 canvas at the mouse click co-ordinates. onmousemove event calls drawonmove() function, in this function we check if drawing is enabled then draw circles on the canvas by calling fill() function onmousemove else don't do anything. onmouseup event calls stop() function which is used to disable drawing on canvas by unsetting the drawing flag (draw = 0).

Css Code:


<style>
canvas{
 border:1px solid black;
}
</style>

Javascript Code:


<script type="text/javascript">
var color = 'black'; // Canvas fill color
var draw = 0;

function drawonmove(event){ 
 if(draw == 1){ // Check if drawing is enabled
  fill(event);
 }
}

function stop(){
 draw = 0; // Disable drawing on canvas
}

function fill(e){
 draw = 1; // Enable drawing on canvas
 if (e == null) 
  e = window.event; 
  
  if (e.x != undefined && e.y != undefined)
        {
          x = e.x;
          y = e.y;
        }
        else // Firefox method to get the position
        {
          x = e.clientX + document.body.scrollLeft +
              document.documentElement.scrollLeft;
          y = e.clientY + document.body.scrollTop +
              document.documentElement.scrollTop;
        }
  
  var paint = document.getElementById('paint');
  x -= paint.offsetLeft;
  y -= paint.offsetTop;
  
  var ctx = paint.getContext('2d');
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x,y,2,0,2*Math.PI);
  ctx.fill();
}

</script>

Stay tuned for more lessons...

No comments:

Post a Comment