<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<label for="angle">角度(度):</label>
<input type="number" id="angle" min="0" max="360"><br><br>
<label for="distance">距离:</label>
<input type="number" id="distance" min="0"><br><br>
<button onclick="addEndpoint()">新增端点</button><br><br>
<button onclick="clearCanvas()">清空画布</button>
<h2>新增的端点数据</h2>
<table>
<tr>
<th>序号</th>
<th>角度(度)</th>
<th>坐标 (X, Y)</th>
</tr>
<tbody id="endpointTableBody"></tbody>
</table>
<script>
// 获取 canvas 元素和上下文对象
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 存储端点数据的数组,每个元素为对象 { angle, distance }
var endpoints = [];
// 初始化初始点
endpoints.push({ angle: 0, distance: 0, x: 7.494, y: 8.354 });
// 根据角度和距离计算新端点坐标的函数
function calculateEndpoint(angle, distance) {
var radians = (angle-90) * (Math.PI / 180);
var x = endpoints[endpoints.length - 1].x + distance * Math.cos(radians);
var y = endpoints[endpoints.length - 1].y + distance * Math.sin(radians);
return { angle: angle, distance: distance, x: x, y: y };
}
// 新增端点并重新绘制线和端点的函数
function addEndpoint() {
var angleInput = document.getElementById("angle");
var distanceInput = document.getElementById("distance");
var angle = parseFloat(angleInput.value);
var distance = parseFloat(distanceInput.value);
if (!isNaN(angle) && !isNaN(distance)) {
var newEndpoint = calculateEndpoint(angle, distance);
endpoints.push(newEndpoint);
// 清空画布并重新绘制线和端点
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawLinesAndEndpoints();
updateEndpointTable();
}
// 清空输入框
angleInput.value = "";
distanceInput.value = "";
}
// 绘制线和端点的函数
function drawLinesAndEndpoints() {
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
// 绘制线
ctx.beginPath();
for (var i = 0; i < endpoints.length - 1; i++) {
ctx.moveTo(endpoints[i].x, endpoints[i].y);
ctx.lineTo(endpoints[i + 1].x, endpoints[i + 1].y);
}
ctx.stroke();
// 绘制端点
ctx.fillStyle = "red";
for (var i = 0; i < endpoints.length; i++) {
ctx.beginPath();
ctx.arc(endpoints[i].x, endpoints[i].y, 5, 0, 2 * Math.PI);
ctx.fill();
}
}
// 更新表格显示新增的端点数据
function updateEndpointTable() {
var tableBody = document.getElementById("endpointTableBody");
tableBody.innerHTML = "";
for (var i = 0; i < endpoints.length; i++) {
var newRow = tableBody.insertRow();
var indexCell = newRow.insertCell(0);
var angleCell = newRow.insertCell(1);
var coordinatesCell = newRow.insertCell(2);
indexCell.textContent = i + 1;
angleCell.textContent = endpoints[i].angle.toFixed(3);
coordinatesCell.textContent = "(" + endpoints[i].x.toFixed(3) + ", " + endpoints[i].y.toFixed(3) + ")";
}
}
// 清空画布并重新绘制线和端点
function clearCanvas() {
endpoints = [];
endpoints.push({ angle: 0, distance: 0, x: 10, y: 10 });
ctx.clearRect(0, 0, canvas.width, canvas.height);
updateEndpointTable();
}
// 初始化绘图
drawLinesAndEndpoints();
</script>
</body>
</html>
实现线段端点显示,输出点序号、水平角、并根据角度和距离上一个点的距离计算下一个点的坐标