简体   繁体   English

画布到数据URL不能正常工作

[英]Canvas to data url not working properly

I have a function that takes an img-element and returns a data url. 我有一个函数,它带有一个img元素并返回一个数据URL。 This works like 7/10 times and returns a blank image 3/10 times. 这相当于7/10次,并返回3/10次空白图像。 I view the created data url through my browser(chrome) and use the same images so I know that this function is returning broken images. 我通过浏览器(chrome)查看创建的数据url,并使用相同的图像,因此我知道此函数返回的图像损坏。 Can anyone spot why? 谁能找到原因?

function imgToDataURL(img) {
    var canvas = document.createElement('canvas');
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    var c = canvas.getContext('2d');
    c.drawImage(img, 0, 0);
    dataurl = canvas.toDataURL();
    return dataurl;
}

$(function() {
    img = new Image();
    img.crossOrigin = '';
    img.onload = function() {
        newimg = new Image();
        newimg.onload = function() {
            document.body.appendChild(newimg);
        }
        newimg.src = imgToDataURL(img);
    }
    img.src = 'https://somedomain.s3.amazonaws.com/someimg.png';
});

This example works most of the time but sometimes ends with a large white rectangle instead of the image. 此示例在大多数情况下都有效,但有时以大的白色矩形而不是图像结尾。

You have to wait for images to load before drawing them using .drawImage function. 使用.drawImage函数绘制图像之前,您必须等待图像加载 Only after the image is loaded by the browser you can call your imgToDataURL function. 只有在浏览器加载了图像之后,您才能调用imgToDataURL函数。

Something like this: 像这样:

var image_sources = ["img1.png", "img2.png", "..."];

for(var i=0; i<image_sources.length; i++) {
    var new_img = document.createElement("img");
    new_img.onload = function() {
       imgToDataURL(this);
    };
    new_img.src = image_sources[i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM