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, xf, yf ){
    this.x  = x;
    this.y  = y;
    this.xf = xf;
    this.yf = yf;
}

Object.defineProperty(Rectangle.prototype, 'partition', {
    value: function(width, height ) {
        var cols = [];
        var rows = [];
        var table = [];

        for( var x = this.x; x < this.xf; x += width  )
            cols.push( x );
        n = cols.length;
        cols.push( this.xf );

        for( var y = this.y; y < this.yf; y += height  )
            rows.push( y );
        m = rows.length;
        rows.push( this.yf );

        var i, j;
        for( i = 0; i < m; ++i ) {
            table.push( [] );
            for( j = 0; j < n; ++j )
                table[i].push( 
                    new Rectangle( cols[j]  , rows[i], 
                                   cols[j+1], rows[i+1]
                ));
        }
        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 w = 4*(this.width - (rectangle.xf-rectangle.x));
        var yf = rectangle.yf;
        var xf = rectangle.xf;
        var offset = 4*(rectangle.y*this.width + rectangle.x);
        for( var i = rectangle.y; i < yf; ++i ) {
            for( var j = rectangle.x; j < xf; ++j ) {
                var newcolor = callback( offset, this.data );
                for( k = 0; k < 4; ++k )
                    this.data[offset+k] = newcolor[k];
                offset += 4;
            }
            offset += w;
        }
    },
    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 w  = 4*(this.width - (rectangle.xf-rectangle.x));
        var yf = rectangle.yf;
        var xf = rectangle.xf;
      ...