How You Can Draw Regular Polygons with the HTML5 Canvas API

How it is look likes goes to here:

http://www.sandywebdesigner.com/canvas/canvas.html

  • a circle is 2 * Pi
  • don’t know how to explain sine and cosine, but if you understand below is help you under stand my JavaScript code.
  • x = r * cosine(a)
    y = r * sine(a)

And here is the JavaScript code for you Polygons

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();
}

When I need a pentagon,here is the code for get it.

function doFirst(){
var x = document.getElementById(“canvas”);

context= x.getContext(‘2d’);

context.beginPath();
polygon(context, 120,120,100,5);
context.stroke();
}
window.addEventListener(“load”,doFirst,false);

And You could use below code generate different shapes.

function doFirst(){
var x = document.getElementById(“canvas”);

context= x.getContext(‘2d’);

context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle=”rgba(227,11,93,0.75)”;
context.fill();
context.stroke();

// Draw a circle to encompass this polygon
context.beginPath();
context.arc(125, 125, 100, 0, Math.PI * 2);
context.stroke();

context.beginPath();
polygon(context,350,125,100,6,-Math.PI/2);
context.fillStyle=”rgba(51,128,255,0.75)”;
context.fill();
context.stroke();

context.beginPath();
polygon(context,125,350,100,7,-Math.PI/2);
context.fillStyle=”rgba(11,227,93,0.75)”;
context.fill();
context.stroke();

context.beginPath();
polygon(context,350,350,100,8,0,false);
polygon(context,350,350,60,8,0,true);
context.fillStyle=”rgba(227,11,93,0.75)”;
context.shadowColor = ‘rgba(0,0,0,0.75)’;
context.shadowOffsetX = 8;
context.shadowOffsetY = 8;
context.shadowBlur = 10;
context.fill();
}
window.addEventListener(“load”,doFirst,false);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s