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.title
                const goodsCover = this.selcetShareImgUrl // 分享商品图片 需要换成自己的产品图片
                const goodsTitle = this.goods.name // 商品名称
                const goodsPrice = '¥ '+this.goods.original_price
                const 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.canvasId
                const ctx        = uni.createCanvasContext(canvasId, this)
                const bgColor    = this.shareInfo.bgColor
                const title      = this.shareInfo.title
                const goodsCover = this.shareInfo.goodsCover
                const goodsTitle = this.shareInfo.goodsTitle
                const goodsPrice = this.shareInfo.goodsPrice
                const des1       = this.shareInfo.des1
                const des2       = this.shareInfo.des2
                const 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-WEIXIN
                            console.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.tempFilePath
                                    this.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 H5
                    uni.hideLoading()
                    var oA = document.createElement("a");
                    oA.download = ''; // 设置下载的文件名,默认是'下载'
                    oA.href = this.canvasImgPath;
                    document.body.appendChild(oA);
                    oA.click();
                    oA.remove(); // 下载之后把创建的元素删除
               // #endif
               
                // #ifdef MP-WEIXIN
                    console.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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/363939.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【数据结构】(三)树Tree

目录 1、基本概念 2、二叉树Binary Tree 3、树、森林与二叉树的转换 4、赫夫曼树Huffman Tree与赫夫曼编码Huffman Coding 1、基本概念 &#xff08;1&#xff09;树&#xff08;Tree&#xff09;是 n&#xff08;n ≥\geq 1&#xff09;个节点的有限集&#xff0c;n 0时称…

JavaScript基础(一)旧版基础笔记总结

开新藩&#xff08;虽然博主早以前已经学过了&#xff09;&#xff0c;从0开始复习JS&#xff0c;一方面应对毕设&#xff0c;一方面后期可能找找实习&#xff0c;一方面复试可能也会涉及到吧&#xff0c;说起这个最近越等越焦虑QAQ&#xff0c;还要一个月才出分呢...... 本帖先…

HubSpot CRM是什么?有什么功能和特点?

HubSpot CRM&#xff08;Customer Relationship Management&#xff0c;客户关系管理&#xff09;是一款由HubSpot公司开发的免费的、云端的CRM软件。HubSpot CRM致力于帮助企业更好地管理客户关系&#xff0c;提高销售效率&#xff0c;同时通过集成多个营销、销售和服务工具&a…

springboot mybatis-plus 项目分层笔记

整体定义 config: 配置项&#xff0c;包含configuration注解 constants: 常量类enums: 枚举 exceptions: 全局异常处理&#xff0c;自定义异常&#xff0c;RestControllerAdvice 注解 fia3: 三大器依据执行顺序&#xff1a;过滤器filter、拦截器interceptor、切面aop 简称 fia…

中科大计网学习记录笔记(一):Internet | 网络边缘

计算机网络 前言&#xff1a; 学习视频&#xff1a;中科大郑烇、杨坚全套《计算机网络&#xff08;自顶向下方法 第7版&#xff0c;James F.Kurose&#xff0c;Keith W.Ross&#xff09;》课程 该视频是B站非常著名的计网学习视频&#xff0c;但相信很多朋友和我一样在听完前面…

时间序列预测 —— LSTM模型

时间序列预测 —— LSTM模型 1. 引言 时间序列预测是指在给定的历史时间序列数据上,使用模型来预测未来的数值。长短时记忆网络(Long Short-Term Memory, LSTM)是一种深度学习模型,广泛应用于时间序列预测任务。本文将介绍LSTM模型的理论基础、相关公式,分析其优缺点,并…

牛客,OR36 链表的回文结构,快慢指针和反转链表的实践

链表的回文结构_牛客题霸_牛客网 (nowcoder.com) 还是比较简单的&#xff0c;主要分为三个步骤&#xff0c;两种需掌握的函数实现 目录 主要思路过程&#xff0c;1&#xff0c;找到中间结点&#xff0c;2&#xff0c;反转中间结点往后的结点&#xff0c;3&#xff0c;遍历比…

ChatGPT 被曝泄露私密对话;美国 AI 企业一天蒸发 1.3 万亿市值丨 RTE 开发者日报 Vol.139

开发者朋友们大家好&#xff1a; 这里是 「RTE 开发者日报」 &#xff0c;每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享 RTE &#xff08;Real Time Engagement&#xff09; 领域内「有话题的 新闻 」、「有态度的 观点 」、「有意思的 数据 」、「有思考的 文…

【产业实践】使用YOLO V5 训练自有数据集,并且在C# Winform上通过onnx模块进行预测全流程打通

