2015-11-08 91 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