HTML5 Game - Canvas Shape Triangle

Drawing a Triangle using path

We can start a new path with the beginPath() method.

The place our drawing cursor using moveTo().

After that, draw consecutive sub paths to form a path.

We can close our path with the closePath() method to create a shape:

context.closePath(); 

This method completes the current path by connecting the last point in the path with the start point of the path.

In the drawTriangle() method, we can begin a new path using beginPath().

Then we position the drawing cursor using moveTo() and draw two sides of the triangle using lineTo().

After that we complete the third side of the triangle with closePath().

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
         function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){ 
             context.beginPath(); //from ww  w. jav a 2 s. c o  m
             context.moveTo(x, y); 
             context.lineTo(x + triangleWidth / 2, y + triangleHeight); 
             context.lineTo(x - triangleWidth / 2, y + triangleHeight); 
             context.closePath(); 
             context.fillStyle = fillStyle; 
             context.fill(); 
         } 

            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                
              
             let grd; 
             let triangleWidth = 150; 
             let triangleHeight = 150; 
             let triangleY = canvas.height / 2 - triangleWidth / 2; 

        // color fill (left) 
        drawTriangle(context, canvas.width * 1 / 5, triangleY, triangleWidth, triangleHeight, "blue"); 

    };   


        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Related Topics