8 css фильтров для изображений

Javascript

Альтернативой вышеприведенному коду является Javascript, который работает во всех браузерах, если он включен, включая IE6 и ниже.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

var imgObj = document.getElementById («js-image» ) ;

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

Используя Javascript, мы можем задавать изображению черно-белый эффект, например, при наведении и клике по изображению. Совместно можно использовать jQuery, чтобы создать плавный эффект перехода к серому. Единственным недостатком является то, что Javascript может быть отключен в браузере.

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements

Numerical representations

A sample grayscale image

The intensity of a pixel is expressed within a given range between a minimum and a maximum, inclusive. This range is represented in an abstract way as a range from 0 (or 0%) (total absence, black) and 1 (or 100%) (total presence, white), with any fractional values in between. This notation is used in academic papers, but this does not define what «black» or «white» is in terms of colorimetry. Sometimes the scale is reversed, as in printing where the numeric intensity denotes how much ink is employed in halftoning, with 0% representing the paper white (no ink) and 100% being a solid black (full ink).

In computing, although the grayscale can be computed through rational numbers, image pixels are usually quantized to store them as unsigned integers, to reduce the required storage and computation. Some early grayscale monitors can only display up to sixteen different shades, which would be stored in binary form using 4 bits. But today grayscale images (such as photographs) intended for visual display (both on screen and printed) are commonly stored with 8 bits per sampled pixel. This pixel depth allows 256 different intensities (i.e., shades of gray) to be recorded, and also simplifies computation as each pixel sample can be accessed individually as one full byte. However, if these intensities were spaced equally in proportion to the amount of physical light they represent at that pixel (called a linear encoding or scale), the differences between adjacent dark shades could be quite noticeable as banding artifacts, while many of the lighter shades would be «wasted» by encoding a lot of perceptually-indistinguishable increments. Therefore, the shades are instead typically spread out evenly on a gamma-compressed nonlinear scale, which better approximates uniform perceptual increments for both dark and light shades, usually making these 256 shades enough (just barely) to avoid noticeable increments.

Technical uses (e.g. in medical imaging or remote sensing applications) often require more levels, to make full use of the sensor accuracy (typically 10 or 12 bits per sample) and to reduce rounding errors in computations. Sixteen bits per sample (65,536 levels) is often a convenient choice for such uses, as computers manage 16-bit words efficiently. The TIFF and PNG (among other) image file formats support 16-bit grayscale natively, although browsers and many imaging programs tend to ignore the low order 8 bits of each pixel. Internally for computation and working storage, image processing software typically uses integer or floating-point numbers of size 16 or 32 bits.

Решение: обесцветить картинку CSS

Сначала сверстаем саму картинку:

Затем пропишем для картинки стиль:

Img { -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: grayscale(100%); filter: gray; /* IE 6-9 */ }

Теперь наша картинка станет черно-белой.

Можно, конечно, на этом остановится, но гораздо интереснее, когда картинка ещё и отвечает на действия пользователя.

Предлагаю сделать так, чтобы при наведении на картинку, она плавно становилась цветной.

На самом деле, сделать это совсем не сложно, и вовсе не обязательно знать Javascript.

How to Use

  1. Add the CSS from gray.css.

    If you want to use your own CSS selector instead of , edit or copy the CSS.

  2. Add the plugin after jQuery at the bottom of the body.

    <script src="/js/jquery.gray.min.js"></script>

    The plugin automatically initializes for all elements with a class of .

    The plugin can also be called manually with:

    $('.my-grayscale-class').gray();

    The effect can be toggled with the class:

    $('.grayscale').toggleClass('grayscale-off');

  3. Add your image with a class of .

    <img src="/img/color.jpg" class="grayscale">

    Images with CSS background-image, background-size and (numeric) background-position are also supported:

    <div style="
      background-image   : url(/img/color-sprite-lg.jpg);
      background-size    : auto 72px;
      background-position: -180px 0;
      display            : inline-block;
      width              : 180px;
      height             : 72px;
    " class="grayscale"></div>

    Non-numeric background-size (cover, contain, …) and background-position (center, …) are not currently supported (pull requests welcome!).

  4. (Optional) Add class of if you want transitioning from grayscale back to color on hover

    <img src="/img/color.jpg" class="grayscale grayscale-fade">
  5. If you are using Modernizr already, make sure that the are included in your build.

  6. Revel in your absolute and utter awesomeness.

