Skip to content

Instantly share code, notes, and snippets.

@anonomis
Last active January 2, 2016 00:19
Show Gist options
  • Select an option

  • Save anonomis/8222381 to your computer and use it in GitHub Desktop.

Select an option

Save anonomis/8222381 to your computer and use it in GitHub Desktop.
Invert colors
$.parseColor = (color) ->
cache = undefined
p = parseInt # Use p as a byte saving reference to parseInt
color = color.replace(/\s\s*/g, "") # Remove all spaces
#var
# Checks for 6 digit hex and converts string to integer
if cache = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/.exec(color)
cache = [p(cache[1], 16), p(cache[2], 16), p(cache[3], 16)]
# Checks for 3 digit hex and converts string to integer
else if cache = /^#([\da-fA-F])([\da-fA-F])([\da-fA-F])/.exec(color)
cache = [p(cache[1], 16) * 17, p(cache[2], 16) * 17, p(cache[3], 16) * 17]
# Checks for rgba and converts string to
# integer/float using unary + operator to save bytes
else if cache = /^rgba\(([\d]+),([\d]+),([\d]+),([\d]+|[\d]*.[\d]+)\)/.exec(color)
cache = [+cache[1], +cache[2], +cache[3], +cache[4]]
# Checks for rgb and converts string to
# integer/float using unary + operator to save bytes
else if cache = /^rgb\(([\d]+),([\d]+),([\d]+)\)/.exec(color)
cache = [+cache[1], +cache[2], +cache[3]]
# Otherwise throw an exception to make debugging easier
else
throw Error(color + " is not supported by $.parseColor")
# Performs RGBA conversion by default
isNaN(cache[3]) and (cache[3] = 1)
# Adds or removes 4th value based on rgba support
# Support is flipped twice to prevent erros if
# it's not defined
cache.slice 0, 3 + !!$.support.rgba
sanityCheck = (str) ->
if str? and
str.length > 0 and
str isnt "transparent" and
str isnt "inherit" and
str isnt "initial" and
str isnt "rgba(0, 0, 0, 0)"
return true
else
return false
soften = (col) ->
sum = 0
min = 0
max = 0
med = 0
coldiff = []
for i, c of col
sum += c
min = c if c < min
max = c if c > max
med += c/3
soft = []
for i, c of col
if sum < 384
#soft.push 128
soft.push (128 - med/2) + (c - med)/2
else
soft.push 10
return soft
toCss = (col) ->
"rgba(#{col[0]},#{col[1]},#{col[2]},1.0)"
cmdPush = (e, prop, cmds) ->
bg = $(e).css prop
if sanityCheck bg
parsed = $.parseColor bg
cmds.push
prop: prop
col: (toCss soften parsed)
elem: e
cmds = []
for e in $("*")
cmdPush e, "background-color", cmds
cmdPush e, "color", cmds
for cmd in cmds
$(cmd.elem).css cmd.prop, cmd.col
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment