stars.js

15/2 2012
gjort js rgb slump

Stars.js draws stars to a canvas. It works like this, and looks like this:

//
// drawStar
// obj: Either a Canvas context or an easelJS graphics object
// If innerR is zero, regular n/2 stars are drawn.
//
// © 2012 lhli.net.
// Licence: http://creativecommons.org/licenses/by-sa/3.0/
//
function drawStar(obj, color, sides, r, innerR, starX, starY, rotation)
{  
    color = color || '#000';
    sides = sides || 5;
    r = r || 100;
    innerR = innerR || 0;
    starX = starX || 0;
    starY = starY || 0;
    rotation = ((Math.PI*2/360)*rotation) || 0; // in degrees
   
    sides = (sides<3)?3:sides;
    if (innerR==0){
        sides = (sides<5)?5:sides;
        innerR=(Math.cos((Math.PI*2)/sides)/Math.cos(Math.PI/sides))*r;
    }
    var rad = ((Math.PI*2)/(sides*2));
   
    if (obj.hasOwnProperty('canvas')){
        // 2D context
        obj.fillStyle = color;
        obj.beginPath();
        obj.moveTo((Math.sin(rotation)*r)+starX, -(Math.cos(rotation)*r)+starY);
        for (var i = 1; i <= sides*2; i++) {
            obj.lineTo((Math.sin(rad*i+rotation)*innerR)+starX, -(Math.cos(rad*i+rotation)*innerR)+starY);
            i++;
            obj.lineTo((Math.sin(rad*i+rotation)*r)+starX, -(Math.cos(rad*i+rotation)*r)+starY);
        }
        obj.fill();
    } else {
        // easel
        obj.beginFill(color);
        obj.moveTo((Math.sin(rotation)*r)+starX, -(Math.cos(rotation)*r)+starY);
        for (var i = 1; i <= sides*2; i++) {
            obj.lineTo((Math.sin(rad*i+rotation)*innerR)+starX, -(Math.cos(rad*i+rotation)*innerR)+starY);
            i++;
            obj.lineTo((Math.sin(rad*i+rotation)*r)+starX, -(Math.cos(rad*i+rotation)*r)+starY);
        }
        obj.endFill();
    }
   
};