首页 > 代码库 > 【笔记】canvas图片预加载及进度条的实现

【笔记】canvas图片预加载及进度条的实现

/*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 =http://www.mamicode.com/ 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图片预加载及进度条的实现