Draw a triangle on HTML5 Canvas in JavaScript

Description

The following code shows how to draw a triangle on HTML5 Canvas.

Example


<!DOCTYPE HTML>
<html>
<head>
<script>
function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){
context.beginPath();<!--from   www. j a  v a  2s  .  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(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var grd;
var triangleWidth = 150;
var triangleHeight = 150;
var triangleY = canvas.height / 2 - triangleWidth / 2;

// linear gradient fill (second from left)
grd = context.createLinearGradient(canvas.width  / 5, triangleY, canvas.width / 5, triangleY + triangleHeight);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
drawTriangle(context, canvas.width / 2, triangleY, triangleWidth, triangleHeight, grd);

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

Click to view the demo

The code above generates the following result.

Draw a triangle on HTML5 Canvas in JavaScript