vue3實現把html頁面轉為圖片


首先我們要把頁面連接放在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

pdf轉圖片同樣適用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM