[英]Jquery - Load an image from url and draw it on canvas
我正在嘗試從URL加載多個圖像,然后將它們繪制到canvas元素中。 但我不想為我必須加載的每個圖像重新創建相同的代碼。
loadImage函數(它工作正常):
function loadImage(divId, imgId, path, width, height) {
var img = $("<img />").attr({ 'id': imgId, 'src': path , 'width': width, 'height': height, 'style': "display:none"})
.load(function () {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image: ' + imgId);
} else {
$("#" + divId).append(img);
}
});
}
但我想多次調用loadImage,然后在畫布上繪制所有圖像:
function myTheme()
{
loadImage("ContentBox", "bottom", "http://mydomain/images/bottom.jpg", 400, 391);
loadImage("ContentBox", "left", "http://mydomain/images/left.jpg", 400, 391);
loadImage("ContentBox", "right", "http://mydomain/images/right.jpg", 400, 391);
loadImage("ContentBox", "top", "http://mydomain/images/top.jpg", 400, 391);
// I need to wait ALL loads before using getElementById (these lines below don't work)
_imgBottom = document.getElementById("bottom");
_imgLeft = document.getElementById("left");
_imgRight = document.getElementById("right");
_imgTop = document.getElementById("top");
Context.drawImage(_imgBottom, 0, 0);
Context.drawImage(_imgLeft, 0, 0);
Context.drawImage(_imgRight, 0, 0);
Context.drawImage(_imgTop, 0, 0);
}
我怎么能這樣做?
謝謝
在開始使用之前,有許多方法可以加載所有圖像。
這是一種方式:
// image loader
var imagesOK=0;
var imgs=[]; // the fully loaded Image objects will be here in the imgs[] array
var imageURLs=[]; // put the paths to your images in the imageURLs[] array
// push the image urls into an array
imageURLs.push("http://mydomain/images/bottom.jpg");
imageURLs.push("http://mydomain/images/left.jpg");
imageURLs.push("http://mydomain/images/right.jpg");
imageURLs.push("http://mydomain/images/top.jpg");
// begin loading
loadAllImages();
function loadAllImages(){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
// start() is called when all images are fully loaded
start();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// the imgs[] array holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// imgs[0] == bottom.jpg
// imgs[1] == left.jpg
// imgs[2] == right.jpg
// imgs[3] == top.jpg
}
如果您的目標是只需加載一堆圖像就可以使用我的YAIL批量圖像加載程序 (MIT許可證=免費且靈活)。
只需設置加載器(這只是執行此操作的眾多方法之一,請參閱上面的鏈接以獲取完整用法):
var loader = (new YAIL({
done: drawImages,
urls: [
"http://mydomain/images/bottom.jpg",
"http://mydomain/images/left.jpg",
"http://mydomain/images/right.jpg",
"http://mydomain/images/top.jpg"
]
})).load();
然后,當所有圖像都已加載時,您只需遍歷圖像數組,該數組與網址列表的順序相同:
function drawImages(e) {
for(var i = 0, img; img = e.images[i]; i++)
context.drawImage(img, 0, 0);
}
理想情況下,您應該提供一個錯誤處理程序(此處未顯示),並且還可以選擇提供進度處理程序。
如果您將其用於教育目的,請查看其源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.