微信小程序实现点击按钮生成海报

页面布局

<view class="mask" v-show="isShow">
			<view class='board'>
				<view class="heart">
                   <span class="sure" @click="isShow=false">×</span>
               </view>
				<canvas @longpress="saveHomepage" 	:style="'width:'+canvasWidth+'px;height:'+ canvasHeight+'px;'"
					canvas-id="myCanvas"></canvas>
			</view>
</view>

<view  class="foot-icon-card" @click="addCanvas(activity)">
		<image src="../../static/icons/haibao.svg"> </image>
		<text>生成海报</text>
</view>

data属性定义

canvasWidth: 300,
canvasHeight: 500,
isShow: false,
img_pop: '',
poster: ''
imageList: [
		"https://s1.ax1x.com/2023/06/02/p9zHfp9.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zHT0K.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zHhlR.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zHRfJ.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zH2Y4.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zHom6.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zH5Ox.jpg",
		"https://s1.ax1x.com/2023/06/02/p9zH461.jpg",
	]

methods实现

//文字自动换行显示,超出指定范围用...代替显示

textSplit(ctx, text, lineWidth, lines) {
				const charWidths = Array.from(text, char => ctx.measureText(char).width);

				let textArr = [];
				let c_text = '';
				let lineCount = 0;

				for (let i = 0; i < text.length; i++) {
					const charWidth = charWidths[i];

					if (ctx.measureText(c_text).width + charWidth < lineWidth) {
						c_text += text[i];
					} else {
						lineCount++;
						if (lineCount === lines) {
							const lastLineWidth = ctx.measureText(c_text).width;
							c_text = c_text.slice(0, -1);
							while (ctx.measureText(c_text + '...').width > lineWidth) {
								c_text = c_text.slice(0, -1);
							}
							c_text += '...';
							textArr.push(c_text);
							return textArr;
						} else {
							textArr.push(c_text);
							c_text = text[i];
						}
					}
				}

				// 当长度小于指定的 `lineWidth` 时,直接返回传入的文本内容
				if (textArr.length === 0) {
					return [text];
				}

				// 添加最后一行文本内容
				textArr.push(c_text);

				// 如果超过了指定行数,则修改最后一行内容,并返回修改后的文本数组。
				if (textArr.length > lines) {
					const lastLineWidth = ctx.measureText(c_text).width;
					c_text = textArr.pop();
					while (ctx.measureText(c_text + '...').width > lineWidth) {
						c_text = c_text.slice(0, -1);
					}
					c_text += '...';
					textArr.push(c_text);
				}

				return textArr;
			}
//图片网络路径转换为临时路径
getImgUrl(img) {
				return new Promise((result, rej) => {
					wx.getImageInfo({
						src: img,
						success: (res) => {
							console.log(res, "获取");
							return result(res.path)
						},
						fail: (error) => {
							rej(error)
						}
					})
				})
},
async addCanvas(item) {
				this.isShow = true
				this.foot = 'close'
				uni.showLoading({
					title: '正在生成海报'
				})
				let ctx = wx.createCanvasContext('myCanvas')
				ctx.fillStyle = '#fff';
				ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight)

				// 封面图
				if (item.avatar) {
					ctx.drawImage(await this.getImgUrl(item.avatar), 0, 0, this.canvasWidth, 200)
				} else {
					//随机背景图
					ctx.drawImage(await this.getImgUrl(this.imageList[Math.floor(Math.random() * 8)]), 0, 0, this
						.canvasWidth, 200)
				}

				//标题
				ctx.font = `normal 20px `
				ctx.fillStyle = '#000'
				let nameText = this.textSplit(ctx, item.name, this.canvasWidth - 20, 1)
				nameText.forEach(r => {
					ctx.fillText(r, 15, 220)
				})

				//活动内容
				let lineHeight = 25; //文字行高
				let text = this.textSplit(ctx, item.description, this.canvasWidth + this.canvasWidth / 3, 3)
				text.forEach((r, index) => {
					ctx.font = `normal 14px `
					ctx.fillStyle = '#636363'
					ctx.fillText(r, 15, 250 + index * lineHeight)
				})

				//地点
				ctx.font = `normal 14px `
				ctx.fillStyle = '#000'
				ctx.fillText('活动地点:', 15, 350)
				let textAdress = this.textSplit(ctx, item.address, this.canvasWidth - 100, 2)
				textAdress.forEach((r, index) => {
					ctx.font = `normal 14px `
					ctx.fillStyle = '#636363'
					ctx.fillText(r, 15, 370 + index * lineHeight)
				})

				//时间
				ctx.font = `normal 14px `
				ctx.fillStyle = '#000'
				ctx.fillText('时间:', 15, 420)
				ctx.font = `normal 14px `
				ctx.fillStyle = '#000'
				ctx.fillText(item.start_date + " " + item.start_time, 15, 440)


				// 二维码
				ctx.drawImage(this.img_pop, this.canvasWidth / 2 + this.canvasWidth / 4, 340, 70, 70)

				// 底部文字
				ctx.font = 'normal 12px '
				ctx.fillStyle = '#9C9C9C'
				ctx.fillText('长按识别或保存图片', this.canvasWidth / 3, 470)

				//开始绘画
				await ctx.draw(true, res => {
					setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: 'myCanvas',
							success: res => {
								this.poster = res.tempFilePath
								uni.hideLoading()
							},
							fail: err => {
								uni.hideLoading()
							}
						}, this)
					}, 1000)
				})
			},
