All Projects → brandly → butter.js

brandly / butter.js

Licence: MIT license
🍴 pixel sorting with canvas

Programming Languages

javascript
184084 projects - #8 most used programming language
CSS
56736 projects
HTML
75241 projects

Butter.js

pixel sorting for canvas

$ npm install --save butter.js

general idea

Take a canvas. Define a filter for which pixels get sorted and which don't. Rows and columns of pixels that pass that filter will be sorted based on their color value.

basic use

var canvas = document.getElementById('my-canvas');
var butter = new Butter();
butter.sort(canvas);

For convenience, you can sort multiple times in quick succession

butter.sort(canvas, 3);

By default, the mode is set to black, but you could also set it to bright or white.

var butter = new Butter({mode: 'bright'});

You can also change the threshold for the current mode using butter.setThreshold(newThreshold)

web worker

Here's the thing: Butter has to loop through a lot of pixels, which isn't super fast. This slowness can lock up your UI, and people don't like that.

Fortunately, we can use Web Workers nowadays to sort our pixels on another thread.

Web Workers don't have access to the DOM, so we need to do a tiny bit more work, but maybe it's worth it. Here's what that looks like.

var canvas = document.getElementById('my-canvas');
var context = canvas.getContext('2d');

var butter = new Worker('butter-worker.js');

// it'll message us back when it's done sorting
butter.addEventListener('message', function afterSort(e) {
  context.putImageData(e.data.imageData, 0, 0);
}, false);

// get the raw pixel data from our canvas' context
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);

// message the worker to tell it to sort those pixels
butter.postMessage({
  imageData: imageData,
  width: canvas.width,
  height: canvas.height,
  mode: 'black',       // optional
  threshold: -10000000 // optional
});

Check out butter.pics

development

$ npm install
$ gulp
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].