Thursday, 11 August 2011

HTML5 Canvas - loading images

Here are some examples of loading images to the HTML5 canvas. I have used the canvas template from this post. The first example loads a single image by creating a new Image object and adding the image onto the canvas once the image has loaded. The drawImage() method renders the image object onto the canvas. The method has three parameters: the first is the reference to the image, the second is the x coordinate position and the third is the y coordinate position.

//Loads single image
var img = new Image();
img.src = "assets/image-1.jpg";
img.onload = function(){
 context.drawImage(img,100,100);
}

The scaling of the image can be altered with the width and height parameters which are the fourth and fifth parameters of the drawImage() method. This example will load the image at 100 on the x and y axis, set the width to 80 and the height to 40.

//Scale image
var img = new Image();
img.src = "assets/image-2.jpg";
img.onload = function(){
 context.drawImage(img,100,100,80,40);
}

Multiple images can be loaded using a function. I have used the loadImages() function to load an array of images and to call a function when all the images have loaded. The images will appear in a 5 x 2 grid.

//Load multiple images 
var xpos = 100;
var ypos = 100;
var imgoffset = 70;
var cols = 5;
   
var imgArray = ["assets/image-1.jpg","assets/image-2.jpg","assets/image-3.jpg", "assets/image-4.jpg","assets/image-5.jpg","assets/image-6.jpg","assets/image-7.jpg","assets/image-8.jpg", "assets/image-9.jpg","assets/image-10.jpg"];
   
function loadImages(arr, callBack){
var count = 0;
 var img = [];
    
 for(var i in arr ){
  img[i] = new Image();
  img[i].src = arr[i];
  img[i].onload = function(){
   count++;
   if(count == arr.length){
    callBack(img);
   }
  }
 }
} 
   
  
function imageLoaded(img){
//creates a 5 x 2 grid
 for(var i in imgArray){
  var xoffsets = xpos +  imgoffset * (i%cols);
  var yoffsets = ypos +  imgoffset * Math.floor(i/cols);
  context.drawImage(img[i],  xoffsets, yoffsets );
 }
}
  

loadImages( imgArray, imageLoaded );

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP