使用 html2canvas 将html元素保存为图片

html2canvas 的作用就是允许用户在浏览器上进行“截图”,但工作原理并不是真正的“截图”,而是读取网页上的目标DOM节点的信息来绘canvas ,所以某些css属性并不支持,因此不会 100% 精确到真实的显示。

1 安装 html2canvas

npm i html2canvas --save

2 引入 html2canvas

import html2canvas from "html2canvas"

3 调用 html2canvas,完成绘制

3.1 获取要绘制的dom区域

const card = document.getElementById("card");

3.2 调用 html2canvas 函数,完成绘制

​ (1) 函数中需要可以传入两个参数,第一个参数为需要绘制的dom元素,第二个参数可以传入一些配置,比如canvas的宽度与高度(特别是有图片需要跨域的,需要进行配置)。返回值是一个canvas画布标签。

​ (2) 创建一个临时a标签

​ (3) 为标签添加属性

​ (4) 最后移除a标签

4 React 使用 html2canvas 实例:

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

猜你喜欢

转载自blog.csdn.net/qq_53931766/article/details/128033879