f8g

OperaのCanvasが凄いのでモザイク

いまさらながらOperaにはgetPixel/setPixelがあることを知りました。
http://orera.g.hatena.ne.jp/higeorange/20080604/1212505679
Operaさんはすげえぜ! ただ、色の指定が文字列ってところが使いづらい。
ということでモザイク。

CanvasRenderingContext2DGame.Color = function(r, g, b){
	this.r = r;
	this.g = g;
	this.b = b;

	this.toString = function(){
		return "rgb(" + [this.r, this.g, this.b] + ")";
	};
};

CanvasRenderingContext2DGame.prototype._getPixel = function(x, y){
	var color = parseInt(this.getPixel(x,y).substr(1),16);
	return new CanvasRenderingContext2DGame.Color(color>>16, color>>8&255, color&255);
};

CanvasRenderingContext2DGame.prototype.colorAverage = function(from_x, from_y, to_x, to_y){
	var color = new CanvasRenderingContext2DGame.Color(0, 0, 0);
	var _color;
	var pixel_n = (to_x - from_x) * (to_y - from_y);

	for(var x = from_x; x < to_x; x++){
		for(var y = from_y; y < to_y; y++){
			_color = this._getPixel(x, y);
			color.r += _color.r;
			color.g += _color.g;
			color.b += _color.b;
		}
	}

	"rgb".split("").map(function(x){
		color[x] = parseInt(color[x] / pixel_n);
	});

	return color;
};

CanvasRenderingContext2DGame.prototype.toMosaic = function(size){
	var to_x, to_y;
	var ctx = this.canvas.getContext("2d");

	for(var x = 0; x < this.canvas.width; x += size){
		for(var y = 0; y < this.canvas.height; y += size){
			to_x = (x + size >= this.canvas.width) ? this.canvas.width  - 1 : x + size;
			to_y = (y + size >= this.canvas.height)? this.canvas.height - 1 : y + size;

			ctx.fillStyle = this.colorAverage(x, y, to_x, to_y).toString();
			ctx.fillRect(x, y, size, size);
		}
	}
};

window.addEventListener("load", function(){
	var img = new Image();
	img.src = "img.png";

	var canvas = document.getElementsByTagName("canvas")[0];
	var ctx = canvas.getContext('2d');
	var gctx = canvas.getContext('opera-2dgame');

	canvas.width = img.width;
	canvas.height = img.height;

	ctx.drawImage(img, 0, 0, img.width, img.height);
	gctx.toMosaic(10);
}, false);

http://gyazo.com/4fda1a4e3cdb189fd72134a5c5d68803.png
setPixelで1pxずつじゃないのでそんなに遅くはない、かもしれない。