现在需要做一个功能:
一个html页面有多个div,每个div里面都含有用echarts画的图表,现在要对这个html页面进行自动截图
我在网上找到了一个方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>htmltopic</title>
<script type="text/javascript" src="js/jquery-2.2.1.min.js"></script>
<script type="text/javascript" src="js/html2canvas.min.js"></script>
<style>
* {
margin: 0;
}
.main{
height: 100%;
width: 100%;
}
body{
background-color: #2e6da4;
}
.test1 {
width: 50%;
height: 100%;
text-align: center;
line-height: 100px;
/*background-color: #87CEEB;*/
display: inline-block;
vertical-align: top;
}
canvas {
/*margin-right: 5px;*/
}
.down {
float: left;
margin: 40px 10px;
}
.down2 {
float: left;
margin: 40px 30px;
}
</style>
</head>
<body id="test">
<div class="main">
<div class="test1" >测试</div>
<div class="test1" >测试</div>
<!--<div class="test1" id="test1">测试</div>-->
</div>
<div><a class="down" href="" download="downImg">下载</a>
</div>
<div><a class="down2" href="" download="downImg">下载2</a></div>
<script>
//直接选择要截图的dom,就能截图,但是因为canvas的原因,生成的图片模糊
//html2canvas(document.querySelector('div')).then(function(canvas) {
// document.body.appendChild(canvas);
//});
//创建一个新的canvas
var canvas2 = document.createElement("canvas");
let
_canvas = document.querySelector('#test');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
canvas2.width = w * 2;
canvas2.height = h * 2;
canvas2.style.width = w + "px";
canvas2.style.height = h + "px";
//可以按照自己的需求,对context的参数修改,translate指的是偏移量
// var context = canvas.getContext("2d");
// context.translate(0,0);
var context = canvas2.getContext("2d");
context.scale(2, 2);
html2canvas(document.querySelector('#test'), { canvas: canvas2 }).then(function(canvas) {
//document.body.appendChild(canvas);
//canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载
document.querySelector(".down").setAttribute('href', canvas.toDataURL());
});
</script>
<script language="javascript">
//这是另一种写法
$(function () {
$(".down2").click(function () {
html2canvas($("#test")).then(function (canvas) {
var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
window.location.href = imgUri; // 下载图片
});
//html2canvas($('.tongxingzheng_bg'), {
// onrendered: function (canvas) {
// var data = canvas.toDataURL("image/png");//生成的格式
// //data就是生成的base64码啦
// alert(data);
// }
//});
});
});
</script>
</body>
</html>
截的图如下:
问题来了,上面只是简单地html页面,当我在html页面放echarts时,就出现问题了
html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- 在IE运行最新的渲染模式 -->
<meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 初始化移动浏览显示