// CanvasImage.js
// Created by Higeorange (http://higeorange.com/)
// MIT License (http://www.opensource.jp/licenses/mit-license.html)

function CanvasImage(image, element) {
    this.canvas = element;
    this.img = new Image();
    this.img.src = image;
    this.w = this.img.width;
    this.h = this.img.height;
    this.canvas.setAttribute('width', this.w);
    this.canvas.setAttribute('height', this.h);
    this.r = 0
    this.dx = 0;
    this.dy = 0;
}

CanvasImage.prototype.rotate = function(dg) {
    var r = dg || 0;
    var s = 180 - r;
    var R = d2r(r); 
    var S = d2r(s);
    var x = this.w;
    var y = this.h;
    if(r >= 0 && r <= 90) {
        this.w = x * Math.cos(R) + y * Math.sin(R);
        this.h = y * Math.cos(R) + x * Math.sin(R);
        this.dx = y * Math.sin(R)
        this.dy = 0;
    } else if(r > 90 && r <= 180) {
        this.w = -1 * (x * Math.cos(R) - y * Math.sin(R));
        this.h = x * Math.sin(S) + y * Math.sin(d2r(90 - s));
        this.dx = w;
        this.dy = y * Math.sin(d2r(90-s));
    } else if(r > 180 && r <= 270) {
        this.w = x * Math.cos(d2r(r-180)) + y * Math.sin(d2r(r-180));
        this.h = -1 * (x * Math.sin(R) + y * Math.cos(R));
        this.dx = x * Math.cos(d2r(r - 180));
        this.dy = h;
    } else if(r > 270 && r <= 360) {
        this.w = x * Math.cos(R) - y * Math.sin(R);
        this.h = x * Math.cos(d2r(r - 270)) + y * Math.sin(d2r(r - 270)); 
        this.dx = 0;
        this.dy = x * Math.cos(d2r(r - 270));
    }
//    this.canvas.style.width = this.w + 'px';
//    this.canvas.style.height = this.w + 'px';
    this.canvas.setAttribute('width', this.w);
    this.canvas.setAttribute('height', this.h);
    this.canvas.style.border = '5px solid red';
    this.r = R;
}

CanvasImage.prototype.translate = function(dx, dy) {
    this.dx = dx;
    this.dy = dy;
}

CanvasImage.prototype.draw = function() {
    var ctx = this.canvas.getContext("2d");
        ctx.translate(this.dx, this.dy);
        ctx.rotate(this.r);
        ctx.drawImage(this.img, 0, 0);
}

function d2r(a) {
    return a * Math.PI / 180;
}
