<script>
// Constants and Canvas Setup
const UNIT = 10; // 1 unit = 10 pixels
const PADDING = 20; // Padding inside the canvas
const leftCanvas = document.getElementById('left-triangle');
const leftCtx = leftCanvas.getContext('2d');
const rightCanvas = document.getElementById('right-triangle');
const rightCtx = rightCanvas.getContext('2d');
const verticalInput = document.getElementById('vertical-side');
const compareBtn = document.getElementById('compare-btn');
const resetBtn = document.getElementById('reset-btn');
let animationInProgress = false;
// Draw the Fixed Left Triangle
drawTriangle(leftCtx, 6, 8, 'blue');
// Event Listeners
verticalInput.addEventListener('input', updateRightTriangle);
compareBtn.addEventListener('click', () => {
if (animationInProgress) return;
animationInProgress = true;
animateTriangles();
});
resetBtn.addEventListener('click', resetTriangles);
// Function to Calculate Hypotenuse
function calculateHypotenuse(baseUnits, heightUnits) {
return Math.sqrt(baseUnits * baseUnits + heightUnits * heightUnits);
}
// Function to Draw a Right-Angled Triangle with Side Labels
function drawTriangle(ctx, baseUnits, heightUnits, color = 'blue') {
const base = baseUnits * UNIT;
const height = heightUnits * UNIT;
const hypotenuseUnits = calculateHypotenuse(baseUnits, heightUnits);
const hypotenuse = hypotenuseUnits * UNIT;
const canvasWidth = ctx.canvas.width;
const canvasHeight = ctx.canvas.height;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Draw the triangle
ctx.beginPath();
ctx.moveTo(PADDING, canvasHeight - PADDING); // Left bottom corner
ctx.lineTo(PADDING + base, canvasHeight - PADDING); // Right bottom corner
ctx.lineTo(PADDING, canvasHeight - PADDING - height); // Top corner
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.stroke();
// Set text styling
ctx.font = '14px Arial';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Label base
ctx.save();
ctx.fillText(
baseUnits + ' units',
PADDING + base / 2,
canvasHeight - PADDING + 15
);
ctx.restore();
// Label height
ctx.save();
ctx.translate(PADDING - 10, canvasHeight - PADDING - height / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(heightUnits + ' units', 0, 0);
ctx.restore();
// Label hypotenuse
ctx.save();
const angle = Math.atan2(height, base);
ctx.translate(30+PADDING + base / 2, canvasHeight - PADDING - height / 2-10);
//ctx.rotate(-angle);
ctx.fillText(hypotenuseUnits.toFixed(2) + ' units', 0, -10);
ctx.restore();
}
// Update the Right Triangle Based on User Input
function updateRightTriangle() {
const heightUnits = parseFloat(verticalInput.value);
const baseUnits = 9; // Given base side is 9 units
if (isNaN(heightUnits) || heightUnits <= 0) {
// Clear the canvas if input is invalid
rightCtx.clearRect(0, 0, rightCanvas.width, rightCanvas.height);
return;
}
// Draw the dynamic right triangle
drawTriangle(rightCtx, baseUnits, heightUnits, 'green');
}
// Animate Triangles When Comparing Similarity
function animateTriangles() {
const scaleFactor = 1.5; // Scaling factor for the left triangle
// Get the positions of the bottom left corners
const leftRect = leftCanvas.getBoundingClientRect();
const rightRect = rightCanvas.getBoundingClientRect();
// Left triangle's bottom left corner position (taking padding into account)
const leftCornerX = leftRect.left + PADDING;
const leftCornerY = leftRect.top + leftCanvas.height - PADDING;
// Right triangle's bottom left corner position
const rightCornerX = rightRect.left + PADDING;
const rightCornerY = rightRect.top + rightCanvas.height - PADDING;
// Compute the target position (midpoint)
const targetX = (leftCornerX + rightCornerX) / 2;
const targetY = (leftCornerY + rightCornerY) / 2;
// Set transform origins to the bottom left corners (with padding)
leftCanvas.style.transformOrigin = `${PADDING}px ${leftCanvas.height - PADDING}px`;
rightCanvas.style.transformOrigin = `${PADDING}px ${rightCanvas.height - PADDING}px`;
// Calculate the adjusted translation amounts for the left triangle
const scaledHeight = leftCanvas.height * scaleFactor;
const leftCornerYAfterScaling = leftCornerY - (scaledHeight - leftCanvas.height);
const leftTx = targetX - leftCornerX;
const leftTy = targetY - leftCornerYAfterScaling-scaledHeight/3;
// Translation amounts for the right triangle
const rightTx = targetX - rightCornerX;
const rightTy = targetY - rightCornerY;
// Apply transformations
leftCanvas.classList.add('animated');
rightCanvas.classList.add('animated');
leftCanvas.style.transform = `translate(${leftTx}px, ${leftTy}px) scale(${scaleFactor})`;
rightCanvas.style.transform = `translate(${rightTx}px, ${rightTy}px)`;
// Change opacity to 0.8 during movement
leftCanvas.style.opacity = '0.8';
rightCanvas.style.opacity = '0.8';
// Check similarity after animation
setTimeout(() => {
animationInProgress = false;
checkSimilarity();
}, 2000);
}
// Check the Similarity of the Two Triangles
function checkSimilarity() {
const scaleFactor = 1.5; // Left triangle is scaled by 1.5
const leftBase = 6 * scaleFactor;
const leftHeight = 8 * scaleFactor;
const rightBase = 9;
const rightHeight = parseFloat(verticalInput.value);
if (isNaN(rightHeight) || rightHeight <= 0) {
alert('Please enter a valid vertical side length.');
return;
}
// Compare the ratios of corresponding sides
const ratioBase = leftBase / rightBase;
const ratioHeight = leftHeight / rightHeight;
if (Math.abs(ratioBase - ratioHeight) < 0.01) {
alert('The triangles are similar!');
} else {
alert('The triangles are not similar.');
}
}
// Reset Triangles to Original Position
function resetTriangles() {
// Remove transformations
leftCanvas.style.transition = '';
rightCanvas.style.transition = '';
leftCanvas.style.transform = 'none';
rightCanvas.style.transform = 'none';
leftCanvas.style.opacity = '1';
rightCanvas.style.opacity = '1';
// Remove animated class
leftCanvas.classList.remove('animated');
rightCanvas.classList.remove('animated');
// Redraw triangles
drawTriangle(leftCtx, 6, 8, 'blue');
updateRightTriangle();
}
// Initialize the Right Triangle on Page Load
updateRightTriangle();
</script>
Certainly! Based on your request, you want to hide the edge length texts (labels) on the triangles when they animate and meet for comparison, and re-display them when the triangles return to their original positions.
To achieve this, we'll modify your existing code to control the visibility of the labels during the animation. Here's how you can do it:
Modify the drawTriangle Function:
Add a new parameter to the drawTriangle function to control whether labels should be displayed.
Use this parameter to conditionally render the labels.
Update the Animation Functions:
Before starting the animation, redraw the triangles without labels.
After the animation ends or when resetting, redraw the triangles with labels.
Below is the updated code with the necessary changes:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Triangle Similarity App</title>
<style>
/* Basic Styling */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
display: flex;
justify-content: space-between;
align-items: center; /* Center items vertically */
margin: 20px;
height: calc(100vh - 160px); /* Adjust height to fill the viewport */
}
.left-side, .right-side {
width: 45%;
display: flex;
flex-direction: column;
align-items: center;
position: relative;
}
.triangle-container {
position: relative;
width: 250px; /* Increased canvas size for labels */
height: 250px;
}
canvas {
position: absolute;
bottom: 0; /* Align canvas to the bottom of the container */
left: 0;
/* Remove background color for transparency */
background-color: transparent;
}
.controls {
margin-top: 20px;
width: 100%;
}
.controls label {
display: block;
margin-bottom: 5px;
}
.controls input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.buttons {
text-align: center;
margin-top: 20px;
}
.buttons button {
margin: 0 10px;
padding: 10px 20px;
font-size: 16px;
}
/* Animation Styles */
.animated {
transition: transform 2s, opacity 2s;
}
</style>
</head>
<body>
<div class="container">
<!-- Left Side (Fixed Triangle) -->
<div class="left-side">
<div class="triangle-container">
<canvas id="left-triangle" width="250" height="250"></canvas>
</div>
</div>
<!-- Right Side (Dynamic Triangle) -->
<div class="right-side">
<div class="triangle-container">
<canvas id="right-triangle" width="250" height="250"></canvas>
</div>
<div class="controls">
<label for="vertical-side">Enter Vertical Side Length (units):</label>
<input type="number" id="vertical-side" min="0" value="1" placeholder="Enter a positive number">
</div>
</div>
</div>
<!-- Buttons -->
<div class="buttons">
<button id="compare-btn">Compare Similarity of Triangles</button>
<button id="reset-btn">Okay</button>
</div>
<script>
// Constants and Canvas Setup
const UNIT = 10; // 1 unit = 10 pixels
const PADDING = 20; // Padding inside the canvas
const leftCanvas = document.getElementById('left-triangle');
const leftCtx = leftCanvas.getContext('2d');
const rightCanvas = document.getElementById('right-triangle');
const rightCtx = rightCanvas.getContext('2d');
const verticalInput = document.getElementById('vertical-side');
const compareBtn = document.getElementById('compare-btn');
const resetBtn = document.getElementById('reset-btn');
let animationInProgress = false;
// Draw the Fixed Left Triangle with labels
drawTriangle(leftCtx, 6, 8, 'blue');
// Event Listeners
verticalInput.addEventListener('input', updateRightTriangle);
compareBtn.addEventListener('click', () => {
if (animationInProgress) return;
animationInProgress = true;
animateTriangles();
});
resetBtn.addEventListener('click', resetTriangles);
// Function to Calculate Hypotenuse
function calculateHypotenuse(baseUnits, heightUnits) {
return Math.sqrt(baseUnits * baseUnits + heightUnits * heightUnits);
}
// Function to Draw a Right-Angled Triangle with Side Labels
function drawTriangle(ctx, baseUnits, heightUnits, color = 'blue', showLabels = true) {
const base = baseUnits * UNIT;
const height = heightUnits * UNIT;
const hypotenuseUnits = calculateHypotenuse(baseUnits, heightUnits);
const hypotenuse = hypotenuseUnits * UNIT;
const canvasWidth = ctx.canvas.width;
const canvasHeight = ctx.canvas.height;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Draw the triangle
ctx.beginPath();
ctx.moveTo(PADDING, canvasHeight - PADDING); // Left bottom corner
ctx.lineTo(PADDING + base, canvasHeight - PADDING); // Right bottom corner
ctx.lineTo(PADDING, canvasHeight - PADDING - height); // Top corner
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
ctx.stroke();
if (showLabels) {
// Set text styling
ctx.font = '14px Arial';
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Label base
ctx.save();
ctx.fillText(
baseUnits + ' units',
PADDING + base / 2,
canvasHeight - PADDING + 15
);
ctx.restore();
// Label height
ctx.save();
ctx.translate(PADDING - 10, canvasHeight - PADDING - height / 2);
ctx.rotate(-Math.PI / 2);
ctx.fillText(heightUnits + ' units', 0, 0);
ctx.restore();
// Label hypotenuse
ctx.save();
const angle = Math.atan2(height, base);
ctx.translate(PADDING + base / 2, canvasHeight - PADDING - height / 2);
ctx.rotate(-angle);
ctx.fillText(hypotenuseUnits.toFixed(2) + ' units', 0, -10);
ctx.restore();
}
}
// Update the Right Triangle Based on User Input
function updateRightTriangle() {
const heightUnits = parseFloat(verticalInput.value);
const baseUnits = 9; // Given base side is 9 units
if (isNaN(heightUnits) || heightUnits <= 0) {
// Clear the canvas if input is invalid
rightCtx.clearRect(0, 0, rightCanvas.width, rightCanvas.height);
return;
}
// Draw the dynamic right triangle with labels
drawTriangle(rightCtx, baseUnits, heightUnits, 'green');
}
// Animate Triangles When Comparing Similarity
function animateTriangles() {
const scaleFactor = 1.5; // Scaling factor for the left triangle
// Hide labels before animation
drawTriangle(leftCtx, 6, 8, 'blue', false);
const rightHeightUnits = parseFloat(verticalInput.value);
drawTriangle(rightCtx, 9, rightHeightUnits, 'green', false);
// Get the positions of the bottom left corners
const leftRect = leftCanvas.getBoundingClientRect();
const rightRect = rightCanvas.getBoundingClientRect();
// Left triangle's bottom left corner position (taking padding into account)
const leftCornerX = leftRect.left + PADDING;
const leftCornerY = leftRect.top + leftCanvas.height - PADDING;
// Right triangle's bottom left corner position
const rightCornerX = rightRect.left + PADDING;
const rightCornerY = rightRect.top + rightCanvas.height - PADDING;
// Compute the target position (midpoint)
const targetX = (leftCornerX + rightCornerX) / 2;
const targetY = (leftCornerY + rightCornerY) / 2;
// Set transform origins to the bottom left corners (with padding)
leftCanvas.style.transformOrigin = `${PADDING}px ${leftCanvas.height - PADDING}px`;
rightCanvas.style.transformOrigin = `${PADDING}px ${rightCanvas.height - PADDING}px`;
// Calculate the adjusted translation amounts for the left triangle
const scaledHeight = leftCanvas.height * scaleFactor;
const leftCornerYAfterScaling = leftCornerY - (scaledHeight - leftCanvas.height);
const leftTx = targetX - leftCornerX;
const leftTy = targetY - leftCornerYAfterScaling - scaledHeight / 3;
// Translation amounts for the right triangle
const rightTx = targetX - rightCornerX;
const rightTy = targetY - rightCornerY;
// Apply transformations
leftCanvas.classList.add('animated');
rightCanvas.classList.add('animated');
leftCanvas.style.transform = `translate(${leftTx}px, ${leftTy}px) scale(${scaleFactor})`;
rightCanvas.style.transform = `translate(${rightTx}px, ${rightTy}px)`;
// Change opacity to 0.8 during movement
leftCanvas.style.opacity = '0.8';
rightCanvas.style.opacity = '0.8';
// Check similarity after animation
setTimeout(() => {
animationInProgress = false;
checkSimilarity();
}, 2000);
}
// Check the Similarity of the Two Triangles
function checkSimilarity() {
const scaleFactor = 1.5; // Left triangle is scaled by 1.5
const leftBase = 6 * scaleFactor;
const leftHeight = 8 * scaleFactor;
const rightBase = 9;
const rightHeight = parseFloat(verticalInput.value);
if (isNaN(rightHeight) || rightHeight <= 0) {
alert('Please enter a valid vertical side length.');
return;
}
// Compare the ratios of corresponding sides
const ratioBase = leftBase / rightBase;
const ratioHeight = leftHeight / rightHeight;
if (Math.abs(ratioBase - ratioHeight) < 0.01) {
alert('The triangles are similar!');
} else {
alert('The triangles are not similar.');
}
}
// Reset Triangles to Original Position
function resetTriangles() {
// Remove transformations
leftCanvas.style.transition = '';
rightCanvas.style.transition = '';
leftCanvas.style.transform = 'none';
rightCanvas.style.transform = 'none';
leftCanvas.style.opacity = '1';
rightCanvas.style.opacity = '1';
// Remove animated class
leftCanvas.classList.remove('animated');
rightCanvas.classList.remove('animated');
// Redraw triangles with labels
drawTriangle(leftCtx, 6, 8, 'blue', true);
updateRightTriangle();
}
// Initialize the Right Triangle on Page Load
updateRightTriangle();
</script>
</body>
</html>
Explanation of Changes:
Added showLabels Parameter to drawTriangle Function:
javascript
function drawTriangle(ctx, baseUnits, heightUnits, color = 'blue', showLabels = true) {
// ... existing code ...
if (showLabels) {
// Code to draw labels goes here
}
}
This parameter defaults to true so that labels are shown by default.
After resetting transformations and styles, we redraw the triangles with labels.
Calling updateRightTriangle() will draw the right triangle with labels again.
Removed Labels During Animation:
The labels are not displayed during the transition because showLabels is set to false during the redraw before animation.
This gives the effect of labels disappearing when triangles meet and reappearing when they return.
Note: Make sure you test the updated code in your environment to ensure everything works as expected.
Alternative Styling Adjustment (Optional):
If you notice any glitch with the labels when the triangles are moving back, you can ensure a smoother transition by adjusting the transition property in the CSS: