Cross-browser gray scale solution

Source: Internet
Author: User
Tags scale image

The implementation of grayscale initially included the exclusive attribute filter Implementation launched by ie6. Later, w3c implemented the standard filter in css3, but the implementation degree of different browsers was different, therefore, at this stage, we must explore a browser-compatible solution.

1. the IE private filter method starts with IE4. IE introduces a private filter to achieve transparency, blur, shadow, light-emitting, and other effects. Of course, it can also achieve gray-scale image effects. The Code is as follows:
img {      filter: gray; /* just for IE6-9 */  }  
IE10 began to discard this private filter, but it has not yet provided support for standard CSSfilter. Therefore, grayscale images of IE10 and later versions are still a problem. 2. the W3c CSS filter Method CSS3 provides a standard CSS Filter solution by referring to the IE private filter method, it supports grayscale gray scale, sepia Brown, saturate saturation, hue-rotate color rotation, invert reversed color, opacity transparency, brightness, contrast, blur, drop-shadow, and other 10 types. effect. For details about CSS3 Filter, refer to the following Tutorial: the ten special effects of CSS3 Filter and the CSS Filter Lab of Adobe. The code for implementing grayscale images is as follows:
Img {-webkit-filter: grayscale (100%);/* a good degree of webkit Kernel support */-moz-filter: grayscale (100%);/* Other kernels are not currently supported, write for future compatibility */-ms-filter: grayscale (100%);-o-filter: grayscale (100%); filter: grayscale (100%);/* standard syntax */}
The value of grayscale () is 0%-100%, which can be replaced by 0-1. 0% represents a color image, and 100% represents a completely gray scale. The browser compatibility of css filter is as follows: Chrome31 +, Safari7 +, Opera20 +, ios Safari6 +, Android Browser4.4 +, and Blackberry 10 + all support the-webkit-filter method, IE is not supported, but firefox is not.
Therefore, we need to consider the compatibility between IE and firefox. Fortunately, for firefox, the SVG effects for HTML method is supported. Next we will introduce it. 3. SVG effects for HTML Firefox does not support css filter, but supports svg effects for html. html files can call effects in svg, not only filters, mask, and clip, for details, refer to the article Applying SVG effects to HTML content on MDN. Shows the compatibility of svg effects for html browsers.
First, you need to declare a filter in an svg file. The svg can be embedded in an html file or saved separately.
<svg xmlns=""> <filter id="grayscale">  <feColorMatrix type="matrix" values="0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/> </filter></svg>
If the file is saved as a separate gray. svg file, we can reference it in the html file.
Img {filter: url ('Gray. svg # grayscal');/* place the grayscale filter in the grayscale filter named id of the gray. svg file */}
If the file is embedded in an html file
Img {filter: url ('# grayscale');/* html files are embedded in the svg filter */}
Of course, we can also directly package the svg file into css, if you do not have code cleanliness
img {          filter: url('url("data:image/svg+xml;utf8,<svg%20xmlns=''><filter%20id='grayscale'><feColorMatrix%20type='matrix'%20values='0.3333%200.3333%200.3333%200%200%200.3333%200.3333%200.3333%200%200%200.3333%200.3333%200.3333%200%200%200%200%200%201%200'/></filter></svg>#grayscale");')  } 
In the above method, we can be compatible with most browsers (except IE10 and IE11). The compatible grayscale code is as follows.
Img {-webkit-filter: grayscale (100%);/* CSS3 filter mode, webkit kernel mode, most modern browsers outside firefox */-moz-filter: grayscale (100%);/* not implemented currently */-ms-filter: grayscale (100%);-o-filter: grayscale (100%); filter: grayscale (100% ); /* CSS3 filter method, standard writing */filter: url (filters. svg # grayscale);/* Firefox 4 + */filter: gray;/* IE 6-9 */} img: hover {-webkit-filter: grayscale (0% ); -moz-filter: grayscale (0%);-ms-filter: grayscale (0%);-o-filter: grayscale (0%); filter: grayscale (0%); filter: none;/* Firefox 4 +, IE 6-9 */}
4. How can we implement js for IE10 and 11? Javascript is used.
var imgObj = document.getElementById('imgToGray'); function gray(imgObj) {    var canvas = document.createElement('canvas');    var canvasContext = canvas.getContext('2d');    var imgW = imgObj.width;    var imgH = imgObj.height;    canvas.width = imgW;    canvas.height = imgH;    canvasContext.drawImage(imgObj, 0, 0);    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);    for (var y = 0; y < imgPixels.height; y++) {        for (var x = 0; x < imgPixels.width; x++) {            var i = (y * 4) * imgPixels.width + x * 4;            var avg = ([i] +[i + 1] +[i + 2]) / 3;  [i] = avg;  [i + 1] = avg;  [i + 2] = avg;        }    }    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);    return canvas.toDataURL();}imgObj.src = gray(imgObj);
For more information about this solution, see ajaxblender's Convert Images to Grayscale. 5. Cross-Browser solution this solution is mainly implemented by referring to Cross-browser Grayscale image example using CSS3 + JS v2.0. With Browser feature detection using Modernizr. You can see the best English kids shoes. The blogger wrote two blogs about how to use JavaScript to implement cross-browser grayscale images. The first one is browser detection, and the second one is Modernizr. This solution uses jQuery and Modernizr, so we need to introduce them. This is omitted here. If you do not know how to introduce the shoes, Please consciously hit the south wall for 100 times. For ie browsers
// IE 10 only CSS propertiesvar ie10Styles = ['msTouchAction','msWrapFlow'];var ie11Styles = ['msTextCombineHorizontal'];/** Test all IE only CSS properties*/var d = document;var b = d.body;var s =;var brwoser = null;var property;// Tests IE10 propertiesfor (var i = 0; i < ie10Styles.length; i++) {    property = ie10Styles[i];    if (s[property] != undefined) {        brwoser = "ie10";    }}// Tests IE11 propertiesfor (var i = 0; i < ie11Styles.length; i++) {    property = ie11Styles[i];    if (s[property] != undefined) {        brwoser = "ie11";    }} //Grayscale images only on browsers IE10+ since they removed support for CSS grayscale filter if(brwoser == "ie10" || brwoser == "ie11" ){    $('body').addClass('ie11'); // Fixes marbin issue on IE10 and IE11 after canvas function on images    $('.grayscale img').each(function(){        var el = $(this);        el.css({"position":"absolute"}).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale ieImage').css({"position":"absolute","z-index":"5","opacity":"0"}).insertBefore(el).queue(function(){            var el = $(this);            el.parent().css({"width":this.width,"height":this.height});            el.dequeue();        });        this.src = grayscaleIe(this.src);    });    // Quick animation on IE10+     $('.grayscale img').hover(        function () {            $(this).parent().find('img:first').stop().animate({opacity:1}, 200);        },         function () {            $('.img_grayscale').stop().animate({opacity:0}, 200);        }    );    // Custom grayscale function for IE10 and IE11    function grayscaleIe(src){        var canvas = document.createElement('canvas');        var ctx = canvas.getContext('2d');        var imgObj = new Image();        imgObj.src = src;        canvas.width = imgObj.width;        canvas.height = imgObj.height;         ctx.drawImage(imgObj, 0, 0);         var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);        for(var y = 0; y < imgPixels.height; y++){            for(var x = 0; x < imgPixels.width; x++){                var i = (y * 4) * imgPixels.width + x * 4;                var avg = ([i] +[i + 1] +[i + 2]) / 3;      [i] = avg;       [i + 1] = avg;       [i + 2] = avg;            }        }        ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);        return canvas.toDataURL();    }; };
For other browsers
// If the browser does not support CSS filters filters, we are applying grayscale.js function// This part of Grayscale images applies on Opera, Firefox and Safari browsersif (!Modernizr.cssfilters) {    var $images = $(".grayscale img"), imageCount = $images.length, counter = 0;    // One instead of on, because it need only fire once per image    $"load",function(){        // increment counter every time an image finishes loading        counter++;        if (counter == imageCount) {            // do stuff when all have loaded            grayscale($('.grayscale img'));            $(".grayscale img").hover(                function () {                    grayscale.reset($(this));                },                 function () {                    grayscale($(this));                }            );        }    }).each(function () {    if (this.complete) {        // manually trigger load event in        // event of a cache pull            $(this).trigger("load");        }    });}
The DEMO won't be done by yourself. Let's look at the DEMO provided by foreigners. That's all.


Front-end development of whqet, focus on web Front-end development technology, and share webpage-related resources.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.