Улучшенные эффекты с режимом смешивания фоновых слоев в CSS
Если одна картина заслуживает тысячи слов, то смешение двух картин заслуживает гораздо большего. Точно так же, возможности дизайна, которые открываются с появлением возможности смешивания слоев в CSS гораздо больше, чем вы думаете.
Когда вы слышите обсуждение функций CSS Blend Modes, то обычно речь идет о трех новых свойствах CSS, которые получили хорошую поддержку в современных браузерах.
Комбинирование CSS-градиентов при помощи background-blend-mode
Но свойство background может допускать более одного градиента, отображая их поверх друг друга, если перечислить каждый следующий через запятую. Lea Verou продемонстрировала впечатляющие образцы, которые могут быть созданы с помощью этой техники: от шахматных досок до кирпичей и звезд.
Спектральный фон
Давайте наложим три градиента, чтобы сделать фон с почти полным спектром цветов, который можно отобразить на мониторе.
Этот эффект ранее был возможен только в виде картинки, занимавшей десятки килобайт. Но мы только что воспроизвели его с помощью CSS размером менее 200 байт, не говоря уже об экономии HTTP-запроса.
Клетчатый фон
Фон в кружочек
Вот еще один фон, теперь с использованием радиального градиента:
Больше фоновых рисунков
С помощью Yoksel и Una Kravets я подготовил коллекцию из 24 шаблонов, сделанных с помощью смешивания, которые сделают ваш сайт быстрее и привлекательнее.
Фотоэффекты с помощью background-blend-mode
Эффект карандашного наброска
Мы можем использовать CSS, чтобы сделать фотографию слева похожей на карандашный набросок. Нам не понадобятся Photoshop, HTML5 canvas, WebGL, библиотеки Javascript. Пять свойств CSS – все, что потребуется.
Давайте начнем моделирование. Заменим chapel.jpg на url картинки, которую вы используете. Мы дважды установим фоновое изображение и сохраним его фоновый размер.
Ниже на первом квадрате результат нашего первого шага:
Теперь добавим режим смешивания:
О нет, куда все делось? У нас получился совершенно черный квадрат. Режим вычитания для смешивания берет два фона и отнимает пиксель за пикселем более темный цвет одного фона из более светлого цвета другого фона.
Используя запятую, мы устанавливаем две позиции фона, каждая из которых соответствует одной копии фонового изображения. Первое изображение мы перемещаемся от центра по оси Х влево на один пиксель и от центра по оси Y вверх на пиксель. Для второй копии фонового изображения мы делаем прямо противоположное, перемещая ее вниз и вправо.
У нас получились два фоновых изображения, которые слегка смещены, но вся картина по-прежнему центрирована в нашем элементе. Теперь, когда режим вычитания обнаруживает разницу между двумя изображениями, видны края на фотографии. Здорово, не так ли?
Для этой конкретной фотографии мы также повысим яркость, которая имеет вторичный эффект относительно повышения контрастности линий.
Вот окончательный фрагмент CSS для этого эффекта:
Эффект школьной доски
Мы можем воссоздать эффект школьной доски, выполнив шаги для эффекта карандашного наброска и исключив функцию invert(1) на заключительном этапе.
Эффект прибора ночного видения
Давайте воссоздадим еще один эффект с помощью возможностей смешивания CSS и сделаем фотографию, выглядящую так, как будто мы сделали ее через объектив прибора ночного видения.
Сначала мы установим фоновое изображение, на этот раз одно.
Теперь добавим градиент и свойство смешивания фоновых слоев. Здесь мы используем радиальный градиент от полупрозрачного лаймового до черного.
Не так уж плохо, можно оставить все так. Но у меня есть еще одна идея, которая может сделать эффект более аутентичным — добавить на фон несколько фальшивых линий развертки с повторяющимся градиентом фона.
И, в итоге, вот полный фрагмент CSS, используемый для этого эффекта:
Больше фотоэффектов
Я сделал галерею из 20 картинок с CSS-эффектами, которые вы можете использовать для своих сайтов.
Поддержка браузера и постепенная деградация
Хорошие новости в том, что свойство background-blend-mode полностью поддерживается в Firefox, Chrome и Opera.
Плохая новость заключается в том, что Internet Explorer и IE Edge вообще не поддерживают свойства смешивания CSS.
Для первого примера мы возьмем наш спектральный фоновый градиент и предусмотрим резервные возможности на случай, если функция background-blend-mode не поддерживается. Мы используем для нашего примера background: gray в качестве резерва, но в этом месте можно использовать любой CSS.
Свойство background-blend-mode
Свойство background-blend-mode — режим смешивания фоновых слоёв — алгоритм, определяющий механизм взаимодействия пикселей каждого слоя. Фон одного элемента может иметь несколько слоёв.
Свойство background-blend-mode делает верхний (активный) слой полупрозрачным, что позволяет показывать сквозь него нижележащие слои. Обязательное условие — фоновых слоёв должно быть минимум два:

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

