<html>
<head>
<meta name="layout" content="main">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.4.0/html2canvas.min.js"></script>
<style>
.myjietuimg {
display: none;
}
</style>
<script type="text/javascript" >
$(document).ready( function(){
$(".example1").on("click", function(event) {
event.preventDefault();
html2canvas(document.body, {
allowTaint: true,
taintTest: false,
onrendered: function(canvas) {
canvas.id = "mycanvas";
//document.body.appendChild(canvas);
//生成base64图片数据
var dataUrl = canvas.toDataURL();
var newImg = document.createElement("img");
newImg.className = 'myjietuimg'
newImg.src = dataUrl;
document.body.appendChild(newImg);
alert('截图已生成,可以下载!')
}
});
});
});
</script>
<script>
function downloadImg(){
var img = document.getElementsByClassName('myjietuimg')[0]; // 获取要下载的图片
var url = img.src; // 获取图片地址
var a = document.createElement('a'); // 创建一个a节点插入的document
var event = new MouseEvent('click') // 模拟鼠标click点击事件
a.download = 'beautifulGirl' // 设置a节点的download属性值
a.href = url; // 将图片的src赋值给a节点的href
a.dispatchEvent(event) // 触发鼠标点击事件
}
</script>
</head>
<body style="padding: 30px;">
Hello World!
<div class="" style="background-color: #abc;">
奥利给,干了兄弟们
<br>关注我简书
</div>
<br>
<br>
<br>
<br>
<br>
<button class="example1">生成图片</button>
<button class="example2" onclick="downloadImg()">下载图片</button>
</body>
</html>