从网站下载图像到桌面

问题描述:

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

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

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

 
function downloadImage() { 
 
\t \t 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>

+0

您的问题是,您的网站上图像编码不正确? – bugfroggy

+0

转换为图像后您是否尝试过下载? – xcalliber

+0

@bugfroggy我改变了我的代码我很抱歉,但仍然无法工作 – xcalliber

看到一些挖后,它看起来像这个问题是你的画布被污染了,你不能导出污点画布。为了确保您的画布不受污染,您不能使用交叉来源图像。例如,我尝试使用base-64编码图像,而那个工作得很好。

+0

你有可能给我一个例子吗? – xcalliber

+0

什么工作对我来说只是改变图像源到别的东西,不玷污它,就像一个base64编码的图像:'数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4 // 8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg == ' – bugfroggy

+0

谢谢我感谢您的帮助 – xcalliber