Thursday, February 2, 2012

Using Javascript load image on HTML5 Canvas

In the html example here, a Image is defined, with src property of the url of the image to be loaded. Using the addEventListener() function to define the callback function(), listen the event of "load". The 3rd parameter "false" specify that it will called AFTER the "load" operation completed.

Load image on HTML5 Canvas

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile-Web-App: Load image on HTML5 Canvas</title>
<script type="text/javascript">
function loadcanvas(){
var canvas;
var context;

var image;
var image_src = "http://goo.gl/BlQEX";

canvas = document.getElementById("mycanvas");
context = canvas.getContext("2d");

image = new Image();
image.src = image_src;

//Define callback function(), it will be called after the event "load".
//The 3rd parameter "false", define that it will be called after "load" event completed.
image.addEventListener("load",
function(){
context.drawImage(image, 0, 0);
} ,
false);

}

</script>
</head>
<body onload="loadcanvas();">
<h1>Mobile-Web-App: Load image on HTML5 Canvas</h1>

<canvas id="mycanvas" style="border: 5px solid;" width="200" height="150">
Sorry! Your browser doesn't support Canvas.
</canvas>

</body>
</html>

No comments:

Post a Comment