Blocks around a circle

Bend blocks around a circular shape

by John Schulz

HTML

<canvas width="200" height="200"></canvas>

JavaScript

var PI2 = Math.PI * 2;

var blocksAroundCircle = function(context, numberOfBlocks, x, y, radius, blockWidth, blockHeight) {
    var circumference = PI2 * radius;
    if (!blockWidth) blockWidth = circumference / numberOfBlocks;
    if (!blockHeight) blockHeight = blockWidth;

    var radiansPerBlock = PI2 / numberOfBlocks;

    // draw the circle
    context.arc(x, y, radius, 0, PI2, true);
    context.stroke();

    // 0 is centered top-dead-center (12 o'clock)
    // `radiansPerBlock / -2` rotates clockwise so that the bottom edge
    //   of the segment touches the horizontal midline
    var startRadians = radiansPerBlock / -2;

    // move to the center
    context.translate(x, y);

    for (var i = 0, angleRadians = startRadians, x, y; i < numberOfBlocks; i++) {

        // `-blockWidth / 2` is the center of the segment
        x = -blockWidth / 2;

        // `-radius` puts edge of block *inside* the circle
        // `-radius - blockHeight` puts edge of block *outside* the circle
        y = -radius - blockHeight/2;

        // rotate to the correct position
        context.rotate(angleRadians);

        // draw the block
        context.strokeRect(x, y, blockWidth, blockHeight);

        // rotate the same amount each time
        angleRadians = radiansPerBlock;
    }
};


var canvas = document.getElementsByTagName('canvas')[0];
var context = canvas.getContext('2d');

var radius = 50;
var numberOfBlocks = 10;
var x = canvas.width / 2;
var y = canvas.height / 2;
var blockWidth = 15;
var blockHeight = radius;

blocksAroundCircle(context, numberOfBlocks, x, y, radius, blockWidth, blockHeight);