一、生成海报图
vue项目中使用html2canvas插件,实现将编写的html代码转成可以保存的图片,只需要以下四步。
1、在vue项目中安装插件
npm i html2canvas
2、在需要使用到的页面引入html2canvas插件
import html2canvas from “html2canvas”;
3、按照设计图编写html代码
<div v-loading="loading" id="haibao_box" :class="loading ? 'noscroll' : ''" class="haibao_box noScrollBar" > <div id="poster"> <img id="bgc" src="https://imgbdb4.bendibao.com/xcxbdb/20239/21/2023921132708_70332.png" /> <div class="main"> <div class="job_name">{{ jobInfo.name }}</div> <div class="detail">{{ jobInfo.content }}</div> <div class="footer"> <img src="https://imgbdb4.bendibao.com/xcxbdb/20239/21/2023921140905_78679.png" id="code" /> <img id="code_bg" src="https://imgbdb4.bendibao.com/xcxbdb/20239/21/2023921132740_17597.png" /> </div> </div> </div> </div>
4、生成海报图
async getHaibao() { let htmlDom = document.getElementById("poster"); let that = this; html2canvas(htmlDom, { allowTaint: true, useCORS: true, scrollY: 0, scrollX: 0, }).then(function (canvas) { let haibaoBox = document.getElementById("haibao_box"); canvas.setAttribute("id", "canvas"); //给我们的海报画布一个id值,后面一键赋值用到 haibaoBox.appendChild(canvas); //新增到页面相应的位置 htmlDom.style.display = "none"; //将我们的html代码隐藏 that.loading = false; }); }
二、一键复制到剪切板
1、需要安装b64-to-blob
npm i b64-to-blob --save
2、具体使用
//页面中引入b64toBlob import b64toBlob from “b64-to-blob”;
给一个按钮绑定这个点击事件即可
copyCanvasImage() { // 获取canvas元素 let canvas = document.getElementById("canvas"); let imageData = canvas.toDataURL(); let str = imageData.replace(/data:image\/png;base64,/, ""); let file = b64toBlob(str, "image/png"); let clipboardItemInput = new window.ClipboardItem({ "image/png": file, }); window.navigator.clipboard.write([clipboardItemInput]); },
可能遇到的问题参考:
1.js 把图片url转化成base64
2.html2canvas (踩坑) 网络图片显示不出来&生成图片只有一半或者空白&文字显示不出来问题处理
标签:插件,vue,canvas,html2canvas,let,blob From: https://www.cnblogs.com/haoran5544/p/18086915