The Leash exercise is a JavaScript Graphics programming activity in CodeHS. It teaches students how to create a moving ball connected to a fixed point using a line. The ball follows the mouse pointer, while the line’s endpoint moves with it. The exercise introduces JavaScript graphics, mouse events, coordinates, functions, and object positioning.
What Is the Leash Exercise in CodeHS?
The Leash exercise is a practical programming challenge that introduces students to interactive graphics using JavaScript. Instead of producing a simple text output, students create visual objects on a graphics canvas and control their movement through code. The activity commonly involves a circle representing a ball and a line connecting that ball to a fixed point. When the mouse moves, the circle follows its position, creating the appearance of a ball attached to a leash.
This exercise is useful because it combines several programming concepts in one relatively small project. Students learn how to create graphics objects, assign positions, register mouse events, and update existing objects. These techniques are important for understanding how interactive applications work. Similar programming principles are used in browser games, drawing applications, animations, and other projects where objects respond to user actions.
What Does the Assignment Actually Require?
The main objective of the JavaScript Graphics version is to make a ball move with the mouse while maintaining a visual connection to a fixed point. The line acts as the leash, and its starting position remains unchanged. The circle and the moving endpoint of the line must receive matching coordinates whenever the mouse moves. This relationship creates the expected visual effect.
The basic requirements of the commonly described exercise include:
- Creating a circle to represent the ball.
- Creating a line to represent the leash.
- Positioning the objects around the canvas centre.
- Registering a mouse movement event.
- Moving the ball to the current mouse position.
- Updating the moving endpoint of the line.
- Keeping the other endpoint fixed.
Students should compare these requirements with their actual assignment page. CodeHS lesson numbers and instructions can vary between courses, so the course version matters.
Understanding the JavaScript Graphics Environment
JavaScript Graphics provides tools that allow students to create and control visual objects. A graphics canvas acts as the working area where shapes appear. Each object has properties and methods that determine its appearance and position. For example, a circle can have a particular radius and colour, while a line requires coordinates defining its starting and ending points.
The graphics environment also provides methods for responding to user interaction. Rather than manually changing an object’s position, a program can receive information about mouse movement and update the object automatically. This makes the exercise a useful introduction to event-driven programming. Students learn that a program can respond continuously to external actions instead of simply executing a fixed sequence of instructions.
Complete JavaScript Code for the Leash Exercise
The following example demonstrates the main programming logic. It creates a circle and a line at the centre of the canvas, then registers a function that responds to mouse movement. Both graphical objects are created once and updated whenever the pointer moves.
JavaScript reference solution:
var BALL_RADIUS = 20;
var ball;
var leash;
function start() {
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
// Create the leash line
leash = new Line(
centerX,
centerY,
centerX,
centerY
);
add(leash);
// Create the ball
ball = new Circle(BALL_RADIUS);
ball.setPosition(centerX, centerY);
ball.setColor(Color.YELLOW);
add(ball);
// Register mouse movement
mouseMoveMethod(updateLeash);
}
function updateLeash(e) {
var mouseX = e.getX();
var mouseY = e.getY();
// Move the ball
ball.setPosition(mouseX, mouseY);
// Update the leash endpoint
leash.setEndpoint(mouseX, mouseY);
}
This example uses a radius of 20 as a demonstration. If your assignment specifies a different radius, colour, variable name, or starting position, follow those original requirements. The important programming logic is creating the objects once and updating their positions through the mouse event handler.
How Does the Start Function Work?
The start() function is responsible for preparing the graphics environment. It runs when the program begins and creates the objects required for the exercise. The first step calculates the centre of the canvas by dividing its width and height by two. These calculations provide coordinates that work with the available canvas dimensions instead of relying on arbitrary fixed numbers.
After calculating the centre, the program creates the leash and the ball. Both objects initially appear at the same location. The add() method places each object on the visible canvas, and the final statement registers the mouse movement function. Once this setup is complete, the program is ready to respond to mouse movement without creating additional graphics objects.
Understanding the Circle and Line Objects
A circle is created using the Circle() constructor, which accepts a radius value. The radius determines the size of the ball. After creating the circle, setPosition() places its centre at the coordinates supplied by the program. The colour can also be changed through setColor(), making it easier to distinguish the ball from the connecting line.
The line uses a different constructor because it needs four coordinate values rather than a single radius. The first two values represent its starting point, while the final two represent its endpoint. Initially, both points are set to the centre of the canvas. This means the line begins with no visible length. When the mouse moves, its endpoint changes while its starting position remains fixed.
How Mouse Movement Controls the Ball
The mouseMoveMethod() function makes the program interactive. It registers another function as a callback, meaning CodeHS will execute that function whenever the mouse moves over the graphics canvas. In the example, updateLeash is passed without parentheses. This is important because the program needs to register the function for later execution rather than call it immediately.
The callback receives an event parameter named e. This parameter contains information about the mouse action, including its current horizontal and vertical coordinates. The program retrieves those values using e.getX() and e.getY(). It then uses the coordinates to update the ball and the line. This is the central mechanism that makes the visual leash effect possible.
Why setPosition() and setEndpoint() Are Important
The setPosition() method changes the position of a supported graphics object. In this exercise, it moves the centre of the circle to the current mouse coordinates. Each time the mouse moves, the program supplies new values, so the circle follows the pointer instead of remaining at its original position.
The setEndpoint() method performs a different operation. It changes the ending coordinates of the line without changing its starting point. This is exactly what the leash effect requires. Both methods are necessary because moving the circle does not automatically move the line. Students must update the two objects separately using matching coordinates.
Understanding the Canvas Coordinate System
The graphics canvas uses two-dimensional coordinates. The X-coordinate represents horizontal position, while the Y-coordinate represents vertical position. The top-left area normally represents the origin, with coordinates increasing as an object moves toward the right or downward. Understanding this system helps students position objects accurately.
For example, if the canvas is 400 pixels wide and 400 pixels high, its centre is approximately at coordinates (200, 200). Dividing the canvas dimensions by two allows the program to calculate this position automatically. The same method works with different canvas sizes, making the code more adaptable and reducing the need for manually entered coordinates.
Common Errors Students Should Avoid
Small mistakes can prevent the graphics program from working properly. One common problem is forgetting to register the mouse movement function. Another is updating the circle but not the line. Students may also accidentally create a new circle every time the mouse moves, which can cause multiple shapes to appear on the screen.
The following table explains common problems and what to check:
| Problem | Possible cause | Recommended fix |
| Ball does not move | Mouse event not registered | Check mouseMoveMethod() |
| Line does not follow | Endpoint is not updated | Use setEndpoint() |
| Ball and line separate | Different coordinates | Use the same X and Y values |
| Multiple balls appear | New circles created repeatedly | Create the circle once |
| Variable is undefined | Incorrect variable scope | Declare shared variables globally |
| Graphics are invisible | Missing add() method | Add both objects to the canvas |
| Entire line moves | Wrong movement method | Update only its endpoint |
Checking these issues individually is more effective than rewriting the entire program whenever an error appears. Students should first confirm that the objects are visible, then test mouse movement, and finally verify that the line stays connected to the circle.
How to Test the Program Correctly
Testing is an important part of completing any programming activity. After running the program, check whether the circle and line appear in their initial positions. Move the mouse slowly across the canvas and observe whether the circle follows the pointer. The line should stretch between the fixed starting point and the moving circle.
Next, test different areas of the canvas. Move the pointer toward the upper-left corner, upper-right corner, lower-left corner, and lower-right corner. This helps identify problems involving horizontal and vertical coordinates. If the ball moves correctly but the line does not, inspect the endpoint update. If neither object responds, check the event registration and function names.
Why Global Variables Are Used in This Exercise
Global variables allow multiple functions to access the same graphics objects. In the example, ball and leash are declared outside the start() and updateLeash() functions. This means the setup function can create the objects, while the event handler can access and modify them later.
If the objects were declared only as local variables inside start(), the separate event handler might not be able to access them. This could produce an undefined-variable error. Learning about variable scope is important because larger programs often contain multiple functions that need to work with shared information and objects.
What Programming Skills Does This Activity Teach?
The activity teaches more than how to move a circle across a screen. It introduces event-driven programming, object creation, coordinate calculations, variable scope, and function callbacks. These concepts are frequently used in interactive applications, making the exercise a useful starting point for students who want to understand how graphical programs work.
It also develops problem-solving skills. Students need to identify which object is not behaving correctly, determine which method controls that object, and test possible corrections. This approach encourages logical thinking rather than simply changing code until the output looks right. Understanding these principles makes it easier to complete more advanced programming exercises.
Where Can You Find Reliable CodeHS Documentation?
The official CodeHS documentation is one of the most useful resources for understanding the JavaScript Graphics library. It explains how graphics objects are created, how lines and circles are positioned, and how mouse events are registered. These explanations help students understand the methods used in the example instead of depending entirely on copied solutions.
Useful resources include:
- CodeHS JavaScript Graphics Documentation – Information about graphics objects and mouse events.
- CodeHS JavaScript Documentation – JavaScript syntax and programming concepts.
- CodeHS JavaScript Library – Reference material for the graphics library.
When using online solutions, compare the code with your own assignment instructions. An example that works for one curriculum version may not satisfy the requirements of another version.
Conclusion: Mastering the Leash Programming Exercise
The Leash exercise provides a practical introduction to JavaScript Graphics and interactive programming. By creating a circle, connecting it to a line, and responding to mouse movement, students learn how graphical objects can work together. The activity also demonstrates why coordinates, event handlers, and shared variables are important when building interactive applications.
The best way to complete the exercise is to understand the purpose of each programming instruction. Create the objects once, register the mouse movement callback, and update the ball and line with matching coordinates. Test the program carefully and compare the final result with your course requirements. These skills will help you approach more advanced CodeHS graphics and animation activities with greater confidence.
Frequently Asked Questions (FAQs)
1. What is the 9.7.4 Leash exercise in CodeHS?
It is a JavaScript Graphics exercise that involves creating a ball connected to a line. The ball follows the mouse pointer while one endpoint of the line remains fixed.
2. Which function makes the ball follow the mouse?
The mouseMoveMethod() function registers a callback that responds to mouse movement. The callback retrieves the pointer’s coordinates and updates the circle’s position.
3. Why is my leash line not following the ball?
The event handler may be updating the circle without updating the line. Make sure setEndpoint() receives the same X and Y coordinates as the circle’s setPosition() method.
4. Can I use the same JavaScript code for every CodeHS course?
No. Different CodeHS courses may use different programming languages or assignment requirements. Check the course name, lesson instructions, and starter code before using an example.
