Calculator for Perpendicular Lines

Perpendicular Lines Calculator & Guide :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –border-color: #ddd; –card-background: #fff; –shadow: 0 2px 5px rgba(0,0,0,0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); line-height: 1.6; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; padding-top: 20px; padding-bottom: 40px; } .container { width: 95%; max-width: 1000px; background-color: var(–card-background); padding: 30px; border-radius: 8px; box-shadow: var(–shadow); margin-bottom: 30px; } h1, h2, h3 { color: var(–primary-color); text-align: center; margin-bottom: 20px; } h1 { font-size: 2.5em; } h2 { font-size: 1.8em; border-bottom: 2px solid var(–primary-color); padding-bottom: 10px; margin-top: 30px; } h3 { font-size: 1.4em; margin-top: 25px; color: #555; } .loan-calc-container { background-color: var(–card-background); padding: 25px; border-radius: 8px; box-shadow: var(–shadow); margin-bottom: 30px; border: 1px solid var(–border-color); } .input-group { margin-bottom: 20px; text-align: left; } .input-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #444; } .input-group input[type="number"], .input-group input[type="text"], .input-group select { width: calc(100% – 22px); padding: 12px 10px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1em; box-sizing: border-box; transition: border-color 0.3s ease; } .input-group input:focus, .input-group select:focus { border-color: var(–primary-color); outline: none; } .input-group .helper-text { font-size: 0.85em; color: #666; margin-top: 5px; display: block; } .error-message { color: #dc3545; font-size: 0.85em; margin-top: 5px; display: none; /* Hidden by default */ } .error-message.visible { display: block; } .button-group { display: flex; justify-content: space-between; margin-top: 25px; gap: 10px; } .button-group button { padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 1em; font-weight: bold; transition: background-color 0.3s ease, transform 0.2s ease; flex: 1; } .button-group button.primary { background-color: var(–primary-color); color: white; } .button-group button.primary:hover { background-color: #003366; transform: translateY(-2px); } .button-group button.secondary { background-color: #6c757d; color: white; } .button-group button.secondary:hover { background-color: #5a6268; transform: translateY(-2px); } .results-container { background-color: var(–primary-color); color: white; padding: 25px; border-radius: 8px; margin-top: 30px; box-shadow: var(–shadow); text-align: center; } .results-container h3 { color: white; margin-top: 0; margin-bottom: 15px; font-size: 1.6em; } .main-result { font-size: 2.5em; font-weight: bold; margin-bottom: 15px; display: block; padding: 10px; background-color: rgba(255, 255, 255, 0.2); border-radius: 5px; } .intermediate-results div { margin-bottom: 10px; font-size: 1.1em; } .intermediate-results span { font-weight: bold; margin-left: 5px; } .formula-explanation { font-size: 0.95em; margin-top: 20px; opacity: 0.9; } table { width: 100%; border-collapse: collapse; margin-top: 25px; margin-bottom: 30px; box-shadow: var(–shadow); } th, td { padding: 12px 15px; text-align: left; border: 1px solid var(–border-color); } thead { background-color: var(–primary-color); color: white; } tbody tr:nth-child(even) { background-color: #f2f2f2; } caption { font-size: 1.1em; font-weight: bold; color: #444; margin-bottom: 10px; text-align: left; } canvas { display: block; margin: 25px auto; background-color: var(–card-background); border-radius: 5px; box-shadow: var(–shadow); } .chart-legend { text-align: center; margin-top: 10px; font-size: 0.9em; color: #555; } .chart-legend span { display: inline-block; margin: 0 10px; } .chart-legend .color-box { display: inline-block; width: 12px; height: 12px; margin-right: 5px; vertical-align: middle; border-radius: 3px; } .article-content { background-color: var(–card-background); padding: 30px; border-radius: 8px; box-shadow: var(–shadow); text-align: left; } .article-content p, .article-content ul, .article-content ol { margin-bottom: 15px; font-size: 1.05em; } .article-content ul, .article-content ol { padding-left: 25px; } .article-content li { margin-bottom: 8px; } .article-content a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .article-content a:hover { text-decoration: underline; } .faq-item { margin-bottom: 20px; padding: 15px; background-color: #fdfdfd; border: 1px solid #eee; border-radius: 5px; } .faq-item h4 { margin: 0 0 8px 0; color: var(–primary-color); font-size: 1.2em; cursor: pointer; display: flex; justify-content: space-between; align-items: center; } .faq-item h4::after { content: '+'; font-size: 1.5em; color: #888; transition: transform 0.3s ease; } .faq-item.open h4::after { transform: rotate(45deg); } .faq-item p { margin: 0; max-height: 0; overflow: hidden; transition: max-height 0.3s ease-out, padding 0.3s ease-out; padding: 0; } .faq-item.open p { max-height: 200px; /* Adjust as needed */ padding-top: 10px; } .related-tools ul { list-style: none; padding: 0; } .related-tools li { margin-bottom: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; background-color: #f9f9f9; } .related-tools li a { font-weight: bold; display: block; margin-bottom: 5px; } .related-tools li p { font-size: 0.95em; color: #555; margin: 0; } .footer { text-align: center; margin-top: 40px; font-size: 0.9em; color: #777; } @media (max-width: 768px) { h1 { font-size: 2em; } h2 { font-size: 1.5em; } .container, .loan-calc-container, .article-content { padding: 20px; } .button-group { flex-direction: column; } .button-group button { width: 100%; } .main-result { font-size: 2em; } }

