Drawing a straight line in canvas

Drawing a line, choosing a color, thickness, the function in details with several examples.

We do not expect that, but the function of line drawing may allow complex graphic effects, as an example is given further. That thanks to the fact that the function is decomposed into separate instructions to set the starting en ending points, the color, the thickness ...

To demonstrate this function, we start by declaring a <canvas> tag as explained in the first article of this series, Getting started with canvas.

<canvas id="moncanevas" width="400" height="150">
  Canvas requires a modern browser: Chrome, Firefox, Edge, Opera, Safari.
</canvas>  

A line is defined with two instructions: moveTo and lineTo

The plot of the line is decomposed into two functions (as in BASIC): moveTo(x,y) defines the X and Y coordinates of current point, which serves as a starting point for drawing a line segment.
And lineTo(x, y) adds a fixed point of arrival to draws a straight path between the first and current point to a point whose coordinates are the X and Y parameters.
The line is not actually drawn until the function stroke() is called.
When we want to draw a new line which is not the continuation of a previous drawing, we must start with the function beginPath().
Therefore at least four instructions are needed for drawing a line. Example:

canvas = document.getElementById("moncanevas"); 
if (canvas.getContext)
{    
    context = canvas.getContext('2d'); 
}

function drawLine()
{
 context.beginPath();
 context.moveTo(20,100);
 context.lineTo(200,10);
 context.stroke(); 
}  
Canvas requires a modern browser: Chrome, Firefox, IE9, Safari.

A color is given with the strokeStyle attribute

Choosing the color of a path is not a parameter but is given as a whole for all drawings to come. The value of strokeStyle attribute will be the color of all plots until it is reassigned.

But this don't applies for the content of solid forms such as a filled rectangle, their color depends on another attribute, fillStyle.

The value we assigns to these attributes is the same than to a CSS color, for example: blue, #008, #000080, rgba (0,0,128,1).

context.strokeStyle='green'; 
context.fillStyle='rgba (0,0,128,1)'

The drawLine function that was previously defined is now enhanced with a color attribute:

function drawLine()
{
  context.beginPath();
  context.strokeStyle='green';
  context.moveTo(20,100);
  context.lineTo(200,10);
  context.stroke(); 
}  

Important: To give different colors to line drawings, one must add the function beginPath() before drawing a new line. Segments even separated are considered part of the same line until the new occurrence of the function beginPath.

Canvas requires a modern browser: Chrome, Firefox, IE9, Safari.

Four formats may be used to define a color ...

And be assigned to strokeStyle or fillStyle (besides textures too, that we will see later). These values ​​are enclosed in quotation marks and can be the name of a color, or the hexadecimal code on the form red/green/blue, or decimal values ​​with three numbers or four with a level of opacity.

ctx.fillStyle = "white";
ctx.fillStyle = "#FFFFFF";
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillStyle = "rgba(128,128,128,0.5)";

The fourth attribute of rgba (a = alpha) sets the opacity that varies from 0.0 to 1, with 0 being completely transparent and 1 total opacity, which is always the case for the simple rgb() format. So intermediate transparency is defined by 0.5.

The lineWidth attribute defines the thickness of the line

Determining the thickness of the line is done with the function lineWidth whose the value has by default the unit in pixels. So the unit do not need to be given if the thickness is measured in pixels, only an integer value is given.

function drawLine()
{
  context.strokeStyle='green';
  context.lineWidth=4; 
  context.moveTo(20,100);
  context.lineTo(200,10);
  context.stroke(); 
}
Canvas requires a modern browser: Chrome, Firefox, IE9, Safari.

The ends of a line may be rounded or squared

When it is more than two pixels thick, we can give ends of the line a round or square shape. It can not have the shape of an arrow (nor in SVG), that would have been usefull to draw graphs.
To change the shape we assign the lineCap attribute with the value round, square or butt (no end) which is the default.
When the line has no end added, its length is not increased, by the length of the ends, that is equivalent to the width of the line as defined by lineWidth.

Example: context.lineCap='round';

In the demo we will try the three values: butt in green, square in blue, round in red.

Canvas requires a modern browser: Chrome, Firefox, IE9, Safari.

We see that the ends of the line increases length in proportion to its width.

Full source code:

function drawLine4()
{
  var context = document.getElementById("canvas4").getContext('2d');
  context.lineWidth='8';
  context.strokeStyle='green';
  context.beginPath();
  context.moveTo(20,20);
  context.lineTo(200,20);
  context.stroke();
  context.beginPath();
  context.strokeStyle='#800';
  context.lineCap='square';
  context.moveTo(20,50);
  context.lineTo(200,50);
  context.stroke();
  context.strokeStyle='rgb(128,0,0)';
  context.lineCap='round';
  context.beginPath();
  context.moveTo(20,80);
  context.lineTo(200,80);
  context.stroke();
}

drawLine4();

The next step is in drawing a curve with Canvas.

Applications