2015-11-08 90 views
1

我已经看到了很多代码片段和教程,介绍如何加载单个图像,然后绘制该图像,并在图像上绘制形状等,但有没有办法加载多个图像(PNG)与透明部分在画布上,所以你可以将它们分层,然后下载组合?在html5画布中加载多个PNG图像

布赖恩

回答

1

下面是一个图像预加载的例子,将等到所有图像都满载,然后调用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); 

} 
+0

你不应该使用'的loop'到去思考每个'图像'对象,然后渲染,而不是重复代码?你也不应该有一个''类可以保持图像的位置? OP可能想要在画布周围移动图像。 – Canvas

+0

@Canvas叹息...请查看代码。确实有一个for循环创建,来源,加载和保存每个图像对象 - 没有重复的代码。如果你愿意,你可以创建一个类,但是(IMO)一个类是过度杀伤性的,因为代码是非常简单的(并且在应用程序开始时经常只用一次)。加载后,所有图像都可以通过'imgs []'数组在代码中随时使用。 – markE