You can draw closed paths that are filled by a color.
The following code draws a triangle that is filled with blue color.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML5 Canvas</title> <script type="text/javascript"> window.onload = function(){/* www . j a va 2 s . c o m*/ let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); // draw stuff here context.beginPath(); context.moveTo(50,20); context.lineTo(50,100); context.lineTo(150, 100); context.closePath(); context.lineWidth = 10; context.strokeStyle = 'red'; context.fillStyle = 'blue'; context.stroke(); context.fill(); }; </script> </head> <body> <canvas id="myCanvas" width="300" height="200"></canvas> </body> </html>
The closePath() method closes a path by joining the start point and the end point of the last drawing operation.
To draw a triangle, draw only two lines using lineTo().
Calling closePath() draws the third side of the triangle.
You used the stroke() method to draw an outline of a shape.
The fill() method fills the shape with a color.
The strokeStyle and fillStyle properties can be used to specify a color.