Perpendicular Lines Calculator

Instantly determine the slope of a line perpendicular to a given line.

Perpendicular Line Slope Calculator

Enter the slope of the first line. Use decimals or fractions.
Standard Line Horizontal Line (m1 = 0) Vertical Line (m1 = undefined) Select the type of the first line.

Perpendicular Line Results

Slope of Line 1 (m1):
Perpendicular Slope (m2):
Relationship:
The slope of a line perpendicular to another line is the negative reciprocal of the original line's slope. If the original slope is m1, the perpendicular slope m2 = -1/m1. Special cases apply for horizontal and vertical lines.

Slope Visualization

Line 1 Perpendicular Line
Visual representation of the two lines and their slopes.

Key Concepts & Formulas

Concept Formula / Description Unit
Slope (m) Rise / Run (Δy / Δx) Unitless
Perpendicular Slope (m2) -1 / m1 Unitless
Horizontal Line m = 0 Unitless
Vertical Line m = Undefined Unitless
Summary of essential slope concepts and the perpendicularity rule.

Understanding Perpendicular Lines and Slopes

What is a Perpendicular Line?

In geometry, two lines are considered perpendicular if they intersect at a right angle (90 degrees). This fundamental concept is crucial in various fields, from basic geometry and trigonometry to advanced calculus, physics, engineering, and computer graphics. Understanding perpendicular lines helps us analyze shapes, determine orientations, and solve complex spatial problems. The relationship between perpendicular lines is most easily understood through their slopes.

Who should use this calculator? Students learning algebra and geometry, mathematics educators, engineers, architects, surveyors, and anyone working with coordinate geometry or needing to determine the relationship between intersecting lines will find this calculator invaluable. It simplifies the process of finding the slope of a perpendicular line, saving time and reducing potential calculation errors.

Common misconceptions about perpendicular lines include:

  • Thinking that any two lines that intersect are perpendicular.
  • Forgetting the "negative" part of the negative reciprocal, leading to just finding the reciprocal.
  • Not accounting for the special cases of horizontal and vertical lines, which have undefined or zero slopes respectively.
  • Confusing perpendicular lines with parallel lines (which have equal slopes).

Perpendicular Lines Formula and Mathematical Explanation

The core principle governing perpendicular lines in a Cartesian coordinate system lies in the relationship between their slopes. Let's denote the slope of the first line as m1 and the slope of the second line as m2.

For two non-vertical lines to be perpendicular, the product of their slopes must equal -1. Mathematically, this is expressed as:
m1 * m2 = -1
This implies that the slope of one line is the negative reciprocal of the slope of the other line.
m2 = -1 / m1

Step-by-step derivation:

  1. Identify the slope of the first line (m1).
  2. If m1 is 0 (a horizontal line), the perpendicular line is vertical (undefined slope).
  3. If m1 is undefined (a vertical line), the perpendicular line is horizontal (m2 = 0).
  4. For any other non-zero, defined slope m1, calculate the negative reciprocal: m2 = -1 / m1.

