我正在使用 html2canvas 将网页转换为图像脚本,工作正常,但我如何才能只下载或打印模态区域,而不是整个主体?
我试过用下面的链接,但没有成功。https:/codepen.ioanonpenPBGaMP
// html2canvas <- https://html2canvas.hertzen.com/dist/html2canvas.min.js
// code reference: https://stackoverflow.com/questions/31656689/how-to-save-img-to-users-local-computer-using-html2canvas
setUpDownloadPageAsImage();
function setUpDownloadPageAsImage() {
document.getElementById("download-page-as-image").addEventListener("click", function() {
html2canvas(document.body).then(function(canvas) {
console.log(canvas);
simulateDownloadImageClick(canvas.toDataURL(), 'file-name.png');
});
});
}
function simulateDownloadImageClick(uri, filename) {
var link = document.createElement('a');
if (typeof link.download !== 'string') {
window.open(uri);
} else {
link.href = uri;
link.download = filename;
accountForFirefox(clickLink, link);
}
}
function clickLink(link) {
link.click();
}
function accountForFirefox(click) { // wrapper function
let link = arguments[1];
document.body.appendChild(link);
click(link);
document.body.removeChild(link);
}
<div id="modal1" class="modal" >
<div class="modal-content" style="background-color: green;">
<h4 style="color: honeydew;">Modal Header</h4>
<script> document.write(new Date().toLocaleDateString()); </script>
<p>Google</p>
</div>
<div class="modal-footer">
<button id="download-page-as-image">Download</button>
<a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat"><i class="material-icons">close</i></a>
</div>
</div>
function sendData() {
var modalButton = $('[data-target="#myModal2"]')[0];
modalButton.click();
var modal = $('#myModal2')[0];
setTimeout(function() {
document.getElementById('myModal2').style.display = 'none'; // you use your modal's style display to "none" before converting to canvas image and again back to style display: 'block' or if any.
html2canvas(document.getElementById('capture'), {
allowTaint: false,
useCORS: true
}).then(function(canvas) {
downloadCanvas(document.getElementById('test'), canvas, 'test.png');
modalButton.click();
});
document.getElementById('myModal2').style.display = 'block'; // changing modal's style back to normal after canvas image gets created
}, 1000);
}
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
function downloadCanvas(link, canvas, filename) {
link.href = canvas.toDataURL();
link.download = filename;
link.click();
}
document.getElementById("defaultOpen").click();
Bit ugly fix, but I hope it helps you as far I understood your issue posted here.