Если для одного элемента задано больше двух фоновых слоёв, то для него можно задать несколько режимов смешивания, перечислив их через запятую.

Свойство background-blend-mode может применяться к любому html-элементу, не анимируется и не наследуется.
Поддержка браузерами
IE: не поддерживает
Edge: не поддерживает
Firefox: 30.0
Chrome: 35.0
Safari: 7.1 частичная поддержка
Opera: 22.0
iOS Safari: 8.0 частичная поддержка
Opera Mini: не поддерживает
Android Browser: 53.0
Chrome for Android: 54.0
1. Виды режимов смешивания
Для каждого режима используются математические расчёты, которые вычисляются в диапазоне от 0 до 1, где 0 соответствует чёрному цвету, 1 — белому. Все режимы смешивания можно разделить на следующие группы:
Photoshop Layer Sets
Like this article? We recommend
Like this article? We recommend
Like this article? We recommend
I’m a big fan of layers. They make almost any project in Photoshop easier and more flexible, and they also significantly expand the creative possibilities available to you. When I’m working in Photoshop, it’s common end up with a lot of layersimage layers, adjustment layers, type layers, vector shape layers, and so on. I used to think that some of my files were pretty heavy on the layers, especially when I had to scroll up and down in the layers palette to find a particular item. It wasn’t until I began working in the Web design world, however, that I realized just how out of control a layers palette could be.
I remember working on a Web design file in Photoshop 5.5 once, and I couldn’t add any new layers because I had reached the maximum limit of 100 layers allowed by the program. Talk about a confusing stack of layers! Fortunately, Photoshop 6.0 has a great feature called layer sets that lets you organize layers into logical groupings. This makes finding a specific layer very easy, and it goes a long way toward taming the wild and crazy layer stacks that are often a part of complex Web designs. It’s also an essential feature to take advantage of in a production work group, with several people working on the same file.
In addition to layer sets, the kind engineers at Adobe have increased the maximum number of layers to a staggering 8,000! I don’t know about you, but I find the idea of a Web comp with 8,000 layers pretty scary.
With things such as layer styles, layer masks, and layer clipping paths coming into play, a more realistic layer ceiling is probably around 1,000if your system doesn’t start protesting first.
To help illustrate how you can make the most of layer sets, I’ve created a Web design comp for a fictitious conglomerate called The Very BIG Company (see Figure 1).
Figure 1 A sample Web design file for the Really Big Company.
Normally, I recommend naming your layers as you go, but to make a point for this example, I departed from that rule. After pushing pixels for a while, I had the basic design in place and a stack of 30 layers, most with ambiguous names such as shape 4 copy 2. Take a look at the screen grab of the layers palette for the file in Figure 2, and see what a mess it is. I couldn’t even fit all of the layers into a single screen grab!
Figure 2 An out-of-control stack of layers. As we’ll see, using layer sets and proper layer naming will help tame this layers palette.
As you can see, it’s a pretty confusing stack of layers. If you were a production artist and I handed this file to you to build out into a Web page, you’d be muttering about my sloppy work habits behind my back!
Appropriate Naming and Logical Grouping
Before you start to organize with layer sets, there’s a few things you can do to prepare the layers palette. First, it’s important to make sure that every layer has a clear and appropriate name (see Figure 3). Not only will this help you find your way around your own file, but it’s also essential if you will be handing your files off to someone else for the building process. I also like to organize layers in the palette next to each other in logical groupings so that items that are grouped together in the design can be found next to each other in the layers palette (see Figure 4). If possible, I also organize the layer stack so that it reflects the visual hierarchy on the page. Graphic elements that appear at the top of the page, for example, would be found near the top of the layers palette; a nav bar that is just under the top elements would be under those layers in the layers palette. The specific layer interactions for each file will determine how much of this latter technique can be used.
Figure 3 Using clear, descriptive names is the first step in creating order out of a chaotic layers palette.
Figure 4 Arrange your layers together in logical groupings within the layers palette.
After you’ve organized and named all the layers, you should go through and delete any layers that you’re sure you’re not going to use. In the creative crucible of the design process, it’s fairly common for many layers to be created that may not be used in the finished design. Once you’re certain that extra layers will not be used, get rid of them! They’re just taking up space and RAM and making your layers palette more cluttered than it needs to be. If you feel that you need to hang on to some, put them into a layer set labeled Unused StuffSave.
Documentation
Substance 3D Painter
Substance 3D Painter
Applications
Plugins & Integrations
Content Platforms
Pipeline Support
Local Search
Sections
Blending modes
Layers and effects have access to many Blending Modes. They allow to mix the result of a layer with the other layers below in different manners. Not all the Blending Modes are suited for all use cases. For example the Normal map Blending Modes are only useful for the Normal channel in a Texture Set.
Blending Mode Order
To understand how and when a Blending Mode is applied, it is important to understand the order in which operations are performed in the Layer Stack:
Changing The Blending Mode
The Blending Mode can be changed for each channel in a layer. To switch between the channels use the top-left dropdown available in the layer stack window.
To change the blending mode simply click on the Blending Mode dropdown on a specific layer:
It is possible to quickly switch between Blending Modes with the following shortcuts if the dropdown has the focus:
List of Blending Modes
Below is the list of all the Blending Modes available in Substance 3D Painter layers and effects. Most Blending Modes work via operations in RGB (or in Grayscale) but some operations are also performed via a different mode which is HSV (Hue, Saturation, Value). All Blending Modes are performed in Linear Gamma space internally.
Normal
Displays the Top layer over the Bottom layer without transformation (copy mode). If the Top layer has transparency (alpha) it will display the Bottom layer through the transparent pixels.
Passthrough
Flattens the Bottom layer into the Top layer. Mostly useful in the following cases :
Disable
Discards the blending of the layer, displaying only the previous layers. It can be used to optimize the computation of a channel by ignoring it in the Top layer.
Replace
Overwrites the Bottom layer. This is useful for example to avoid blending information with the layers below. Replace works differently from the Normal blending because it will also ignore the alpha present in the Top layer, which could result is Transparent pixels.
Multiply
Multiplies the Top layer over the Bottom layer. The result will always be a darker color.
Divide
Divides the layers below by the color information of the current layer. The result image is most of the time lighter and sometimes can look burned out.
Inverse Divide
Identical to the Divide blending mode but the Top and Bottom layer are exchanged in the blending operation.
Darken (Min)
Keeps the minimum color value between the Top layer and the Bottom layer.
Lighten (Max)
Keeps the maximum color value between the Top layer and the Bottom layer.

