7.14 LAB: Move the heart image with a timer In this lab, you will use a timer to animate the movement of a heart image to the location where the mouse clicks, as shown below. The given web page shows a heart image. When the user clicks anywhere in the page, the startAnimation () function is called. startAnimation () determines where the user clicked and calls move Image () with the clicked (x, y) coordinate. move Image () moves th heart 1 pixel in the direction of the given (x, y) coordinates. Make the following JavaScript modifications using clear Interval() and setInterval() where appropriate: • In startAnimation (), add an if statement that stops the timer with the ID timerId if timer Id is not null. • In startAnimation (), start a timer that calls move Image (clickx, clicky) every 10 milliseconds. Save the timer ID in the timerId variable. • Add an if statement in move Image() that stops the timer with the ID timerId if (imgx, imgY) is equal to (centerX, centerY). Also se timerId to null. After the modifications are complete, the user should be able to click anywhere in the browser, and the heart will move to the clicked location. 360818.2547616.qx3zqy7
question in the image:
let timerId = null;
window.addEventListener("DOMContentLoaded", function() {
document.addEventListener("click", startAnimation);
});
function startAnimation(e) {
// Get mouse coordinates
let clickX = e.clientX;
let clickY = e.clientY;
// TODO: Modify the code below
moveImage(clickX, clickY);
}
function moveImage(x, y) {
const img = document.querySelector("img");
// Determine location of image
let imgX = parseInt(img.style.left);
let imgY = parseInt(img.style.top);
// Determine (x,y) coordinates that center the image
// around the clicked (x, y) coords
const centerX = Math.round(x - (img.width / 2));
const centerY = Math.round(y - (img.height / 2));
// TODO: Add code here
// Move 1 pixel in both directions toward the click
if (imgX < centerX) {
imgX++;
}
else if (imgX > centerX) {
imgX--;
}
if (imgY < centerY) {
imgY++;
}
else if (imgY > centerY) {
imgY--;
}
img.style.left = imgX + "px";
img.style.top = imgY + "px";
}
------------------
<!DOCTYPE html>
<html lang="en">
<title>Animate the Heart</title>
<script src="animate.js"></script>
<body>
<img src="heart.png" alt="heart" style="position:absolute; left:50px; top:50px">
</body>
</html>
Trending now
This is a popular solution!
Step by step
Solved in 4 steps with 4 images