Skip to content

Instantly share code, notes, and snippets.

@adrianseeley adrianseeley/col.js.html
Last active Aug 29, 2015

Embed
What would you like to do?
Multi-Pass Color Sort Lamba X and Lambda Y
<canvas id="canvas" width="256" height="256"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var imgdata = ctx.createImageData(canvas.width, canvas.height);
function set_pixel (x, y, r, g, b) { var index = (x + y * imgdata.width) * 4; imgdata.data[index + 0] = r; imgdata.data[index + 1] = g; imgdata.data[index + 2] = b; imgdata.data[index + 3] = 255; };
function swap_pixels (x1, y1, x2, y2) { var p1 = get_pixel(x1, y1); var p2 = get_pixel(x2, y2); set_pixel(x1, y1, p2[0], p2[1], p2[2]); set_pixel(x2, y2, p1[0], p1[1], p1[2]); };
function get_pixel (x, y) { var index = (x + y * imgdata.width) * 4; return [imgdata.data[index + 0], imgdata.data[index + 1], imgdata.data[index + 2]]; };
function draw () { ctx.putImageData(imgdata, 0, 0); };
function prep () {
// meant for 4096x4096 canvas, slow as fuck
var r = 0;
var g = 0;
var b = 0;
for (var x = 0; x < canvas.width; x++) {
for (var y = 0; y < canvas.height; y++) {
set_pixel(x, y, r, g, b);
b++;
if (b > 255) {
b = 0;
g++;
if (g > 255) {
g = 0;
r++;
}
}
}
}
draw();
};
function preprandom () {
// way prettier
for (var x = 0; x < canvas.width; x++) for (var y = 0; y < canvas.height; y++) set_pixel(x, y, Math.floor(Math.random() * 255), Math.floor(Math.random() * 255), Math.floor(Math.random() * 255));
draw();
};
function multi_pass_sort (lambda_x, lambda_y) {
var sorted = true;
for (var x = 1; x < canvas.width; x++) for (var y = 0; y < canvas.height; y++) if (lambda_x(get_pixel(x - 1, y), get_pixel(x, y))) { swap_pixels(x - 1, y, x, y); sorted = false; }
for (var x = 0; x < canvas.width; x++) for (var y = 1; y < canvas.height; y++) if (lambda_y(get_pixel(x, y - 1), get_pixel(x, y))) { swap_pixels(x, y - 1, x, y); sorted = false; }
draw();
if (!sorted) setTimeout(function () { multi_pass_sort(lambda_x, lambda_y); }, 0);
else console.log('done!');
};
//prep();
preprandom();
setTimeout(function () { multi_pass_sort(function lambda_x (a, b) { return a[0] > b[0] || a[1] > b[1]; }, function lambda_y (a, b) { return a[1] > b[1] || a[2] > b[2]; });
}, 1000);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.