屏幕截图功能
实现方式:主要通过html2canvas
插件实现, html2canvas
版本^1.4.1
带水印截图
const getScreenShotWatermark = ( element: string, text: string, widthSpace: number, heightSpace: number ) => {
return html2canvas ( document. querySelector ( element) as HTMLElement) . then ( ( canvas ) => {
let canvasShot = document. createElement ( "canvas" ) ;
let context: any = canvasShot. getContext ( "2d" ) ;
canvasShot. setAttribute ( "width" , canvas. width. toString ( ) )
canvasShot. setAttribute ( "height" , canvas. height. toString ( ) )
context. drawImage ( canvas, 0 , 0 , canvas. width, canvas. height) ;
context. textAlign = "left" ;
context. textBaseline = "top" ;
context. font = "32px Microsoft Yahei" ;
context. fillStyle = "rgba(0, 0, 0, .2)" ;
context. translate ( - ( canvas. width / 2 ) , canvas. height / 2 ) ;
context. rotate ( ( Math. PI / 180 ) * - 45 ) ;
let num = ( canvas. height > canvas. width) ? canvas. height : canvas. width;
for ( let i = 0 ; i < num * 2 / heightSpace; i++ ) {
for ( let j = 0 ; j < num * 2 / widthSpace; j++ ) {
context. fillText ( text, j * widthSpace, i * heightSpace) ;
}
}
return Promise. resolve ( {
base64Url: canvasShot. toDataURL ( ) ,
width: canvas. width,
height: canvas. height
} )
} ) ;
}
不带水印截图
const getScreenShot = ( element: string ) => {
return html2canvas ( document. querySelector ( element) as HTMLElement) . then ( ( canvas ) => {
console. log ( canvas. width, canvas. height)
return Promise. resolve ( {
base64Url: canvas. toDataURL ( ) ,
width: canvas. width,
height: canvas. height
} )
} ) ;
}
最后生成文件魏base64编码的图片,通常需要将base64转为blob (防止生成文件过大)
base64转为blob
const dataURLtoBlob = ( dataURI: any ) => {
if ( dataURI) {
let arr = dataURI. split ( ',' )
let fileType = arr[ 0 ] . match ( / :(.*?); / )
let type
if ( fileType) {
type = fileType[ 1 ]
}
let binary = atob ( arr[ 1 ] )
let len = binary. length
let array = new Uint8Array ( len) ;
for ( let i = 0 ; i < len; i++ ) {
array[ i] = binary. charCodeAt ( i) ;
}
return new Blob ( [ array] , {
type } ) ;
}
}