JSFiddle - React, Tailwind, and code Playground

by Brondem Brondem

HTML

<canvas id="canvas"></canvas>
<br/>
<button id="btn">Pixelar</button>

JavaScript

function Rectangle( x, y, w, h ){
    this.x      = x;
    this.y      = y;
    this.width  = w;
    this.height = h;
}

// tranforma un rectangulo en una tabla de rectangulos de anchura width y altura height
Object.defineProperty(Rectangle.prototype, 'partition', {
    value: function(width, height ) {
        var table = [];
        var x = 0;
        var y = 0;
        for( var y = 0; y < this.height; y += height ) {
            var i = table.push( [] ) - 1;
            for( var x = 0; x < this.width; x += width ) {
                table[i].push( 
                    new Rectangle( x, y, 
                        Math.min( width,this.width -x), 
                        Math.min(height,this.height-y)
                ));
            }
        }
        return table;
    },
    enumerable: false
});

// recorre los pixeles asociados a rectangle y modifica
// cada pixel según el valor retornado por callback
Object.defineProperty( ImageData.prototype, 'map', {
    value: function( rectangle, callback ) {
        var x, xtop, y, ytop;
        x = xtop = rectangle.x;
        y = ytop = rectangle.y;
        xtop += rectangle.width;
        ytop += rectangle.height;
        color = [0,0,0,0];
        var w = this.width;
        for( var i = y; i < ytop; ++i ) {
            for( var j = x; j < xtop; ++j ) {
                var color  = new Uint8ClampedArray( 4 );
                var offset = i*w+j;
                for( var k = 0; k < 4; ++k )
                    color[k] = this.data[4*offset+k]; 
                var newcolor = callback( color, offset );
                for( var k = 0; k < 4; ++k )
                    this.data[4*offset+k] = newcolor[k];
            }
        }
    },
    enumerable: false
});

// recorre los pixeles asociados a rectangle y ejecuta
// en cada pixel la función callback
Object.defineProperty( ImageData.prototype, 'forEach', {
    value: function( rectangle, callback ) {
        var x, xtop, y, ytop;
        x = xtop = rectangle.x;
        y...