效果图:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Marker Example</title>
</head>
<body>
<!-- 图片 -->
<img
id="myImage"
src='图片地址'
alt="Image to mark"
style="display: none"
/>
<!-- 画布 -->
<canvas id="myCanvas" width="1270" height="670"></canvas>
<script>
const canvas = document.getElementById("myCanvas")
const context = canvas.getContext("2d")
// 获取图像
const image = document.getElementById("myImage")
image.onload = () => {
console.log(image.width, image.height)
// 将图像绘制到Canvas上
context.drawImage(image, 0, 0, canvas.width, canvas.height)
let rect = [
{
left_top_x: 605,
left_top_y: 331,
right_bottom_x: 680,
right_bottom_y: 522,
prob: "测试0.02",
},
{
left_top_x: 1091,
left_top_y: 255,
right_bottom_x: 1167,
right_bottom_y: 443,
prob: "测试0.01",
},
]
for (let index = 0; index < rect.length; index++) {
const el = rect[index]
// 设置绘制矩形
context.beginPath()
context.moveTo(el.left_top_x, el.left_top_y)
context.lineTo(el.right_bottom_x, el.left_top_y)
context.lineTo(el.right_bottom_x, el.right_bottom_y)
context.lineTo(el.left_top_x, el.right_bottom_y)
context.lineTo(el.left_top_x, el.left_top_y)
context.strokeStyle = "#798afc"
context.lineWidth = "2"
context.stroke()
// 设置填充颜色为紫色
context.fillStyle = "#798afc"
context.fillRect(el.left_top_x, el.left_top_y - 20, 78, 20)
// 在矩形框内绘制矩形文字
context.fillStyle = "white"
context.font = "15px Arial"
context.fillText(el.prob, el.left_top_x + 2, el.left_top_y - 4)
}
var detailImg = canvas.toDataURL("image/png")
console.log(detailImg)
}
</script>
</body>
</html>