首页 > 其他分享 >网页截图并添加文字、图片

网页截图并添加文字、图片

时间:2022-10-17 14:01:05浏览次数:47  
标签:截图 网页 img ctx canvas height width 添加 const

安装依赖

yarn add html2canvas

实现代码

toImage() {
	// 手动创建一个 canvas 标签
	const canvas = document.createElement("canvas")
	// 获取父标签,意思是这个标签内的 DOM 元素生成图片
	// imageTofile是给截图范围内的父级元素自定义的ref名称
	let canvasBox = this.$refs.imageTofile
	// 获取父级的宽高
	const width = parseInt(window.getComputedStyle(canvasBox).width)
	const height = parseInt(window.getComputedStyle(canvasBox).height)
	// 宽高 * 2 并放大 2 倍 是为了防止图片模糊
	canvas.width = width * 2
	canvas.height = height * 2
	canvas.style.width = width + 'px'
	canvas.style.height = height + 'px'
	const context = canvas.getContext("2d");
	context.scale(2, 2);
	const options = {
		backgroundColor: null,
		canvas: canvas,
		useCORS: true
	}
	html2canvas(canvasBox, options).then((canvas) => {
		var img = new Image();
		// 需要添加文字的图片
		img.src = "/img/borders.png";
		img.setAttribute("crossOrigin", 'Anonymous')
		img.onload = () => {
			var ctx = canvas.getContext("2d");
			// 将图片添加到canvas
			ctx.drawImage(img, width - 200, 100, 170, 110)
			// 设置字体
			ctx.font = "22px 微软雅黑 bolder"
			// 设置字体颜色
			ctx.fillStyle = "#06ebe7"
			// 添加文字和位置
			ctx.fillText("经度  114.22", width - 180, 132);
			ctx.fillText("维度  32.43", width - 180, 164);
			ctx.fillText("电流  12.12", width - 180, 196);
			let dataURL = canvas.toDataURL("image/png")
			this.imageFile = dataURL;
			this.dialogTableVisible = true;
		}
	})
}

实现效果

仅作记录,如果有什么不对的地方欢迎大家指正

标签:截图,网页,img,ctx,canvas,height,width,添加,const
From: https://www.cnblogs.com/tanxj/p/16798954.html

相关文章