//加載多張圖片方法
var preloadImg = function (list, imgs) { //預加載
var def = $.Deferred(),
len = list.length;
$(list).each(function (i, e) {
var img = new Image();
//img.crossOrigin = ""; //跨域請求資源
img.setAttribute('crossOrigin', 'anonymous');
img.onload = (function (j) {
return function () {
imgs[j] = img
len--;
if (len == 0) {
def.resolve();
}
};
})(i);
img.onerror = function () {
len--;
// alert('fail to load image');
};
img.src = e; // 確保緩存的圖片也觸發 load 事件
});
console.log(def.promise())
return def.promise();
}
複製代碼
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = document.body.clientWidth;
c.height = document.body.clientHeight;
var list = ['../images/bg_result.jpg',...];//待加載的圖片列表
var imgs = []; //生成後可以使用的圖片列表
$.when(preloadImg(list, imgs)).done(
function () {
//draw
var rimg = c.toDataURL("image/png");
$(".canvasImg").html("<img src='" + rimg + "' alt='from canvas' />");
});
複製代碼