Inscribed and circumscribed shapes

by John Schulz

JavaScript

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var diameter = canvas.width = canvas.height = 500;
var radius = diameter / 2;
var width = radius;
var height = width;
var Pi2 = Math.PI * 2;
var PiBy180 = Math.PI / 180;
var deg2rad = function(deg) {
    return deg * PiBy180
};

function square(size) {
    rectangle(size, size);
}

function rectangle(width, height) {
    ctx.strokeRect(-width, -height, width * 2, height * 2);
}

function centeredCircle(radius) {
    ctx.moveTo(radius, 0);
    ctx.arc(0, 0, radius, 0, deg2rad(360), false);
}

function inscribedPolygon(size, sides, rotate) {
    var i = sides + 1;

    while (i--) {
        var renderTo = i === sides ? 'moveTo' : 'lineTo';
        var radians = i * Pi2 / sides; // 6 o'clock on the dial
        radians += Math.PI; // 12 o'clock on the dial
        if (rotate) radians -= deg2rad(rotate); // rotate clockwise
        var x = Math.sin(radians) * size;
        var y = Math.cos(radians) * size;

        ctx[renderTo](x, y);
    }
}

// add canvas element
document.body.appendChild(canvas);

// make more like a traditional grid
ctx.translate(canvas.width / 2, canvas.height / 2);

square(width);
centeredCircle(width);
for (var i = 1, size; i < 15; i++) {
    size = width * Math.pow(0.705, i);
    centeredCircle(size);
    inscribedPolygon(size, 4, i*30);
}
inscribedPolygon(width, 4, 45)
// finish
ctx.stroke();