Usage

Import the css module

@import"css-filter-hue-rotate";
$ npm i -g tachyons-cli$ tachyons path/to/css-file.css > dist/t.css

The easiest and most simple way to use the css is to use the cdn hosted version. Include it in the head of your html with:

The built css is located in the directory. It contains an unminified and minified version. You can either cut and paste that css or link to it directly in your html.

<linkrel="stylesheet"href="path/to/module/css/css-filter-hue-rotate">

The source css files can be found in the directory. Running will process the source css and place the built css in the directory.

ИЗОБРАЖЕНИЯ

Слайд шоуГалерея слайд шоуМодальное изображениеЛайтбоксОтзывчивая сетка изображенийСетка изображенийГалерея вкладокЭффект наведения на изображениеНаложение слайда на изображениеНаложение на изображениеНаложение заголовка на изображениеНаложение иконки на изображениеЭффект к изображениюЧерно-белое изображениеТекст на изображенииИзображение с текстовым блокомИзображение c прозрачным текстомИзображение на всю страницуФорма на изображенииИзображение герояРазмытое фоновое изображениеФоновое изображениеВыравненные изображенияОкругленные изображенияИзображение аватарОтзывчивое изображениеИзображение по центруМинитюрное изображениеЗнакомство с командойЛипкое изображениеЗеркальное изображениеДрожание изображенияГалерея портфолиоПортфолио фильтрЗум изображенияЛупа изображенияПолзунок сравнения

Grayscale as single channels of multichannel color images

Color images are often built of several stacked color channels, each of them representing value levels of the given channel. For example, RGB images are composed of three independent channels for red, green and blue primary color components; CMYK images have four channels for cyan, magenta, yellow and black ink plates, etc.

Here is an example of color channel splitting of a full RGB color image. The column at left shows the isolated color channels in natural colors, while at right there are their grayscale equivalences:

Composition of RGB from 3 Grayscale images

The reverse is also possible: to build a full color image from their separate grayscale channels. By mangling channels, using offsets, rotating and other manipulations, artistic effects can be achieved instead of accurately reproducing the original image.

Анимировать обесцветить картинку CSS

Немного дополним наш предыдущий стиль:

Img { -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: grayscale(100%); filter: gray; /* IE 6-9 */ } img:hover { -webkit-filter: none; -moz-filter: none; -ms-filter: none; -o-filter: none; filter: none; filter: none; /* IE 6-9 */ }

Это позволит картинке при наведении на неё мышкой, становится цветной. А ещё восмользуемся CSS3 transition, чтобы сделать процесс обесцвечивания анимированным:

Img { -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: grayscale(100%); filter: gray; /* IE 6-9 */ /*Добавим вот такой вот код*/ -webkit-transition: all 1s; -moz-transition: all 1s; -o-transition: all 1s; transition: all 1s; /*конец кода с transition*/ } img:hover { -webkit-filter: none; -moz-filter: none; -ms-filter: none; -o-filter: none; filter: none; filter: none; /* IE 6-9 */ }

Параметр all в transition говорит, что правило будет работать для всех стилей, а второй параметр — время анимации. В первый параметр можно указать определённое свойство (например height, чтобы анимировать только высоту), а во второй время в секундах (можно в десятичных дробях — 0,1s).

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements

Implementing invert()

The filter is implemented by with .

The spec states:


An explanation of this formula:

  • The filter defines this table: . This is tableValues or v.
  • The formula defines n, such that n + 1 is the table’s length. Since the table’s length is 2, n = 1.
  • The formula defines k, with k and k + 1 being indexes of the table. Since the table has 2 elements, k = 0.

Thus, we can simplify the formula to:

Inlining the table’s values, we are left with:

One more simplification:

The spec defines C and C’ to be RGB values, within the bounds 0-1 (as opposed to 0-255). As a result, we must scale down the values before computation, and scale them back up after.

