vue+canvas:在图片上绘制矩形、文字及添加图片

247 阅读1分钟

image.png

<canvas id="imgCanvas" width="1200" height="700"></canvas>
const handleImg = (url: any) => {
	// 获取canvas元素
	const canvas = document.getElementById('imgCanvas');
	const ctx = canvas.getContext('2d');
	const shipLabel = dataInfo.value.shipLabel || '--'
	const aiShipTypeName = dataInfo.value.aiShipTypeName || '--'
	const directionName = dataInfo.value.directionName || '--'
	const rect = JSON.parse(dataInfo.value.rect)
	// 创建Image对象
	const img = new Image();
	// 替换为实际图片URL
	img.src = url;

	// 图片加载完成后的回调
	img.onload = function () {
		// 将图片绘制到canvas上
		ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

		// 设置选中渔船矩形的样式
		ctx.strokeStyle = 'rgba(0, 255, 0, 0.5)'; // 边框颜色
		ctx.lineWidth = 2; // 边框宽度
		ctx.fillStyle = 'rgba(0, 255, 0, 0)'; // 填充色及透明度

		// 绘制选中渔船矩形矩形
		const rectX = rect.x1 * (1200 / 1920); // 矩形左上角x坐标
		const rectY = rect.y1 * (700 / 1080); // 矩形左上角y坐标
		const rectWidth = (rect.x2 - rect.x1) * (1200 / 1920); // 矩形宽度
		const rectHeight = (rect.y2 - rect.y1) * (700 / 1080); // 矩形高度
		ctx.strokeRect(rectX, rectY, rectWidth, rectHeight);
		ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
		// 绘制渔船详情矩形矩形
		let width2 = rectX + rectWidth * 0.1;
		let height2 = 1080 - rect.y2 > 100 ?  rectY + rectHeight : rectY - 60;
		ctx.strokeRect(width2, height2, 140, 60);
		ctx.font = '12px Arial';
		ctx.fillStyle = 'rgba(0, 255, 0, 1)';
		// 绘制渔船详情文字
		ctx.fillText(`船牌识别: ${shipLabel}` , width2 + 5, height2 + 15);
		ctx.fillText(`船舶类型:${aiShipTypeName}`, width2 + 5, height2 + 35);
		ctx.fillText(`方向: ${directionName}`, width2 + 5, height2 + 55);
		// 覆盖层图片路径
		if (dataInfo.value.shipLabelUrl && dataInfo.value.shipLabelUrl != '') {
			const overlayImage = new Image();
			overlayImage.src = dataInfo.value.shipLabelUrl;
			// 绘制覆盖层图片
			overlayImage.onload = () => {
				// 假设您希望在图片上插入的位置为(x, y),宽度为w,高度为h
				ctx.drawImage(overlayImage, width2 + 145, height2, 60, 30);
			};
		}
		loading.value = false;
	};
};