Skip to content

Instantly share code, notes, and snippets.

@ordnungswidrig
Created February 2, 2017 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ordnungswidrig/a477a04f3cdfc213aa789d8e672a3012 to your computer and use it in GitHub Desktop.
Save ordnungswidrig/a477a04f3cdfc213aa789d8e672a3012 to your computer and use it in GitHub Desktop.
Mutliple color overlay functions rendered with reagent in kilpse
;; color definitions in css rgba format
(def base-color [60 151 35 1])
(def overlays [[255 255 255 .23]
[255 255 255 .61]
[255 255 255 1]])
(require '[clojure.string :as s]
'[reagent.core :as reagent])
(defn color-swatch [[r g b a]]
[:div {:style {:width "120px" :height "120px"
:background-color (str "rgba(" (s/join "," [r g b a])")")
:border "1px solid #888"
:display :flex
:flex-direction :column
:justify-content :center
}}
[:div {:style {:text-align :center :color "#333"}} (pr-str [r g b a])]
[:div {:style {:text-align :center :color "#ccc"}} (pr-str [r g b a])]])
(defn mix-weighted-average [[r1 g1 b1 a1] [r2 g2 b2 a2]]
(let [w (+ a1 a2)]
[(int (/ (+ (* r1 a1) (* r2 a2)) w))
(int (/ (+ (* g1 a1) (* g2 a2)) w))
(int (/ (+ (* b1 a1) (* b2 a2)) w))
1]))
(defn mix-max
"Blends the two colors by taking the max value of each
rgb channel adjusted by alpha"
[[r1 g1 b1 a1] [r2 g2 b2 a2]]
(let [w (+ a1 a2)]
[(int (max (* r1 a1) (* r2 a2)))
(int (max (* g1 a1) (* g2 a2)))
(int (max (* b1 a1) (* b2 a2)))
1]))
(defn mix-min
"Blends the two colors by taking the min value of each
rgb channel adjusted by alpha"
[[r1 g1 b1 a1] [r2 g2 b2 a2]]
(let [w (+ a1 a2)]
[(int (min (* r1 a1) (* r2 a2)))
(int (min (* g1 a1) (* g2 a2)))
(int (min (* b1 a1) (* b2 a2)))
1]))
(defn mix-blend
"Blends the two colors as described in http://stackoverflow.com/questions/746899/how-to-calculate-an-rgb-colour-by-specifying-an-alpha-blending-amount#746937.
Basically it's c = alpha2 * value2 + (1 - alpha2) * value1"
[[r1 g1 b1 a1] [r2 g2 b2 a2]]
(let [a' (- 1 a2)]
[(int (+ (* r1 a') (* r2 a2)))
(int (+ (* g1 a') (* g2 a2)))
(int (+ (* b1 a') (* b2 a2)))
a1]))
(defn root [base overlays]
[:div
[:h1 "Color mix overlay calculation"]
(for [f [#'mix-blend #'mix-weighted-average #'mix-max #'mix-min ]]
[:div
[:h2 (str f)]
(into [:div {:style {:display :flex :flex-direction :row}}
[color-swatch base]]
(map (fn [o] [color-swatch (f base o)])
overlays))])])
(reagent/render [root base-color overlays]
(js/document.getElementById "klipse-container"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment