背景:通過(guò)html2canvas插件使用最新的二維碼替換宣傳頁(yè)上的原有的二維碼并下載該圖片,并解決圖片下載不完整的問(wèn)題
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.container{
position: relative;
display: inline-block;
}
/*設(shè)置img1尺寸為原圖尺寸或者等比縮放尺寸*/
.img1{
width: 1080px;
height: 1920px;
}
/*設(shè)置img2尺寸和img1的二維碼尺寸一直并定位覆蓋到二維碼上面*/
.img2{
width: 460px;
height: 460px;
position: absolute;
left: 294px;
top: 1060px;
z-index: 2;
}
</style>
</head>
<body>
<div class="container" id="container">
<img class="img1" src="./lib/download.jpg" alt="" />
<img class="img2" src="./lib/qrcode.png" alt="" />
</div>
<p>
<button type="button" id="button" class="btn">點(diǎn)擊</button>
</p>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script type="text/javascript">
/*let btn = document.getElementById("button")
btn.onclick = function () {
//設(shè)置滾動(dòng)為0避免截圖不完整
document.documentElement.scrollTop = 0
document.body.scrollTop = 0
new html2canvas(document.querySelector('#container'), {
backgroundColor: 'white',
useCORS: true, //支持圖片跨域
scale: 1, //設(shè)置放大的倍數(shù)
height: document.getElementById('container').scrollHeight,
windowHeight: document.getElementById('container').scrollHeight
}).then(canvas => {
const a = document.createElement('a');
a.href = canvas.toDataURL('image/png');
a.download = 'title';
a.click();
})
}*/
$("#button").on("click", function(){
document.documentElement.scrollTop = 0
document.body.scrollTop = 0
new html2canvas($('#container')[0], {
height: $('#container')[0].scrollHeight,
windowHeight: $('#container')[0].scrollHeight,
scale: 1,
useCORS: true,
}).then(canvas => {
let a = document.createElement('a')
a.href=canvas.toDataURL('image/png')
a.download = 'zqf'
a.click()
})
})
</script>
</body>
</html>