Certainly! Let's modify your code to use the provided car images instead of drawing circles. We'll need to:
- Load the images in JavaScript.
- Draw the images at the calculated positions.
- Rotate the images so that the cars point in the direction they're moving.
Here's the updated HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Circular Track Animation with Car Images</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
#trackCanvas {
background-color: #fff;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="trackCanvas" width="600" height="600"></canvas>
<script>
var canvas = document.getElementById('trackCanvas');
var ctx = canvas.getContext('2d');
// Center of the canvas
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
// Radius of the track
var radius = 200;
// Initial angles for the cars (in radians)
var angle1 = 0;
var angle2 = 0;
// Angular speeds (convert degrees per second to radians per second)
var speed1 = (30 * Math.PI) / 180; // 30 degrees per second
var speed2 = (45 * Math.PI) / 180; // 45 degrees per second
// Load images for the cars
var car1 = new Image();
car1.src = "https://img.freepik.com/premium-psd/2d-green-sports-car-top-view_998359-126.jpg";
var car2 = new Image();
car2.src = "https://img.freepik.com/premium-psd/2d-yellow-car-top-view_998359-198.jpg";
// Timestamp of the last frame
var lastTime = null;
// Draw the scene
function draw() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the track
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.stroke();
// Calculate positions of the cars
var x1 = centerX + radius * Math.cos(angle1);
var y1 = centerY + radius * Math.sin(angle1);
var x2 = centerX + radius * Math.cos(angle2);
var y2 = centerY + radius * Math.sin(angle2);
// Calculate tangents for rotation
var tangentAngle1 = angle1 + Math.PI / 2;
var tangentAngle2 = angle2 + Math.PI / 2;
// Draw car1
drawRotatedImage(car1, x1, y1, tangentAngle1);
// Draw car2
drawRotatedImage(car2, x2, y2, tangentAngle2);
}
// Function to draw and rotate the image
function drawRotatedImage(image, x, y, angle) {
var imgWidth = 40; // Adjust as needed
var imgHeight = 40; // Adjust as needed
ctx.save(); // Save the current state
ctx.translate(x, y); // Translate to the car's position
ctx.rotate(angle); // Rotate to the car's angle
ctx.drawImage(image, -imgWidth / 2, -imgHeight / 2, imgWidth, imgHeight); // Draw the image centered
ctx.restore(); // Restore the original state
}
// Animation loop
function animate(time) {
if (lastTime != null) {
// Time difference in seconds
var deltaTime = (time - lastTime) / 1000;
// Update the angles
angle1 += speed1 * deltaTime;
angle2 += speed2 * deltaTime;
// Normalize the angles
angle1 %= 2 * Math.PI;
angle2 %= 2 * Math.PI;
// Redraw the scene
draw();
}
lastTime = time;
// Request the next frame
requestAnimationFrame(animate);
}
// Start the animation once the images are loaded
car1.onload = function() {
car2.onload = function() {
requestAnimationFrame(animate);
}
}
</script>
</body>
</html>
Explanation of the Changes:
-
Loading the Images:
- We created two
Image objects (car1 and car2) and set their src properties to the URLs you provided.
-
Drawing and Rotating the Images:
- Added a helper function
drawRotatedImage(image, x, y, angle) that handles drawing each car image at the correct position and rotation.
- Inside this function, we use
ctx.save() and ctx.restore() to preserve the canvas state before and after transformation.
- The
ctx.translate(x, y) moves the origin to the car's position.
- The
ctx.rotate(angle) rotates the canvas so that the car points in the direction of movement.
- The car image is drawn centered at the new origin.
-
Calculating the Tangent Angle:
- The tangent angle is calculated by adding
Math.PI / 2 to the angle of movement (angle1 and angle2).
- This ensures that the car image is oriented tangentially to the track, pointing in the direction of motion.
-
Adjusting Image Size:
- Set
imgWidth and imgHeight in the drawRotatedImage function to control the size of the car images on the canvas.
- You can adjust these values (
40 in the example) to fit your specific needs.
-
Starting the Animation After Images Load:
- The animation starts only after both images (
car1 and car2) have loaded, ensuring that the images are available when we begin drawing.
Important Notes:
-
Cross-Origin Restrictions:
- The images you're using are hosted on an external server. Due to browser security policies (CORS), loading images from a different origin might cause issues, especially when manipulating them in a canvas.
- If you encounter errors like
Cross-Origin Request Blocked, you may need to host the images on your own server or use images that support cross-origin requests.
-
Adjusting for Image Orientation:
- The
Math.PI / 2 adjustment in the rotation accounts for the orientation of the car images assuming they are initially pointing upwards.
- If your car images are oriented differently (e.g., pointing to the right), you might need to adjust the angle accordingly.
-
Image Size and Aspect Ratio:
- Ensure that the
imgWidth and imgHeight maintain the aspect ratio of your images to avoid distortion.
- You can also retrieve the actual dimensions of the image using
image.width and image.height, then scale them appropriately.
Example Adjustments:
// If the car image is 100x50 pixels, and you want to scale it down by half
var imgWidth = image.width / 2;
var imgHeight = image.height / 2;
Testing the Code:
- Copy and paste the entire code into a local HTML file and open it in your browser.
- Ensure that your browser allows loading images from the provided URLs.
- Watch as the two car images move around the circular track at their respective speeds.
Troubleshooting:
Feel free to adjust the parameters and styles to suit your preferences!