How do you convert a color image to black/white using only Javascript?
AND, also make it cross compatible in most browsers because I hear Internet E
The way I would do it is to set the src of the img to point to a server-side PHP script
eg.,
<img src="http://mysite/grayscale.php?url='...'
That script fetches the image, runs some GD code, and returns a JPG. Something like this
Despite my initial scepticism it appears that such magic is indeed possible, using the new Canvas functionality in some browsers.
This page shows how to do it using browsers that support Canvas:
http://www.permadi.com/tutorial/jsCanvasGrayscale/index.html
For IE you need to use filters, there is an example of doing greyscale here:
http://www.javascriptkit.com/filters/basicimage.shtml
Modern browsers can now do this in CSS – on any HTML element, not just images. Combined with IE's old filter
CSS, you can get pretty good compatibility:
image.grayscale {
/* IE */
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
/* Chrome, Safari */
-webkit-filter: grayscale(1);
/* Firefox */
filter: grayscale(1);
}
OP specifies "only JavaScript" but also mentions that IE's filter
would be acceptable if it were more widely supported, which it now (effectively) is, so I believe this is the best solution in 2015. If you really must have JavaScript:
element.style.filter = 'grayscale(1)';
Sources: