From 37c3635a46c14f5f4cc217249f59a2af47fd9c4d Mon Sep 17 00:00:00 2001 From: Deimos Date: Thu, 25 Jul 2019 21:27:16 -0600 Subject: [PATCH] SCSS: Add function for "perceived brightness" Previously I've been using the built-in SASS lightness function, but that doesn't necessarily always line up with how light we perceive a color to be. This function seems to do a better job of matching up with the "expected" result for a color. --- tildes/scss/_functions.scss | 39 +++++++++++++++++++++++++++++++++++++ tildes/scss/styles.scss | 1 + 2 files changed, 40 insertions(+) create mode 100644 tildes/scss/_functions.scss diff --git a/tildes/scss/_functions.scss b/tildes/scss/_functions.scss new file mode 100644 index 0000000..483cb9c --- /dev/null +++ b/tildes/scss/_functions.scss @@ -0,0 +1,39 @@ +// Copyright (c) 2019 Tildes contributors +// SPDX-License-Identifier: AGPL-3.0-or-later + +@function sqrt($r) { + // Adapted from https://www.antimath.info/css/sass-sqrt-function/ + // stylelint-disable scss/dollar-variable-pattern + $x0: 1; + $x1: $x0; + + @for $i from 1 through 10 { + $x1: $x0 - ($x0 * $x0 - abs($r)) / (2 * $x0); + $x0: $x1; + } + + @return $x1; +} + +@function perceived-brightness($color) { + // Adapted from https://gist.github.com/jlong/f06f5843104ee10006fe + // Perceived Brightness math based on: http://alienryderflex.com/hsp.html + $red-magic-number: 299; + $green-magic-number: 587; + $blue-magic-number: 114; + $brightness-divisor: $red-magic-number + $green-magic-number + $blue-magic-number; + + // Extract color components + $red-component: red($color); + $green-component: green($color); + $blue-component: blue($color); + + // Calculate a brightness value in 3d color space between 0 and 255 + $red: $red-component * $red-component * $red-magic-number; + $green: $green-component * $green-component * $green-magic-number; + $blue: $blue-component * $blue-component * $blue-magic-number; + $number: sqrt(($red + $green + $blue) / $brightness-divisor); + + // Convert to percentage and return + @return 100% * $number / 255; +} diff --git a/tildes/scss/styles.scss b/tildes/scss/styles.scss index d8fdeca..6b71c24 100644 --- a/tildes/scss/styles.scss +++ b/tildes/scss/styles.scss @@ -1,4 +1,5 @@ // stylelint-disable at-rule-empty-line-before +@import "functions"; @import "variables"; @import "spectre-0.5.1/variables";