import { Injectable , ElementRef , OnInit } from '@angular/core' ; import { MatDialog } from '@angular/material/dialog' ; import { MatSnackBar } from '@angular/material/snack-bar' ; import * as html2canvas from 'html2canvas' ; import { NotaddScreenshotComponent } from '@notadd/components/screenshot/screenshot.component' ; @ Injectable ( ) export class NotaddScreenshotService implements OnInit { constructor ( private dialog , private snackBar ) { } ngOnInit ( ) { } capture ( element ) { this . captureDom ( element ) . then ( canvas => { this . dialog . open ( NotaddScreenshotComponent , { data : { canvas } } ) ; } , err => { this . snackBar . open ( err , '知道了' , { duration : 3000 , horizontalPosition : 'center' , verticalPosition : 'top' } ) ; } ) ; } private captureDom ( dom ) { const { width , height , offsetTop } = dom ; const canvas = document . createElement ( 'canvas' ) ; canvas . id = 'capture-canvas' ; const context = canvas . getContext ( '2d' ) ; const scaleBy = this . getPixelRatio ( context ) ; canvas . width = width * scaleBy ; canvas . height = ( height + offsetTop ) * scaleBy ; context . scale ( scaleBy , scaleBy ) ; const options = { allowTaint : true , useCORS : true , tainttest : true , scale : scaleBy , canvas , logging : false , width , height } ; return html2canvas ( dom , options ) ; } private getPixelRatio ( context ) { const backingStore = context . backingStorePixelRatio || context . webkitBackingStorePixelRatio || context . mozBackingStorePixelRatio || context . msBackingStorePixelRatio || context . oBackingStorePixelRatio || context . backingStorePixelRatio || 1 ; return ( window . devicePixelRatio || 1 ) / backingStore ; } }