I have the following code to draw any polygon on an HTML5 canvas on a button click. The user supplies the radius, sides, x and y co-ordinates. Using the sides any regular polygon should be drawn. First we move to the perimeter using moveTo() and then draw lines using lineTo() depending on the sides.
js.js
function drawPolygon() {
var numberOfSides = parseFloat(prompt("Enter number of sides"));
var Xcenter = parseFloat(prompt("Enter x"));
var Ycenter = parseFloat(prompt("Enter y"));
var size = parseFloat(prompt("Enter radius"));
var con=document.getElementById("myCanvas");
var cxt=con.getContext("2d");
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 = "#000000";
cxt.lineWidth = 1;
cxt.stroke();
}
function registerEvents(){
var poly = document.getElementById("polygon");
poly.addEventListener( "click", drawPolygon, false);
}
window.addEventListener('load', registerEvents, false);
The code works fine. My issue is that all drawings are positoned on the top left corner (default) of the canvas. How can i take control of the positioning of the drawings?. I want to be able to place the drawings anywhere on the canvas. Thanks