将图像从网站下载到桌面

时间:2016-12-14 19:49:19

标签: javascript jquery html css

有人可以向我解释一下。为什么我的代码不起作用?我一遍又一遍地改变了我的代码,很难解释什么不起作用。所以我最终把它放在我的网站上,这样我就可以告诉你发生了什么。这是我找到代码的地方:convert div to single image with canvas-javascript css我用这个例子是因为我试图做同样的事情。我更改了图片,以便您在我的网站https://torcdesign.com/mom.php

上看到

var download = document.getElementById("download"),
		result = document.getElementById("result");

function renderContent() {
    html2canvas(document.getElementById("content"), {
        allowTaint: true
    }).then(function(canvas) {
    		result.appendChild(canvas);
        download.style.display = "inline";
    });
}

function downloadImage() {
		download.href = result.children[0].toDataURL("image/png");
}

document.getElementById("button").onclick = renderContent;
download.onclick = downloadImage
<style>
#content {
    position: absolute;
    width: 300px;
    height: 200px;
    border: 5px solid red;
    overflow: hidden;
}

#img1 {
    width: 300px;
    height: 200px;
    position: absolute;
    z-index: 5;
}

#img2 {
    position: absolute;
    z-index: 6;

    width: 150px;
    height: 190px;
}

#img3 {
    position: absolute;
    z-index: 7;
    width: 200px;
    height: 100px;
}

#download {
    display: none;
}
</style>
<script src="https://rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>

<div id="content">
    <img id="img1" src="https://torcdesign.com/shirts/brown.jpg">
    <img id="img2" src="https://torcdesign.com/shirts/kiwi.jpg">
    <img id="img3" src="https://torcdesign.com/shirts/lswhite.jpg">   
</div>
<br><br><br><br><br><br><br><br><br><br><br><br>
<input id="button" type="button" value="convert div to image"><br>
<h3>result:</h3>
<div id="result"></div>
<a id="download" download="my_image.png" href="#">Download image</a>

1 个答案:

答案 0 :(得分:1)

经过一番挖掘,看起来问题是你的画布被污染了,你无法导出受污染的画布。要确保画布没有污染,您不能使用跨原始图像。例如,我尝试使用base-64编码的图像,而那个工作完全正常。