Variable Explanations:

Variable Meaning Unit Typical Range
m1 Slope of the first line Unitless (-∞, ∞), including 0 and undefined
m2 Slope of the perpendicular line Unitless (-∞, ∞), including 0 and undefined
Angle of Intersection The angle formed where the two lines meet Degrees or Radians 90° (or π/2 radians) for perpendicular lines

Practical Examples (Real-World Use Cases)

Understanding perpendicular lines has numerous practical applications. Here are a couple of examples:

Example 1: Construction and Architecture Imagine an architect designing a building. They need to ensure that walls are perfectly vertical (perpendicular to the ground) and floors are perfectly horizontal. If a blueprint defines a wall's line with a slope of m1 = 3/4 (meaning for every 4 units horizontally, it rises 3 units), the floor line must be perpendicular to it.
Inputs:

  • Slope of the wall line (m1) = 3/4
  • Line Type = Standard Line
Calculation: The perpendicular slope (m2) = -1 / (3/4) = -4/3.
Interpretation: The floor line must have a slope of -4/3. This ensures the wall and floor meet at a 90-degree angle, crucial for structural integrity and aesthetics.

Example 2: Surveying and Land Measurement A surveyor is marking out a rectangular plot of land. They establish one boundary line. To ensure the adjacent boundary is perpendicular, they need to calculate the correct slope. Suppose the first boundary line runs with a slope of m1 = -2.
Inputs:

  • Slope of the first boundary line (m1) = -2
  • Line Type = Standard Line
Calculation: The perpendicular slope (m2) = -1 / (-2) = 1/2.
Interpretation: The adjacent boundary line must have a slope of 1/2 to form a 90-degree angle with the first boundary, ensuring the plot is indeed rectangular. This is vital for accurate land division and property rights.

How to Use This Perpendicular Lines Calculator

Our calculator is designed for simplicity and accuracy. Follow these steps to find the slope of a perpendicular line:

  1. Input the Slope (m1): Enter the slope of your first line into the "Slope of the First Line (m1)" field. You can use integers (e.g., 5), decimals (e.g., 0.75), or fractions (e.g., 1/3). The calculator handles these formats.
  2. Select Line Type: If your first line is horizontal (slope = 0) or vertical (slope = undefined), select the appropriate option from the "Line Type" dropdown. This ensures correct calculation for these special cases. If it's a standard line, choose "Standard Line".
  3. Calculate: Click the "Calculate Perpendicular Slope" button.
  4. View Results: The calculator will display:
    • The main result: The calculated slope of the perpendicular line (m2).
    • Intermediate values: The original slope (m1), the calculated perpendicular slope (m2), and a brief description of their relationship.
    • A visualization on the chart, showing both lines.
  5. Understand the Formula: A brief explanation of the negative reciprocal rule is provided.
  6. Use Additional Buttons:
    • Reset: Clears all inputs and results, returning the calculator to its default state.
    • Copy Results: Copies the main result, intermediate values, and key assumptions to your clipboard for easy pasting elsewhere.

Decision-making guidance: Use the calculated perpendicular slope (m2) to verify angles in geometric shapes, set up perpendicular axes in coordinate systems, or ensure right-angle intersections in design and construction projects.

Key Factors That Affect Perpendicular Line Results

While the calculation for perpendicular slopes is straightforward (m2 = -1/m1), several underlying factors influence the context and application of this concept:

  • Accuracy of Input Slope (m1): The most critical factor. If the initial slope (m1) is entered incorrectly, the calculated perpendicular slope (m2) will also be incorrect. Precision matters, especially in engineering and scientific applications.
  • Handling of Special Cases: Failing to recognize or correctly calculate for horizontal (m1=0) and vertical (m1=undefined) lines is a common pitfall. A line perpendicular to a horizontal line is always vertical, and vice versa. Our calculator explicitly handles these edge cases.
  • Coordinate System Precision: In real-world applications like surveying or CAD, the accuracy of the underlying coordinate system and measurement tools directly impacts the reliability of calculated slopes and perpendicularity.
  • Definition of "Line": The calculator assumes ideal straight lines. In practice, curves or irregular shapes might approximate lines, but the strict perpendicular slope rule applies only to true linear segments.
  • Dimensionality: This calculator operates in a 2D Cartesian plane. Perpendicularity in 3D space involves vector concepts (dot product) and has different, though related, mathematical underpinnings.
  • Context of Application: The significance of a perpendicular line depends on the field. In construction, it ensures structural stability. In mathematics, it defines geometric properties. Understanding the context helps interpret the result's importance.

