Project 5: Wallpaper

var s = 50;
function hexagon(xCenter,yCenter,color,col) {

    var canvas = document.getElementById('hexagons');
    var ctx = canvas.getContext('2d');
    
    ctx.beginPath();

    ctx.moveTo(xCenter - s, yCenter);
    ctx.lineTo(xCenter - (s/2), yCenter - s*Math.sqrt(3)/2);
    ctx.lineTo(xCenter + (s/2), yCenter - s*Math.sqrt(3)/2);
    ctx.lineTo(xCenter + s, yCenter);
    ctx.lineTo(xCenter + (s/2), yCenter + s*Math.sqrt(3)/2);
    ctx.lineTo(xCenter - (s/2), yCenter + s*Math.sqrt(3)/2);
    ctx.lineTo(xCenter - s, yCenter);

    ctx.closePath();
    ctx.stroke();
    if (col) {
        if (color % 3 == 1) {
            ctx.fillStyle = '#f00';
        } else if (color % 3 == 2) {
            ctx.fillStyle = '#0f0';
        } else {
            ctx.fillStyle = '#00f';
        }
    } else {
        if (color % 3 == 1) {
            ctx.fillStyle = '#00f';
        } else if (color % 3 == 2) {
            ctx.fillStyle = '#f00';
        } else {
            ctx.fillStyle = '#0f0';
        }
    }
    
    ctx.fill();
}

function draw() {

    var above = true;
    for (var i = 1; i <= 6; i++) {

        for (var j = 1; j <= 5; j++) {
            hexagon(150 * j - 100, (25 * Math.sqrt(3) * 2 * i),i,true);
        }
        
    }

    for (var i = 1; i <= 5; i++) {

        for (var j = 1; j <= 4; j++) {

        hexagon(150 * j - 25,(25 * Math.sqrt(3) * 2 * i) + 25 * Math.sqrt(3),i,false);
        }
    }

}
draw();

Leave a Reply