Rendering article content...
JavaScript Geometry 영역 계산기 구축 : 대화식 개발자 튜토리얼 2025
JavaScript를 사용하여 대화식 다각형 영역 계산기를 만듭니다. 단순하고 복잡한 다각형 모두에 대한 마스터 지오메트리 공식, 좌표 계산 및 웹 기반 측정 도구.

JavaScript를 사용하여 대화식 다각형 영역 계산기를 만듭니다. 단순하고 복잡한 다각형 모두에 대한 마스터 지오메트리 공식, 좌표 계산 및 웹 기반 측정 도구.
Rendering article content...
JavaScript를 사용하여 자신만의 대화 형 지오메트리 계산기를 만드는 심층적 인 안내서, 간단하고 복잡한 다각형에 대한 영역 계산이 완성됩니다.
지오메트리 계산은 토지 측량 및 아키텍처에서 게임 개발 및 지리 정보 시스템에 이르기까지 수많은 실제 응용 프로그램의 기초를 형성합니다.개발자로서 우리는 종종 다양한 모양의 영역을 계산하기 위해 신뢰할 수있는 도구가 필요합니다.사용 가능한 온라인 계산기가 많이 있지만 자체적으로 구축하면 몇 가지 장점이 있습니다.
이 포괄적 인 튜토리얼에서는 JavaScript를 사용하여 강력한 대화식 지오메트리 영역 계산기를 구축하는 과정을 살펴 보겠습니다.결국, 좌표 지오메트리를 사용하여 단순하고 복잡한 다각형의 영역을 정확하게 계산하는 완전히 기능적인 웹 응용 프로그램이 있습니다.
우리의 형상 계산기는 다음과 같습니다.
대화식 다각형 입력을 갖춘 최종 JavaScript Geometry 영역 계산기 미리보기
이 튜토리얼을 따라 가려면 다음을 수행해야합니다.
코드로 다이빙하기 전에 지오메트리 계산기에 전원을 공급하는 수학적 원리를 이해해 봅시다.
다각형 (일반 또는 불규칙)의 면적을 계산하기 위해 측량사의 공식 또는 가우스 영역 공식으로도 알려진 떼 공식을 사용합니다.이 강력한 알고리즘은 모양이 얼마나 복잡한 지에 관계없이 정점에 의해 정의 된 다각형에 대해 작동합니다.
공식은 다음과 같이 표현됩니다.
Area = 0.5 * |∑(x_i * y_(i+1) - x_(i+1) * y_i)|
어디:
x_i
and y_i
are the coordinates of the i-th vertex이 공식은 다각형 주변 주위를 "걷기"하여 연속 지점 사이의 교차 제품을 계산하여 작동합니다.우리가 이것을 합치고 2로 나눌 때, 우리는 다각형의 영역을 얻습니다.
기하학 계산기의 기본 구조를 설정하여 시작하겠습니다.
Create a new file named index.html
with the following structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Geometry Area Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator-container">
<h2>Geometry Area Calculator</h2>
<div class="input-section">
<h2>Enter Polygon Coordinates</h2>
<p>Click on the canvas to add points or enter them manually below.</p>
<div class="canvas-container">
<canvas id="polygon-canvas" width="400" height="400"></canvas>
<button id="clear-canvas">Clear Canvas</button>
</div>
<div class="manual-input">
<div class="coordinates-container" id="coordinates-list">
<div class="coordinate-pair">
<input type="number" placeholder="X1" class="x-coord">
<input type="number" placeholder="Y1" class="y-coord">
<button class="remove-point">×</button>
</div>
</div>
<button id="add-point">Add Point</button>
</div>
<div class="units-selection">
<label for="units">Measurement Units:</label>
<select id="units">
<option value="pixels">Pixels</option>
<option value="meters">Meters</option>
<option value="feet">Feet</option>
</select>
</div>
<button id="calculate-area">Calculate Area</button>
</div>
<div class="results-section" id="results">
<!-- Results will be displayed here -->
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Create a file named styles.css
for styling our calculator:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: #f5f5f5;
padding: 20px;
}
.calculator-container {
max-width: 800px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
}
h2 {
font-size: 1.5rem;
margin-bottom: 15px;
color: #444;
}
p {
margin-bottom: 20px;
color: #666;
}
.canvas-container {
margin-bottom: 30px;
text-align: center;
}
canvas {
border: 1px solid #ccc;
background-color: #f9f9f9;
}
.manual-input {
margin-bottom: 25px;
}
.coordinates-container {
max-height: 200px;
overflow-y: auto;
margin-bottom: 15px;
}
.coordinate-pair {
display: flex;
margin-bottom: 8px;
align-items: center;
}
input {
width: 80px;
padding: 8px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 8px 15px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
.remove-point {
background-color: #f44336;
padding: 8px 12px;
}
.remove-point:hover {
background-color: #d32f2f;
}
#clear-canvas {
margin-top: 10px;
}
.units-selection {
margin-bottom: 25px;
}
select {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.results-section {
margin-top: 30px;
padding: 20px;
background-color: #f0f8ff;
border-radius: 6px;
display: none;
}
.results-section.active {
display: block;
}
.area-result {
font-size: 1.3rem;
margin-bottom: 15px;
}
.calculation-steps {
margin-top: 20px;
padding: 15px;
background-color: #f5f5f5;
border-radius: 4px;
font-family: monospace;
}
Now, let's create the script.js
file that will power our geometry area calculator:
// DOM Elements
const canvas = document.getElementById('polygon-canvas');
const ctx = canvas.getContext('2d');
const clearCanvasBtn = document.getElementById('clear-canvas');
const addPointBtn = document.getElementById('add-point');
const coordinatesList = document.getElementById('coordinates-list');
const calculateBtn = document.getElementById('calculate-area');
const resultsSection = document.getElementById('results');
const unitsSelect = document.getElementById('units');
// Global Variables
let points = [];
let isDragging = false;
let dragIndex = -1;
// Canvas Setup
function setupCanvas() {
// Set canvas coordinate system (origin at center)
ctx.translate(canvas.width / 2, canvas.height / 2);
drawGrid();
// Event listeners for canvas interaction
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mousemove', handleMouseMove);
canvas.addEventListener('mouseup', () => isDragging = false);
// Redraw canvas initially
redrawCanvas();
}
// Draw coordinate grid
function drawGrid() {
const width = canvas.width;
const height = canvas.height;
ctx.strokeStyle = '#e0e0e0';
ctx.lineWidth = 1;
// Vertical lines
for (let x = -width/2; x <= width/2; x += 20) {
ctx.beginPath();
ctx.moveTo(x, -height/2);
ctx.lineTo(x, height/2);
ctx.stroke();
}
// Horizontal lines
for (let y = -height/2; y <= height/2; y += 20) {
ctx.beginPath();
ctx.moveTo(-width/2, y);
ctx.lineTo(width/2, y);
ctx.stroke();
}
// X and Y axes (darker)
ctx.strokeStyle = '#aaa';
ctx.lineWidth = 2;
// X-axis
ctx.beginPath();
ctx.moveTo(-width/2, 0);
ctx.lineTo(width/2, 0);
ctx.stroke();
// Y-axis
ctx.beginPath();
ctx.moveTo(0, -height/2);
ctx.lineTo(0, height/2);
ctx.stroke();
}
// Handle mouse down event on canvas
function handleMouseDown(e) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const canvasX = (e.clientX - rect.left) * scaleX - canvas.width / 2;
const canvasY = (e.clientY - rect.top) * scaleY - canvas.height / 2;
// Check if clicking near an existing point (for dragging)
for (let i = 0; i < points.length; i++) {
const dx = points[i].x - canvasX;
const dy = points[i].y - canvasY;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 10) {
isDragging = true;
dragIndex = i;
return;
}
}
// If not dragging, add a new point
points.push({x: canvasX, y: canvasY});
updateCoordinateInputs();
redrawCanvas();
}
// Handle mouse move event on canvas
function handleMouseMove(e) {
if (!isDragging || dragIndex === -1) return;
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const canvasX = (e.clientX - rect.left) * scaleX - canvas.width / 2;
const canvasY = (e.clientY - rect.top) * scaleY - canvas.height / 2;
points[dragIndex] = {x: canvasX, y: canvasY};
updateCoordinateInputs();
redrawCanvas();
}
// Redraw the canvas with all points and connections
function redrawCanvas() {
// Clear the canvas
ctx.clearRect(-canvas.width/2, -canvas.height/2, canvas.width, canvas.height);
// Redraw the grid
drawGrid();
if (points.length === 0) return;
// Draw the polygon
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
// Connect back to the first point if we have at least 3 points
if (points.length >= 3) {
ctx.lineTo(points[0].x, points[0].y);
// Fill the polygon with a semi-transparent color
ctx.fillStyle = 'rgba(76, 175, 80, 0.2)';
ctx.fill();
}
// Draw the polygon outline
ctx.strokeStyle = '#4CAF50';
ctx.lineWidth = 2;
ctx.stroke();
// Draw the points
for (let i = 0; i < points.length; i++) {
ctx.beginPath();
ctx.arc(points[i].x, points[i].y, 5, 0, Math.PI * 2);
ctx.fillStyle = '#4CAF50';
ctx.fill();
// Label the points
ctx.fillStyle = '#333';
ctx.font = '12px Arial';
ctx.fillText(`P${i+1}`, points[i].x + 8, points[i].y - 8);
}
}
// Update the coordinate inputs based on canvas points
function updateCoordinateInputs() {
// Clear all existing inputs
coordinatesList.innerHTML = '';
// Add new inputs for each point
for (let i = 0; i < points.length; i++) {
const pair = document.createElement('div');
pair.className = 'coordinate-pair';
const xInput = document.createElement('input');
xInput.type = 'number';
xInput.className = 'x-coord';
xInput.placeholder = `X${i+1}`;
xInput.value = Math.round(points[i].x);
xInput.dataset.index = i;
const yInput = document.createElement('input');
yInput.type = 'number';
yInput.className = 'y-coord';
yInput.placeholder = `Y${i+1}`;
yInput.value = Math.round(points[i].y);
yInput.dataset.index = i;
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-point';
removeBtn.textContent = '×';
removeBtn.dataset.index = i;
pair.appendChild(xInput);
pair.appendChild(yInput);
pair.appendChild(removeBtn);
coordinatesList.appendChild(pair);
// Event listeners for manual input changes
xInput.addEventListener('change', updatePointFromInput);
yInput.addEventListener('change', updatePointFromInput);
removeBtn.addEventListener('click', removePoint);
}
}
// Update a point from manual input
function updatePointFromInput(e) {
const index = parseInt(e.target.dataset.index);
const value = parseFloat(e.target.value);
if (isNaN(value)) return;
if (e.target.className === 'x-coord') {
points[index].x = value;
} else {
points[index].y = value;
}
redrawCanvas();
}
// Remove a point
function removePoint(e) {
const index = parseInt(e.target.dataset.index);
points.splice(index, 1);
updateCoordinateInputs();
redrawCanvas();
}
// Add a new point via button
function addNewPoint() {
// Add a new point at (0, 0) or near the last point if one exists
if (points.length > 0) {
const lastPoint = points[points.length - 1];
points.push({x: lastPoint.x + 20, y: lastPoint.y + 20});
} else {
points.push({x: 0, y: 0});
}
updateCoordinateInputs();
redrawCanvas();
}
// Clear all points
function clearCanvas() {
points = [];
updateCoordinateInputs();
redrawCanvas();
resultsSection.style.display = 'none';
}
// Calculate area using the Shoelace formula
function calculatePolygonArea(vertices) {
if (vertices.length < 3) return 0;
let area = 0;
const n = vertices.length;
for (let i = 0; i < n; i++) {
const j = (i + 1) % n;
area += vertices[i].x * vertices[j].y;
area -= vertices[j].x * vertices[i].y;
}
return Math.abs(area / 2);
}
// Display the calculation results
function displayResults() {
if (points.length < 3) {
alert("You need at least 3 points to calculate area.");
return;
}
const area = calculatePolygonArea(points);
const selectedUnit = unitsSelect.value;
let unitSymbol = 'px²';
let convertedArea = area;
// Apply unit conversions if needed
if (selectedUnit === 'meters') {
unitSymbol = 'm²';
// Assuming 1 pixel = 0.01 meter for example
convertedArea = area * 0.0001;
} else if (selectedUnit === 'feet') {
unitSymbol = 'ft²';
// Assuming 1 pixel = 0.0328 feet
convertedArea = area * 0.001;
}
// Format the result
const formattedArea = convertedArea.toFixed(2);
// Create the result HTML
let resultHTML = `
<h2>Calculation Results</h2>
<div class="area-result">
<strong>Polygon Area:</strong> ${formattedArea} ${unitSymbol}
</div>
<p>Based on ${points.length} vertices</p>
<div class="calculation-steps">
<h3>Calculation Steps:</h3>
<p>Using the Shoelace formula: A = 0.5 × |∑(xᵢyᵢ₊₁ − xᵢ₊₁yᵢ)|</p>
<ol>
`;
// Add the calculation steps
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
const term = (points[i].x * points[j].y - points[j].x * points[i].y).toFixed(2);
resultHTML += `<li>Step ${i+1}: (${points[i].x} × ${points[j].y}) - (${points[j].x} × ${points[i].y}) = ${term}</li>`;
}
resultHTML += `
</ol>
<p>Summing all steps and taking absolute value: ${Math.abs(area).toFixed(2)}</p>
<p>Dividing by 2: ${(Math.abs(area)/2).toFixed(2)}</p>
</div>
`;
resultsSection.innerHTML = resultHTML;
resultsSection.style.display = 'block';
resultsSection.scrollIntoView({ behavior: 'smooth' });
}
// Initialize the application
function init() {
setupCanvas();
// Event listeners
clearCanvasBtn.addEventListener('click', clearCanvas);
addPointBtn.addEventListener('click', addNewPoint);
calculateBtn.addEventListener('click', displayResults);
}
// Start the app when the page loads
window.addEventListener('load', init);
떼 공식이 다각형의 영역을 계산하는 방법에 대한 시각적 표현
Geometry 영역 계산기의 주요 구성 요소를 분류합시다.
계산기는 대화식 다각형 생성을 위해 HTML 캔버스 요소를 사용합니다.사용자는 다음과 같습니다.
캔버스는 (0,0)이 중심에있는 좌표계로 설정되어 사용자가 양수 및 부정적인 좌표 모두에서 작업하는 것이 직관적입니다.
사용자는 두 가지 방법으로 좌표를 입력 할 수 있습니다.
두 입력 방법은 동기화되어 직관적 인 시각적 배치와 정확한 수치 입력을 모두 허용합니다.
계산기의 핵심은 Shoelace 공식의 구현입니다.
function calculatePolygonArea(vertices) {
if (vertices.length < 3) return 0;
let area = 0;
const n = vertices.length;
for (let i = 0; i < n; i++) {
const j = (i + 1) % n;
area += vertices[i].x * vertices[j].y;
area -= vertices[j].x * vertices[i].y;
}
return Math.abs(area / 2);
}
이 기능 :
이 알고리즘의 아름다움은 상호 교차하지 않는 한 볼록한 사람이든 오목한 지에 관계없이 다각형에 적합하다는 것입니다.
기본 계산기가 작동하므로 몇 가지 고급 기능으로 확장하겠습니다.
우리의 계산기는 다양한 측정 단위를 지원합니다.
유닛 변환은 영역 계산 후에 적용됩니다.
// Apply unit conversions if needed
if (selectedUnit === 'meters') {
unitSymbol = 'm²';
// Assuming 1 pixel = 0.01 meter for example
convertedArea = area * 0.0001;
} else if (selectedUnit === 'feet') {
unitSymbol = 'ft²';
// Assuming 1 pixel = 0.0328 feet
convertedArea = area * 0.001;
}
특정 요구 사항에 따라 변환 요소를 사용자 정의 할 수 있습니다.
다른 측정 시스템에 대한 단위 변환 옵션을 보여주는 계산기 인터페이스
사용자가 영역 계산 방법을 이해하도록 돕기 위해 계산 단계에 대한 자세한 분석을 제공합니다.
// Add the calculation steps
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
const term = (points[i].x * points[j].y - points[j].x * points[i].y).toFixed(2);
resultHTML += `<li>Step ${i+1}: (${points[i].x} × ${points[j].y}) - (${points[j].x} × ${points[i].y}) = ${term}</li>`;
}
이 투명성은 사용자가 결과를 확인하고 다각형 영역 계산의 수학적 원리에 대해 배우는 데 도움이됩니다.
지오메트리 계산기가 완료하기 전에 알려진 모양으로 테스트하여 정확도를 확인해 봅시다.
(0,0), (100,0), (100,50) 및 (0,50)의 정점이있는 간단한 사각형은 5,000 평방 단위의 면적을 가져야합니다.
(0,0), (50,100) 및 (100,0)에 정점이있는 삼각형은 5,000 평방 단위의 면적을 가져야합니다.
(0,0), (50,100), (100,50), (75,25) 및 (25,25)에서 정점이있는 불규칙한 다각형은 슈 일러스 공식에 따라 올바른 영역을 제공해야합니다.
각 테스트 사례에 대해 계산기는 다음과 같습니다.
지오메트리 계산기가 완전히 반응을 보이게하려면 다음과 같은 향상을 추가 할 수 있습니다.
이러한 추가로 계산기는 스마트 폰 및 태블릿에서 사용할 수 있으므로 모든 장치의 사용자가 액세스 할 수 있습니다.
지오메트리 영역 계산기를 더욱 강력하게 만들려면 이러한 추가 기능을 구현하는 방법을 고려하십시오.
버튼을 추가하여 다음과 같은 공통 모양을 신속하게 만듭니다.
다음을 사용하여 원 영역을 처리하도록 계산기를 확장하십시오.
function calculateCircleArea(radius) {
return Math.PI * radius * radius;
}
다각형의 주변을 계산하기 위해 기능 추가 :
function calculatePolygonPerimeter(vertices) {
let perimeter = 0;
const n = vertices.length;
for (let i = 0; i < n; i++) {
const j = (i + 1) % n;
const dx = vertices[j].x - vertices[i].x;
const dy = vertices[j].y - vertices[i].y;
perimeter += Math.sqrt(dx * dx + dy * dy);
}
return perimeter;
}
다각형 구성을 저장하고로드하기위한 로컬 스터를 구현하십시오.
// Save polygon
function savePolygon(name) {
const polygonData = JSON.stringify(points);
localStorage.setItem(`polygon_${name}`, polygonData);
}
// Load polygon
function loadPolygon(name) {
const polygonData = localStorage.getItem(`polygon_${name}`);
if (polygonData) {
points = JSON.parse(polygonData);
updateCoordinateInputs();
redrawCanvas();
}
}
형상 영역 계산기가 귀중한 솔루션을 제공하는 다양한 실제 응용 프로그램
JavaScript Geometry 영역 계산기에는 다양한 실제 응용 프로그램이 있습니다.
이 포괄적 인 자습서에서는 JavaScript를 사용하여 강력한 대화식 지오메트리 영역 계산기를 구축했습니다.우리의 계산기는 다음과 같습니다.
우리가 다루었던 원리와 기술과 같은 지오메트리, Shoelace 알고리즘, 캔버스 조작 및 사용자 인터페이스 설계는이 특정 프로젝트를 넘어 확장되는 귀중한 기술입니다.데이터 시각화에서 대화식 응용 프로그램에 이르기까지 다양한 웹 개발 문제에 적용 할 수 있습니다.
이 지오메트리 계산기를 구축하면 유용한 도구를 만들뿐만 아니라 수학 개념과 JavaScript에서의 구현에 대한 이해가 심화되었습니다.추가 기능으로 계산기를 확장하거나 성능을 최적화하거나 자신의 프로젝트에 통합하십시오.
행복한 코딩!