是否有html画布的onload函数

是否有html画布的onload函数

本文介绍了是否有html画布的onload函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是从一系列png图像创建一个imageData数组。

My goal is to create an array of imageData from a series of png images.

为了做到这一点,我使用for循环来浏览图像,将它们放在画布中,然后检索并将创建的imageData存储在数组中。

In order to do this I use a for loop to go through the images, put them in the canvas and then retrieve and store the created imageData in an array.

问题是图像没有足够的时间加载到画布中。
我现在的解决方案是让计时器留出足够的时间,但这太可怕了。

The problem is that the image does not have enough time to be loaded in the canvas.My solution for now is to have a timer leave enough time but it's horrible.

我似乎无法找到解决这个问题的方法。有没有办法为画布设置onload功能?

I can't seem to find any solution to this problem. Is there a way to have an "onload" function for the canvas?

for(var i=1;i<50;i++){
  (function(i){
     setTimeout(function(){
        return function(){
            var newpath = path+i+".png";            //path to the image
            baliseimg.onload = function(){          //baliseimg : html image tag
                ctxt.drawImage(baliseimg,0,0);
                ctxt.fillText(i, 50, 50);    //just to stamp the image number on the imagedata
                imgs[i-1]=ctxt.getImageData(0,0,512,512);
            }
            baliseimg.src=newpath;

        }();
     },100*i);  //100ms works, limit seems to be at 40
  }(i));
}

感谢您的时间。

推荐答案

这是预加载所有图像的代码。

Here's code to preload all your images.

当它们完全加载时,调用start()函数。

When they are fully loaded the start() function is called.

// image loader

var imageURLs=[];
var imagesOK=0;
var imgs=[];

// put the paths to your images in imageURLs[]

imageURLs.push("yourImage1.png");
imageURLs.push("yourImage2.png");
imageURLs.push("yourImage3.png");
imageURLs.push("yourImage4.png");
imageURLs.push("yourImage5.png");


loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){
            imagesOK++;
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        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[]


    // for example, draw the images on the canvas

    var nextX=10;

    for(var i=0;i<imgs.length;i++){
        context.drawImage(imgs[i],nextX,10);
        nextX+=imgs[i].width;
    }

}

这篇关于是否有html画布的onload函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:29