// 判断是否有写入相册的权限
			saveHomepage() {
				let that = this;
				//判断当前小程序是否有保存相册的权限
				wx.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							wx.authorize({
								scope: 'scope.writePhotosAlbum',
								success(res) {
									that.startSaveImage();
								},
								fail() { //这里是用户拒绝授权后的回调
									wx.showModal({
										content: '请允许相册权限,拒绝将无法正常使用小程序',
										showCancel: false,
										success() {
											wx.openSetting({
												success(settingdata) {
													if (settingdata.authSetting[
															"scope.writePhotosAlbum"
														]) {} else {
														console.log("获取权限失败")
													}

												}
											})
										}
									})
								}
							})
						} else {
							that.startSaveImage();
						}
					}
				})
},
			
//保存本地

startSaveImage() {
				uni.saveImageToPhotosAlbum({
					filePath: this.poster,
					success: (res) => {
						uni.showToast({
							title: '保存成功',
							icon: 'none',
							duration: 4000
						})
						this.$refs.popup.close()
					}
				})
},

css样式

.mask {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 998;
		width: 100vw;
		height: 100%;
		background-color: #000000;
		overflow: hidden;
	}

	.board {
		animation: myframe 0.3s;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);

		z-index: 999;
	}

	.sure {
		text-align: center;
		display: block;
		width: 46rpx;
		margin: 0 auto;
		font-size: 32rpx;
		color: #fff;
		height: 46rpx;
		border-radius: 50%;
		line-height: 44rpx;
		border: 1px solid #ffffff;
		font-family: '楷体';
	}
.heart {
		position: relative;
		bottom: -540px;
	}

效果图

效果图

参考:uniapp点击生成商品海报、下载海报、分享海报
微信小程序Canvas绘制主页保存到手机相册
我的个人博客

### 回答1: 微信小程序点击按钮跳转页面可以使用 `wx.navigateTo` 或 `wx.redirectTo` 方法。 首先,在按钮的绑定事件中调用方法,如: ``` <button bindtap='jumpPage'>跳转页面</button> ``` 然后,在页面的 js 文件中实现跳转逻辑,如: ``` Page({ jumpPage: function() { wx.navigateTo({ url: '/pages/newpage/newpage' }) } }) ``` 注意,需要在项目的 `app.json` 文件中注册新页面,才能在小程序中使用。 使用 `wx.navigateTo` 方法会在当前页面下方加载新页面,而使用 `wx.redirectTo` 方法会替换当前页面,也就是关闭当前页面,并打开新页面。 希望这些信息能帮到你! ### 回答2: 要在微信小程序实现点击按钮跳转页面,首先需要在小程序的页面中添加一个按钮组件,并设置按钮的事件绑定。在按钮的事件处理函数中,可以通过调用微信小程序的导航API实现页面的跳转。 具体步骤如下: 1. 在小程序的页面中,添加一个按钮组件: ``` <button bindtap="redirectToPage">点击跳转</button> ``` 2. 在小程序页面的js文件中,定义按钮的点击事件处理函数: ``` Page({ redirectToPage: function() { wx.navigateTo({ url: '跳转的页面路径' }) } }) ``` 其中,`wx.navigateTo`是微信小程序的导航API,可以跳转到应用的某个页面。在`url`参数中,填入跳转页面的路径,如`'pages/other/other'`。跳转的页面路径需要在小程序的配置文件`app.json`中进行配置。 3. 在小程序的配置文件`app.json`中,为跳转的页面路径进行配置: ``` { "pages": [ "pages/index/index", "pages/other/other" ], "window":{ "backgroundTextStyle":"light", "navigationBarBackgroundColor": "#fff", "navigationBarTitleText": "微信小程序", "navigationBarTextStyle":"black" } } ``` 在`pages`数组中,添加需要跳转的页面路径,以使跳转路径有效。 通过以上步骤,就可以在微信小程序实现点击按钮跳转页面的功能了。 ### 回答3: 要实现微信小程序点击按钮跳转页面,可以按照以下步骤进行操作: 1. 在当前页面的.wxml文件中,定义一个按钮,并设置相应的样式和事件绑定,例如: ``` <button bindtap="navigateToPage">跳转到新页面</button> ``` 2. 在当前页面的.js文件中,编写相应的事件处理函数,例如: ``` Page({ navigateToPage: function() { wx.navigateTo({ url: '/pages/newPage/newPage' }) } }) ``` 3. 在app.json文件中配置新页面的路径和窗口样式,例如: ``` { "pages": [ "pages/index/index", "pages/newPage/newPage" ], "window": { "backgroundColor": "#ffffff", "navigationBarTitleText": "微信小程序" } } ``` 4. 在新页面的.wxml文件中,定义相应的内容和样式。 以上就是在微信小程序实现点击按钮跳转页面的基本步骤。需要注意的是,页面间的跳转可以使用`wx.navigateTo`方法跳转到新页面,也可以使用`wx.redirectTo`方法进行页面重定向,具体使用哪种方法根据需求来决定。同时,还可以使用`wx.navigateBack`方法返回上一页,或者使用`wx.switchTab`方法切换到指定的tab页。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嗬呜阿花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值