HTML and CSS Reference
In-Depth Information
lineTo(
x
,
y
)
Draw a line from the current Canvas “cursor” location to the (
x
,
y
) location speci-
fied.
translate(
x
,
y
)
Allows you to set a new “origin” for the Canvas, from which
x
- and
y
-coordinates
are measured. By default, the Canvas origin is its top-left corner, but to simplify
the graphing calculator code, it will be helpful to relocate the Canvas origin to
coincide with the coordinate-plane origin at the center of the grid.
Here's the
drawGrid()
function for creating the coordinate grid on the Canvas:
function drawGrid() {
var i = 0;
axis_pos = 1;
can_width = theCanvas.width;
// Get the width of the canvas
// Loop through and draw horizontal/vertical lines at each eighth of the grid
// All logic below presumes canvas has square dimensions
for (i=0;i<=can_width;i+=(can_width)/8)
{
if (i == (can_width)/2)
// Special handling for horiz/vert axes
{
context.lineWidth = 3;
// Axes are thicker...
context.strokeStyle = 'red';
//... and in red
}
else
{
context.lineWidth = 1;
context.strokeStyle = 'black';
}
// First draw horizontal line
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, can_width);
context.stroke();
context.closePath();
// Then draw vertical line
context.beginPath();
context.moveTo(0, i);
context.lineTo(can_width, i);
context.stroke();
context.closePath();
}
// Then add axis number labels
context.font = '20px _sans';
context.textBaseline = 'top';
// Move canvas origin to center of grid
context.translate(can_width / 2, can_width / 2);
for (i=-3;i<=3;i++) {
if (i != 0) {
// Skip labeling origin
// horizontal label
context.fillText (i, i*(can_width/8) + 5, 5);