1.安装 html2canvas
npm install html2canvas --save
2.案例
import React, { Component } from 'react';
import html2canvas from 'html2canvas';
class Sales extends Component {
constructor(props) {
super(props);
this.state = {
isPrint: false,
isInfo: false,
};
}
componentDidMount () {
const maxBoxDemo = document.getElementById('maxBox');
const heights = document.body.clientHeight;
maxBoxDemo.style.height = heights + 'px';
}
DPR = () => {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
} else {
return 1;
}
}
parseValue = (value) => {
return parseInt(value, 10);
}
drawCanvas = async () => {
// 获取想要转换的 DOM 节点
const dom = document.getElementById('printHtml');
// const dom = document.querySelector('printHtml');
const box = window.getComputedStyle(dom);
// DOM 节点计算后宽高
const width = this.parseValue(box.width);
const height = this.parseValue(box.height);
// 获取像素比-防止模糊
const scaleBy = this.DPR();
// 创建自定义 canvas 元素
const canvas = document.createElement('canvas');
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 获取画笔
const context = canvas.getContext('2d');
// 将所有绘制内容放大像素比倍
context.scale(scaleBy, scaleBy);
// 将自定义 canvas 作为配置项传入,开始绘制
return await html2canvas(dom, { canvas }).then(canvas => {
//document.querySelector("#canvasContainer").appendChild(canvas);
//return canvas.toDataURL("image/png");
return canvas.toDataURL("image/png");
});
};
render () {
return (
<div id='printHtml'>
<div onClick={this.drawCanvas}>dowmloadImg</div>
</div>
);
}
}
export default Sales;
本文介绍了如何在React应用中使用html2canvas库来实现网页内容的截图功能。通过安装html2canvas,设置DOM元素样式,计算宽高比例,然后在组件挂载后绘制到canvas上,并转换为图片数据URL。点击按钮即可触发截图操作。
1418

被折叠的 条评论
为什么被折叠?



