I looked up on google and there was an interesting tutorial/code which draws a regular polygon with n-sides & size. So I thought of making a function out of it, one of the technical problems I encountered is that when the canvas is drawed and I click to draw another canvas, the second canvas is "overwritten" on the first one. Luckily someone here solved this problem by clearing the canvas.
So here's my code, you may change it to your needs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Regular Polygon</title>
</head>
<body>
<canvas id="regular_polygon" width="400" height="400"></canvas>
<p>Polygon drawer:</p>
<p>Number of sides <input type="text" id="nSides"></p>
<p>Size <input type="text" id="size"></p>
<p>Color <input type="text" id="color"></p>
<p>Width <input type="text" id="width"></p>
<button id="draw">Draw!</button>
<script type="text/javascript">
function polygon (element_id, nSides, psize, pcolor, pwidth) {
var c = document.getElementById(element_id);
c.width = c.width;
var cxt = c.getContext("2d");
var numberOfSides = nSides,
size = psize,
Xcenter = c.width/2,
Ycenter = c.height/2;
cxt.beginPath();
cxt.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));
for (var i = 1; i <= numberOfSides;i += 1) {
cxt.lineTo (
Xcenter + size * Math.cos(i * 2 * Math.PI / numberOfSides),
Ycenter + size * Math.sin(i * 2 * Math.PI / numberOfSides)
);
}
cxt.strokeStyle = pcolor;
cxt.lineWidth = pwidth;
cxt.stroke();
}
(function () {
polygon("regular_polygon", 3, 40, "#000000", 2);
document.querySelector('#draw').addEventListener('click', function (e) {
e.preventDefault();
var nSides = document.querySelector('#nSides'),
size = document.querySelector('#size'),
color = document.querySelector('#color'),
width = document.querySelector('#width');
polygon("regular_polygon", nSides.value, size.value, color.value, width.value);
});
})();
</script>
</body>
</html>