使用YOLO V5 训练自有数据集,并且在C# Winform上通过onnx模块进行预测全流程打通 效果图 背景介绍 当谈到目标检测算法时,YOLO(You Only Look Once)系列算法是一个备受关注的领域。YOLO通过将目标检测任务转化为一个回归问题,实现了快速且准确的目标检测。以下是YOLO的基…

PVE报错处理:kvm [2205]: vcpu0 ignored RDMSR: 0x1b8

PVE使用过程中如果遇到&#xff1a;kvm [2205]: vcpu0 ignored RDMSR: 0x1b8 报错信息处理方法 vim /etc/modprobe.d/kvm.conf "options kvm ignore_msrsY"&#xff0c;这里在msrsY后面加一个空格&#xff0c;然后粘贴report_ignored_msrsN&#xff0c;使其变成 op…

学习嵌入式第十五天之结构体

用变量a给出下面的定义 a) 一个整型数&#xff08;An integer&#xff09; //int a;b) 一个指向整型数的指针&#xff08;A pointer to an integer&#xff09; //int *a;c) 一个指向指针的的指针&#xff0c;它指向的指针是指向一个整型数&#xff08;A pointer to a poin…

这篇秒杀设计都可以拿来讲课了【史上最详细的秒杀设计方案】

文章目录 &#x1f340; 简介&#x1f335; 设计关注点&#x1f332; 瞬时高并发&#x1f333; 页面静态化&#x1f334; 秒杀按钮&#x1f33e; 读多写少&#x1f344; 缓存问题&#x1f680; 缓存击穿&#x1f33d; 缓存穿透 &#x1f34e; 库存问题&#x1f353; 数据库扣减…

【数据结构】 归并排序超详解

1.基本思想 归并排序&#xff08;MERGE-SORT&#xff09;是建立在归并操作上的一种有效的排序算法,该算法是采用分治法&#xff08;Divide andConquer&#xff09;的一个非常典型的应用。 将已有序的子序列合并&#xff0c;得到完全有序的序列&#xff0c;即先使每个子序列有序…

vulnhub通关-2 DC-2(含靶场资源)

文章目录 一、环境搭建1.环境描述靶场描述题目表述概括&#xff08;目标&#xff09; 2.靶场下载下载地址 3.环境启动 二、渗透靶场1.信息收集&#xff1a;寻找靶机IP分析nmap扫描存活主机 2.信息收集&#xff1a;服务和端口探测命令解析 3.访问Web跳转问题解决办法hosts文件路…

js 设置、获取、删除标签属性以及H5自定义属性

1. 设置标签属性 使用setAttribute()(‘属性名’, ‘属性值’)方法可以添加、修改、删除属性。   下面的demo是为input添加、修改、删除value属性&#xff1a; 1.1. HTML <input type"text" class"input"> <input type"text" class…

【数据结构(C语言)】树、二叉树详解

目录 文章目录 前言 一、树的概念及结构 1.1 树的概念 1.2 树的相关概念 1.3 树的表示 1.4 树在实际中的运用 二、二叉树的概念及结构 2.1 二叉树的概念 2.2 二叉树的基本形态 ​编辑2.3 特殊的二叉树 2.4 二叉树的性质 2.5 二叉树的存储结构 三、二叉树的顺序结…

【C语言】数组的应用:三子棋游戏

由于代码较长&#xff0c;为了增加可读性&#xff0c;我们把代码分别写到game.h&#xff0c;game.c&#xff0c;test.c&#xff0c;里面&#xff0c;其中game.h用来声明函数&#xff0c;实现函数功能的代码在game.c&#xff0c;测试游戏的代码在test.c 为了方便后续的更改&…

使用 ChatGPT 为生物信息学初学者赋能

论文&#xff1a;Empowering Beginners in Bioinformatics with ChatGPT. 2023 对于生信初学者而言&#xff0c;最大的困难是身边没有经验丰富的人给予指导。而ChatGTP的出现可能改变这一现状&#xff0c;学生可以自己作为导师&#xff0c;指导ChatGPT完成数据分析工作。 众所周…

Kotlin中的内置函数-apply、let

在使用Kotlin的过程中会经常用到其内置函数&#xff0c;包括apply&#xff0c;let&#xff0c;run&#xff0c;with&#xff0c;also&#xff0c;takeIf,takeUnless函数等&#xff0c;想要更好熟悉Kotlin&#xff0c;这些函数必须烂熟于心&#xff0c;接下来让我们来逐步了解&a…

ubuntu16.04环境轻松安装和应用opencv4.9.0(基于源码编译)

目录 一、环境准备 1、安装cmake 2、安装依赖 3、从github上下载opencv4.9.0.zip 二、安装opencv4.9.0 1、解压4.9.0.zip 2、进入build目录编译 3、安装编译好的相关库 4、修改opencv配置文件并使其生效 5、添加PKG_CONFIG路径&#xff0c;并使其生效 三、opencv环境…