Tuesday, September 25, 2012

Callback Function

Callback function is very important into javascript. As we know we can pass different type of variable, object as function's parameter . In javascript if a function is passed as parameter then it is called Callback funbction.

The callback function is called on some event/condition till then the program can execute other code. We can say its uses the concept of asyncrhonous function. The callback function would executed only when the particular event is occurred or particular condition is satisfied.

Note:- Please don't forget to create a folder named image and place the image named(you can do rename) sham1.jpg inside that created folder. And of-course the below code and that folder should be exist into same directory.

Here is the exmaple, if there is any problem to understand code please share it with me.

<html>

<head>
<title>Call Back function</title>

<script type="text/javascript">
window.onload = function (){
loadImages(
//this functio runs only when the image would be 
// loaded into window
function (images, total){
  for(var i=0; i<total; i++){
 alert(images.src);
  }
}
);


function loadImages(callback){
var imgload = function (){
callback(myimage, 1);
}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');

var myimage  = document.createElement('img');
myimage.onload = function (){
ctx.drawImage(myimage, 0, 10, 100, 100);
imgload();
}
myimage.src = "images/sham1.jpg";
}
}
</script>

</head>

<body>
<canvas id="myCanvas">
The canvas is missing in your browser
</canvas>
</body>

</html>

No comments:

Post a Comment