js canvas图片添加重复背景水印

/**
	 	* 给图片添加水印
	 	* @memberof DomUtils.
	 	* @param {string} dataUrl - png图片的data url
	 	* @param {string} text - 水印文字
 	*/
	watermarkImage (dataUrl, text, style = {opacity: 0.5, font: '14px serif', fillStyle: 'rgb(227,232,238)'}) {
		return new Promise((resolve, reject) => {
			let targetImage = new Image();
			targetImage.onload = function () {
				let h = targetImage.height,
					w = targetImage.width,
					canvas = Object.assign(document.createElement('canvas'), {width: w, height: h}),
					ctx = canvas.getContext('2d');

				ctx.drawImage(targetImage, 0, 0);

				ctx.globalAlpha = style.opacity;
				ctx.font = style.font;
				ctx.fillStyle = style.fillStyle;

				let fwidth = w / 4,
					fheight = h / 4;

				for (let hh = fheight; hh < h; hh += fheight) {
					for (let ww = fwidth; ww < w; ww += fwidth) {
						ctx.setTransform(1, 0, 0, 1, 0, 0);
						ctx.translate(ww, hh);
						ctx.rotate(-Math.atan(h / w));
						ctx.fillText('text', -fwidth / 2, fheight / 2);
					}
				}

				try {
					canvas.toBlob(blob => {
						resolve(blob);
					});
				} catch (e) {
					console.error('Cannot watermark image with text:', text);
					reject(e);
				}
			};
			targetImage.src = dataUrl;
		})
	}

具体用法:

domToImage.toPng(document.querySelector('.read-template .items')).then(dataUrl => {
				DomUtils.watermarkImage(dataUrl, 'test...').then((blob) => {
					saveAs(blob, '文档.png');
				});
			});

domToImage和saveAs分别为dom-to-image,file-saver库

你可能感兴趣的:(Web前端,点滴技巧,JavaScript学习)