So, time to bring our hero in picture. I will load the image saved in my local folder.
Load Image
[code language="javascript"]
//create init function to initialize image loading
var img = new Image();
var imgLoaded = false;
img.onload = function() {
imgLoaded=true;
}
img.src = 'images/hero.png';
[/code]
After loading the image, we need to draw it on canvas
[code language="javascript"]context.drawImage(img,x,y);[/code]
Create Hero Object
To keep code sane, we will create hero object that will hold all properties and methods of hero. If you are new to Objects in javascript refer Working with objects
[code language="javascript"]
var hero = {
x: 50,
y: 50,
width:img.width,
height:img.height,
draw: function() {
if(imgLoaded){
context.drawImage(img,this.x,this.y);
}
}
};
[/code]