uni-app完成保存大图分享到朋友圈

canvas简单画布-保存大图分享到朋友圈

这篇博客记录的是使用uni-app完成微信小程序开发的时候需要使用canvas进行大图海报的绘制以及进行图片的保存。

好了,我这人比较懒,啥都不说了直接上代码了:

const ctx = uni.createCanvasContext('myCanvas');
ctx.beginPath()
// 填充整块画布背景(白)色
ctx.rect(0, 0, 画布宽度, 画布高度)
ctx.setFillStyle('#004D39')
ctx.fill()
ctx.save()//保存当前的绘图上下文
ctx.beginPath()//开始创建一个路径
ctx.arc(100, 100, 50, 0, 2 * Math.PI)
ctx.fill()
ctx.clip()//裁剪
ctx.drawImage('你的图片地址', 50, 50, 100, 100)//绘制图片
//ctx.save()//保存当前的绘图上下文
ctx.restore()//恢复之前保存的绘图上下文
// 绘制文本信息-商品分享人
ctx.setFontSize(40)
ctx.setFillStyle('#D1B285')
ctx.setTextAlign('left')
ctx.fillText('随便的文字', 180, 120)

// 绘制文本信息-分享说明
ctx.setFontSize(40)
ctx.setFillStyle('#D1B285')
ctx.setTextAlign('right')
ctx.fillText('推荐了一个宝贝', 画布宽度 - 50, 180)

ctx.beginPath()
// 绘制主图
ctx.drawImage(that.canvasPath, 0, 210, 画布宽度, that.canvasHeight)
// 绘制文本信息-标注商品名称
ctx.setFontSize(40)
ctx.setFillStyle('#004D39')
ctx.setTextAlign('right')
ctx.fillText(that.list1.ProductName, 画布宽度 - 50, that.canvasHeight + 130)
// 绘制文本信息-标注商品价格
ctx.setFontSize(35)
ctx.setFillStyle('red')
ctx.setTextAlign('right')
ctx.fillText('¥', 画布宽度 - 210, that.canvasHeight + 190)
// 绘制文本信息-标注商品价格
ctx.setFontSize(50)
ctx.setFillStyle('red')
ctx.setTextAlign('right')
ctx.fillText(that.list1.Price, 画布宽度 - 50, that.canvasHeight + 190)
// 绘制文本信息-标注小程序名字
ctx.setFontSize(50)
ctx.setFillStyle('#D1B285')
ctx.setTextAlign('left')
ctx.fillText(uni.getStorageSync('storeinfor').name + '小程序', 50, that.canvasHeight + that.qrHeight / 3 + 210)
// 绘制文本信息-长按识别
ctx.setFontSize(40)
ctx.setFillStyle('#D1B285')
ctx.setTextAlign('left')
ctx.fillText('长按识别二维码,查看商品', 50, that.canvasHeight + that.qrHeight / 3 + 280)
// 绘制文本信息-价格说明
ctx.setFontSize(30)
ctx.setFillStyle('#D1B285')
ctx.setTextAlign('left')
ctx.fillText('注:价格和促销以商品详情页为准', 50, that.canvasHeight + that.qrHeight / 3 + 340)
// 绘制二维码
ctx.drawImage(that.qrPath, 画布宽度 - that.qrWidth - 20, that.canvasHeight + 230, that.qrWidth, that.qrHeight);

ctx.save();
ctx.beginPath();
ctx.draw(false,
	setTimeout(function() {
		uni.canvasToTempFilePath({
			x: 0,
			y: 0,
			width: 画布宽度,
			height: that.VisualHeight,
			destWidth: 画布宽度,
			destHeight: that.VisualHeight,
			quality: Number(1),
			canvasId: 'myCanvas',
			success: function(res) {
				that.filePath = res.tempFilePath;
				console.log('合成成功!');
				console.log(res.tempFilePath);
			},
			fail: function(res) {
				console.log('合成失败!');
			},
			complete: function(res) {
				uni.hideLoading();
			}
		})
	}, 200)
)

功能是很简单的,就是定位置与文字的字体大小稍稍要花点时间,具体的可以看代码里的注释以及官网提供的API文档。
PS:画布的宽度为1080px,画布的高度是根据获取到的主图的高度、二维码的高度进行自适应的

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值