uni-app小程序canvas绘制宣传图片的爬坑整理(绘制本地图片,http链接图片和https链接图片)

本文详述了使用uni-app进行小程序canvas操作的过程,包括文字处理如设置字体大小、颜色、阴影及居中,以及绘制本地和网络图片。特别提醒,绘制http网络图片时需处理本地存储的base64文件,防止存储满导致问题。最后,阐述了如何将canvas内容转化为图片并保存至本地。
<template>
    <canvas canvas-id="shareImg"></canvas>
</template>

1、canvas写入文字

const ctx = uni.createCanvasContext('shareImg');
ctx.fillText('hello,wold!', 30,20);//30X到左边的距离,20Y到顶部的距离,单位是px

2、canvas文字设置fontSize

const ctx = uni.createCanvasContext('shareImg');
ctx.setFontSize(25);//设置文字的fontSize为25px
ctx.fillText('hello,wold!', 30,20);

3、canvas设置文字颜色

const ctx = uni.createCanvasContext('shareImg');
ctx.setFillStyle('#fff');//设置文字颜色为白色
ctx.fillText('hello,wold!', 30,20);

4、canvas设置文字阴影

const ctx = uni.createCanvasContext('shareImg');
ctx.shadowOffsetX = -3; //用来设定阴影在 X轴的延伸距
ctx.shadowOffsetX = 4; //用来设定阴影在 Y轴的延伸距
ctx.shadowBlur = 2; //设定阴影的模糊程度 默认0
ctx.shadowColor = "rgba(255, 255, 255)"; //设定阴影颜色效果
ctx.font = 'normal bold 25px sans-serif';
ctx.fillText('hello,wold!', 30,20);

5、canvas设置文字居中

const ctx = uni.createCanvasContext('shareImg');
ctx.setTextAlign('center');//设置居中
ctx.fillText('hello,wold!', 100,20);//文字居中与0-100px距离之间居中

6、canvas绘制本地项目内的图片或是https链接图片

init(){
    const ctx = uni.createCanvasContext('shareImg');
    let img = "../../img.png";
    //let img = "https://static.daoba.com//221328929171.png";
    that.httpsDrawing(img , ctx, 0, 0, 330, 540).then((res) => {
        ctx.draw(true, () => {
		    that.share();
	    })
    })
},

//绘制本地图片和https链接的图片
httpsDrawing(codeimg, ctx, x, y, width, height, radius) {
//(codeimg:图片地址, ctx:canvas, x:起始x, y:起始Y, width:图片宽度, height:图片高度, radius:弧度)
	const that = this;
	return new Promise(function(resolve, reject) {
		wx.getImageInfo({
			src: codeimg,
			success: function(res) {
				if (radius) {
					ctx.save();
					ctx.strokeStyle = "#fffbff";
					ctx.beginPath();
					ctx.moveTo(x, y + radius);
					ctx.lineTo(x, y + height - radius);
					ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
					ctx.lineTo(x + width - radius, y + height);
					ctx.quadraticCurveTo(x + width, y + height, x + width, y + height -
						radius);
					ctx.lineTo(x + width, y + radius);
					ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
					ctx.lineTo(x + radius, y);
					ctx.quadraticCurveTo(x, y, x, y + radius);
					if (res.path) {
						ctx.clip();
						ctx.drawImage(res.path, x, y, width, height); // logo
					}
					resolve(true);
					ctx.restore()
				} else {
					ctx.drawImage(res.path, x, y, width, height) //背景
					resolve(true);
				}
			}
		})
	})
}

7、canvas绘制http网络图片

init(){
    const ctx = uni.createCanvasContext('shareImg');
    let img = "http://static.daoba.com//221328929171.png";
    that.httpsDrawing(img , ctx, 0, 0, 330, 540).then((res) => {
        ctx.draw(true, () => {
		    that.share();
	    })
    })
},

//绘制本地图片和http链接的图片,需要先将图片转换成为base64的格式,然后存入文件管理本地生成https的图片临时路径,再将图片绘制出来。因为微信小程序不支持http图片的绘制。
QRCodeDrawing(code, ctx, x, y, width, height, radius, pathVal){
	const that = this;
	return new Promise(function(resolve, reject) {
		const that = this;
		const fs = wx.getFileSystemManager();
		//随机定义路径名称
		var times = 'chuwanning';
		var codeimg = wx.env.USER_DATA_PATH + '/' + times + pathVal + '.png';
	
		//将base64图片写入
		fs.writeFile({
			filePath: codeimg,
			data: code.slice(22),
			encoding: 'base64',
			success: (el) => {
				//写入成功了的话,新的图片路径就能用了
				if (radius) {
					ctx.save();
					ctx.strokeStyle = "#fffbff";
					ctx.beginPath();
					ctx.moveTo(x, y + radius);
					ctx.lineTo(x, y + height - radius);
					ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
					ctx.lineTo(x + width - radius, y + height);
					ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
					ctx.lineTo(x + width, y + radius);
					ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
					ctx.lineTo(x + radius, y);
					ctx.quadraticCurveTo(x, y, x, y + radius);
					if (codeimg) {
						ctx.clip();
						ctx.drawImage(codeimg, x, y, width, height); // logo
					}
					resolve(true);
					ctx.restore()
				} else {
					ctx.drawImage(codeimg, x, y, width, height) //背景
					console.log('路径', res);
					resolve(true);
				}
			},
			fail: () => {
				uni.hideLoading()
			}
		});
	})
},

