<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas图片标注示例</title>
<style type="text/css">
canvas {
border: 2px solid #f00;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var isDragging = false;
var startX, startY;
var x, y, width, height;
var boxes = [];
canvas.addEventListener('mousedown', function (e) {
isDragging = true;
startX = e.clientX - canvas.getBoundingClientRect().left;
startY = e.clientY - canvas.getBoundingClientRect().top;
x = startX;
y = startY;
width = 0;
height = 0;
});
canvas.addEventListener('mousemove', function (e) {
if (isDragging) {
width = e.clientX - canvas.getBoundingClientRect().left - startX;
height = e.clientY - canvas.getBoundingClientRect().top - startY;
draw();
}
});
canvas.addEventListener('mouseup', function (e) {
isDragging = false;
var rect = canvas.getBoundingClientRect();
var left = Math.min(startX, x) + rect.left;
var top = Math.min(startY, y) + rect.top;
var right = Math.max(startX + width, x + width) + rect.left;
var bottom = Math.max(startY + height, y + height) + rect.top;
var box = {
left: left,
top: top,
right: right,
bottom: bottom
};
boxes.push(box);
console.log('boxes:', boxes);
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
ctx.beginPath();
ctx.rect(box.left, box.top, box.right - box.left, box.bottom - box.top);
ctx.strokeStyle = '#f00';
ctx.lineWidth = 2;
ctx.shadowColor = '#f00';
ctx.shadowBlur = 5;
ctx.stroke();
}
if (isDragging) {
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.strokeStyle = '#f00';
ctx.lineWidth = 2;
ctx.shadowColor = '#f00';
ctx.shadowBlur = 5;
ctx.stroke();
}
}
</script>
</body>
</html>
Canvas图片标注示例
最新推荐文章于 2024-08-15 18:19:19 发布