从Image Source生成base64 DataURL

时间:2017-01-05 20:46:21

标签: javascript reactjs html5-canvas

我正在尝试从图像源生成base64数据URL,但每当我尝试转换它时,输出的dataURL只是没有图像的空白画布。我在这里错过了什么?

src到base64函数:

imageToBase64(url, callback) {
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
        let canvas = document.createElement('CANVAS');
        const ctx = canvas.getContext('2d');
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        const dataURL = canvas.toDataURL('image/png|gif|jpg');
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
}

用法:

componentDidMount() {
    this.imageToBase64(this.props.originalUploadFile.data, (dataUrl) => {
        console.log(dataUrl) // I am getting a result, but it does not contain the image data
    });
}

0 个答案:

没有答案