#' Create a tinycolor.
#'
#' Create a vector of valid colors from Hex, 8-bit Hex, Rgb, Rgba, Hsl, Hsla, Hsv, Hsva, and so on.
#'
#' @param x a any type color string or a javascript color object specifying.
#' @param na.rm a logical value indicating whether NA values should be stripped before the computation proceeds.
#'
#' @details
#' The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value).
#' Hsl and Hsv both require either 0%-100% or 0-1 for the S/L/V properties. The H (Hue) can have values between 0%-100% or 0-360.
#' Rgb input requires either 0-255 or 0%-100%.
#'
#' @return a valid color string.
#' @export
#' @examples
#' # Hex colors
#' tinycolor("000") # "#000000"
#' tinycolor("#000") # "#000000"
#' tinycolor("f0f0f6") # "#F0F0F6"
#' tinycolor("#f0f0f6") # "#F0F0F6"
#' tinycolor("#f0f0f688") # "RGBA(240, 240, 246, 0.53)"
#' # Rgb colors
#' tinycolor("rgb (255, 0, 0)") # "RGB(255, 0, 0)"
#' tinycolor("rgb 255 0 0") # "RGB(255, 0, 0)"
#' tinycolor("rgba (255, 0, 0, 0.5)") # "RGBA(255, 0, 0, 0.5)"
#' tinycolor("{ r: 255, g: 0, b: 0 }") # "RGB(255, 0, 0)"
#' # Hsl colors
#' tinycolor("hsl(0, 100%, 50%)") # "HSL(0, 100%, 50%)"
#' tinycolor("hsla(0, 100%, 50%, 0.5)") # "HSLA(0, 100%, 50%, 0.5)"
#' tinycolor("{ h: 0, s: 1, l: 0.5 }") # "HSL(0, 100%, 50%)"
#' # Hsv colors
#' tinycolor("hsv(0, 100%, 100%)") # "HSV(0, 100%, 100%)"
#' tinycolor("hsva(0, 100%, 100%, 0.5)") # "HSVA(0, 100%, 100%, 0.5)"
#' tinycolor("{ h: 0, s: 100, v: 100 }") # "HSV(0, 100%, 100%)"
#' # Name colors
#' tinycolor("RED") # "#FF0000"
#' tinycolor("blanchedalmond") # "#FFEBCD"
#' tinycolor("darkblue") # "#00008B"
#' # From ratio
#' from_ratio("{r: 1, g: 0, b: 0 }") # "RGB(100%, 0%, 0%)"
#' from_ratio("{ h: 1, s: 0, l: 0 }") # "HSL(0, 0%, 0%)"
#' from_ratio("{ h: 0.5, s: 0.5, v: 0.5 }") # "HSV(180, 50%, 50%)"
tinycolor <- function(x, na.rm = FALSE) {
if(na.rm) x <- x[! is.na(x)]
cmd <- ifelse(is_js_object(x),
paste0("tinycolor", "(", x, ")"),
paste0("tinycolor", "(\"", x, "\")"))
out <- v8_eval(cmd)
return(out)
}
#' @rdname tinycolor
#' @export
from_ratio <- function(x, hex = FALSE, na.rm = FALSE) {
if(all(is.na(x))) return(NA_character_)
if(!all(is_js_object(x[!is.na(x)])))
stop("`x` is not a ratio color object.", call. = FALSE)
if(na.rm) x <- x[!is.na(x)]
cmd <- ifelse(!is.na(x), paste0("tinycolor.fromRatio", "(", x, ")"), NA)
if(hex) cmd <- ifelse(!is.na(cmd), paste0(cmd, ".toHexString()"), NA)
out <- v8_eval(cmd)
return(out)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.