Drawing a Line



CanvasThe simplest kind of drawing you can do with canvas is drawing lines. Last week we looked at context properties for setting the line style. Now that we've done that, let's go over how to actually draw.


Like most 2d drawing systems, the origin of the coordinate system is 0,0 and located in the top left corner of the canvas. When drawing with canvas, we start our drawing operations by using the beginPath() method. When we are finished our drawing we use the closePath() method.


In order to draw lines, we use to moveTo() method, and the lineTo() method. The canvas API assumes that you are doing any drawing from the current pen position, so the moveTo() and lineTo() methods simply take coordinates of the destination. The first parameter to both routines is the x location; the second is the y location. See below.


context = canvasTag.getContext('2d');
// Draw a line to 40 pixels over, 30 pixels down.
context.lineTo(40, 30);


The line drawing uses whatever line style properties are currently set. moveTo() on the other hand, doesn't actually do any drawing. It simply moves the cursor to the destination coordinate.


context = canvasTag.getContext('2d');
// Moves the pen position to 40 pixels over, 30 pixels down.
// Any further drawing will use this coordinate as the starting point.
context.moveTo(40, 30);


Lastly, if you find yourself using lots of line drawing commands, you may find it pays off to create a function that handles both the drawing and the pen moving. By doing this, you can cut your total number of lines in half. See below:


function drawLine(x1, y1, x2, y2)
{
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
}
context.beginPath();
drawLine(0, 0, 255, 255);
context.stroke();
context.closePath();

You'll notice in the above example that we use the stroke() method. This method draws the line that you've defined with your moveTo() and lineTo() calls; without it, you wouldn't see the line at all!



No comments :