首先我們要把頁面連接放在ifram中,利用html2canvas和Canvas2Image對頁面進行轉換
<template>
<div style="height: 90vh;"><iframe src="XXX.html" frameborder="0" height="90%" id="frameid" width="100%"></iframe></div>
<div id="img" v-html="html"></div>
<button @click="toPic">下載圖片</button>
script
import html2canvas from 'html2canvas'
import Canvas2Image from './canvas2image/index'
const toPic = () => {
const ifram: any = document.getElementById('frameid')
const testbody: any = ifram.contentWindow.document.getElementById('testbody'); // textbody為XXX.html的body的id名稱
let canvas2 = document.createElement("canvas");
let w = parseInt(window.getComputedStyle(testbody).width);
let h = parseInt(window.getComputedStyle(testbody).height);
let context = canvas2.getContext("2d");
context?.scale(1,1);
canvas2.width = w;
canvas2.height = h;
html2canvas(testbody, {canvas: canvas2}).then((canvas: any) => {
const data = document.getElementById('img');
let img:any = Canvas2Image.convertToImage(canvas, w , h)
data?.appendChild(img)
// console.log(state.html)
})
}
Canvas2Image 下載地址 https://github.com/randreucetti/canvas2image
html2canvas 可以直接用npm安裝: npm install html2canvas -S