uniapp前端绘制海报,H5,微信小程序

一,H5绘制

downloadImageA() {
				let that = this
				const imageUrl = '图片地址https形式';

				uni.showLoading({
					title: '正在下载',
					mask: true
				})

				const link = document.createElement('a');
				link.href = imageUrl;
				link.download = 'image.jpg';
				link.target = '_blank';
				link.style.display = 'none';
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);

				uni.hideLoading()
				uni.showToast({
					title: '图片下载成功',
					icon: 'success',
					duration: 2000
				})
			},
savePhoto: function(index) {
				let that = this
				// 提示用户正在合成,否则用户可能有不当操作或者以为手机卡死
				uni.showLoading({
					title: '合成中......',
					mask: true
				})
				// 创建画布对象
				const ctx = uni.createCanvasContext("myCanvas", that)
				// 获取图片信息,要按照原图来绘制,否则图片会变形 
				uni.getImageInfo({
					src: 'https://xindong.hnjjwl.cn/uploads/common/haibao.png',
					success: function(res) {
						uni.createSelectorQuery().select('#canvas-container').boundingClientRect(function(
							rect) {
							var height = rect.height;
							var right = rect.right;
							let width = rect.width * 0.8;
							var left = rect.left + 5;
							let imgPath = res.path
							ctx.setFillStyle('#fff');
							ctx.fillRect(0, 0, rect.width, height);
							// 这里处理自适应
							let rpx = 1;
							let px = 1
							uni.getSystemInfo({
								success(res) {
									rpx = res.screenWidth / 350;
								},
							})
							//背景图
							ctx.drawImage(imgPath, 0, 0, rect.width, rect.height);
							//  绘制二维码
							uni.getImageInfo({
								src: that.code, // 二维码图片的路径
								success: function(res) {
									console.log(" 绘制二维码》》》", res)
									// 绘制二维码
									ctx.drawImage(res.path, (rect.width - 110) / 2 *
										px, 240 * rpx, 111 * rpx, 111 * rpx)
									ctx.draw()
									uni.showLoading({
										title: '正在保存',
										mask: true
									})
									setTimeout(() => {
										uni.canvasToTempFilePath({
											canvasId: 'myCanvas',
											success: function(res) {
												console.log(
													"合成的带有小程序码的图片success》》》",
													res)
												let tempFilePath =
													res
													.tempFilePath

												const link =
													document
													.createElement(
														'a');
												link.href =
													tempFilePath;
												link.download =
													'image.jpg';
												link.target =
													'_blank';
												link.style
													.display =
													'none';
												document.body
													.appendChild(
														link);
												link.click();
												document.body
													.removeChild(
														link);
												uni.hideLoading()
												const isSafari =
													/^((?!chrome|android).)*safari/i
													.test(navigator
														.userAgent
														);
												if (isSafari) {
													uni.showModal({
														title: '温馨提示',
														content: '图片保存成功,可在浏览器下载目录中查看',
														showCancel: false
													})
												} else {
													uni.showModal({
														title: '温馨提示',
														content: '图片保存成功,稍等相册查看..',
														showCancel: false
													})
												}

												console.log(
													"合成的带有小程序码的图片的信息》》》",
													res)
											},
											fail: function(res) {
												console.log(
													"生成的图拍呢 失败 fail fail fail ",
													res)
												uni.hideLoading()
												uni.showModal({
													title: '温馨提示',
													content: '小程序码图片合成失败,请重试',
													showCancel: false
												})
											}
										}, that)
									}, 1500)
								},
								fail(res) {
									console.log(res, '二维码获取失败,请重试');
									uni.hideLoading()
									uni.showModal({
										title: '温馨提示',
										content: '二维码获取失败,请重试',
										showCancel: false
									})
								}
							})
						}).exec()
					},
					fail(res) {
						console.log(res, '图片信息获取失败,请重试');
						uni.hideLoading()
						uni.showModal({
							title: '温馨提示',
							content: '图片信息获取失败,请重试',
							showCancel: false
						})
					}
				})
				// }
			},

二,小程序绘制

