1、安裝html2canvas npm install --save html2canvas 官方網站 https://html2canvas.hertzen.com/ 2、在需要的組件中引入html2canvas // 導入整個模塊的內容 import html2canvas from 'html2canvas'; 3、定義方法,將數據轉換為canvas
let element:any = document.querySelector("#mainTable");
//要顯示圖片的img標簽
let image:any = document.querySelector('#img');
//調用html2image方法
html2canvas(element).then( canvas=> {
this.canvasImg = canvas.toDataURL("image/png");
})
// 然后給初始化的public canvasImg: any = ""; 復制,他就是圖片地址。 // 展示圖片 <img src="{{canvasImg}}" />
4、將圖片下載到本地,定義轉換圖片格式方法。 下載cordova插件
$ ionic cordova plugin add cordova-plugin-photo-library --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="To choose photos" $ npm install --save @ionic-native/photo-library 導入 import { PhotoLibrary } from '@ionic-native/photo-library'; this.photoLibrary.requestAuthorization().then(() => { this.photoLibrary.saveImage(this.canvasImg , 'NewPayQr', '').then((libraryItem)=>{ this.commonUtils.alertCommon('', this.translateObj.saveImgSucc); // alert(JSON.stringify(libraryItem)); console.log(libraryItem.id); // ID of the photo console.log(libraryItem.photoURL); // Cross-platform access to photo console.log(libraryItem.thumbnailURL);// Cross-platform access to thumbnail console.log(libraryItem.fileName); console.log(libraryItem.width); console.log(libraryItem.height); console.log(libraryItem.creationDate); console.log(libraryItem.latitude); console.log(libraryItem.longitude); console.log(libraryItem.albumIds); // array of ids of appropriate AlbumItem, only of includeAlbumsData was used }); }).catch(err =>{ console.log('permissions weren\'t granted') this.commonUtils.alertCommon('',this.translateObj.saveImgFail+','+err); } );