vue将页面(dom元素)转换成图片,并保存到本地
1 npm install html2canvas --save
<template> <div class="QRCode-box"> <img id="imageWrapper" class="QRCode" src="@/assets/shun.png" alt="" /> <button color="#29c37f" type="info" @click="toSave" >保存二维码到手机</button > </div> </template> <script lang="ts"> import { defineComponent, onMounted, reactive, ref } from "vue"; import html2canvas from 'html2canvas' export default defineComponent({ setup() { const state = reactive<InitData1>({}); const toSave = () => { const candom: any = document.getElementById("imageWrapper") html2canvas(candom).then((canvas) => { let saveUrl = canvas.toDataURL("image/png"); //将图片元素转成base64图片 console.log(saveUrl) let aLink = document.createElement("a"); let blob = base64ToBlob(saveUrl); //将base64转成blob流 console.log(blob) let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); aLink.download = "二维码.jpg"; aLink.href = URL.createObjectURL(blob); //转成下载链接 aLink.click(); console.log(aLink.href); if (aLink.href) { alert('保存成功') } }); }; return { toSave, }; }, }); // 这里把图片转base64 function base64ToBlob(code: any) { let parts = code.split(";base64,"); let contentType = parts[0].split(":")[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); } </script>