Lets start drawing some lines in the Canvas. The point here is, it may feel like we are drawing in Bitmap, but actually its a vector drawing while its being drawn. But then once drawing is complete, it can not be modified directly. The Canvas does not remember any reference to the drawings we have already drawn. So the point to remember is its one time vector drawing. If at all we need to modify it, we have to redraw everything or may save everything inside our code.
The drawing is all javascript. The drawing itself is kind of two part process. First part is to draw the lines. The second part is making them visible. That means the first part draws in memory but not visible. Its only visible after we call the required methods to make them visible.
Lets dive into the code, yay.
canvas_one=document.getElementById('board_one');
context_one=canvas_one.getContext("2d");
We got the context. Now the drawing code comprises of
moveTo(xPosition,yPosition);
lineTo(xPosition,yPosition);
The first command ie; moveTo(xPos,yPos), takes the pen to the “xPos,yPos” position. The next command lineTo(xPos,yPos), draws a line from the pen position to the new position specified by “lineTo”. Thats all, the more number of these commands are called, the points get connected by a straight line. Till now we are only drawing but the are not visible yet.
Lets make the lines visible. These are done by
//define the pen
context_one.strokeStyle = "#000";
context_one.lineWidth = 5;
//make the lines visible
context_one.stroke();
Thats beautiful. Now are lines are visible. All is well and good, but how to create new kind of lines, means how to create lines with different colour and thickness? This is simply done with
//beginPath() creates a new line
context_one.beginPath();
After this all we are going to do is moveTo and lineTo commands to draw and the stroke with a different pen.
The source files are here for you to download and test.