需求是可以在图片上画多边形区域,以方便其他团队进行标记处理,于是想到用 canvas 来实现绘制多边形以及圆点功能,代码实现如下:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const points = [];
let isDrawing = false;
function drawPoint(points) {
points.forEach((point, index) => {
ctx.beginPath();
ctx.arc(point.x, point.y, 3, 0, Math.PI * 2, true);
ctx.fillStyle = '#2ecc71';
ctx.fill();
ctx.closePath();
});
}
function drawLine(points) {
ctx.beginPath();
points.forEach((point, index) => {
ctx[index === 0 ? 'moveTo' : 'lineTo'](point.x, point.y);
});
ctx.fillStyle = 'rgba(24, 144, 255, 0.3)';
ctx.fill();
ctx.closePath();
ctx.strokeStyle = 'rgba(24, 144, 255, 1)';
ctx.stroke();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPoint(points);
drawLine(points);
}
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) {
return;
}
if (!points.length) {
return;
}
const point = {
x: e.clientX,
y: e.clientY,
};
if (points.length === 1) {
points.push(point);
} else {
points[points.length - 1] = point;
}
draw();
});
canvas.addEventListener('click', (e) => {
isDrawing = true;
points.push({
x: e.clientX,
y: e.clientY,
});
draw();
});
canvas.addEventListener('dblclick', () => {
if (!isDrawing) {
return;
}
isDrawing = false;
points.push(points[0]);
draw();
});