安装并引入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
}
}