Canvas JavaScript

Draw a Polygon

This JavaScript program demonstrates how to draw a polygon on a canvas element.

DrawAPolygon.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="DrawAPolygon.js"></script>
  </head>
  <body onload="Initialize()">
     <canvas id="idCanvas" width="640" height ="480" style="background-color: #F0F0F0;"></canvas>
  </body>
</html>

DrawAPolygon.js

function Initialize() {
	var qCanvas = document.getElementById("idCanvas");
	var qContext = qCanvas.getContext("2d");
	qContext.beginPath();
	qContext.moveTo(320, 100);
	qContext.lineTo(500, 400);
	qContext.lineTo(160, 400);
	qContext.closePath();
	qContext.strokeStyle = "black";
	qContext.lineWidth = 5;
	qContext.stroke();
	qContext.fillStyle = "gray";
	qContext.fill();
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.