通过js插件html2canvas实现
a.下载html2canvas.js(github地址:https://github.com/niklasvh/html2canvas/releases/、官网地址:http://html2canvas.hertzen.com/)
b.个人需求实现
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no" />
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>截图功能</title>
</head>
<script src="/js/jquery.js"></script>
<body>
<!-- 放置图片容器 -->
<div id="canvasContainer">
<div class="poster_box">
<img src="https://img-blog.csdnimg.cn/20200605172234757.png" alt="">
</div>
</div>
</body>
</html>
<script src="/html2canvas/html2canvas.js"></script>
<script>
// 创建一个新的canvas
let Canvas = document.createElement('canvas');
let width = document.getElementById('canvasContainer').width; // 画布指定区域的宽
let height = document.getElementById('canvasContainer').height; // 画图指定区域的高
let scale = DPR(); // 设备的devicePixelRadio
// 将Canvas画布放大scale倍,然后放在小的屏幕里,解决模糊问题
Canvas.width = width * scale;
Canvas.height = height * scale;
Canvas.getContext('2d').scale(scale, scale);
html2canvas(document.getElementById('canvasContainer'),{
canvas: Canvas,
scale,
logging: true,
useCORS:true, // 允许使用跨域图片
allowTaint: false, // 不允许跨域图片污染画布
width: width + 'px',
height: height + 'px',
}).then(function(canvas) {
let context = canvas.getContext('2d');
// 关闭抗锯齿形
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
// canvas转化为图片
let canvasImg = canvas2Image(canvas, canvas.width, canvas.height);
document.body.appendChild(canvasImg);
$(canvasImg).css('width','100%')
.css('height','100%')
.css('position','absolute')
.css('top','0')
.css('left','0')
.css('right','0')
.css('bottom','0')
.css('opacity','0');
})
/**
* 画步转换成图片
*/
function canvas2Image(canvas, width, height) {
let retCanvas = document.createElement('canvas');
let retCtx = retCanvas.getContext('2d');
retCanvas.width = width;
retCanvas.height = height;
retCtx.drawImage(canvas, 0, 0, width, height, 0, 0, width, height);
let img = document.createElement('img');
img.src = retCanvas.toDataURL('image/jpeg'); // 可以根据需要更改格式
return img;
}
/**
* 根据window.devicePixelRatio获取像素比
*/
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
</script>
c.参考实现文档
https://segmentfault.com/a/1190000021275782
https://www.jianshu.com/p/41ff1d103d3f(JS获取图片实际高度)