I'm trying to ordered dither images in HTML5 canvas down or close to 256 colours every time. I have the dither algorithm working which you can see on my test page (Check the browser console for the colour counts).
But I'm having trouble understanding how I can select or generate the optimal depth and threshold map for different images, the results vary massively depending on how many colours the original image has.
I have one of these functions for 2x2,3x3,4x4,8x8 maps so far,
function ditherImageData4x4(imageDataToDither){
var depth = $('#depth').val();
var threshold_map = [
[ 1, 9, 3, 11 ],
[ 13, 5, 15, 7 ],
[ 4, 12, 2, 10 ],
[ 16, 8, 14, 6 ]
];
var dataWidth = imageDataToDither.width;
var dataHeight = imageDataToDither.height;
var pixel = imageDataToDither.data;
var x, y, a, b;
for ( x=0; x<dataWidth; x++ ){
for ( y=0; y<dataHeight; y++ ){
a = ( x * dataHeight + y ) * 4;
b = threshold_map[ x%4 ][ y%4 ];
pixel[ a + 0 ] = ( (pixel[ a + 0 ]+ b) / depth | 0 ) * depth;
pixel[ a + 1 ] = ( (pixel[ a + 1 ]+ b) / depth | 0 ) * depth;
pixel[ a + 2 ] = ( (pixel[ a + 2 ]+ b) / depth | 0 ) * depth;
//pixel[ a + 3 ] = ( (pixel[ a + 3 ]+ b) / depth | 3 ) * depth;
}
}
return pixel;
};