简体   繁体   English

Jquery - 从url加载图像并在画布上绘制它

[英]Jquery - Load an image from url and draw it on canvas

I'm trying to load multiple images from URLs and then draw them into a canvas element. 我正在尝试从URL加载多个图像,然后将它们绘制到canvas元素中。 But I don't want to recreate the same code for each image I have to load. 但我不想为我必须加载的每个图像重新创建相同的代码。

The loadImage function (it works fine): 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);
    }
});

} }

But I would like to call loadImage multiple times and then draw all the images on the canvas: 但我想多次调用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);
}

How could I do this please ? 我怎么能这样做?

Thanks 谢谢

There are many ways to load all images before starting to use them. 在开始使用之前,有许多方法可以加载所有图像。

Here's one way: 这是一种方式:

// 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

}

If your goal is to simply be able to load a bunch of images you can use something like my YAIL bulk image loader (MIT license = free and flexible). 如果您的目标是只需加载一堆图像就可以使用我的YAIL批量图像加载程序 (MIT许可证=免费且灵活)。

Simply setup the loader (this is just one of many ways to do this, please see link above for full usage): 只需设置加载器(这只是执行此操作的众多方法之一,请参阅上面的链接以获取完整用法):

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();

Then when all the images has loaded you simply iterate through the image array which is in the same order as the url list: 然后,当所有图像都已加载时,您只需遍历图像数组,该数组与网址列表的顺序相同:

function drawImages(e) {
    for(var i = 0, img; img = e.images[i]; i++)
        context.drawImage(img, 0, 0);
}

Ideally you should provide an error handler (not shown here) and there is the option of providing progress handler as well. 理想情况下,您应该提供一个错误处理程序(此处未显示),并且还可以选择提供进度处理程序。

If you try this for educational purposes then please have a look at the source code for it. 如果您将其用于教育目的,请查看其源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM