参照:
html2canvas截取div内容下载解决图片模糊和图片偏移
demo实现
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
background: #f2f2f2;
}
#box {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#cBox {
width: 80%;
height: 60%;
border: 1px solid #c00;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.img {
max-width: 100%;
}
.img1 {
height: 20%;
}
.img2 {
height: 30%;
}
.img3 {
height: 20%;
}
p {
padding: 10px;
}
button {
background-color: #ccc;
padding: 10px 20px;
outline: 0;
border-radius: 6px;
margin-top: 50px;
color: #c00;
font-size: 17px;
}
#saveImg {
position: absolute;
border: 1px solid #00f;
width:80%;
height: 60%;
margin-top: -50px;
opacity: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="cBox">
<img class="img img1" src="../imgs/20.png" alt="">
<img class="img img2" src="../imgs/bq_60.png" alt="">
<p>测试div保存图片功能</p>
<img class="img img3" src="../imgs/btn_again.png" alt="">
</div>
<button id="btn">长按保存图片</button>
<img id="saveImg" alt="">
</div>
<script type="text/javascript">
var box = document.getElementById("box");
var el = document.getElementById("cBox");
var saveImg = document.getElementById("saveImg");
var canvas = document.createElement("canvas");
var scale = window.devicePixelRatio;
var ctx=canvas.getContext("2d")
var rect = el.getBoundingClientRect(); //获取元素相对于视察的偏移量
var w = el.offsetWidth;
var h = el.offsetHeight;
canvas.width = w * scale;
canvas.height = h * scale;
canvas.style.width = w ;
canvas.style.height = h ;
ctx.scale(scale, scale);
ctx.translate(-rect.left,-rect.top); //设置context位置,值为相对于视窗的偏移量负值,让图片复位
html2canvas(el, {
scale: scale,
canvas: canvas,
width: w,
height: h,
logging: false,
background: "#f2f2f2",
useCORS: true
}).then(function (canvas) {
var dataUrl = canvas.toDataURL("jpeg");
saveImg.src=dataUrl;
});
</script>
</body>
</html>
效果图如下(红框位置为需要保存的内容)
网友评论