There are many dithering algorithms to crush multi-colored images down to black and white but the one I like best was introduced with the original Apple Macintosh for its crisp 512x342 monochrome display. One of Apple's engineers, Bill Atkinson, developed what came to be known as Atkinson Dithering, a good trade-off between fast and accurate with results possessing a certain charm that on-paper "better" dithers cannot match.
I wanted to bring this to the web. For some examples of how to use this project and an interactive demo see my blog post on the subject.
You can pre-dither your images but this gives bad results because dithering relies on the precise correspondence between the source and out pixels. Unless you can guarantee that your image will be displayed at exactly the same size (in pixels) as it was output, the pixels of the image will not align with the pixels of your screen and the results will be either blurry or fulled with weird patterns. The technical term for this is aliasing but whatever you call it, it ruins your image.
The only way to get really crisp results in a web browser is to dither the source image to the exact pixel size of the element when it is displayed.
There is other javascript floating around out there that does much the same thing. as-dithered-image has a few advantages:
You will need to copy the following two files into your web project, they should be placed together in the same directory.
Example usage:
<script src="https://github.com/andrewstephens75/as-dithered-image/raw/main/as-dithered-image.js"></script>
<as-dithered-image src="https://github.com/andrewstephens75/as-dithered-image/raw/main/mypicture.jpg" alt="Description of the image for screen readers"></as-dithered-image>
as-dithered-image takes 6 attributes:
"rgba(0, 0, 0, 255)"
(and only this form because I am lazy). Sets the RGBA value for dark pixels, defaulting to fully opaque black, useful for matching the image to the colors of the surrounding page or making transparent areas. Note that this just controls the output color, the dithering is still performed based on the closeness of a pixel to black or white."rgba(255, 255, 255, 255)"
. Similar to the above but for the light pixels.See LICENSE file for usage.