R/get-alpha.R

#' Get color's transparency
#'
#' Get the transparency of a color vector.
#'
#' @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.
#'
#' @return Returns the alpha value of a color vector, from 0-1.
#' @export
#' @examples
#' get_alpha("red")
#' get_alpha("#808080A0")
#' get_alpha("{ h: 0.5, s: 0.5, v: 0.5 }")
get_alpha <- function(x, na.rm = FALSE) {
  if(na.rm) x <- x[! is.na(x)]
  if(all(is.na(x))) return(NA_real_)
  cmd <- ifelse(is_js_object(x),
                paste0("tinycolor(", x, ").getAlpha()"),
                paste0("tinycolor(\"", x, "\").getAlpha()"))
  out <- as.numeric(ifelse(is_valid_color(x), v8_eval(cmd), NA))
  return(out)
}
houyunhuang/tinycolor documentation built on June 6, 2019, 7:43 p.m.