gpt4 book ai didi

javascript - 等待图像加载后再继续

转载 作者:行者123 更新时间:2023-11-28 07:53:07 25 4
gpt4 key购买 nike

我有以下代码,可以加载图像并将其写在 Canvas 上。加载图像后,我想进一步编辑 Canvas ,但此时必须加载图像。目前,我试图阻止类的构造函数完成,直到加载图像,但这似乎不起作用,因为即使图像已经存在,它也会保持“等待”。

你能告诉我为什么这不起作用吗?

我发现这不是一个好的解决方案,你能告诉我应该如何做吗?

var Handler = function(canvasId,imageSrc){

this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext("2d");
var self = this;
var image = new Image();
image.src = imageSrc;
this.finish = false;
image.onload = function(){
self.canvas.width = this.width;
self.canvas.height = this.height;
self.ctx.drawImage(image,0,0, self.canvas.width,self.canvas.height,
0,0,this.width,this.height);
self.finish = true;
};

this.applyFilter = function(filter){
//some unimportant code code....
};

this.toGrayScale = function(){
var imgData = this.ctx.getImageData(0,0,this.canvas.width,this.canvas.height);
///manipulate the data ....
this.ctx.putImageData(imgData,50,50);

};

while(!this.finish){};

};//end handler

var handler = new Handler("myCanvas","myImage.jpg");
handler.applyFilter(1); //will be executed before image has loaded if you remove while loop
handler.toGrayScale();

最佳答案

我认为你的问题是你正在创建一个图像节点,但你从未将图像附加到 DOM 中。因此 onload 函数永远不会被调用。

关于javascript - 等待图像加载后再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26536594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com