How do you convert a color image to black/white using Javascript?

后端 未结 9 1409
梦如初夏
梦如初夏 2020-12-05 11:01

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

9条回答
  •  情话喂你
    2020-12-05 11:41

    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:

    • Browser support
    • Spec
    • Tutorial

提交回复
热议问题