JavaScript中的同步图像加载 [英] Synchronous image loading in JavaScript
本文介绍了JavaScript中的同步图像加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写JavaScript函数:
I'm writing a JavaScript function:
function imgstr(url) {
var img = new Image();
img.src = url;
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL('image/png');
}
目标是从给定的图像URL输出base64字符串.
The target is to output a base64 string from a given image URL.
以上代码不起作用,原因是img src
由URL分配后,它会异步地加载图像内容 .如何使此过程同步?
While the above code doesn't work, the reason being that after img src
gets assigned by a URL, it loads the image content asynchronously. What can be done to make this procedure synchronous?
推荐答案
使用下面的方法,直到图像加载完毕
Use below method that will wait till thge image to load
currentimage.onload = function(e){
// code, runned after image load
}
希望这对您有帮助...
Hope this helps...
这篇关于JavaScript中的同步图像加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文