单击该按钮后,图像已正确加载,但无法下载。它只是显示在div上。一切工作正常,只是图像无法保存。

我的HTML和JS:



<script>

document.getElementById("download").addEventListener("click", function()
{
	html2canvas(document.getElementById("output"), {allowTaint: true}).then(function(canvas)
	{
	    document.getElementById("output2").appendChild(canvas);

	});
});

</script>

<button type="button" id="download" class="btn btn-success">Preview Image</button>
<div id="output2"></div>

<div id="output" class="dark-mode">
    <h1><b>{{heading}}</b></h1>
    <i class="fa fa-twitter" id="author"></i> <a id="authorname">{{author}}</a>
    <span id="time" class="date">{{date}}</span>
    <p>{{news}}</p>
    <img :src="image" width="100%"/>
    <p id="img_text">{{caption}}</p>
</div>

最佳答案

为了达到预期的效果,请创建保存方法



document.getElementById("download").addEventListener("click", function()
{
	html2canvas(document.getElementById("output"), {allowTaint: true}).then(function(canvas)
	{
	    document.getElementById("output2").appendChild(canvas);
    saveAs(canvas.toDataURL(), 'file-name.png');

	});
});

function saveAs(uri, filename) {

    var link = document.createElement('a');

    if (typeof link.download === 'string') {

        link.href = uri;
        link.download = filename;

        //Firefox requires the link to be in the body
        document.body.appendChild(link);

        //simulate click
        link.click();

        //remove the link when done
        document.body.removeChild(link);

    } else {

        window.open(uri);

    }
}

#output2 {
  border: 1px solid black;
}

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

<button type="button" id="download" class="btn btn-success">Preview Image</button>
Output 2 - <div id="output2"></div>

<div id="output" class="dark-mode">
    <h1><b>{{heading}}</b></h1>
    <i class="fa fa-twitter" id="author"></i> <a id="authorname">{{author}}</a>
    <span id="time" class="date">{{date}}</span>
    <p>{{news}}</p>
    <img :src="image" width="100%"/>
    <p id="img_text">{{caption}}</p>
</div>





Codepen-https://codepen.io/nagasai/pen/jXavqm

下图下载

javascript - html2canvas图片未保存-LMLPHP

请参考下面的链接了解不同的保存选项
Download html2canvas image to desktop

关于javascript - html2canvas图片未保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53991275/

10-15 03:15
查看更多