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:
Watch the video below and then scroll down the page to see the sample code.
Here is the sample code:
<!DOCTYPE html> <html> <title>Styling lines on the canvas</title> <style> #myCanvas{ background-color:#FFFFFF; border: 1px solid #000000; } </style> </head> <body> <script> 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 </script> <canvas id="myCanvas" width="300" height="300"> </body> </html> |
Next tutorial: Joining lines on the canvas