【uniapp】canvas画海报保存图片兼容H5和APP

本文探讨了如何在H5和APP中实现海报长按保存功能,包括HTML代码示例、canvas海报生成、以及针对不同平台的保存操作。重点介绍了使用canvas绘制海报并转化为本地图片的步骤和兼容性技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

APP、H5长按保存海报

海波实现如下:

html

<!-- #ifdef H5 -->
<div class="app-h5-save-poster">
	<image :src="posterImage" mode="widthFix"></image>
</div>
<!-- #endif -->

<!-- #ifdef APP-PLUS -->
<div @longtap="longtapImageApp" class="app-h5-save-poster" style="height: 100%;opacity: 0;"></div>
<!-- #endif -->

<!-- canvas -->
<div class="canvas-wrap">
	<div class="canvas">
		<canvas 
			style="width: 330px;height: 660px;"
			id="mycanvas"
			canvas-id="firstCanvas">
		</canvas>
	</div>
</div>

canvas宽高建议使用px,不要使用upx,upx部分手机保存图片大小不一致。

// 分享码海报生成
createPoster(){
	let _this = this
	_this.context = uni.createCanvasContext('firstCanvas', _this);
	_this.context.drawImage('/static/more/business_code.png', 0, 0, 330, 660);
	uni.getImageInfo({
		src: _this.info.qrCode,
		success(res){
			_this.context.drawImage(res.path, 230, 574, 70, 70);
		}
	})
	setTimeout(function(){	//必须延迟执行 不然H5不显示
		_this.context.stroke();
		_this.context.draw(true); //绘制
		// #ifdef H5
		uni.showLoading({
			title: '海报生成中'
		})
		setTimeout(()=>{
			_this.savePoster();
			uni.hideLoading();
		},1000)
		// #endif
	},500)
},

// app保存图片到相册
longtapImageApp(){
	uni.showLoading({
		title: '保存中'
	})
	uni.canvasToTempFilePath({
		canvasId: 'firstCanvas',
		fileType: 'png',
		quality: 1, //图片质量
		success: function(result) {
			var tempFilePath = result.tempFilePath;
			// #ifdef APP-PLUS
			uni.saveImageToPhotosAlbum({
				filePath: tempFilePath,
				success: function() {
					uni.hideLoading();
					uni.showToast({
						title: '已成功保存至相册',
						icon: 'none'
					})
				},
				fail() {}
			});
			// #endif
		},
	});
},

// h5保存海报
saveH5Poster(){
	let that = this
	uni.canvasToTempFilePath({
		canvasId: 'firstCanvas',
		fileType: 'png',
		quality: 1, //图片质量
		success(res) {
			// that.posterImage
			let base64 = res.tempFilePath
			that.posterImage = base64
		}
	})
},

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

菜又爱编程

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

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

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

打赏作者

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

抵扣说明:

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

余额充值