前端-如何將網頁保存爲圖片

問題重現

前臺生成一張複雜的海報,海報中包含外鏈圖片資源
問題難點

  1. 網頁由多個內容組成,前端不好將整個網頁保存爲圖片。當然,可以使用canvas進行繪圖(canvas語法參考
  2. 網頁中存在外鏈圖片資源

解決方案

概述(筆者以Vue爲例)

主要使用html2canvas,將頁面轉成canvas,從而轉成圖片。但使用html2canvas無法對外鏈圖片資源進行良好的處理,當然網上有很多跨域的解決方案,但是,很不好意思的是,網上處理的跨域方案,都不太適用。所以,我採用了image-to-base64,將圖片轉成base64格式,然後使用html2canvas,保存圖片。
綜上所述,本文主要處理的問題是,將含有外鏈圖片資源的網頁保存爲圖片.

安裝依賴包(使用npm)

圖片轉base64

import imageToBase64 from 'image-to-base64';
// this.postImage = url;
imageToBase64(this.postImage).then((baseUrl) => {
  this.postImage = `data:image/jpg;base64,${baseUrl}`;
}).catch((error) => {
  console.log(error);
});

下載圖片

  • html片段演示
<div ref='post'>
	海報內容
</div>
<a ref='down' style="display:none"></a>
  • js片段演示
drawPostImage() {
  html2canvas(this.$refs.post).then((canvas) => {
    const oImg = new Image();
    oImg.src = canvas.toDataURL(); // 導出圖片
    this.$refs.down.href = canvas.toDataURL();
    this.$refs.down.download = '下載圖片名稱';
    this.$refs.down.click();
  });
},
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章