注意:本地写入存储的base64文件是需要清除的,不然当存储满了之后会出现图片无法绘制生成的情况。以下是清除图片写入文件代码。

//清除文件
clearFile() {
	const that = this;
	const fs = wx.getFileSystemManager();
	fs.readdir({ // 获取文件列表
		dirPath: wx.env.USER_DATA_PATH,
		success(res) {
			let indexVal = res.files.length;
			res.files.forEach((el) => {
				let name = (wx.env.USER_DATA_PATH + el).replace(/usr/g, "usr/");
				fs.unlink({
					filePath: name, // 这里注意。文件
					fail(e) {
						console.log('readdir文件删除失败:', e)
					},
					success(succ) {
						indexVal++;
						if (indexVal == 0) {
                            console.log('readdir文件删除成功:', succ);
						}
					}
				});
			})
		}
	})
},

8、将canvas绘制生成图片

//点击生成图片
share() {
	const that = this;
	wx.canvasToTempFilePath({
		canvasId: 'shareImg',
		success: function(res) {
			that.tempFilePath = res.tempFilePath;
			that.canvasShow = true;
			uni.hideLoading(); //绘制成功
		}
	})
},

9、点击保存图片到本地

//保存海报
onPreservation(){
	const that = this;
	wx.getSetting({
		success(res) {
			if (!res.authSetting['scope.writePhotosAlbum']) {
				wx.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						that.saveImage()
					},
					fail() {
						wx.openSetting({
							success: (res) => {}
						})
					}
				})
			} else {
				that.saveImage()
			}
		}
	})
},

//保存图片到本地
saveImage() {
	const that = this;
	wx.saveImageToPhotosAlbum({
		filePath: that.tempFilePath,
		success: function(res) {
			setTimeout(function() {
				uni.navigateBack({
					delta: 1
				})
			}, 2000)
			uni.showToast({
				title: '保存图片成功',
				duration: 2000
			});
		},
		fail: function(err) {
			uni.showToast({
				title: '保存图片失败',
				icon: 'none',
				duration: 2000
			});
		}
	})
},

uni-app中开发微信小程序时,使用`<canvas>`组件绘制背景图,如果背景图需要通过接口获取,可以按照以下步骤实现。 首先,我们需要: 1. 通过`uni.request`请求图片接口,获取图片地址; 2. 使用`uni.downloadFile`下载图片本地; 3. 使用`uni.createCanvasContext`在`canvas`上绘制图片。 以下是一个完整的示例代码: ### 1. 模板部分(template): ```html <template> <view> <canvas :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" :canvas-id="canvasId" @error="canvasError"> </canvas> <button @click="drawBackground">绘制背景图</button> </view> </template> ``` ### 2. 脚本部分(script): ```javascript <script> export default { data() { return { canvasId: 'myCanvas', canvasWidth: 375, canvasHeight: 667, imageUrl: '' }; }, methods: { // 请求图片地址 async drawBackground() { try { const res = await uni.request({ url: 'https://yourdomain.com/api/getImage', // 替换为你的图片接口 method: 'GET' }); const imageUrl = res[1].data.imageUrl; // 假设接口返回的图片地址字段是imageUrl this.imageUrl = imageUrl; // 下载图片 const { tempFilePath } = await uni.downloadFile({ url: imageUrl }); // 绘制图片 const ctx = uni.createCanvasContext(this.canvasId); ctx.drawImage(tempFilePath, 0, 0, this.canvasWidth, this.canvasHeight); ctx.draw(); } catch (err) { console.error('绘制失败', err); } }, canvasError(e) { console.error('canvas发生错误', e.detail.errMsg); } } }; </script> ``` ### 3. 样式部分(style): ```css <style scoped> canvas { background-color: #f0f0f0; } </style> ``` --- ### 解释: - `uni.request`:请求后端接口获取图片地址。 - `uni.downloadFile`:下载远程图片本地,返回临时路径。 - `uni.createCanvasContext`:创建canvas上下文对象。 - `ctx.drawImage(tempFilePath, 0, 0, width, height)`:将图片绘制canvas上。 - `ctx.draw()`:执行绘制--- ### 注意事项: 1. 微信小程序中,`canvas`的绘制需要在`ctx.draw()`之后才会生效。 2. 微信小程序要求图片必须是本地路径或临时路径,不能直接使用网络路径绘制。 3. 接口返回的图片地址必须是合法的可访问URL,并且在微信小程序后台配置了域名白名单。 --- ### 相关问题:
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值