微信小程序 uview 使用Upload 组件时添加水印

菜鸟一枚,本文只为记录

html


	


js

data(){
return{
    maxSize: 500, // 图片宽高的最大尺寸
    myCanvas: null,
    myCtx: null,
    dpr: null,
    canvasDisplayW: 300,
    canvasDisplayH: 300,
    fillNum: 120
}
}
mounted() {
	this.initCanvas()
	},
methods:{

// 新增图片
			async afterRead(event) {
				// console.log(event)
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				// lists.map((item) => {
				// 	this[`fileList${event.name}`].push({
				// 		...item,
				// 	})
				// })
				// console.log(this[`fileList${event.name}`])
				let imgz = event.file
				this.chooseImage(imgz)
			},
// 初始化canvas
			initCanvas() {
				const _ = this;
				// 若在自定义组件中,此处应写为this.createSelectorQuery();
				const query = wx.createSelectorQuery();
				query.select('#myCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						let myCanvas = res[0].node;
						let myCtx = myCanvas.getContext('2d');
						myCtx.font = "normal bold 18px PingFangSC-Regular";
						const dpr = wx.getSystemInfoSync().pixelRatio;

						this.myCanvas = myCanvas
						this.myCtx = myCtx
						this.dpr = dpr
					})
			},
			// 压缩图片
			compress(imgW, imgH) {
				const _ = this;
				const dpr = _.dpr;
				const maxSize = _.maxSize;
				const ratio = imgW / imgH;
				let canvas = _.myCanvas;
				let ctx = _.myCtx;

				let canvasWidth = imgW;
				let canvasHeight = imgH;
				while (canvasWidth > maxSize || canvasHeight > maxSize) {
					if (canvasWidth > maxSize) {
						canvasWidth = maxSize;
						canvasHeight = maxSize / ratio;
					} else if (canvasHeight > maxSize) {
						canvasHeight = maxSize;
						canvasWidth = maxSize * ratio;
					}
				}
				canvas.width = dpr * canvasWidth;
				canvas.height = dpr * canvasHeight;
				ctx.scale(dpr, dpr);

				return {
					canvasWidth,
					canvasHeight
				}
			},
			// 图片添加水印
			addMask(img, imgW, imgH) {
				const _ = this;
				// const date = 'namename';
				const fillTexts = [];
				fillTexts.push('用途:' + '打卡')
				fillTexts.push('时间:' + this.getNowTime())
				fillTexts.push('地址:' + this.form.address)
				if (!_.myCanvas) {
					_.initCanvas();
				}
				let canvas = _.myCanvas;
				let ctx = _.myCtx;
				// 1. 压缩图片
				let {
					canvasWidth,
					canvasHeight
				} = _.compress(imgW, imgH);
				return new Promise((resolve, reject) => {
					// 2. 生成图片
					let image = canvas.createImage();
					image.src = img;
					image.onload = (e) => {
						// 3. 绘图
						ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
						ctx.fillStyle = '#222';
						ctx.shadowColor = "#333"; // 阴影颜色
						ctx.shadowOffsetX = 0; // 阴影x轴位移。正值向右,负值向左。
						ctx.shadowOffsetY = 0; // 阴影y轴位移。正值向下,负值向上。
						ctx.shadowBlur = 15; // 阴影模糊滤镜。数据越大,扩散程度越大。
						// fillTexts
						this.fillNum = 120
						fillTexts.forEach((mark, index) => {
							this.fillNum += 20
							ctx.fillText(mark, 10, this.fillNum += 10);
						});
						// 4. 将canvas转为图片
						wx.canvasToTempFilePath({
							destWidth: canvasWidth,
							destHeight: canvasHeight,
							canvas: canvas,
							success(res) {
								resolve(res.tempFilePath);
							},
							fail(error) {
								reject(error)
							}
						})
					}
					image.onerror = (e) => {
						console.error('创建图片错误', e)
					}
				})
			},
			// 选择图片
			chooseImage(imgPath) {
				const _ = this;
				let imgPathitem = imgPath[0]
				wx.getImageInfo({
					src: imgPath[0].url,
					success(res) {
						// 2. 添加水印
						_.addMask(imgPathitem.url, res.width, res.height).then(imgPath => {
							_.fileList1.push({
								size: imgPathitem.size,
								thumb: imgPath,
								type: imgPathitem.type,
								url: imgPath,
							})
						});
					},
					fail(res) {
						console.log("fail res", res);
					}
				})
				// 

			},
			getNowTime() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
			}
}

你可能感兴趣的:(前端,小程序)