在html5画布中加载多个png图像

时间:2015-11-08 17:11:04

标签: html5 image canvas

我已经看过很多关于如何加载单个图像然后绘制图像但是在图像上绘制形状等的代码片段和教程,但有没有办法加载带有透明部分的多个图像(png)在画布上,你可以分层然后下载合成?

布赖恩

1 个答案:

答案 0 :(得分:2)

这是一个图像预加载器的示例,它将等待所有图像完全加载,然后调用start()函数:

// image preloader

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// put the paths to your images in imageURLs[]
var imageURLs=[];  
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face1.png");
imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/multple/face2.png");

// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
startLoadingAllImages(imagesAreNowLoaded);

// Create a new Image() for each item in imageURLs[]
// When all images are loaded, run the callback (==imagesAreNowLoaded)
function startLoadingAllImages(callback){

  // iterate through the imageURLs array and create new images for each
  for (var i=0; i<imageURLs.length; i++) {
    // create a new image an push it into the imgs[] array
    var img = new Image();
    // Important! By pushing (saving) this img into imgs[],
    //     we make sure the img variable is free to
    //     take on the next value in the loop.
    imgs.push(img);
    // when this image loads, call this img.onload
    img.onload = function(){ 
      // this img loaded, increment the image counter
      imagesOK++; 
      // if we've loaded all images, call the callback
      if (imagesOK>=imageURLs.length ) {
        callback();
      }
    };
    // notify if there's an error
    img.onerror=function(){alert("image load failed");} 
    // set img properties
    img.src = imageURLs[i];
  }      
}

// All the images are now loaded
// Do drawImage & fillText
function imagesAreNowLoaded(){

  // the imgs[] array now holds fully loaded images
  // the imgs[] are in the same order as imageURLs[]

  ctx.font="30px sans-serif";
  ctx.fillStyle="#333333";

  // drawImage the first image (face1.png) from imgs[0]
  // and fillText its label below the image
  ctx.drawImage(imgs[0],0,10);
  ctx.fillText("face1.png", 0, 135);

  // drawImage the first image (face2.png) from imgs[1]
  // and fillText its label below the image
  ctx.drawImage(imgs[1],200,10);
  ctx.fillText("face2.png", 210, 135);

}