img.onload 拒绝在新的 Image() 声明后触发



我正在尝试将图像加载到画布上,以便我可以在上面写一些文本,也许以后可以保存它。我有两个以下功能:

openImage = (memeURL, index) => {
this.setState({currentMeme: index}, () => {
const base_image = new Image();
base_image.crossOrigin = "anonymous";
base_image.src = memeURL;
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
})

}
getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}

openImage函数绑定到onClick事件,因此当我单击图像时,它会触发上述操作,以便我的<img src="">可以从状态馈送并显示图像。

问题是当我单击图像时,它永远不会显示,并且我的currentImagebase64状态值始终data;但是如果使用Web工具进行调试,则看起来很好,因为有足够的时间加载图像。解决方案在下面的答案中:

canvas.toDataUrl(( 返回 'data:,'

但是,如果我写一些建议的东西,onload函数永远不会触发。例如,下面的代码由于某种原因不会触发加载,它只是在到达它时停止执行:

openImage = (memeURL, index) => {
this.setState({currentMeme: index}, () => {
const base_image = new Image();
base_image.onload = function() {
this.crossOrigin = "anonymous";
}
//Set src AFTER the image has loaded
base_image.src = memeURL;
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
})

}

请任何学科专家伸出援手吗?

const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});

需要在加载图像后执行

base_image.crossOrigin = "anonymous";

需要在设置src之前完成

因此,代码变为

openImage = (memeURL, index) => {
this.setState({currentMeme: index}, () => {
const base_image = new Image();
base_image.crossOrigin = "anonymous";
base_image.onload = () => { // use arrow function so `this` will be what is needed
const base64 = this.getBase64Image(base_image);
this.setState({currentImagebase64: base64});
}
base_image.src = memeURL;
})
}

您的评论

//Set src AFTER the image has loaded

建议你不知道加载是如何工作的...您设置开始加载图像的 src,然后在图像完成加载时触发加载

我不完全确定 react 如何处理上述状态,但我在香草 JS 中遇到了类似的问题,其中 src 在添加到 DOM 之前不会加载。 不过,将其隐藏起来很好:

const image = new Image();
image.onload = (e)=>{
// do something
}
image.src = YOUR_IMAGE_PATH;
image.hidden = true;
// add to body
document.body.appendChild(image); // at this point the src is loaded and onload handler is fired

最新更新