Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

css - How to calculate required hue-rotate to generate specific colour?

I have a white image that I am using as a background for a div, and I would like to colour to match the themes main colour. I am aware I can do:

filter: sepia() saturate(10000%) hue-rotate(30deg);

and cycle through hue-rotate to find a colour, but is it possible to calculate this value in advance? Given that the specified hex value is quite dark, I imagine I will need to include the invert(%) filter as well.

Given a hex value of #689d94 what math do I need to do to calculate the desired hue-rotate and invert value to convert my white background image into the same colour?

Edit

Here's a snippet of a div with a white background image being filtered green. The trick here, is it is the whole of the div that is being filtered, not just the image. If I was to enter some text into the div the text colour would turn green as well.

div {
  background:url(http://richard.parnaby-king.co.uk/basket.svg) no-repeat scroll 0 0 transparent;
  background-size:5em;
  width:5em;
  height:5em;
  -webkit-filter: invert(25%) sepia() saturate(100000%) hue-rotate(174deg);
  filter: invert(25%) sepia() saturate(100000%) hue-rotate(174deg);
}
<div>
  </div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The key in this case is to define an initial color. White nor black or any gray-scale is technically an actual color - you can't saturate or rotate it. You'll have to "colorize" it somehow, and the sepia filter is the only filter which do some form of colorizing.

It would be easier if your image was pure 100% red. Then you could just add the target degree directly and adjust saturation and lightness using HSL for target. For a white color start point the first step is to convert and define an intermediate color so we can saturate and rotate it later on.

Lets first darken the white image and apply sepia to get a "base" color we can work with:

filter: brightness(50%) sepia(1);

This will produce RGB color value of approximately:

rgb(178, 160, 128)

Step two is to convert that to HSL color-space which gives us:

hsl(38, 24.5%, 60%);

Base color result

div {
  background:url(http://richard.parnaby-king.co.uk/basket.svg) no-repeat;
  background-size:5em;
  width:5em;
  height:5em;
  -webkit-filter: brightness(50%) sepia(1);
  filter: brightness(50%) sepia(1);
}
<div></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...