Step-by-Step Code Solution for 9.7.4 Leash
start function, and updating the positions inside a mouse movement function.var BALL_RADIUS = 30;
var ball;
var line;
function start() {
// Center calculations for the canvas
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
ball = new Circle(BALL_RADIUS);
ball.setPosition(centerX, centerY);
ball.setColor(Color.yellow);
add(ball);
// Line starts and ends at the center initially
line = new Line(centerX, centerY, centerX, centerY);
add(line);
mouseMoveMethod(leash);
}
function leash(e) {
line.setEndpoint(e.getX(), e.getY());
ball.setPosition(e.getX(), e.getY());
// Keep the ball on top of the line
add(ball);
}
Why is My Ball Drawing Behind the Line?
The Z-Index Layering Trick
leash function continuously updates the endpoint of the line, the system redraws that line constantly.leash(e) function above: add(ball);. By calling the add method again right after moving the ball, you force the program to pull the circle back to the very front of the visual stack. Without that single line of code, your leash looks broken every time the cursor changes direction.Common Pitfalls to Avoid in This Lesson
- Adding multiple event listeners: Only call
mouseMoveMethod(leash);once inside yourstart()block. If you call it multiple times or put it inside a loop, your program will lag and crash the browser tab. - Hardcoding canvas dimensions: Do not use fixed numbers like
200or250for the center of the screen. CodeHS tests your code on different screen widths. Always usegetWidth() / 2andgetHeight() / 2to ensure it works on a mobile layout or a massive desktop monitor. - Forgetting variable scope: Keep
ballandlineas global variables at the very top of your script. If you declare them withvarinside thestart()function, theleash()function will not be able to find them, resulting in a “variable not defined” error.
FAQ Section
How do I find the coordinates of the mouse in CodeHS?
e. Calling e.getX() extracts the horizontal pixel location, while e.getY() extracts the vertical pixel location of the cursor.What does the mouseMoveMethod do?
Why does my line stretch from the top-left corner instead of the center?
Line object to 0, 0. Make sure the first two numbers in your new Line() constructor are explicitly set to half of the canvas width and height.Conclusion

John Carrol is a Christian writer and prayer minister with over a decade of experience in faith-based content, devotional writing, and spiritual encouragement. Rooted in Scripture and a lifelong love of intercessory prayer, John created PrayersFlower to help believers find the right words when their own run out. His writing draws from pastoral study, personal faith practice, and a deep conviction that prayer is the most powerful act available to the human heart. When he is not writing, John is found in quiet study of the Word, mentoring young believers, and serving his local church community.