Thus we arrive at our implementation:

Добавление фильтра SVG

Код CSS, показанный выше, работает во всех современных версиях браузеров, как на настольных компьютерах, так и на мобильных устройствах, включая браузер Microsoft Edge.

Чтобы добиться такого же эффекта в браузере Firefox до версии 35, понадобится использовать фильтр SVG, который создадим в отдельном файле под названием desaturate.svg. В этом файле будет следующий код:

version =»1.1″ xmlns=»http://www.w3.org/2000/svg» >

id =»greyscale» >

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″ />

Если код SVG выше выглядит слегка пугающе и массив в нем слишком сложен, не волнуйтесь. Это один из фрагментов кода, который мы советуем просто копировать и вставлять как стандартный рецепт для создания черно-белого изображения.

Вместе с этим файлом SVG, находящимся рядом со страницей HTML и нужным изображением, код CSS дополнится такой строкой:

Img.desaturate {

filter: grayscale(100 % ) ; filter: url (desaturate.svg #greyscale

) ; }

Usage

Import the css module

@import"css-filter-grayscale";
$ npm i -g tachyons-cli$ tachyons path/to/css-file.css > dist/t.css

The easiest and most simple way to use the css is to use the cdn hosted version. Include it in the head of your html with:

The built css is located in the directory. It contains an unminified and minified version. You can either cut and paste that css or link to it directly in your html.

<linkrel="stylesheet"href="path/to/module/css/css-filter-grayscale">

The source css files can be found in the directory. Running will process the source css and place the built css in the directory.

Caveats

Non-visible elements will not be correctly initialized

Calling the plugin on hidden images (or other images that cannot have their size calculated) will fail in polyfill browsers. Workarounds can be found in the discussions at and .

Child elements removed in browsers without support for CSS filters

Target elements with child elements will have those child elements removed in browsers without support for CSS filters. #61

Colored borders


Colored borders will be also converted to grayscale in non-polyfill browsers. To also convert to grayscale in polyfill browsers, the class can be used:

.grayscale-replaced {
  border-color: #494949 !important;
}

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

The css

