uniapp 使用canvas 画海报,有手粘贴即可用(拆成组件了,看后面)

2024-02-02 19:20

本文主要是介绍uniapp 使用canvas 画海报,有手粘贴即可用(拆成组件了,看后面),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

1.直接使用

html部分

<view  ="doposter">下载海报</view>
<canvas canvas-id="myCanvas" type='2d' style="width: 370px; height: 550px;opcity:0;position: fixed;z-index:-1;" id="myCanvas" />

js 部分

 drawBackground() {const canvasId   = 'myCanvas'const ctx        = uni.createCanvasContext(canvasId, this)const title      = this.titleconst goodsCover = this.selcetShareImgUrl // 分享商品图片 需要换成自己的产品图片const goodsTitle = this.goods.name // 商品名称const goodsPrice = '¥ '+this.goods.original_priceconst des1       = '① 长按识别二维码'const des2       = '② 查看商品详情'const qrcode     = this.goods.share.code //二维码地址 需要换成自己的二维码//  绘制背景图ctx.setFillStyle('#fff')ctx.fillRect(0, 0, 370, 550)// 字体颜色ctx.setFontSize(17)ctx.setFillStyle('#111')ctx.fillText(title, 50, 39.9)ctx.fillText(title, 49.9, 40)ctx.fillText(title, 50,40)ctx.fillText(title, 50, 40.1)ctx.fillText(title, 50.1, 40.1)// 商品名称 且拦截页面文字长度let titleGoods = this.goods.name.split('').length <= 20 ? this.goods.name : this.goods.name.substring(0,18)+' ...'ctx.setFontSize(16)ctx.setFillStyle('#111')ctx.fillText(titleGoods , 30 , 420)// 商品价格ctx.setFontSize(18)ctx.setFillStyle('#f36d00')ctx.fillText(goodsPrice, 29.9, 450)ctx.fillText(goodsPrice, 30,450)ctx.fillText(goodsPrice, 30, 450.1)ctx.fillText(goodsPrice, 30.1, 450)//  二维码描述ctx.setFontSize(13)ctx.setFillStyle('#999')ctx.fillText(des1, 30, 490)ctx.setFontSize(13)ctx.setFillStyle('#999')ctx.fillText(des2, 30, 520)uni.downloadFile({url:goodsCover,success: (res) => {// 商品图片ctx.drawImage(res.tempFilePath, 30, 70, 310, 310)//  二维码ctx.drawImage(qrcode, 240, 420, 110, 110)ctx.draw(false, () => {uni.canvasToTempFilePath({canvasId: canvasId,success: (res) => {console.log('临时图片路径:', res.tempFilePath);uni.saveImageToPhotosAlbum({filePath: res.tempFilePath,success: () => {uni.hideLoading()uni.showModal({title: '提示',content: ' 图片保存成功',showCancel: false,confirmText: '知道了',confirmColor: '#f36d00',success: res => {uni.navigateBack()}})}})},fail: (error) => {console.error('转化图片失败:', error);}},this)});}})},async doposter() {uni.showLoading({title: '正在生成海报'});await this.drawBackground();},

2.拆分成组件方便使用组件

<template><view><canvas canvas-id="myCanvas" type='2d' style="width: 370px; height: 550px; opacity:0;position: fixed;z-index:-1;" id="myCanvas"  /></view>
</template><script>export default {name:"shareQrcode",data() {return {canvasId:'myCanvas',canvasImgPath :''};},props:{shareInfo:{type:Object,default:() => {return{bgColor    : '#fff',title      : '看到这个第一眼就想分享给你',goodsCover : 'http://storage.zh.shangkelian.cn/images/2022/01/07/08e732962fc55a2a196f193c94c22cf9.png', //  换自己图片goodsTitle : '大菠萝大菠萝大菠萝蜜菠萝蜜大菠萝大菠萝大菠萝蜜菠萝蜜', // 商品名称goodsPrice : '¥ 123',des1       : '① 长按识别二维码',des2       : '② 查看商品详情',qrcode     : require('@/static/ewm.png'), //二维码地址}}}},methods:{drawBackground() {const canvasId   = this.canvasIdconst ctx        = uni.createCanvasContext(canvasId, this)const bgColor    = this.shareInfo.bgColorconst title      = this.shareInfo.titleconst goodsCover = this.shareInfo.goodsCoverconst goodsTitle = this.shareInfo.goodsTitleconst goodsPrice = this.shareInfo.goodsPriceconst des1       = this.shareInfo.des1const des2       = this.shareInfo.des2const qrcode     = this.shareInfo.qrcode//  绘制背景图ctx.setFillStyle(bgColor)ctx.fillRect(0, 0, 370, 550)// 字体颜色ctx.setFontSize(17)ctx.setFillStyle('#111')ctx.fillText(title, 50, 39.9)ctx.fillText(title, 49.9, 40)ctx.fillText(title, 50,40)ctx.fillText(title, 50, 40.1)ctx.fillText(title, 50.1, 40.1)// 商品名称let titleGoods = goodsTitle.split('').length <= 20 ? goodsTitle : goodsTitle.substring(0,18)+' ...'ctx.setFontSize(16)ctx.setFillStyle('#111')ctx.fillText(titleGoods , 30 , 420)// 商品价格ctx.setFontSize(18)ctx.setFillStyle('#f36d00')ctx.fillText(goodsPrice, 29.9, 450)ctx.fillText(goodsPrice, 30,450)ctx.fillText(goodsPrice, 30, 450.1)ctx.fillText(goodsPrice, 30.1, 450)//  二维码描述ctx.setFontSize(13)ctx.setFillStyle('#999')ctx.fillText(des1, 30, 490)ctx.setFontSize(13)ctx.setFillStyle('#999')ctx.fillText(des2, 30, 520)uni.downloadFile({url:goodsCover,success: (res) => {// 商品图片ctx.drawImage(res.tempFilePath, 30, 70, 310, 310)//  二维码ctx.drawImage(qrcode, 250, 440, 90, 90)// #ifdef MP-WEIXINconsole.log('...........downloadFile............')wx.showModal({title:'作者友情提示',content:'小程序端生成二维码功能暂未完善,作者会尽快完成的!',showCancel:false,confirmText:'我已知道',confirmColor:'green'})uni.hideLoading()// 保存海报 // uni.canvasToTempFilePath({//     canvasId: canvasId,//     success: (res) => {//         console.log(res)//         this.canvasImgPath = res.tempFilePath//         // this.save()//     },//     fail: (error) => {//         console.error('转化图片失败:', error)//     }// },this)return// #endif// app 和 h5  调用这个方法ctx.draw(false, () => {uni.canvasToTempFilePath({canvasId: canvasId,success: (res) => {this.canvasImgPath = res.tempFilePaththis.save()},fail: (error) => {console.error('转化图片失败:', error)}},this)})}})},//   生成本地海报async doposter() {uni.showLoading({title: '正在生成海报'});await this.drawBackground()},//  获取权限( 只适用于小程序)saveAlbum(){wx.hideLoading()//获取权限保存相册uni.getSetting({//获取用户的当前设置success:(res)=> {console.log(res.authSetting['scope.writePhotosAlbum'])if(res.authSetting['scope.writePhotosAlbum']){//验证用户是否授权可以访问相册this.save();}else{uni.authorize({//如果没有授权,向用户发起请求scope: 'scope.writePhotosAlbum',success:()=> {this.save();},fail:()=>{uni.showToast({title:"请打开保存相册权限,再点击保存相册分享",icon:"none",duration:3000});setTimeout(()=>{uni.openSetting({//调起客户端小程序设置界面,让用户开启访问相册success:(res2)=> {// console.log(res2.authSetting)}});},3000);}})}},fail: (error) => {console.log(error)}})},// 保存海报save(){// #ifdef APP uni.saveImageToPhotosAlbum({filePath: this.canvasImgPath,success: () => {uni.hideLoading()uni.showModal({title: '提示',content: ' 图片保存成功',showCancel: false,confirmText: '知道了',confirmColor: '#f36d00',success: res => {uni.navigateBack()}})}})// #endif// #ifdef H5uni.hideLoading()var oA = document.createElement("a");oA.download = ''; // 设置下载的文件名,默认是'下载'oA.href = this.canvasImgPath;document.body.appendChild(oA);oA.click();oA.remove(); // 下载之后把创建的元素删除// #endif// #ifdef MP-WEIXINconsole.log('wx',this.canvasImgPath)// uni.saveImageToPhotosAlbum({//     filePath: this.canvasImgPath,//     success: () => {//         uni.hideLoading()//         uni.showModal({//             title: '提示',//             content: ' 图片保存成功',//             showCancel: false,//             confirmText: '知道了',//             confirmColor: '#f36d00',//             success: res => {//                 uni.navigateBack()//             }//         })//     }// })// #endif}}}
</script><style></style>

父组件中引用

<template><view><shareQrcode ref="shareQrcode" :shareInfo="shareInfo"/><button type="primary" ="$refs.shareQrcode.doposter()">二维码生成图片</button>   </view>
</template><script>import shareQrcode from '@/components/share-qrcode.vue'export default {data() {return {shareInfo:{// 背景色bgColor    : '#fff',// 标题title      : '看到他的第一时间就忍不住分享给你',//  商品图goodsCover : 'http://storage.zh.shangkelian.cn/images/2022/01/07/08e732962fc55a2a196f193c94c22cf9.png', // 商品名称goodsTitle : '大菠萝大菠萝大菠萝蜜菠萝蜜大菠萝大菠萝大菠萝蜜菠萝蜜', //  商品价格goodsPrice : '¥ 123', // 二维码描述des1       : '① 长按识别二维码', // 二维码描述des2       : '② 查看商品详情', //二维码地址qrcode     : require('@/static/ewm.png'), }}},components:{shareQrcode},}
</script><style>
</style>

这篇关于uniapp 使用canvas 画海报,有手粘贴即可用(拆成组件了,看后面)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/671701

相关文章

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件