HTML and CSS Reference
In-Depth Information
equation"
}
}
}
First, we check to see if another line is currently being drawn, and only proceed if this
is not the case; this ensures that the function is not called twice simultaneously, since
it is designed to track the coordinates of one line at a time. Then we calculate the initial
x - and y -coordinates for the line ( init_x and init_y ). For init_x , we start at the left
edge of the grid; since we reset the origin of the Canvas to the center of the grid in the
drawGrid() function, the leftmost x -coordinate is now equal to the negative of one-half
of the canvas width ( -(theCanvas.width)/2 ). Then, we calculate the corresponding
init_y by taking the negative of init_x and multiplying by the slope.
It's necessary to reverse the sign when calculating the y -coordinate, be-
cause even though we reset the origin of the Canvas to the center of the
grid, y-coordinates are still measured differently on the canvas than on
the traditional Cartesian coordinate plane. On the Cartesian coordinate
plane, y- values go from negative to positive as you travel up the y-axis
from bottom to top , but on the Canvas, they go from negative to positive
as you travel down the y-axis from top to bottom . Flipping the sign on
the y -value resolves this discrepancy.
Once we have the starting point of the line, we can go ahead and trigger the animation
that draws the line on the grid. We update the status message above the graphing
calculator, and then set the graph_in_progress variable to yes to indicate that the line
is now being drawn. Then we call the embedded function do_animation() using the
JavaScript setInterval() method . setInterval allows us to repeatedly call a function
at designated intervals of time, measured in milliseconds. Here, we call do_anima
tion() every 33 milliseconds, which will draw the line at a nice speed.
Each time do_animation() is called, we calculate a new ending point for our line
( new_x and new_y ) by increasing the x -coordinate by 5 and calculating the corresponding
y -coordinate by taking the negative of new_x and multiplying by the slope. Then we
draw a line from ( init_x , init_y ) to ( new_x , new_y ). As do_animation() is called in suc-
cession, each new line drawn is a little bit longer than the last, which creates the visual
impression that one continuous line is being drawn across the grid.
When the x -coordinate in new_x exceeds the right edge of the Canvas, we call clearIn
terval() to end the animation, and then set graph_in_progress to no and reset the status
message above the calculator, so that draw_grid_line() is now ready to graph another
linear equation when triggered.
All that's left to code is the initial setup upon page load, and the functionality for the
graphing calculator buttons. Here's the code that initializes the graphing calculator:
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
 
Search WWH ::




Custom Search