要在 JavaScript 中画多边形并获取当前的坐标值,你可以使用 HTML5 的 Canvas 元素和相关的绘图 API。以下是一个示例代码,演示如何在 Canvas 上绘制多边形,并获取当前鼠标所在位置的坐标值:
<!DOCTYPE html>
<html>
<head>
<title>多边形绘制示例</title>
<style>
#canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
const polygonVertices = [];
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(event) {
isDrawing = true;
const { offsetX, offsetY } = event;
polygonVertices.push({ x: offsetX, y: offsetY });
if (polygonVertices.length === 1) {
ctx.beginPath();
ctx.moveTo(offsetX, offsetY);
} else {
ctx.lineTo(offsetX, offsetY);
ctx.stroke();
}
}
function draw(event) {
if (isDrawing) {
const { offsetX, offsetY } = event;
const currentVertex = { x: offsetX, y: offsetY };
polygonVertices.push(currentVertex);
ctx.lineTo(offsetX, offsetY);
ctx.stroke();
}
}
function stopDrawing() {
isDrawing = false;
console.log('Polygon vertices:', polygonVertices);
}
</script>
</body>
</html>
我们创建了一个带有 Canvas 元素的 HTML 页面,并添加了绘图事件处理函数。当用户在 Canvas 上按下鼠标并移动时,会触发 mousedown 和 mousemove 事件,从而绘制多边形的边线。当用户松开鼠标或离开 Canvas 区域时,绘制结束,我们可以通过 stopDrawing 函数获取到绘制多边形的顶点坐标数组。
在绘制过程中,我们将每个顶点的坐标保存在 polygonVertices 数组中。你可以在 stopDrawing 函数中使用 polygonVertices 数组,对顶点坐标进行进一步的处理。