Linear Dodge (Add)
Adds the Top layer color value to the Bottom layer. The result can give colors that are below 0 or higher than 1, in which case the result will be clamped/clipped if the channel is not HDR. This Blending Mode is useful to accumulate height information for example.
Subtract
Subtracts the Top layer Color from the Bottom layer. The result can give colors that are below 0, in which case the result will be clamped/clipped if the channel is not HDR.
Inverse Subtract
Identical to the Subtract Blending Mode but the Top and Bottom layer are exchanged in the blending operation.
Difference
Subtracts the Top layer Color from the Bottom Layer, but take the absolute value of the result (negative values will become positive).
Exclusion
Similar to the Difference blending mode but it will produce a result with a lower contrast.
Signed Addition (AddSub)
Both Adds and Subtracts Color information from the Bottom layer based on the Top layer colors. Grayscale values have no effect, while darker colors will subtract information and lighter colors will add information.
Overlay
Combine both the Screen and Multiply Blending Modes. Grayscale values in the Top layer will have no effect, but dark colors will Multiply colors while bright colors will lighten the colors.
Screen
Color information from the Top and Bottom layer are inverted then multiplied against each other, this result is then inverted again. This produce a visual result that is the opposite of the Multiply blending mode and gives a brighter image.
Linear Burn
Adds the Top and Bottom layer Color information together and then subtract 1 from the result.
Color Burn
Divides the Bottom layer by the Top layer. The Bottom layer is inverted before the operation is performed. This blending operation darkens the Top layer and increase its contrast to show the colors of the Bottom layer. The darker the Bottom layer is, the more of its color is used.
Color Dodge
Divides the Bottom Layer by the inverted Top layer. This operation lightens the Bottom layer depending on the value of the Top layer. The brighter the Top layer is, the more its colors affect the Bottom layer.
Soft Light
Similar to the Overlay Blending Mode, but applied with a different curve to blend the Color information which result in a less contrasted image.
Hard Light
Vivid Light
Combines Color Dodge and Color Burn blending modes. Dodging is applied to colors that are lighter than gray and burning is applied to colors that are darker than gray. Gray values are unaffected. The result is a more contrasted image.
Linear Light
Combines Linear Dodge and Linear Burn. Dodging is applied to colors that are lighter than gray and burning is applied to colors that are darker than gray. Gray values are unaffected. The result is similar to Vivid Light but with less contrast.
Pin Light
Lightens and darkens color information based on the Top layer colors. If the dark colors on the Top layer are darker than the colors on the Bottom layer they will be visible, if they aren’t they will drop away. Same principle applies for bright colors. This blend mode can result in patches or blotches (large noise), and it completely removes all mid-tones.
Performs the operation with the HSV model. Keeps only the Hue of the Top Layer and uses the Saturation and Value of the Bottom Layer. Black and very dark colors don’t have any Hue, therefore colors of the Bottom layer will remain unchanged.
Saturation
Performs the operation with the HSV model. Keeps only the Saturation of the Top Layer and uses the Hue and Value of the Bottom Layer. Black and very dark colors are desaturated, therefore colors of the Bottom layer will become grayscale values.
Color
Performs the operation with the HSV model. Keeps only the Hue and Saturation of the Top Layer and uses the Value of the Bottom Layer. Black and very dark colors don’t have any Hue and are desaturated, therefore colors of the Bottom layer will become grayscale values.
Value
Performs the operation with the HSV model. Keeps only the Value of the Top Layer and uses the Hue and Saturation of the Bottom Layer.
Normal Map Combine
Whiteout Blending operation. Preserve details while making sure flat normals still operate properly.
See Normal Map Painting for more information.
Normal Map Detail
Detail Oriented Blending operation (Reoriented Normal Mapping), more precise than Normal Map Combine. Preserve flat normal maps and the intensity of the two sources. To ensure that result the Top layer normal is reoriented to follow the surface of the bottom layer.
See Normal Map Painting for more information.
Normal Map Inverse Detail
Same behavior as for the Normal Map Detail blending operation, however it is the Bottom layer that is transformed to fit the surface of the Top layer.
See Normal Map Painting for more information.





































