html2canvas 实现html生成图片

安装并引入html2canvas

import html2canvas from 'html2canvas'

interface loadparam {
  _loading: boolean;
  _scale: number;
  _imageData: string;
  _imageTimeout: number
  _useCORS: boolean;
  _cutDom: any
  _isDom: boolean;
  cut: () => void;
}

export class screenShot implements loadparam {
  _loading: boolean;
  _scale: number;
  _imageData: string;
  _imageTimeout: number
  _useCORS: boolean;
  _cutDom: any;
  _isDom: boolean;
  constructor(id: string, useCors: boolean, timeOut: number, scale?: number) {
    const dom = document.getElementById(id)
    // loading状态开始
    if (dom) {
      this._isDom = (typeof HTMLElement === 'object') ? dom instanceof HTMLElement : dom && typeof dom === 'object' && dom.nodeType === 1 && typeof dom.nodeName === 'string';
    }
    if (!this._isDom) {
      console.error("请输入正确的DOM参数");
      return;
    }
    this._cutDom = dom;
    this._scale = scale || window.devicePixelRatio;
    this._useCORS = useCors;
    this._imageTimeout = timeOut;
  }
  async cut() {
    if (!this._isDom) {
      console.error("DOM结构不存在");
      // loading状态取消
      return;
    }
    this._loading = true
    const canvasImage = await html2canvas(this._cutDom, {
      imageTimeout: this._imageTimeout,
      useCORS: this._useCORS,
      scale: this._scale,
    })
    if (canvasImage) {
      this._imageData = (canvasImage as any).toDataURL('image/png').split(',')[1]
      this._loading = false
    } else {
      this._imageData = ''
      this._loading = false
      // loading状态取消
     console.log('图片生成失败')
    }
    return this._imageData
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值