The 9.7.4 Leash exercise is a beginner-friendly programming activity that teaches students how to create interactive graphics using JavaScript. It focuses on drawing a line, positioning a graphical object, and responding to mouse movement. Although the task may look simple, it introduces several important programming concepts that students can use in animations, interactive applications, and beginner game development.
Students searching for 9.7.4 Leash usually want to understand what the assignment requires, how to write the correct code, and why the program behaves the way it does. The key is to understand the relationship between a moving object, its coordinates, and a line that connects it to a fixed point.
In this guide, you will learn what the 9.7.4 Leash exercise means, how to approach the solution, which JavaScript graphics methods are involved, and how to identify common coding mistakes. You will also find a complete example, a step-by-step explanation, testing advice, and answers to frequently asked questions.
What Is 9.7.4 Leash?
9.7.4 Leash is a JavaScript graphics exercise associated with the Drawing Lines lesson in a CodeHS introductory computer science curriculum. The activity helps students understand how graphical objects can respond to user input while maintaining a visual connection to another point on the screen.
The central idea is straightforward. A circle or ball appears on a graphics canvas, and a line connects it to a fixed position. When the user moves the mouse, the circle follows the pointer, and the moving endpoint of the line follows the same coordinates.
This creates an effect similar to a leash connecting two points. The fixed endpoint remains in place, while the other endpoint changes as the mouse moves.
The exercise is useful because it combines several concepts in one small program:
- Creating graphical objects with JavaScript.
- Drawing lines between coordinate points.
- Positioning circles on a canvas.
- Reading mouse coordinates.
- Using event handlers to respond to user actions.
- Updating existing objects instead of repeatedly creating new ones.
- Understanding how different graphical elements can move together.
The lesson is not primarily about designing an attractive picture. Its purpose is to demonstrate how programming instructions control what users see on a screen.
What Does 9.7.4 Mean?
The number 9.7.4 identifies the exercise within a particular course structure. It generally represents a section, lesson, and individual activity, although numbering can vary between courses and curriculum versions.
The number is not a JavaScript version, a graphics setting, or a measurement for a physical leash.
For students working on the assignment, the important part is the exercise called Leash. The task focuses on connecting a moving graphical object to another point with a line.
If the assignment appears under a different number in your course, read the instructions provided in your own classroom environment. Similar exercises can appear in different locations depending on the course version.
What Is the Main Goal of the Leash Exercise?
The primary goal is to create a visual relationship between a moving object and a line.
Imagine a circle positioned in the center of the canvas. A line begins at that same central location. When the mouse moves toward the upper-right corner, the circle moves to the pointer, and the line stretches from the center toward the circle.
If the mouse moves toward the lower-left corner, both the circle and the moving endpoint of the line move accordingly.
The fixed starting point does not change.
This behavior requires the program to perform two coordinated actions whenever a mouse movement event occurs:
- Update the position of the circle using the current mouse coordinates.
- Update the line’s endpoint using those same coordinates.
When both operations use the same X and Y values, the circle and line remain visually connected.
Understanding this relationship is more important than memorizing the code. Once you understand how the objects share coordinates, you can build similar interactive graphics without relying on a copied solution.
Complete JavaScript Example for 9.7.4 Leash
The following example demonstrates the basic leash effect using the JavaScript graphics methods commonly associated with CodeHS. It creates a circle in the center of the canvas and connects that circle to the center with a line.
var BALL_RADIUS = 30;
var ball;
var line;
function start() {
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
line = new Line(
centerX,
centerY,
centerX,
centerY
);
line.setColor(Color.black);
add(line);
ball = new Circle(BALL_RADIUS);
ball.setPosition(centerX, centerY);
ball.setColor(Color.yellow);
add(ball);
mouseMoveMethod(leash);
}
function leash(e) {
var mouseX = e.getX();
var mouseY = e.getY();
ball.setPosition(mouseX, mouseY);
line.setEndpoint(mouseX, mouseY);
}
This example illustrates the central programming logic. The circle is created once, the line is created once, and the mouse event handler updates their positions as the pointer moves.
The exact appearance, permitted methods, and required object properties can depend on the assignment instructions. If your teacher supplies specific dimensions, colors, or starter code, preserve those requirements when adapting the example.
How the 9.7.4 Leash Code Works
To understand the solution, divide the program into three parts: variable declarations, object creation, and mouse movement handling.
Each part has a different responsibility. The variable declarations make the graphical objects accessible to the necessary functions. The initialization function creates the objects. The event handler updates them in response to the mouse.
Step 1: Define the Ball Radius
var BALL_RADIUS = 30;
This statement defines a constant-style variable that represents the radius of the circle.
A circle’s radius is the distance from its center to its edge. A radius of 30 creates a circle with a diameter of 60 coordinate units.
Using a named value makes the code easier to maintain. If you need a larger or smaller circle, you can change the radius in one place instead of searching through the entire program.
The radius is not responsible for making the circle move. It only determines the circle’s size.
Step 2: Declare the Graphical Objects
var ball;
var line;
These declarations create variables that will later refer to the circle and line objects.
They are placed outside the functions so that both start() and leash() can access the same objects.
This is an important programming concept called variable scope.
If the objects were declared only as local variables inside start(), the separate leash() function would not be able to access those local variables directly.
By declaring the variables outside the functions, the program can create the objects once and then update them whenever a mouse event occurs.
Step 3: Create the Start Function
function start() {
The start() function contains the initialization instructions.
In a typical CodeHS graphics program, this function is used to prepare the canvas before the interactive part begins.
It calculates the center of the canvas, creates the line, creates the circle, adds both objects, and registers the mouse movement handler.
The function does not need to recreate these objects whenever the mouse moves. Its main job is to establish the initial state of the program.
Step 4: Find the Center of the Canvas
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
A graphics canvas uses a coordinate system to identify positions.
The X coordinate represents horizontal position, while the Y coordinate represents vertical position.
The getWidth() method returns the canvas width, and getHeight() returns its height. Dividing each value by two identifies the center point.
For example, suppose the canvas is 400 units wide and 400 units high. Its center is:
- Center X: 200
- Center Y: 200
Using these calculations is more flexible than entering fixed coordinates manually. If the canvas dimensions change, the program can still calculate its center.
The exact dimensions of the canvas depend on the environment in which the exercise runs.
Step 5: Create the Leash Line
line = new Line(
centerX,
centerY,
centerX,
centerY
);
The Line constructor accepts four coordinate values.
The first two values identify the starting point, while the last two identify the ending point.
In this example, both endpoints initially use the center coordinates. As a result, the line initially has zero length and may appear as a single point.
That is intentional.
When the mouse begins moving, the program changes the ending point. The starting point remains at the center, so the line stretches toward the mouse position.
This is the main visual feature of the leash effect.
Step 6: Set the Line Color and Add It
line.setColor(Color.black);
add(line);
The first statement sets the line color to black. The second adds the line to the graphics canvas.
Creating a graphical object and displaying it are separate operations in this programming model. The constructor defines the object, while add() places it on the canvas.
Adding the line before the circle also helps the circle appear in front of the line when the two overlap, depending on the graphics environment’s drawing order.
If your assignment specifies a different color or object order, follow those instructions.
Step 7: Create and Position the Circle
ball = new Circle(BALL_RADIUS);
ball.setPosition(centerX, centerY);
ball.setColor(Color.yellow);
add(ball);
The Circle constructor creates a circle with the specified radius.
The setPosition() method places the circle’s center at the calculated canvas center. The color method sets its appearance, and add() displays it.
At this point, the program has created both graphical objects.
The circle sits at the center, and the line connects the center to itself. The next step is to make them respond to the mouse.
Step 8: Register the Mouse Movement Handler
mouseMoveMethod(leash);
This statement tells the graphics environment to call the leash function when the mouse moves over the canvas.
The function name is passed without parentheses.
This distinction matters because the program needs to register the function as a callback. The graphics environment will call it later when the relevant event occurs.
Writing mouseMoveMethod(leash()) would attempt to execute the function immediately rather than passing the function reference in the intended way.
Event handlers allow programs to react to user activity instead of running every instruction in a simple, uninterrupted sequence.
Step 9: Read the Mouse Coordinates
function leash(e) {
var mouseX = e.getX();
var mouseY = e.getY();
The leash() function receives a mouse event object, represented here by the parameter e.
The event object provides information about the current mouse position.
The getX() method retrieves the horizontal coordinate, and getY() retrieves the vertical coordinate.
Storing these values in variables makes the remaining instructions easier to read.
Both the circle and the line endpoint will use the same pair of coordinates.
Step 10: Move the Circle and Line Endpoint
ball.setPosition(mouseX, mouseY);
line.setEndpoint(mouseX, mouseY);
The first instruction moves the circle so its center matches the mouse position.
The second instruction changes the ending point of the line to the same position.
The line’s starting point stays fixed because the code updates only its endpoint.
This creates the connected movement required for the leash effect. When the mouse moves, both graphical objects respond to the same event and remain visually aligned.
Understanding Mouse Events in JavaScript
Mouse events allow a program to respond when a user interacts with a graphical interface.
In the Leash exercise, mouse movement is the event that triggers the update function.
The program does not need to continuously check the mouse position in a loop. Instead, the event system calls the registered function when movement occurs.
This approach is known as event-driven programming.
It is widely used in interactive applications because users do not always perform actions at predictable times. A program may need to respond to a click, a key press, a mouse movement, or another event whenever it happens.
What Happens When the Mouse Moves?
The basic sequence is:
- The user moves the mouse over the canvas.
- The graphics environment detects the movement.
- The registered leash() function runs.
- The event object provides the current X and Y coordinates.
- The circle moves to those coordinates.
- The line endpoint moves to the same coordinates.
- The updated graphics become visible.
This sequence repeats whenever another relevant mouse movement occurs.
Understanding the sequence helps explain why registering the event handler is necessary. Without the handler, the initial objects can appear correctly but remain stationary.
How X and Y Coordinates Control the Leash
Coordinates are the foundation of the exercise.
The X coordinate describes horizontal placement. Smaller X values are generally closer to the left side of the canvas, while larger X values move toward the right.
The Y coordinate describes vertical placement. In the typical canvas coordinate system, smaller Y values are closer to the top, while larger Y values move toward the bottom.
The precise origin and coordinate conventions should be confirmed for the graphics environment being used.
Consider a canvas with its center at (200, 200).
If the mouse moves to (300, 100), the circle moves to that position and the line stretches from (200, 200) to (300, 100).
If the mouse moves to (100, 300), the circle follows it, and the line now stretches from (200, 200) to (100, 300).
The same process works at any valid position within the canvas.
The important relationship is that the circle center and the moving line endpoint use matching coordinates.
Common Problems With 9.7.4 Leash Code
Students sometimes find that the program compiles but does not behave as expected. Most problems come from incorrect variable scope, event registration, coordinates, or object updates.
The Circle Does Not Move
If the circle stays in the center, first check whether the mouse movement handler has been registered.
mouseMoveMethod(leash);
Next, verify that the handler receives the event object and calls setPosition() with the event’s coordinates.
Also confirm that the code is running in the expected graphics environment. A standard browser JavaScript console does not automatically provide CodeHS-specific graphics methods.
The Line Does Not Follow the Circle
If the circle moves but the line remains stationary, inspect the line update statement.
line.setEndpoint(mouseX, mouseY);
Make sure it uses the same coordinate values as the circle.
Changing the line’s starting point instead of its ending point can cause the fixed anchor to move. The desired behavior is to keep the starting point unchanged and update the endpoint.
The Program Reports That an Object Is Undefined
An undefined-object error can occur when a function attempts to access a variable that has not been initialized or is outside its scope.
For this example, ball and line are declared outside the functions and assigned graphical objects inside start().
Check that the variables are spelled consistently and that the event handler does not run before the objects have been created.
The Line Appears to Have Zero Length
A zero-length line is expected at the initial position in this example because both endpoints begin at the center.
It should stretch after the mouse moves and the endpoint is updated.
If it remains invisible, check whether the mouse event handler is active and whether setEndpoint() receives changing coordinates.
The Circle and Line Do Not Stay Connected
The most likely cause is that the circle and line use different coordinates.
Both should use the same current mouse X and Y values. Avoid calculating a different target position for one object unless the assignment specifically requires a gap or offset.
The Program Creates Too Many Circles or Lines
Do not create a new circle and line inside the mouse movement function for this basic solution.
Creating new objects repeatedly can leave old objects on the canvas, increase resource usage, and produce unwanted trails or clutter.
Create the objects once in start() and update their existing positions inside the event handler.
The Code Uses Incorrect Capitalization
JavaScript is case-sensitive. Method names must match the names supported by the graphics environment.
For example, getX() and getx() are not equivalent.
Check the spelling of setPosition(), setEndpoint(), mouseMoveMethod(), getWidth(), and getHeight() carefully.
How to Test Your 9.7.4 Leash Program
Testing is an important part of programming. A solution that looks correct in the editor may still contain mistakes that become visible when the user interacts with it.
Use the following checklist to evaluate the example.
- Run the program. Confirm that the graphics canvas loads without syntax errors.
- Check the initial position. Verify that the circle begins at the center and that the line’s initial endpoints match.
- Move the mouse slowly. Watch whether the circle follows the pointer and the line stretches from its fixed anchor.
- Test different directions. Move the mouse left, right, up, down, and diagonally.
- Check the connection. Confirm that the circle center and line endpoint continue to use the same coordinates.
- Look for unwanted objects. Make sure the program updates the existing circle and line rather than leaving copies behind.
- Read error messages. If something fails, identify the reported line and check the relevant variable or method.
- Compare the result with the assignment. Make sure your implementation follows any required object size, color, positioning, or naming conventions.
A useful test is to move the mouse to several widely separated points on the canvas. This makes it easier to identify whether the line’s anchor is fixed or accidentally moves with the pointer.
Why the Objects Should Be Created Only Once
One of the most useful lessons in this exercise is the difference between creating an object and updating an object.
The statement new Circle(BALL_RADIUS) creates a new circle. The statement ball.setPosition(mouseX, mouseY) changes the position of an existing circle.
These operations serve different purposes.
The initialization function should generally create the objects needed for the program. The mouse movement function should update those objects.
If a new circle is created for every mouse event, the canvas may accumulate hundreds of circles. This is unnecessary when the intended effect requires only one moving circle.
The same principle applies to the line. Create it once, then change its endpoint whenever the mouse moves.
This approach makes the program simpler, easier to debug, and more efficient.
What Can You Learn From the 9.7.4 Leash Exercise?
The exercise introduces skills that are useful well beyond one classroom assignment.
Basic JavaScript Functions
Functions group instructions into reusable blocks. The start() function initializes the program, while leash() handles mouse movement.
Separating these responsibilities makes the code easier to understand and maintain.
Variable Scope
The ball and line variables need to be accessible to both the initialization function and the event handler.
Learning where to declare variables helps prevent undefined-variable errors and makes it easier to manage state in larger programs.
Coordinate-Based Graphics
The exercise shows how numerical values control the position of visual objects.
Once you understand X and Y coordinates, you can position shapes, draw lines, create diagrams, and build interactive scenes.
Event-Driven Programming
The mouse movement handler demonstrates how programs respond to user actions.
The same general idea applies to button clicks, keyboard input, touch interactions, and many other interface events.
Object Manipulation
The program creates a circle and a line, then modifies their properties while running.
This introduces a useful pattern for building animations and interactive interfaces without repeatedly recreating graphical objects.
Read more: Uploadwords.com USA: Complete Guide to Features, Uses, Benefits, and Text Analysis
Practical Uses of the Leash Concept
The leash effect is a simple example of a relationship between two graphical points. Similar techniques can be adapted for more advanced projects.
Interactive Drawing Applications
A drawing application can display a line from a fixed starting point to the current mouse position. This helps users preview a line before committing it to the canvas.
Beginner Games
A game can use a line to connect a character to a target, a tool to an object, or one visual element to another.
More advanced versions can add distance limits, collision checks, or movement constraints.
Animation Projects
Animations often involve updating positions over time or in response to input. The Leash exercise introduces the basic idea of keeping related graphical elements synchronized.
Visual Learning Tools
Teachers and students can use moving points and connecting lines to explore coordinate systems, geometry, and interactive mathematics.
Interface Prototypes
Interactive graphics can help demonstrate how elements respond to a pointer. The same event-driven principles are useful when prototyping menus, visual controls, and other interfaces.
These are possible applications of the underlying technique, rather than additional requirements of the original exercise.
How to Improve Your Understanding of the Exercise
If you want to learn the programming concepts instead of simply copying a solution, try making small changes after the basic version works.
First, change the circle’s radius and observe how its appearance changes without affecting its movement.
Next, change the initial anchor position to another valid point on the canvas. Make sure the line still starts at that location and follows the mouse at its other endpoint.
You can also experiment with the line color or the circle color if your assignment permits it.
Another useful experiment is to temporarily print or display the mouse coordinates using methods supported by your programming environment. Move the pointer and compare the changing coordinate values with the circle’s position.
Finally, explain the purpose of each important statement in your own words. If you can explain why the line uses setEndpoint() and why the variables are declared outside the functions, you understand the core logic.
Avoid adding advanced features until the required behavior works correctly. A small, understandable program is a better starting point than a complicated solution that is difficult to debug.
9.7.4 Leash and Related Programming Concepts
The exercise is connected to several topics that appear throughout introductory computer science.
Interactive graphics: Visual objects can change in response to user actions.
Event handlers: Functions can be registered to run when a particular event occurs.
Coordinates: Numerical values describe positions on a two-dimensional surface.
State: Variables can hold references to objects whose properties change while the program runs.
Callbacks: A function can be passed to another method so that it can be called later.
Debugging: Testing and examining code helps identify problems in the program’s logic.
These concepts work together in the Leash exercise. Understanding how they interact will make future programming lessons easier, especially those involving animation, user input, and graphical interfaces.
Frequently Asked Questions About 9.7.4 Leash
What is 9.7.4 Leash in CodeHS?
9.7.4 Leash is a JavaScript graphics exercise associated with a Drawing Lines lesson. It demonstrates how a graphical object can follow mouse movement while a line connects the moving object to a fixed point.
What programming language is used for the Leash exercise?
The exercise is associated with JavaScript graphics in an introductory computer science curriculum. The example in this guide uses JavaScript syntax and graphics methods such as Circle, Line, and mouseMoveMethod().
What is the purpose of the line in the Leash program?
The line visually connects a fixed point to the moving circle. Its starting point stays in place, while its endpoint changes according to the current mouse coordinates.
Why does the circle follow the mouse?
The event handler reads the mouse’s X and Y coordinates and passes them to ball.setPosition(). This updates the circle’s center whenever the mouse movement handler runs.
Why does the line use setEndpoint()?
The setEndpoint() method updates the line’s ending point. This allows the line to follow the circle while preserving its fixed starting point.
Why are the ball and line variables declared outside the functions?
Declaring these variables outside the functions makes them accessible to both the initialization function and the mouse event handler. Both functions can therefore work with the same graphical objects.
What does mouseMoveMethod(leash) do?
It registers the leash function as a mouse movement handler. When a relevant mouse movement occurs, the graphics environment calls the function with event information.
Why should I avoid parentheses in mouseMoveMethod(leash)?
Passing leash without parentheses supplies the function reference so the graphics environment can call it later. Adding parentheses attempts to call the function immediately, which is not the intended registration pattern.
Why is the line invisible when the program first starts?
In the example, both endpoints initially occupy the same coordinate. This gives the line zero length. Once the mouse moves and the endpoint changes, the line becomes visible.
Why does my program show an undefined variable error?
The variable may not have been declared in a scope accessible to the function using it, or the object may not have been initialized before the function tried to access it. Check declarations, spelling, and initialization order.
Should I create a new circle every time the mouse moves?
No. For the basic leash effect, create one circle and one line during initialization. Update their positions in the event handler. Repeatedly creating new objects can cause unwanted duplicates.
Can I change the ball’s color and size?
You can experiment with the color and radius when the assignment permits customization. If the exercise specifies particular values, follow those requirements rather than changing them arbitrarily.
Is 9.7.4 Leash useful for learning game development?
Yes. The exercise introduces mouse events, coordinates, object movement, and synchronized graphical updates. These concepts are useful foundations for simple games and interactive graphics projects.
Is the same solution guaranteed to work in every JavaScript editor?
No. The example uses methods associated with a particular graphics environment. Ordinary JavaScript does not automatically provide CodeHS-specific objects such as Circle, Line, or mouseMoveMethod(). Use the appropriate environment and follow the methods supported by your assignment.
What should I do if the assignment number is different?
Course numbering can vary between curricula and versions. Check the title and instructions of the activity in your own course. The relevant task requirements matter more than assuming every course uses identical numbering.
Conclusion
The 9.7.4 Leash exercise is a practical introduction to interactive JavaScript graphics. It demonstrates how a circle can follow mouse movement while a line connects the circle to a fixed point on the canvas.
The core solution depends on a few important ideas: create the graphical objects once, keep their variables accessible to the required functions, register the mouse movement handler, read the current X and Y coordinates, and update both the circle and the line endpoint using the same values.
Once these concepts are clear, the exercise becomes much easier to understand and troubleshoot. More importantly, the same principles can help you build interactive drawings, basic animations, and beginner game projects.
Rather than memorizing the code alone, focus on understanding what each function does and why the two graphical objects must use matching coordinates. That understanding will help you solve similar programming exercises with greater confidence.




One comment on “9.7.4 Leash: Complete CodeHS Guide With JavaScript Solution and Explanation”