在javascript中同步图片加载 [英] sync image load in javascript

查看:123
本文介绍了在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');
}

目标是输出给定图像网址的base64字符串。

The target is to output a base64 string for a given image url.

虽然上面的鳕鱼不起作用,但我知道原因:在img.src由url分配后,它会异步加载图像内容。那么,如果我想让这个程序同步,我该怎么办?

While the above cod doesn't works, and I know the reason: that after img.src was assigned by a url, it loads the image content asynchronously. So what can I do if I want this procedure be sync?

推荐答案

使用下面的方法来等待加载图像

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