polyRotate

an n-gon whose 0-endpoint always points toward the mouse. angle to rotate by is calculated using the center point, the 0-endpoint and the mouse point.

by theoperatore

HTML

<canvas id='playground' width='300' height='300'>Your browser must support html5 canvas element</canvas>

JavaScript

function Vector2D(x, y) {
    this.x = x;
    this.y = y;
}

Vector2D.prototype.rotate = function (radians, counterclockwise) {
    var direction = (typeof counterclockwise === 'undefined') ? true : counterclockwise,
        tmpX = this.x,
        tmpY = this.y;
    
    //this is using the rotation matrix |  cos(rads) sin(rads) |
    //                                  | -sin(rads) cos(rads) |
    //
    //it might be the incorrect matrix to use...
    
    if (direction) {
        this.x = (Math.cos(radians) * tmpX) + (-Math.sin(radians) * tmpY);
        this.y = (Math.sin(radians) * tmpX) + (Math.cos(radians) * tmpY);
    } else {
        this.x = (Math.cos(-radians) * tmpX) + (-Math.sin(-radians) * tmpY);
        this.y = (Math.sin(-radians) * tmpX) + (Math.cos(-radians) * tmpY);
    }
};

function Polygon2D(initEndPoints) {
    this.endpoints = initEndPoints || [];
    this.centerPoint = this._center();
}

Polygon2D.prototype._center = function () {
    var sumX = 0,
        sumY = 0,
        center = new Vector2D(0, 0);

    //add up all of the x values and y values
    for (var i = 0; i < this.endpoints.length; i++) {
        sumX += this.endpoints[i].x;
        sumY += this.endpoints[i].y;
    }

    //the center is the average of the coordinates
    center.x = sumX / this.endpoints.length;
    center.y = sumY / this.endpoints.length;

    return center;
};

Polygon2D.prototype.render = function (ctx) {

    //start this polygon
    ctx.beginPath();

    ctx.fillStyle = 'blue';

    //move to the starting position
    ctx.moveTo(this.endpoints[0].x, this.endpoints[0].y);

    //draw lines through all of the points
    for (var i = 0; i < this.endpoints.length; i++) {
        ctx.lineTo(this.endpoints[i].x, this.endpoints[i].y);
    }

    //...and close this polygon
    ctx.lineTo(this.endpoints[0].x, this.endpoints[0].y);

    //fill or stroke the polygon?
    //(fill) ? ctx.fill() : ctx.stroke();
    ctx.fill();

    //draw center
    ctx.beginPath();
 ...