Use solid color to fill a triangle in JavaScript

Description

The following code shows how to use solid color to fill a triangle.

Example


<!-- w w w  .j  a  v a 2 s . c o  m-->

<!DOCTYPE HTML>
<html>
<head>
<script>
function drawTriangle(context, x, y, triangleWidth, triangleHeight, fillStyle){
context.beginPath();
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;

drawTriangle(context, canvas.width /2, triangleY, triangleWidth, triangleHeight, "blue");

};
</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.

Use solid color to fill a triangle in JavaScript