Frequently Asked Questions (FAQ)

What is the slope of a line perpendicular to y = 3x + 5?

The slope of the given line (m1) is 3. The slope of a perpendicular line (m2) is the negative reciprocal: m2 = -1 / m1 = -1 / 3.

What if the first line is horizontal?

A horizontal line has a slope of m1 = 0. A line perpendicular to it is a vertical line, which has an undefined slope. Our calculator handles this when you select "Horizontal Line".

What if the first line is vertical?

A vertical line has an undefined slope. A line perpendicular to it is a horizontal line, which has a slope of m2 = 0. Our calculator handles this when you select "Vertical Line".

Can the slope of a perpendicular line be positive?

Yes, but only if the original line has a negative slope. For example, if m1 = -1/4, then m2 = -1 / (-1/4) = 4. If the original slope is positive, the perpendicular slope will always be negative, and vice versa.

What does it mean for slopes to be negative reciprocals?

It means you take the original slope, flip its numerator and denominator (find the reciprocal), and then change its sign (make it negative). For example, the negative reciprocal of 2/3 is -3/2.

Does this calculator work for lines in 3D space?

No, this calculator is designed for 2D Cartesian coordinates. Perpendicularity in 3D involves vector mathematics and is a more complex concept.

How can I verify the result visually?

You can plot both lines on a graph. If they intersect at a 90-degree angle, your calculation is correct. The included chart provides a visual representation.

What if I have the equation of the line in standard form (Ax + By = C)?

First, convert the equation to slope-intercept form (y = mx + b) to find the slope (m). The slope is -A/B. Then, use that slope in our calculator. For example, for 2x + 3y = 6, the slope m1 = -2/3. The perpendicular slope m2 would be -1 / (-2/3) = 3/2.

© 2023 Your Company Name. All rights reserved.

