Created
January 9, 2015 17:56
-
-
Save st44100/e97b226f504b75eba087 to your computer and use it in GitHub Desktop.
Angular.js Shade and Tint color converter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##* | |
# UAGE: | |
# app = angular.module('yourApp', []) | |
# app.factory(require('./shadeAndTintColor')) | |
# app.controller('yourCtrl', ['ShadeAndTintColor', (Color) | |
# -> | |
# Color.shade('#f9ea62', 0.1) # '#E0D258' | |
# Color.tint('#f9ea62', 0.39) # '#FBF29F' | |
# ]) | |
# | |
module.exports = 'ShadeAndTintColor', : [ | |
( | |
) -> | |
##* | |
# @param {string} hex cf. '#F12345' | |
# @return {Array} [R, G, B] | |
toRgb = (hex = null) -> | |
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) | |
if result | |
[ | |
parseInt(result[1], 16) | |
parseInt(result[2], 16) | |
parseInt(result[3], 16) | |
] | |
else | |
null | |
toHex = (src = [0, 0, 0]) -> | |
to = (n) -> | |
n = parseInt(n, 10) | |
return "00" if isNaN(n) | |
n = Math.max(0, Math.min(n, 255)) | |
"0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16) | |
return "##{[to(src[0]), to(src[1]), to(src[2])].join('')}" | |
##* | |
# @param {Array} src Mix src [R, G, B] | |
# @param {Array} target Mix target [R,G,B] | |
# @param {float} m Amount of mix 0 ~ 1.0 | |
# @return {Array} [R, G, B] | |
mix = (src, target, m) -> | |
[ | |
Math.floor(target[0] + (src - target[0]) * m) | |
Math.floor(target[1] + (src - target[1]) * m) | |
Math.floor(target[2] + (src - target[2]) * m) | |
] | |
##* | |
# @param {string} target Mix target HEX | |
# @param {float} m Amount of mix 0 ~ 1.0 | |
# @return {Array} [R, G, B] | |
shade = (target, m) -> mix(0, toRgb(target), m) | |
##* | |
# @param {string} target Mix target HEX | |
# @param {float} m Amount of mix 0 ~ 1.0 | |
# @return {Array} [R, G, B] | |
tint = (target, m) -> mix(255, toRgb(target), m) | |
return { | |
toRgb: toRgb | |
toHex: toHex | |
mix: mix | |
shade: shade | |
tint: tint | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment