第一步
可使用npm install --save html2canvas
或yarn add html2canvas
进行安装,也可以点击下图所指位置进行代码的复制,在自己的项目中创建html2canvas.min.js文件,并将复制内容粘贴到创建的文件中。
引入js文件<script src="js/html2canvas.min.js"></script>
本例采用这种方式。
第二步
html:
<div>
<div class="reportContaint">要截图的部分</div>
<div>
<button
type="button"
style="width: 100%"
class="saveImage"
>
生成图片
</button>
</div>
<div class="motai" id="mo">
<img class="motaiimg" id="moimg">
<div id="caption">长按保存图片</div>
</div>
</div>
css:
#mo {
display:none;
/*隐藏*/
width:100%;
height:100%;
position:fixed;
overflow:auto;
background-color:rgba(0,0,0,0.7);
top:0;
right:0;
z-index:1;
}
#moimg {
display:block;
margin:25px auto;
width:60%;
max-width:750px;
}
#caption {
text-align:center;
margin:15px auto;
width:60%;
max-height:750px;
font-size:20px;
color:#ccc;
}
#moimg,#caption {
-webkit-animation:first 1s;
-o-animation:first 1s;
animation:first 1s;
}
@keyframes first {
from {
transform:scale(0.1);
}
to {
transform:scale(1);
}
}
为按钮添加点击事件
$(".saveImage").click(function () {
html2canvas(jQuery(".reportContaint")[0], {
allowTaint: true,
useCORS: true,
}).then(function (canvas) {
document.getElementById('mo').style.display='block'
$("#moimg").attr("src", canvas.toDataURL()); // 生成的图片
});
});
//点击空白处关闭模态框
var span1 = document.getElementById('mo');
span1.onclick = function(){
span1.style.display = "none"
}