下载动态创建的画布为空白

时间:2019-03-07 20:44:32

标签: javascript html svg canvas

我无法下载动态创建的画布。我希望用户能够创建SVG图像并将其下载为位图。为此,我创建了一个画布并将其SVG图像绘制到该画布上。然后我要下载它。但是,画布是空白的。现在我知道这可能是因为画布尚未完全加载,但是在onload上附加了canvas侦听器却无法工作,因为它从未触发过。

第二次单击链接将下载正确的图像,这对我来说又是一个提示,它是时间问题。有人可以告诉我为什么从未解雇onload吗?也许我误会了事件的处理方式或原因。

document.getElementById('downloadDirectly').addEventListener('click', function () {
    downloadDirectly();
});

document.getElementById('downloadOnLoad').addEventListener('click', function () {
    downloadOnLoad();
});

function createCanvas() {
    var img = new Image();
    img.src = 'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1000"><line x1="0" y1="0" x2="500" y2="500" stroke="black" stroke-width="5"/></svg>';

    var canvas = document.createElement('canvas');
    canvas.width = 1000;
    canvas.height = 1000;
    canvas.getContext('2d').drawImage(img, 0, 0, 1000, 1000, 0, 0, 1000, 1000);
    return canvas;
}

function downloadDirectly() {
    let canvas = {};
    canvas = createCanvas();
    let el = document.getElementById('downloadDirectly');
    el.href = canvas.toDataURL();
    console.log('This downloads, but canvas is not ready');
    el.download = name + ".png";
}

function downloadOnLoad() {
    let canvas = {};
    canvas = createCanvas();
    canvas.onload = function() {
        console.log('This is never reached :(');
        let el = document.getElementById('downloadOnLoad');
        el.href = canvas.toDataURL();
        el.download = name + ".png";
    };
}
<p><a id="downloadDirectly">Download directly</a></p>
<p><a id="downloadOnLoad">Download using onLoad</a></p>

0 个答案:

没有答案