Tuesday, December 20, 2011

Draw image using html5 canvas element

<html>
 <head>
 <meta charset = "utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
 var cx = new Array();
 var cy = new Array();
 Element.prototype.lefttop = function () {
 var x = this.offsetLeft; // it returns the left width value from parent element eg 421
 var y = this.offsetTop; // it returns the top width value from parent element eg 8
 var elmnt = this.offsetParent;
while (elmnt !== null) {
 x = parseInt (x) + parseInt (elmnt.offsetLeft); // adding the left of the parent element to child to get full left width
 y = parseInt (y) + parseInt (elmnt.offsetTop); // adding the left of the parent element to child to get full left width
elmnt = elmnt.offsetParent;
 }
return new Array (x, y); // return the x,y coordinates as array
 }
$(document).ready (function () {
 // create object for canvas element
 var flip = document.getElementById ("flip");
 var xy = flip.lefttop (); // call the lefttop function..
var ctx = flip.getContext ("2d"); // gettin 2d context.. drawing property
 // below two line for the box
 ctx.fillStyle = "rgb(255,255,255)"; // apply color..
 ctx.fillRect (0, 0, 500, 500); // draw rect
 $(flip).mousemove (function (event) { // call function on mouse move
 var x = event.clientX; // getting position of mouse point cordinate x
 var y = event.clientY; // getting position of mouse point cordinate y
 cx.push(x-xy[0]); // assign values cx array eg 421-422
 cy.push(y-xy[1]); // assign values cx array eg 8-9
 ctx.fillStyle = "rgb(255, 0, 0)"; // fill style
 var i = 0;
 for(; i < cx.length; i++) //loop for each value
 {
 ctx.beginPath();
 if(i){
 ctx.moveTo(cx[i-1], cy[i-1]);
 }else{
 ctx.moveTo(cx[i], cy[i]);
 }
 ctx.lineTo(cx[i], cy[i]);
 ctx.closePath();

ctx.lineJoin = "round"; //line joins: miter, round, or bevel for corner shapes
 ctx.lineWidth = 2; // line weight
 ctx.stroke(); // define end of portion
 }
 });
 });
 </script>
<style>
#flip {
 border: 1px solid black;
 display: inline-block;
}
body {
 text-align: center;
 }
 </style>
 </head>
<body>
 <canvas id = "flip" width = "500" height = "500"></canvas>
 <br/>
 <button value="save" name="save" onClick="save()">save</button>
 </body>
 </html>

Bind Some Event to Element and trigger that function when click the element

Scenario: Suppose if we used same click event function in various web pages. if you want do some logic some page button for that need to re...