.gray-10{-webkit-filtergrayscale( 10% );filtergrayscale( 10% );}.gray-20{-webkit-filtergrayscale( 20% );filtergrayscale( 20% );}.gray-30{-webkit-filtergrayscale( 30% );filtergrayscale( 30% );}.gray-40{-webkit-filtergrayscale( 40% );filtergrayscale( 40% );}.gray-50{-webkit-filtergrayscale( 50% );filtergrayscale( 50% );}.gray-60{-webkit-filtergrayscale( 60% );filtergrayscale( 60% );}.gray-70{-webkit-filtergrayscale( 70% );filtergrayscale( 70% );}.gray-80{-webkit-filtergrayscale( 80% );filtergrayscale( 80% );}.gray-90{-webkit-filtergrayscale( 90% );filtergrayscale( 90% );}.gray-100{-webkit-filtergrayscale( 100% );filtergrayscale( 100% );}@mediascreenand (min-width48em){.gray-10-ns{-webkit-filtergrayscale( 10% );filtergrayscale( 10% );}.gray-20-ns{-webkit-filtergrayscale( 20% );filtergrayscale( 20% );}.gray-30-ns{-webkit-filtergrayscale( 30% );filtergrayscale( 30% );}.gray-40-ns{-webkit-filtergrayscale( 40% );filtergrayscale( 40% );}.gray-50-ns{-webkit-filtergrayscale( 50% );filtergrayscale( 50% );}.gray-60-ns{-webkit-filtergrayscale( 60% );filtergrayscale( 60% );}.gray-70-ns{-webkit-filtergrayscale( 70% );filtergrayscale( 70% );}.gray-80-ns{-webkit-filtergrayscale( 80% );filtergrayscale( 80% );}.gray-90-ns{-webkit-filtergrayscale( 90% );filtergrayscale( 90% );}.gray-100-ns{-webkit-filtergrayscale( 100% );filtergrayscale( 100% );}}@mediascreenand (min-width48em)and (max-width64em){.gray-10-m{-webkit-filtergrayscale( 10% );filtergrayscale( 10% );}.gray-20-m{-webkit-filtergrayscale( 20% );filtergrayscale( 20% );}.gray-30-m{-webkit-filtergrayscale( 30% );filtergrayscale( 30% );}.gray-40-m{-webkit-filtergrayscale( 40% );filtergrayscale( 40% );}.gray-50-m{-webkit-filtergrayscale( 50% );filtergrayscale( 50% );}.gray-60-m{-webkit-filtergrayscale( 60% );filtergrayscale( 60% );}.gray-70-m{-webkit-filtergrayscale( 70% );filtergrayscale( 70% );}.gray-80-m{-webkit-filtergrayscale( 80% );filtergrayscale( 80% );}.gray-90-m{-webkit-filtergrayscale( 90% );filtergrayscale( 90% );}.gray-100-m{-webkit-filtergrayscale( 100% );filtergrayscale( 100% );}}@mediascreenand (min-width64em){.gray-10-l{-webkit-filtergrayscale( 10% );filtergrayscale( 10% );}.gray-20-l{-webkit-filtergrayscale( 20% );filtergrayscale( 20% );}.gray-30-l{-webkit-filtergrayscale( 30% );filtergrayscale( 30% );}.gray-40-l{-webkit-filtergrayscale( 40% );filtergrayscale( 40% );}.gray-50-l{-webkit-filtergrayscale( 50% );filtergrayscale( 50% );}.gray-60-l{-webkit-filtergrayscale( 60% );filtergrayscale( 60% );}.gray-70-l{-webkit-filtergrayscale( 70% );filtergrayscale( 70% );}.gray-80-l{-webkit-filtergrayscale( 80% );filtergrayscale( 80% );}.gray-90-l{-webkit-filtergrayscale( 90% );filtergrayscale( 90% );}.gray-100-l{-webkit-filtergrayscale( 100% );filtergrayscale( 100% );}}

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

Tuning SPSA

Warning: Do not mess with the SPSA code, especially with its constants, unless you are sure you know what you are doing.

The important constants are A, a, c, the initial values, the retry thresholds, the values of in , and the number of iterations of each stage. All of these values were carefully tuned to produce good results, and randomly screwing with them will almost definitely reduce the usefulness of the algorithm.

If you insist on altering it, you must measure before you «optimize».

First, apply this patch.

Then run the code in Node.js. After quite some time, the result should be something like this:

Now tune the constants to your heart’s content.

Some tips:

  • The average loss should be around 4. If it is greater than 4, it is producing results that are too far off, and you should tune for accuracy. If it is less than 4, it is wasting time, and you should reduce the number of iterations.
  • If you increase/decrease the number of iterations, adjust A appropriately.
  • If you increase/decrease A, adjust a appropriately.
  • Use the flag if you want to see the result of each iteration.

Usage

Import the css module

@import"css-filter-hue-rotate";
$ npm i -g tachyons-cli$ tachyons path/to/css-file.css > dist/t.css

The easiest and most simple way to use the css is to use the cdn hosted version. Include it in the head of your html with:

The built css is located in the directory. It contains an unminified and minified version. You can either cut and paste that css or link to it directly in your html.

<linkrel="stylesheet"href="path/to/module/css/css-filter-hue-rotate">

The source css files can be found in the directory. Running will process the source css and place the built css in the directory.

The css

