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

APP、H5长按保存海报

海波实现如下:

html


<div class="app-h5-save-poster">
	<image :src="posterImage" mode="widthFix">image>
div>



<div @longtap="longtapImageApp" class="app-h5-save-poster" style="height: 100%;opacity: 0;">div>



<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
		}
	})
},

【uniapp】canvas画海报保存图片兼容H5和APP_第1张图片

你可能感兴趣的:(UNI-APP,html5,html,小程序)