Sunday, September 2, 2012

HTML5 and Javascript example; detect mouse event and free-draw on canvas.

Example to detect mouse event and free-draw on HTML5 canvas, using Javascript.

detect mouse event and free-draw on canvas.


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: HTML5 Canvas</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">

var canvas;
var context; 
var mouseon;

$(window).bind("resize", resetCanvas);

function loadcanvas(){
 window.scrollTo(0, 1);
 resetCanvas();
 
 mouseon = false;
 
 document.body.addEventListener(
  "mousedown",
  function(event){
   context.moveTo(event.pageX, event.pageY);
   mouseon = true;
  },
  false
 ); 

 document.body.addEventListener(
  "mouseup",
  function(event){
   mouseon = false;
  },
  false
 );
 
 document.body.addEventListener(
  "mousemove",
  function(event){
   if(mouseon){
    context.lineTo(event.pageX, event.pageY);
    context.stroke();
   }
  },
  false
 );

}

function drawBackground(){

 context.fillStyle = "#505050";
 context.fillRect(0, 0, canvas.width, canvas.height);
 
}

function resetCanvas(){
 canvas = document.getElementById("mycanvas");

 canvas.width = window.innerWidth;
 canvas.height = window.innerHeight; 
 
 context = canvas.getContext("2d");
 
 drawBackground();
}

</script>
</head>
<body onload="loadcanvas();">

<canvas id="mycanvas">
Sorry! Your browser doesn't support Canvas.
</canvas>
</body>
</html>


Related:
- HTML5 and Javascript example; detect Touch event and free-draw on canvas for mobile device.

No comments:

Post a Comment