.hue-rotate1{-webkit-filterhue-rotate( 45deg );filterhue-rotate( 45deg );}.hue-rotate2{-webkit-filterhue-rotate( 90deg );filterhue-rotate( 90deg );}.hue-rotate3{-webkit-filterhue-rotate( 135deg );filterhue-rotate( 135deg );}.hue-rotate4{-webkit-filterhue-rotate( 180deg );filterhue-rotate( 180deg );}.hue-rotate5{-webkit-filterhue-rotate( 225deg );filterhue-rotate( 225deg );}.hue-rotate6{-webkit-filterhue-rotate( 270deg );filterhue-rotate( 270deg );}.hue-rotate7{-webkit-filterhue-rotate( 315deg );filterhue-rotate( 315deg );}.hue-rotate8{-webkit-filterhue-rotate( 360deg );filterhue-rotate( 360deg );}@mediascreenand (min-width48em){.hue-rotate1-ns{-webkit-filterhue-rotate( 45deg );filterhue-rotate( 45deg );}.hue-rotate2-ns{-webkit-filterhue-rotate( 90deg );filterhue-rotate( 90deg );}.hue-rotate3-ns{-webkit-filterhue-rotate( 135deg );filterhue-rotate( 135deg );}.hue-rotate4-ns{-webkit-filterhue-rotate( 180deg );filterhue-rotate( 180deg );}.hue-rotate5-ns{-webkit-filterhue-rotate( 225deg );filterhue-rotate( 225deg );}.hue-rotate6-ns{-webkit-filterhue-rotate( 270deg );filterhue-rotate( 270deg );}.hue-rotate7-ns{-webkit-filterhue-rotate( 315deg );filterhue-rotate( 315deg );}.hue-rotate8-ns{-webkit-filterhue-rotate( 360deg );filterhue-rotate( 360deg );}}@mediascreenand (min-width48em)and (max-width64em){.hue-rotate1-m{-webkit-filterhue-rotate( 45deg );filterhue-rotate( 45deg );}.hue-rotate2-m{-webkit-filterhue-rotate( 90deg );filterhue-rotate( 90deg );}.hue-rotate3-m{-webkit-filterhue-rotate( 135deg );filterhue-rotate( 135deg );}.hue-rotate4-m{-webkit-filterhue-rotate( 180deg );filterhue-rotate( 180deg );}.hue-rotate5-m{-webkit-filterhue-rotate( 225deg );filterhue-rotate( 225deg );}.hue-rotate6-m{-webkit-filterhue-rotate( 270deg );filterhue-rotate( 270deg );}.hue-rotate7-m{-webkit-filterhue-rotate( 315deg );filterhue-rotate( 315deg );}.hue-rotate8-m{-webkit-filterhue-rotate( 360deg );filterhue-rotate( 360deg );}}@mediascreenand (min-width64em){.hue-rotate1-l{-webkit-filterhue-rotate( 45deg );filterhue-rotate( 45deg );}.hue-rotate2-l{-webkit-filterhue-rotate( 90deg );filterhue-rotate( 90deg );}.hue-rotate3-l{-webkit-filterhue-rotate( 135deg );filterhue-rotate( 135deg );}.hue-rotate4-l{-webkit-filterhue-rotate( 180deg );filterhue-rotate( 180deg );}.hue-rotate5-l{-webkit-filterhue-rotate( 225deg );filterhue-rotate( 225deg );}.hue-rotate6-l{-webkit-filterhue-rotate( 270deg );filterhue-rotate( 270deg );}.hue-rotate7-l{-webkit-filterhue-rotate( 315deg );filterhue-rotate( 315deg );}.hue-rotate8-l{-webkit-filterhue-rotate( 360deg );filterhue-rotate( 360deg );}}

Вывод

Для поддержки данного эффекта всеми браузерами, необходимо комбинировать все способы. Данный код будет работать в Firefox 3.5+, Opera15+, Safari, Chrome и IE.

1 2 3 4 5 6 7 8

img {

-webkit-filter: grayscale(100% ) ;

-webkit-filter: grayscale(1 ) ;

filter : grayscale(100% ) ;

filter : url («../img/gray.svg#grayscale» ) ;

filter : gray ;

}

Данный код можно использовать вместе с Javascript, и в случае, если Javascript отключен, будет работать данный код. В этом может помочь Modernizr.

Modernizr добавляет js класс для body, если Javascript включен в браузере, и пропишет класс no-js если Javascript отключен. А в CSS осталось прописать сдедующее:

1 2 3 4 5 6 7 8

.no-js img {

-webkit-filter: grayscale(100% ) ;

-webkit-filter: grayscale(1 ) ;

filter : grayscale(100% ) ;

filter : url («../img/gray.svg#grayscale» ) ;

filter : gray ;

}


С этим читают