javascript实用图像加载器

一、HTML代码

<!DOCTYPE html>
<html>
 <head>
  <meta charset="gbk">
  <title>javascript实用图像加载器</title>
  <script type="text/javascript" src="resources.js"></script>
 </head>
<body>
 <canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>
<script>
 //使用方法:
 resources.load(['img/sprites.png','img/terrain.png']);
 resources.onReady(start);
 function start(){
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var img=resources.get("img/sprites.png");
  ctx.drawImage(img,0,0);
 }
</script>
二、图像加载器resources.js

(function() {
    var resourceCache = {};//缓存器
    var loading = [];
    var readyCallbacks = [];//回调函数集合
    // Load an image url or an array of image urls
    function load(urlOrArr) {
        if(urlOrArr instanceof Array) {
            urlOrArr.forEach(function(url) {
                _load(url);
            });
        }
        else {
            _load(urlOrArr);
        }
    }
    function _load(url) {
        if(resourceCache[url]) {
            return resourceCache[url];//如果缓存器中有,直接从缓存器中取数据
        }
        else {
            var img = new Image();
            img.onload = function() {
                resourceCache[url] = img;
                if(isReady()) {//图像加载完毕,执行所有回调函数
                    readyCallbacks.forEach(function(func) { func(); });
                }
            };
            resourceCache[url] = false;
            img.src = url;
        }
    }
    //从缓存器中取数据
    function get(url) {
        return resourceCache[url];
    }
	
    //检查图像是否加载完毕
    function isReady() {
        var ready = true;
        for(var k in resourceCache) {
            if(resourceCache.hasOwnProperty(k) &&
               !resourceCache[k]) {
                ready = false;
            }
        }
        return ready;
    }
     //将回调函数加入
    function onReady(func) {
        readyCallbacks.push(func);
    }
    window.resources = { 
        load: load,
        get: get,
        onReady: onReady,
        isReady: isReady
    };
})();

下载源代码及效果:

http://www.108js.com/article/article3/30171.html

相关推荐