Draw a trianlge on the HTML5 canvas

Fetches the canvas element. Creates a 2D context. Clears the canvas, the sets the fill style to red and then creates a path with lineto points. After the path has been created it fills it with the earlier selected color.
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="300"></canvas>
    <script>

    var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext('2d'); 

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'red';

    ctx.beginPath();
    ctx.moveTo(20, 125);
    ctx.lineTo(70, 25);
    ctx.lineTo(120, 125);
    ctx.lineTo(20, 125);
    ctx.fill();

   </script>
  </body>
</html>      

Responses

0 Replies