一、安裝html2canvas
npm install --save html2canvas
官方網站
https://html2canvas.hertzen.com/
二、在須要的組件中引入html2canvas
// 導入整個模塊的內容
import html2canvas from 'html2canvas';
三、定義方法,將數據轉換爲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}}" />
四、將圖片下載到本地,定義轉換圖片格式方法。
下載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);
} );