VUE 图片上加文字水印

我这里用的是uniapp上传方法

上传的方法

uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						// console.log(res);
						this.base64AddWaterMaker(res.tempFiles[0].path, this.waterMakeConfig).then((res) => {
							console.log("res", res);
							this.img=res
						});
					}
				});
			//处理水印的方法
		base64AddWaterMaker(base64Img, waterMakeConfig) {
		// 保留this指向 后面会用到的
		let _this = this;
		return new Promise((resolve, reject) => {
			const canvas = document.createElement('canvas');
			const ctx = canvas.getContext('2d');
			const img = new Image();
			img.crossOrigin = 'Anonymous'; // 图片加载的过程中允许出现跨域
			// 先有src属性才会触发 onload函数
			img.src = base64Img;
			// 异步加载
			img.onload = function() {
				// 注意img.onload方法是异步的
				canvas.width = img.width;
				canvas.height = img.height;
				ctx.font = `40px Georgia`;

				// 给文字添加颜色
				// ctx.fillStyle = 'red';
				// 添加渐变颜色的水印
				var gradient = ctx.createLinearGradient(0, 0, 200, 0);
				gradient.addColorStop(0, 'blue');
				gradient.addColorStop(1, 'red');
				ctx.fillStyle = gradient;

				// 以左上角为坐标原点 开始绘制图像
				ctx.drawImage(img, 0, 0, img.width, img.height);
				ctx.fillText(waterMakeConfig.textArray[0], img.width * 0.05, img.height *
					0.8); //在图片上添加字体
				ctx.fillText(waterMakeConfig.textArray[1], img.width * 0.05, img.height * 0.85);

				let resultBase64 = canvas.toDataURL('image/png'); // 返回的图片文件也是base64格式的
				if (!resultBase64) {
					reject();
				} else {
					_this.imgBase64 = resultBase64;
					resolve(resultBase64);
				}
			};
		});
	},
		水印样式
	waterMakeConfig: {
			font: 'microsoft yahei', //字体
			textArray: ['风-温迪', '2022/9/1 10:13'],
		},

最终效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值