<template>
	<view class="">
		<view class="haibao po_re dis_c _c">
			<image class="back_img" src="/static/haibao.jpg" mode=""></image>
			<image :src="code" class="ewm_img" mode=""></image>
		</view>
		<view class="cont" id='canvas-container' style="width: 100%;height: 794rpx;">
			<canvas canvas-id="myCanvas" style="width:100%;height:100%;" catchlongtap='saveShareImg'></canvas>
		</view>
		<!-- <view class="save_btn" @click="save"> -->
		<view class="save_btn" @click="savePhoto">
			保存海报到相册
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code: '',
				bg: 'https://happlove.xilian.love/uploads/common/haibao.jpg',
			}
		},
		onShow() {
			let that = this
			let data={
				user_id:uni.getStorageSync('user_id'),
				user_token:uni.getStorageSync('user_token')
			}
			this.$http.post("user/info",this.$Base64.encode(JSON.stringify(data))).then(res=>{
				console.log(res)
				if(res.status==1){
					that.code = res.result.promo_code
					// that.getImg(that.code,"http://happylove.zzqtrj.net/uploads/common/haibao.jpg")
				}
			})
		},
		methods: {
			savePhoto: function(index) {
			    let that = this
			    // let imgs = that.data.imgs
			
			    // if (imgs[index].isDownLoad) {
			    //   // 如果已经下载过 提示用户
			    //   wx.showToast({
			    //     title: '你已经下载过该图片',
			    //     icon: 'none'
			    //   })
			    //   return
			    // } else {
			      // 提示用户正在合成,否则用户可能有不当操作或者以为手机卡死
			      uni.showLoading({
			        title: '合成中......',
			        mask: true
			      })
			
			      // 创建画布对象
			      const ctx = uni.createCanvasContext("myCanvas", that)
			      // 获取图片信息,要按照原图来绘制,否则图片会变形 
			      uni.getImageInfo({
			        src: that.bg,
			        success: function(res) {
						uni.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
							var height = rect.height;
							var right = rect.right;
							let width = rect.width * 0.8;
							var left = rect.left + 5;
							let imgPath = res.path
							ctx.setFillStyle('#fff');
							ctx.fillRect(0, 0, rect.width, height);
							// 这里处理自适应
							let rpx = 1;
							let px = 1
							uni.getSystemInfo({
								success(res) {
									rpx = res.screenWidth / 350;
								},
							})
							//背景图
							// if (cardbg) {
								ctx.drawImage(imgPath, 0, 0, rect.width, rect.height);
							// }
							//  绘制二维码
							uni.getImageInfo({
							  src: that.code, // 二维码图片的路径
							  success: function(res) {
							    console.log(" 绘制二维码》》》", res)
							    // 绘制二维码
							    // ctx.drawImage(res.path, 50, imgH - 380, 300, 300)
								ctx.drawImage(res.path, (rect.width-110)/2 * px, 240 * rpx, 111 * rpx, 111 * rpx)
							    ctx.draw()
										
							    uni.showLoading({
							      title: '正在保存',
							      mask: true
										
							    })
										
							    setTimeout(() => {
							      uni.canvasToTempFilePath({
							        canvasId: 'myCanvas',
							        success: function(res) {
							          console.log("合成的带有小程序码的图片success》》》", res)
							          let tempFilePath = res.tempFilePath
							          // 保存到相册
							          uni.saveImageToPhotosAlbum({
							            filePath: tempFilePath,
							            success(res) {
										
							              // 修改下载状态
							              // imgs[index].isDownLoad = true
										
							              uni.hideLoading()
							              uni.showModal({
							                title: '温馨提示',
							                content: '图片保存成功,可在相册中查看',
							                showCancel: false,
							                success(res) {
							                  uni.clear
							                  if (res.confirm) {
							                    // that.setData({
							                    //   isShow: true
							                    // })
							                  }
							                }
							              })
										
							              // that.setData({
							              //   imgs: imgs,
							              // })
							            },
										
							            fail(res) {
							              uni.hideLoading()
							              uni.showModal({
							                title: '温馨提示',
							                content: '图片保存失败,请重试',
							                showCancel: false
							              })
							            }
							          })
										
							          console.log("合成的带有小程序码的图片的信息》》》", res)
							        },
							        fail: function(res) {
							          console.log("生成的图拍呢 失败 fail fail fail ", res)
							          uni.hideLoading()
							          uni.showModal({
							            title: '温馨提示',
							            content: '小程序码图片合成失败,请重试',
							            showCancel: false
							          })
							        }
							      }, that)
							    },1500)
							  },
							  fail(res) {
							    uni.hideLoading()
							    uni.showModal({
							      title: '温馨提示',
							      content: '二维码获取失败,请重试',
							      showCancel: false
							    })
							  }
							})
						}).exec()
			          // 根据 图片的大小 绘制底图 的大小
			          // console.log(" 绘制底图 的图片信息》》》", res)
			          // let imgW = res.width
			          // let imgH = res.height
			          // let imgPath = res.path
			
			          // that.setData({
			          //   canvasHeight: imgH,
			          //   canvasWidth: imgW
			          // })
			          // 绘制底图 用原图的宽高比绘制
			          // ctx.drawImage(imgPath, 0, 0, imgW, imgH)
			
			          
			
			        },
			        fail(res) {
			          uni.hideLoading()
			          uni.showModal({
			            title: '温馨提示',
			            content: '图片信息获取失败,请重试',
			            showCancel: false
			          })
			        }
			      })
			    // }
			
			  },
			save: function() {
				const that = this
				uni.showLoading({
					title: '正在保存',
					mask: true,
				})
				setTimeout(function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas',
						success: function(res) {
							uni.hideLoading();
							var tempFilePath = res.tempFilePath;
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success(res) {
									uni.showModal({
										content: '图片已保存到相册,赶紧晒一下吧~',
										showCancel: false,
										confirmText: '好的',
										confirmColor: '#333',
										success: function(res) {
											if (res.confirm) {}
										},
										fail: function(res) {}
									})
								},
								fail: function(res) {
									if (res.errMsg ===
										"saveImageToPhotosAlbum:fail:auth denied" ||
										res.errMsg ===
										"saveImageToPhotosAlbum:fail auth deny" || res
										.errMsg ===
										"saveImageToPhotosAlbum:fail authorize no response"
									) {
										uni.openSetting({
											success(settingdata) {
												if (settingdata.authSetting[
														"scope.writePhotosAlbum"
													]) {} else {}
											}
										})
									}
								}
							})
						}
					});
				}, 1000);
			},
			getImg: function(codeImg, cardbg) {
				const that = this
				console.log(codeImg)
				uni.downloadFile({
					url: codeImg,
					success: function(res) {
						that.getuser(res.tempFilePath, cardbg)
					},
					fail: function(err) {
						console.log(err)
					}
				})
			},
			getuser: function(codeImg, cardbg) {
				const that = this
				console.log(cardbg)
				uni.downloadFile({
					url: cardbg,
					success: function(res) {
						var cardbg = res.tempFilePath;
						that.getCanvas(codeImg, cardbg);
					},
					fail: function(err) {
						console.log(err)
					}
				})
			},
			createRpx2px(rpx) {
				return uni.getSystemInfoSync().windowWidth / 750 * rpx
			},
			getCanvas: function(codeImg, cardbg) {
				var that = this;
				console.log(codeImg,cardbg)
				// var cardBase = that.data.cardBase; //需要绘制的数据集合
				const ctx = uni.createCanvasContext('myCanvas'); //创建画布
				var width = "";
				uni.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
					var height = rect.height;
					var right = rect.right;
					width = rect.width * 0.8;
					var left = rect.left + 5;
					ctx.setFillStyle('#fff');
					ctx.fillRect(0, 0, rect.width, height);
					// 这里处理自适应
					let rpx = 1;
					let px = 1
					uni.getSystemInfo({
						success(res) {
							rpx = res.screenWidth / 350;
						},
					})
					//背景图
					if (cardbg) {
						ctx.drawImage(cardbg, 0, 0, rect.width, rect.height);
					}
					//  绘制二维码
					if (codeImg) {
						ctx.drawImage(codeImg, (rect.width-110)/2 * px, 240 * rpx, 111 * rpx, 111 * rpx)
					}
				}).exec()

				setTimeout(function() {
					ctx.draw();
				}, 1000)
			},
		}
	}
</script>

<style>
	page {
		padding: 43rpx 32rpx 0rpx;
		background-color: #F5F5F5;
		box-sizing: border-box;
	}
	.cont{
		position: fixed;
		left: 300%;
	}
	.ewm_img {
		width: 220rpx;
		height: 220rpx;
		position: absolute;
		bottom: 53rpx;
	}

	.back_img {
		width: 100%;
		height: 100%;
	}

	.haibao {
		width: 100%;
		height: 794rpx;
	}

	.save_btn {
		width: 90%;
		margin: 70rpx auto 0rpx;
		height: 90rpx;
		background-color: #826AF8;
		border-radius: 20rpx;
		line-height: 90rpx;
		text-align: center;
		font-size: 30rpx;
		color: #FFFFFF;
	}
</style>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

黑云压城After

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

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

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

打赏作者

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

抵扣说明:

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

余额充值