Styling lines on the canvas

In the previous tutorial we looked at how to draw lines on the canvas. In this tutorial we will style lines on the canvas by changing the following properties:

  • colour
  • width
  • line cap (shape on the ends of a line) for a line on the canvas

The line that we will create will look like this:

Screen Shot 2015-05-08 at 6.58.05 pm

Watch the video below and then scroll down the page to see the sample code.

Here is the sample code:

<!DOCTYPE html>
 <title>Styling lines on the canvas</title>
 border: 1px solid #000000;
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.lineWidth=20; // specify the width of the line
 ctx.lineCap="round"; // lineCap options are square, round, butt
 ctx.moveTo(50,50); // x,y positions - where the line begins
 ctx.lineTo(250,250); // x,y positions - where the line ends
 ctx.strokeStyle="#0000FF"; // specify the colour of the line
 ctx.stroke(); // draw the line
 window.onload=draw; // run the draw function when the page loads
 <canvas id="myCanvas" width="300" height="300">

Next tutorial: Joining lines on the canvas