var chartInstance = null; // Global variable to hold chart instance function getElement(id) { return document.getElementById(id); } function validateInput(value, id, min, max, allowZero = true, allowUndefined = false) { var errorElement = getElement(id + "Error"); var inputElement = getElement(id); errorElement.innerText = ""; errorElement.classList.remove("visible"); inputElement.style.borderColor = "var(–border-color)"; if (value === "") { errorElement.innerText = "This field cannot be empty."; errorElement.classList.add("visible"); inputElement.style.borderColor = "#dc3545"; return false; } if (allowUndefined && value === "undefined") { return true; // Special case for vertical line slope } var numValue = parseFloat(value); if (isNaN(numValue)) { errorElement.innerText = "Please enter a valid number."; errorElement.classList.add("visible"); inputElement.style.borderColor = "#dc3545"; return false; } if (!allowZero && numValue === 0) { errorElement.innerText = "Value cannot be zero."; errorElement.classList.add("visible"); inputElement.style.borderColor = "#dc3545"; return false; } if (numValue max) { errorElement.innerText = "Value out of range."; errorElement.classList.add("visible"); inputElement.style.borderColor = "#dc3545"; return false; } return true; } function calculatePerpendicular() { var slope1Input = getElement("slope1"); var lineTypeSelect = getElement("lineType"); var resultsSection = getElement("resultsSection"); var chartSection = getElement("chartSection"); var slope1Str = slope1Input.value.trim(); var lineType = lineTypeSelect.value; var m1 = NaN; var m1Display = ""; var m2 = NaN; var m2Display = ""; var relationship = ""; // Reset errors getElement("slope1Error").innerText = ""; getElement("slope1Error").classList.remove("visible"); slope1Input.style.borderColor = "var(–border-color)"; getElement("lineTypeError").innerText = ""; getElement("lineTypeError").classList.remove("visible"); lineTypeSelect.style.borderColor = "var(–border-color)"; if (lineType === "horizontal") { m1 = 0; m1Display = "0 (Horizontal)"; m2 = "undefined"; // Perpendicular to horizontal is vertical m2Display = "Undefined (Vertical)"; relationship = "Perpendicular (Horizontal & Vertical)"; slope1Input.value = "0"; // Set input value for consistency slope1Input.disabled = true; } else if (lineType === "vertical") { m1 = "undefined"; m1Display = "Undefined (Vertical)"; m2 = 0; // Perpendicular to vertical is horizontal m2Display = "0 (Horizontal)"; relationship = "Perpendicular (Vertical & Horizontal)"; slope1Input.value = ""; // Clear input for vertical slope1Input.disabled = true; } else { slope1Input.disabled = false; if (!validateInput(slope1Str, "slope1", -Infinity, Infinity, true)) { resultsSection.style.display = "none"; chartSection.style.display = "none"; return; } m1 = parseFloat(slope1Str); m1Display = m1.toString(); if (m1 === 0) { // Handle case where user enters 0 but selects standard m2 = "undefined"; m2Display = "Undefined (Vertical)"; relationship = "Perpendicular (Horizontal & Vertical)"; } else { m2 = -1 / m1; m2Display = m2.toString(); relationship = "Perpendicular (m1 * m2 = -1)"; } } // Update results display getElement("intermediate1").getElementsByTagName("span")[0].innerText = m1Display; getElement("intermediate2").getElementsByTagName("span")[0].innerText = m2Display; getElement("intermediate3").getElementsByTagName("span")[0].innerText = relationship; var mainResultText = ""; if (m2 === "undefined") { mainResultText = "Undefined"; } else { mainResultText = m2.toFixed(4); // Display with reasonable precision } getElement("mainResult").innerText = mainResultText; resultsSection.style.display = "block"; chartSection.style.display = "block"; updateChart(m1, m2); } function resetCalculator() { getElement("slope1").value = ""; getElement("slope1").disabled = false; getElement("lineType").value = "standard"; getElement("resultsSection").style.display = "none"; getElement("chartSection").style.display = "none"; if (chartInstance) { chartInstance.destroy(); chartInstance = null; } // Clear error messages getElement("slope1Error").innerText = ""; getElement("slope1Error").classList.remove("visible"); getElement("lineTypeError").innerText = ""; getElement("lineTypeError").classList.remove("visible"); } function copyResults() { var mainResult = getElement("mainResult").innerText; var m1 = getElement("intermediate1").getElementsByTagName("span")[0].innerText; var m2 = getElement("intermediate2").getElementsByTagName("span")[0].innerText; var relationship = getElement("intermediate3").getElementsByTagName("span")[0].innerText; var textToCopy = "Perpendicular Line Results:\n"; textToCopy += "————————–\n"; textToCopy += "Perpendicular Slope (m2): " + mainResult + "\n"; textToCopy += "Slope of Line 1 (m1): " + m1 + "\n"; textToCopy += "Perpendicular Slope (m2): " + m2 + "\n"; textToCopy += "Relationship: " + relationship + "\n"; textToCopy += "\nFormula Used: The slope of a line perpendicular to another line is the negative reciprocal of the original line's slope (m2 = -1/m1), with special cases for horizontal and vertical lines."; navigator.clipboard.writeText(textToCopy).then(function() { // Optional: Show a confirmation message var copyButton = getElement("copyButton"); // Assuming you add an ID to the copy button if (!copyButton) { // Fallback if ID is not set copyButton = document.querySelector('.button-group button:nth-child(3)'); } var originalText = copyButton.innerText; copyButton.innerText = "Copied!"; setTimeout(function() { copyButton.innerText = originalText; }, 1500); }).catch(function(err) { console.error('Failed to copy text: ', err); // Optional: Show an error message }); } function updateChart(m1, m2) { var ctx = getElement('slopeChart').getContext('2d'); // Destroy previous chart instance if it exists if (chartInstance) { chartInstance.destroy(); } // Define chart parameters var chartWidth = 600; var chartHeight = 400; var padding = 50; var canvasWidth = chartWidth + 2 * padding; var canvasHeight = chartHeight + 2 * padding; var canvas = getElement('slopeChart'); canvas.width = canvasWidth; canvas.height = canvasHeight; ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas var xAxisMin = -10, xAxisMax = 10; var yAxisMin = -10, yAxisMax = 10; // Adjust axis limits based on slopes for better visualization var maxAbsSlope = 0; if (typeof m1 === 'number' && !isNaN(m1)) maxAbsSlope = Math.max(maxAbsSlope, Math.abs(m1)); if (typeof m2 === 'number' && !isNaN(m2)) maxAbsSlope = Math.max(maxAbsSlope, Math.abs(m2)); if (maxAbsSlope > 0) { var range = Math.max(10, maxAbsSlope * 3); // Extend range based on slope magnitude xAxisMin = -range; xAxisMax = range; yAxisMin = -range; yAxisMax = range; } // Function to map data coordinates to canvas coordinates function mapX(x) { return padding + ((x – xAxisMin) / (xAxisMax – xAxisMin)) * chartWidth; } function mapY(y) { return padding + chartHeight – ((y – yAxisMin) / (yAxisMax – yAxisMin)) * chartHeight; } // Draw Axes ctx.beginPath(); ctx.strokeStyle = '#ccc'; ctx.lineWidth = 1; // X-axis ctx.moveTo(padding, mapY(0)); ctx.lineTo(padding + chartWidth, mapY(0)); // Y-axis ctx.moveTo(mapX(0), padding); ctx.lineTo(mapX(0), padding + chartHeight); ctx.stroke(); // Draw Labels for Axes ctx.fillStyle = '#555′; ctx.font = '10px Arial'; ctx.textAlign = 'center'; ctx.fillText('X', padding + chartWidth, padding + chartHeight + 15); ctx.fillText('Y', padding – 15, padding + 5); // Draw Ticks and Labels var tickCount = 5; for (var i = -tickCount; i <= tickCount; i++) { if (i === 0) continue; // X-ticks ctx.beginPath(); ctx.moveTo(mapX(i), mapY(0) – 5); ctx.lineTo(mapX(i), mapY(0) + 5); ctx.stroke(); ctx.fillText(i.toString(), mapX(i), mapY(0) + 15); // Y-ticks ctx.beginPath(); ctx.moveTo(mapX(0) – 5, mapY(i)); ctx.lineTo(mapX(0) + 5, mapY(i)); ctx.stroke(); ctx.fillText(i.toString(), mapX(0) – 15, mapY(i) + 5); } // Function to draw a line function drawLine(slope, color, lineWidth, label) { ctx.beginPath(); ctx.strokeStyle = color; ctx.lineWidth = lineWidth; var startX, startY, endX, endY; if (slope === "undefined") { // Vertical line startX = 0; startY = yAxisMin; endX = 0; endY = yAxisMax; } else if (slope === 0) { // Horizontal line startX = xAxisMin; startY = 0; endX = xAxisMax; endY = 0; } else { // Calculate points on the line within the visible range // Using y = mx + c, assume c=0 for simplicity, passing through origin // Find x when y = yAxisMax and y = yAxisMin // Find y when x = xAxisMax and x = xAxisMin var yAtMinX = slope * xAxisMin; var yAtMaxX = slope * xAxisMax; var xAtMinY = (slope === 0) ? xAxisMin : (yAxisMin / slope); var xAtMaxY = (slope === 0) ? xAxisMax : (yAxisMax / slope); // Determine the segment of the line that falls within the viewport var points = []; // Check intersections with vertical boundaries if (Math.min(yAtMinX, yAtMaxX) = yAxisMin) { points.push({ x: xAxisMin, y: yAtMinX }); points.push({ x: xAxisMax, y: yAtMaxX }); } // Check intersections with horizontal boundaries if (Math.min(xAtMinY, xAtMaxY) = xAxisMin) { points.push({ x: xAtMinY, y: yAxisMin }); points.push({ x: xAtMaxY, y: yAxisMax }); } // Filter points to be within the axis limits var validPoints = points.filter(p => p.x >= xAxisMin && p.x = yAxisMin && p.y p.x === 0 && p.y === 0)) { validPoints.push({x: 0, y: 0}); } // Sort points by x-coordinate to draw a continuous line segment validPoints.sort((a, b) => a.x – b.x); // Remove duplicate points validPoints = validPoints.filter((point, index, self) => index === 0 || point.x !== self[index – 1].x || point.y !== self[index – 1].y ); if (validPoints.length >= 2) { startX = validPoints[0].x; startY = validPoints[0].y; endX = validPoints[1].x; endY = validPoints[1].y; } else if (validPoints.length === 1) { // Handle case where line might only touch one boundary startX = validPoints[0].x; startY = validPoints[0].y; endX = validPoints[0].x; // Draw a point if only one valid point endY = validPoints[0].y; } else { // No visible segment, maybe line is too steep or outside bounds return; } } ctx.moveTo(mapX(startX), mapY(startY)); ctx.lineTo(mapX(endX), mapY(endY)); ctx.stroke(); // Add label ctx.fillStyle = color; ctx.font = '12px Arial'; ctx.textAlign = 'center'; var midX = mapX((startX + endX) / 2); var midY = mapY((startY + endY) / 2); ctx.fillText(label, midX + 10, midY – 5); } // Draw Line 1 var color1 = '#004a99′; // Primary color var lineWidth1 = 3; var label1 = "m1"; if (m1 === "undefined") { // Draw a vertical line segment var xPos = mapX(0); // Vertical line is at x=0 ctx.beginPath(); ctx.strokeStyle = color1; ctx.lineWidth = lineWidth1; ctx.moveTo(xPos, padding); ctx.lineTo(xPos, padding + chartHeight); ctx.stroke(); ctx.fillStyle = color1; ctx.font = '12px Arial'; ctx.textAlign = 'center'; ctx.fillText(label1, xPos + 15, padding + 15); } else if (m1 === 0) { // Draw a horizontal line segment var yPos = mapY(0); // Horizontal line is at y=0 ctx.beginPath(); ctx.strokeStyle = color1; ctx.lineWidth = lineWidth1; ctx.moveTo(padding, yPos); ctx.lineTo(padding + chartWidth, yPos); ctx.stroke(); ctx.fillStyle = color1; ctx.font = '12px Arial'; ctx.textAlign = 'center'; ctx.fillText(label1, padding + chartWidth – 20, yPos – 10); } else { drawLine(m1, color1, lineWidth1, label1); } // Draw Perpendicular Line 2 var color2 = '#28a745′; // Success color var lineWidth2 = 3; var label2 = "m2"; if (m2 === "undefined") { // Draw a vertical line segment var xPos = mapX(0); // Vertical line is at x=0 ctx.beginPath(); ctx.strokeStyle = color2; ctx.lineWidth = lineWidth2; ctx.moveTo(xPos, padding); ctx.lineTo(xPos, padding + chartHeight); ctx.stroke(); ctx.fillStyle = color2; ctx.font = '12px Arial'; ctx.textAlign = 'center'; ctx.fillText(label2, xPos – 15, padding + 15); } else if (m2 === 0) { // Draw a horizontal line segment var yPos = mapY(0); // Horizontal line is at y=0 ctx.beginPath(); ctx.strokeStyle = color2; ctx.lineWidth = lineWidth2; ctx.moveTo(padding, yPos); ctx.lineTo(padding + chartWidth, yPos); ctx.stroke(); ctx.fillStyle = color2; ctx.font = '12px Arial'; ctx.textAlign = 'center'; ctx.fillText(label2, padding + 20, yPos – 10); } else { drawLine(m2, color2, lineWidth2, label2); } } function toggleFaq(element) { var faqItem = element.parentElement; faqItem.classList.toggle('open'); } // Initial calculation on load if default values are set document.addEventListener('DOMContentLoaded', function() { // Optionally pre-fill and calculate if needed, or just set up listeners // For now, we'll var the user trigger the calculation. // Example: // getElement("slope1").value = "2"; // calculatePerpendicular(); }); // Handle line type change to enable/disable slope input getElement("lineType").addEventListener("change", function() { var slope1Input = getElement("slope1"); if (this.value === "horizontal") { slope1Input.value = "0"; slope1Input.disabled = true; } else if (this.value === "vertical") { slope1Input.value = ""; slope1Input.disabled = true; } else { slope1Input.disabled = false; // Clear value if it was set for horizontal/vertical if (slope1Input.value === "0") { slope1Input.value = ""; } } });

Leave a Comment