html2canvas
The role of html2canvas is to allow users to "screenshot" on the browser, but the working principle is not a real "screenshot", but to read the information of the target DOM node on the web page to draw the canvas, so some css attributes do not support , so not 100% accurate to the real display.
1 Install html2canvas
npm i html2canvas --save
2 Introducing html2canvas
import html2canvas from "html2canvas"
3 Call html2canvas to finish drawing
3.1 Get the dom area to be drawn
const card = document.getElementById("card");
3.2 Call the html2canvas function to complete the drawing
(1) Two parameters need to be passed in to the function, the first parameter is the dom element to be drawn, and the second parameter can pass in some configurations, such as the width and height of the canvas (especially if there are pictures that need to cross-domain , requires configuration). The return value is a canvas tag.
(2) Create a temporary a tag
(3) Add attributes to the label
(4) Finally remove the a tag
4 React uses html2canvas instance:
import {
Card, Button } from 'antd';
import html2canvas from "html2canvas";
const {
Meta } = Card;
const View = () => {
const handleClick = async () => {
// 获取需要渲染的dom元素
const card = document.getElementById("card");
// 调用 html2canvas
const canvas = await html2canvas(
card as HTMLElement,
{
width: 240, //设置canvas的宽度
height: 400, //设置canvas的高度
useCORS: true, // 【重要】开启跨域配置
allowTaint: true, // 允许跨域图片
}
)
// 创建一个临时的a标签
let a = document.createElement("a");
document.body.appendChild(a);
// 为a标签添加属性
a.setAttribute("href", canvas.toDataURL("image/jpg", 1.0)); //toDataUrl:将canvas画布信息转化为base64格式图片
a.setAttribute("download", "text.png"); //导出图片名称
a.setAttribute("target", "_self"); // 在当前窗口中打开
a.click(); // 同时调用a标签的点击事件
// 最后删除该临时节点
document.body.removeChild(a);
}
return (
<div style={
{
width: 240, margin: '100px auto' }}>
<Card
id='card'
hoverable
cover={
<img alt="example" src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png" />}
>
<Meta title="Europe Street beat" description="www.instagram.com" />
</Card>
<Button
type='primary'
onClick={
handleClick}
style={
{
width: 240, margin: '40px auto' }}
>
点击下载图片
</Button>
</div >
)
}
export default View