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

2024-02-02 19:20

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

在这里插入图片描述

1.直接使用

html部分

<view  @click="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" @click="$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

相关文章

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

在ASP.NET项目中如何使用C#生成二维码

《在ASP.NET项目中如何使用C#生成二维码》二维码(QRCode)已广泛应用于网址分享,支付链接等场景,本文将以ASP.NET为示例,演示如何实现输入文本/URL,生成二维码,在线显示与下载的完整... 目录创建前端页面(Index.cshtml)后端二维码生成逻辑(Index.cshtml.cs)总结

Spring Integration Redis 使用示例详解

《SpringIntegrationRedis使用示例详解》本文给大家介绍SpringIntegrationRedis的配置与使用,涵盖依赖添加、Redis连接设置、分布式锁实现、消息通道配置及... 目录一、依赖配置1.1 Maven 依赖1.2 Gradle 依赖二、Redis 连接配置2.1 配置 R

Python WSGI HTTP服务器Gunicorn使用详解

《PythonWSGIHTTP服务器Gunicorn使用详解》Gunicorn是Python的WSGI服务器,用于部署Flask/Django应用,性能高且稳定,支持多Worker类型与配置,可处... 目录一、什么是 Gunicorn?二、为什么需要Gunicorn?三、安装Gunicorn四、基本使用启

MySQL 临时表创建与使用详细说明

《MySQL临时表创建与使用详细说明》MySQL临时表是存储在内存或磁盘的临时数据表,会话结束时自动销毁,适合存储中间计算结果或临时数据集,其名称以#开头(如#TempTable),本文给大家介绍M... 目录mysql 临时表详细说明1.定义2.核心特性3.创建与使用4.典型应用场景5.生命周期管理6.注

python urllib模块使用操作方法

《pythonurllib模块使用操作方法》Python提供了多个库用于处理URL,常用的有urllib、requests和urlparse(Python3中为urllib.parse),下面是这些... 目录URL 处理库urllib 模块requests 库urlparse 和 urljoin编码和解码

使用Python提取PDF大纲(书签)的完整指南

《使用Python提取PDF大纲(书签)的完整指南》PDF大纲(Outline)​​是PDF文档中的导航结构,通常显示在阅读器的侧边栏中,方便用户快速跳转到文档的不同部分,大纲通常以层级结构组织,包含... 目录一、PDF大纲简介二、准备工作所需工具常见安装问题三、代码实现完整代码核心功能解析四、使用效果控

C#异步编程ConfigureAwait的使用小结

《C#异步编程ConfigureAwait的使用小结》本文介绍了异步编程在GUI和服务器端应用的优势,详细的介绍了async和await的关键作用,通过实例解析了在UI线程正确使用await.Conf... 异步编程是并发的一种形式,它有两大好处:对于面向终端用户的GUI程序,提高了响应能力对于服务器端应

MySQL慢查询工具的使用小结

《MySQL慢查询工具的使用小结》使用MySQL的慢查询工具可以帮助开发者识别和优化性能不佳的SQL查询,本文就来介绍一下MySQL的慢查询工具,具有一定的参考价值,感兴趣的可以了解一下... 目录一、启用慢查询日志1.1 编辑mysql配置文件1.2 重启MySQL服务二、配置动态参数(可选)三、分析慢查

MYSQL中information_schema的使用

《MYSQL中information_schema的使用》information_schema是MySQL中的一个虚拟数据库,用于提供关于MySQL服务器及其数据库的元数,这些元数据包括数据库名称、表... 目录关键要点什么是information_schema?主要功能使用示例mysql 中informa