Triangles in HTML5 canvas

Three filled triangles, two unfilled (stroke) triangles.

HTML

<canvas id="myCanvas">
  <p>Some default content can appear here.</p>
</canvas>

JavaScript

// JavaScript for drawing on canvas
// applying colors + three triangles

function fillPolygon(ctx, polygon, color) {
  ctx.beginPath();
  for (const [i, p] of polygon.entries()) {
    if (i === 0) {
      ctx.moveTo(p.x, p.y);
    } else {
      ctx.lineTo(p.x, p.y);
    }
  }
  ctx.closePath();
  ctx.fillStyle = color;
  ctx.fill();
}

function draw() {
  // canvas with id="myCanvas"
  var canvas = document.getElementById('myCanvas');
  canvas.width = 500;
  canvas.height = 500;
  canvas.style.width = '250px';
  canvas.style.height = '250px';

  const ctx = canvas.getContext('2d');

  const rect = [{
    x: 200,
    y: 225
  }, {
    x: 490,
    y: 225
  }, {
    x: 490,
    y: 375
  }, {
    x: 200,
    y: 375
  }];

  const triangle1 = [rect[0], rect[1], rect[2]];
  const triangle2 = [rect[0], rect[2], rect[3]];

  fillPolygon(ctx, triangle1, 'blue');
  fillPolygon(ctx, triangle2, 'blue');
}

draw();