1. 程式人生 > >【筆記】canvas圖片預加載及進度條的實現

【筆記】canvas圖片預加載及進度條的實現

函數 style uil 圖片加載 mage code 重繪 執行 ces

/*star
 *loading模塊
 *實現圖片的預加載,並顯示進度條
 *參數:圖片數組對象,加載完成的回調函數
 */
function loadImages(sources,callback){    
    var loadedImages = 0;    
    var numImages = 0;  
    ctx.font=‘14px bold‘;
    ctx.lineWidth=5;
    var clearWidth=canvas.width;
    var clearHeight=canvas.height;
    // get num of sources    
for (var src in sources) { numImages++; } for (var src in sources) { images[src] = new Image(); //當一張圖片加載完成時執行 images[src].onload = function(){ //重繪一個進度條 ctx.clearRect(0,0,clearWidth,clearHeight); ctx.fillText(
‘Loading:‘+loadedImages+‘/‘+numImages,200,280); ctx.save(); ctx.strokeStyle=‘#555‘; ctx.beginPath(); ctx.moveTo(200,300); ctx.lineTo(600,300); ctx.stroke(); ctx.beginPath(); ctx.restore(); ctx.moveTo(
200,300); ctx.lineTo(loadedImages/numImages*400+200,300); ctx.stroke(); //當所有圖片加載完成時,執行回調函數callback if (++loadedImages >= numImages) { callback(); } }; //把sources中的圖片信息導入images數組 images[src].src = sources[src]; } } //定義預加載圖片數組對象,執行loading模塊 window.onload = function(){ var sources = { PaperBoy1: "images/run/PaperBoy1.png", PaperBoy2: "images/run/PaperBoy2.png", PaperBoy3: "images/run/PaperBoy3.png", PaperBoy4: "images/run/PaperBoy4.png", PaperBoy5: "images/run/PaperBoy5.png", PaperBoy6: "images/run/PaperBoy6.png", PaperBoy7: "images/run/PaperBoy7.png", PaperBoy8: "images/run/PaperBoy8.png", PaperBoy9: "images/run/PaperBoy9.png", PaperBoy10: "images/run/PaperBoy10.png", PaperBoy11: "images/run/PaperBoy11.png", PaperBoy12: "images/run/PaperBoy12.png", PaperBoy13: "images/run/PaperBoy13.png", PaperBoy14: "images/run/PaperBoy14.png", PaperBoy15: "images/run/PaperBoy15.png", PaperBoy16: "images/run/PaperBoy16.png", PaperBoy17: "images/run/PaperBoy17.png", PaperBoy18: "images/run/PaperBoy18.png", PaperBoy19: "images/run/PaperBoy19.png", PaperBoy20: "images/run/PaperBoy20.png", PaperBoy21: "images/run/PaperBoy21.png", PaperBoy22: "images/run/PaperBoy22.png", PaperBoy23: "images/run/PaperBoy23.png", PaperBoy24: "images/run/PaperBoy24.png", _Street:‘images/_Street.png‘, AD:‘images/AD.png‘, building:‘images/building.png‘, cloud:‘images/cloud.png‘ }; //執行圖片預加載,加載完成後執行main loadImages(sources,main); }; /*end*/

【筆記】canvas圖片預加載及進度條的實現