HTML and CSS Reference
In-Depth Information
// vertical label
context.fillText (i, 5, -i*(can_width/8));
// Add bold-italic x- and y labels on the axes, too
context.font = 'italic bold 20px _sans';
context.fillText ("x", (can_width/2)-12, 1);
context.fillText ("y", 4, -(can_width/2));
First, we grab the width of the <canvas> element ( theCanvas.width ), and then we run a
for loop to draw eight evenly spaced horizontal and vertical lines across the grid; the
x - and y -axes are handled specially, bolded and colored red. Then we run one more
for loop to add number labels (from -3 to 3) on both axes. Finally, we add x - and y -
labels to clearly identify the two axes.
Now that the grid is in place, we also need a function that will graph a specified linear
equation on the plane. We'll create a function called draw_grid_line() that is capable
of plotting any linear equation that can be expressed in the format y = m x , where m is
the slope of the equation. This function will take two parameters: slope and color ,
which accepts a valid CSS color value . Here's the code:
function draw_grid_line (slope, color) {
if (graph_in_progress == "yes") {
// Only draw one line at a time
alert("Another line is being drawn. Please wait until it's complete");
} else {
init_x = -(theCanvas.width)/2; // start with x = left edge of grid
// Note: Must reverse sign y-coordinate, as negative y-coordinates are top half of grid by default,
not bottom
init_y = -(init_x) * slope // y = mx
new_x = init_x;
new_y = init_y;
var drawLineIntervalId = 0;
status_message.innerHTML = "Drawing equation y = " + slope + "x";
graph_in_progress = "yes" // line now being drawn
drawLineIntervalId = setInterval(do_animation, 33);
function do_animation () {
context.lineWidth = 6;
context.strokeStyle = color;
context.moveTo(init_x, init_y);
context.lineTo(new_x, new_y);
new_x = new_x + 5
new_y = -(new_x) * slope
context.lineTo(new_x, new_y)
if (new_x == theCanvas.width + 5) {
clearInterval(drawLineIntervalId); // stop animation when line is complete
graph_in_progress = "no" // line is now done
status_message.innerHTML = "Click a button below the grid to graph an
Search WWH ::

Custom Search