How to do math with colors like SASS, but in Ruby?

In SASS, I can do:

!pink = #ff43a7
!darker_pink = !pink - #333333

I would like to do the same in Ruby.

+3
source share
5 answers

Hex can be represented in Ruby, a prefix value 0x:

pink = 0xff43a7
darker_pink = pink - 0x333333

color assistant

def color(hex)
  "#%06x" % hex
end

Usage in an ERb Template

.container {
  color: <%= color pink %>;
  border: 1px solid <%= color darker_pink %>;
}

Output

.container {
  color: #ff43a7;
  border: 1px solid #cc1074;
}
+4
source

The basic approach to adding / subtracting colors in Sass is nonsense and really only works when using the gray setting. Therefore, in Sass 3, we now fully support operations in the HSL domain, which is closely related to how people think about colors.

Since Sass is written in Ruby, you can at least read our code to see what happens.

Color class , .

. Sass?

+2

Sass

Sass, .

:

red  = Sass::Script::Color.new([255, 0, 0])
gray = Sass::Script::Color.new([128, 128, 128])
red.lightness < gray.lightness # => true

#00FF00 Color, , :

# @param color_string - hex string, like '#22FF22'. MUST be 6 characters,
# because I don't feel like dealing with the use-case for 3. :)
def color_from_hex_string(color_string)
  # Drop the leading '#', if any
  color_string = color_string[1..-1] if color_string.start_with?('#')
  raise ArgumentError.new('Hex string must be 6 characters') unless color_string.length == 6

  # Turn into array of 2-digit decimal numbers. 
  # Eg, '808080' becomes [128, 128, 128]; '#ff0000' becomes [255, 0, 0]
  rgb_array = color_string.split('').each_slice(2).map do |slice|
    slice.join('').to_i(16).to_s(10)
  end

  # Use that to build a new Color object
  color = Sass::Script::Color.new(rgb_array)

  # Set this option so it won't complain (?)
  color.options = {:style => :compressed}

  return color
end
+2

@macek, @drawnownward @lpsquiggle:

, :

  def color(color)
    "#%06x" % color
  end

  def darker_color(color)
    x = color.match(/0x(..)(..)(..)/)
    r = x[1].sub(/[0-3]/, '5')
    g = x[2].sub(/[0-3]/, '5')
    b = x[3].sub(/[0-3]/, '5')
    rgb = "0x#{r}#{g}#{b}"
    "#%06x" % (rgb.hex - 0x444444)
  end

: ( 0 3, ), , 0 , , c, d, e f ( , ). #rrggbb, # 313131 # 0d0d0d, , , #fdfdfd, , .

Erb :

.container {
  color: <%= color pink %>;
  border: 1px solid <%= darker_color pink %>;
}

:

.container {
  color: <%= color pink %>;
  border: 1px solid <%= color darker_pink %>;
}

, -.

0

I just stumbled on where I wanted to hand out colors for a set in different shades. The SASS source did not help much because I did not see a way to get RGB from HSV.

colored stone had what I needed.

I wrote this helper:

def region_color(index, size)
  h = (index.to_f / (size - 1).to_f)
  Color::HSL.from_fraction(h, 0.95, 0.3).html
end
0
source

Source: https://habr.com/ru/post/1742845/


All Articles