uni-app 中使用 html2canvas 生成图片
1.在项目中安装 html2canvas 插件
npm install html2canvas -D
在需要生成图片的页面中引入 html2canvas 插件
不过此时需要在 页面中新建一个 script 节点,将 lang 属性设置为renderjs
如对 renderjs 不了解,可看下uniapp 官网的说明
2.效果
3.编写生成图片的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | <template> <view class = "demo" > <button @click= "text.onClick" > 生成图片 </button> <view class = "canvas-module" id= "pagePoster" > <view class = "user-info" > <view class = "user-detail" > <view class = "user-name" >测试</view> <view class = "user-num" >12345678901</view> </view> </view> <view class = "section" > <view class = "title" >简单介绍</view> <view class = "detail-text" > 把我生成图片 </view> </view> </view> <image :src= "posterUrl" style= "width: 100%; height: 300px;" ></image> </view> </template> <!-- 普通的script标签 --> <script> export default { data(){ return { posterUrl: "" , } }, methods:{ // 获取生成的base64 图片路径 receiveRenderData(val) { console.log( "调用方法成功" ) var posterUrl = val.replace(/[]/g, '' ); // 去除base64位中的空格 console.log(posterUrl) this .posterUrl = posterUrl; }, } } </script> <!-- renderjs的script标签 --> <script module= "text" lang= "renderjs" > import html2canvas from 'html2canvas' export default { methods:{ // 生成图片需要调用的方法 onClick( event , ownerInstance) { //console.log("22222") setTimeout(() => { const dom = document.getElementById( 'pagePoster' ) // 需要生成图片内容的 dom 节点 html2canvas(dom, { width: dom.clientWidth, //dom 原始宽度 height: dom.clientHeight, scrollY: 0, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0 scrollX: 0, useCORS: true , //支持跨域 // scale: 2, // 设置生成图片的像素比例,默认是1,如果生成的图片模糊的话可以开启该配置项 }).then((canvas) => { // 生成成功 console.log( "生成成功" ) // html2canvas 生成成功的图片链接需要转成 base64位的url ownerInstance.callMethod( 'receiveRenderData' , canvas.toDataURL( 'image/png' )) }). catch (err=>{ console.log( "生成图片失败" ); }) }, 300) } } } </script> |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步