html2canvas图片未保存

时间:2018-12-31 20:43:54

标签: javascript html5 html5-canvas html2canvas

当我单击按钮时,图像已正确加载,但无法下载。它只是显示在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>

1 个答案:

答案 0 :(得分:1)

要达到预期效果,请创建保存方法

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

下载下面的图片

enter image description here

请参考以下链接以获取不同的保存选项 Download html2canvas image to desktop