使用 html2canvas 將畫面儲存

Willy
5 min readApr 30, 2024

--

html2canvas 這套件可以將 html 轉換成 canvas,也就是可以將畫面轉換成圖片並存起來。

簡單使用範例:

html2canvas(element).then(canvas => {
// TODO SOMETHING
});

這篇會特別針對 IOS 裝置進行相關處理。

下面就來介紹如何實作:

安裝套件:

Install NPM

npm install --save html2canvas

Install Yarn

yarn add html2canvas

封裝 html2canvas :

import html2canvas from 'html2canvas';

export const useHtml2canvas = () => {
return (element, options = {}) => {
// 預設選項 避免在 IOS 裝置上異常
const defaultOptions = {
useCORS: true,
allowTaint: true,
ignoreElements: (e) => {
if ((e.tagName === 'A' && e.host !== window.location.host) || e.getAttribute('loading') === 'lazy') {
return true;
} else {
return false;
}
},
};

// 合併選項 確保可以帶入其它 options
const mergedOptions = {...defaultOptions, ...options};

// 使用 html2canvas
return html2canvas(element, mergedOptions);
};
}

封裝是確保以後如果換套件,就只要調整此處就可以了。

其中要特別注意的是下面這段,此套件在 IOS 裝置上會異常,所以需要帶入的 option,所以就在封裝階段直接代入:

const defaultOptions = {
useCORS: true,
allowTaint: true,
ignoreElements: (e) => {
if ((e.tagName === 'A' && e.host !== window.location.host) || e.getAttribute('loading') === 'lazy') {
return true;
} else {
return false;
}
},
};

參考 ISSUE: Stuck at “0ms Starting document clone” on IOS (Safari and Chrome) #3053

元件示意:

script :

// 封裝 html2canvas 的位置
import {useHtml2canvas} from 'src/composables';

const html2canvas = useHtml2canvas();

const saveCard = () => {
const card = document.querySelector('#card');

html2canvas(card).then((canvas) => {
// 轉換成 blob 在 IOS 裝置上檢視時才會正常
canvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;

// 設定下載的檔案名稱
a.download = 'fileNmae';
a.click();
a.remove();
}, 'image/png');
});
};

template:

<!-- 使用 quasar -->
<div class="row justify-center" id="card">
<q-card class="custom-card-list-item">
<q-card-section class="text-center q-pb-none q-px-lg">
<CustomButton
id="save-card-button"
class="custom-button-light full-width q-mb-md"
color="main-orange"
outlined
rounded
label="儲存"
@click="saveCard"
/>
<!-- 產生 Qrcode -->
<QrcodeVue
value="https://www.google.com/"
:size="175"
level="H"
/>
<div class="q-my-md separator-line"></div>
</q-card-section>
</q-card>
</div>

在 IOS 上的效果:

如果點選檢視會直接開啟圖片,點選下載就會儲存(存到檔案裡不會存到相簿)

官方文件

--

--

Willy
Willy

Written by Willy

前端修練筆記本,記錄一些踩雷及學習過程,希望能順便幫助一些,在學習或開發路上卡關的人們。

No responses yet