/*
	canvas wrapper

	author:nakagawa[]ville.jp
	license:NYSL
*/
function VilleCanvas(elem, width, height){
	this.elem = elem;
	this.ctx = null;
	this.width = elem.width = width;
	this.height = elem.height = height;

	if(!this.elem || !this.elem.getContext) return null;
	this.ctx = this.elem.getContext('2d');
}
VilleCanvas.prototype = {
	plot : function(point, color, size){
		if(!size) size = 1;
		this.ctx.beginPath();
		this.ctx.globalAlpha = 1;
		this.setFillStyle(color);
		//this.ctx.fillRect(point.x, point.y, size, size);
		this.ctx.arc(point.x, point.y, size, 0, Math.PI*2, false);
		this.ctx.closePath();
		this.ctx.fill();
	},
	drawTriangle : function(triangle, lineColor, lineWidth, fillColor){
		this.ctx.beginPath();
		this.setLineStyle(lineColor, lineWidth);
		this.setFillStyle(fillColor);
		this.ctx.globalAlpha = 0.8;
		this.ctx.moveTo(triangle[0].x, triangle[0].y);
		this.ctx.lineTo(triangle[1].x, triangle[1].y);
		this.ctx.lineTo(triangle[2].x, triangle[2].y);
		this.ctx.closePath();
		this.ctx.stroke();
		this.ctx.fill();
	},
	clear : function(){
		this.ctx.clearRect(0, 0, this.width, this.height);
	},
	setFillStyle : function(color){
		if(!color) color = '#000000';
		this.ctx.fillStyle = color;
	},
	setLineStyle : function(color, width){
		if(!color) color = '#000000';
		if(!width) width = 1;
		this.ctx.strokeStyle = color;
		this.ctx.lineWidth = width;
	},
	loadImage : function(img, x, y){
		this.ctx.drawImage(img, x, y);
		var im = new VilleImageObject();
		var imagedata = this.ctx.getImageData(0, 0, img.width, img.height);
		im.init(imagedata.width, imagedata.height, imagedata.data);
		return im;
	}
}

var VilleImageObject = function(){
	this.w = 0;
	this.h = 0;
	this.pixels = [];
}
VilleImageObject.prototype = {
	init : function(w, h, pixels){
		this.w = w;
		this.h = h;
		this.pixels = pixels;
	},
	getPixel : function(p){
		var n = (Math.floor(p.y)*this.w + Math.floor(p.x) + 1) * 4;
		return [	// r,g,b,alpha
			this.pixels[n],
			this.pixels[n+1],
			this.pixels[n+2],
			this.pixels[n+3]
		];
	},
	getColor : function(p){
		var px = this.getPixel(p);
		var color = '#';
		for(var i=0; i<3; i++){
			var n  = px[i];
			var c = Math.round(n).toString(16);
			if(n<16) c = '0' + c;
			color += c;
		}
		return color;
	}
};