dhani
dhani

Reputation: 127

Error drawing polygon on HTML5 canvas

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 = prompt("Enter number of sides");
var Xcenter = prompt("Enter x");
var Ycenter = prompt("Enter y");
var size = 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);

After supplying the inputs, nothing gets drawn on the canvas. Is my code erroneous?

Upvotes: 2

Views: 333

Answers (2)

John R
John R

Reputation: 126

Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  ctx.restore();
}

// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

Upvotes: 0

ubik
ubik

Reputation: 4560

You are getting your math wrong because you are not converting the input to a numeric value.

e.g. Ycenter + size * Math.sin(0) will not return the correct result unless Ycenter and size are numeric values.

You should probably do something like this:

var Xcenter = parseFloat(prompt("Enter x"));
var Ycenter = parseFloat(prompt("Enter y"));
var size = parseFloat(prompt("Enter radius"));

Upvotes: 3

Related Questions