2016-12-14 197 views
0

有人可以向我解釋。爲什麼我的這段代碼不工作?我一遍又一遍地改變了我的代碼,很難解釋什麼是不工作的。所以我終於把它放在我的網站上,以便我可以告訴你發生了什麼事情。這裏是我找到代碼的地方: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

回答

1

看到一些挖後,它看起來像這個問題是你的畫布被污染了,你不能導出污點畫布。爲了確保您的畫布不受污染,您不能使用交叉來源圖像。例如,我嘗試使用base-64編碼圖像,而那個工作得很好。

+0

你有可能給我一個例子嗎? – xcalliber

+0

什麼工作對我來說只是改變圖像源到別的東西,不玷污它,就像一個base64編碼的圖像:'數據:圖像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4 // 8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg == ' – bugfroggy

+0

謝謝我感謝您的幫助 – xcalliber