UtilAdded in v15Optional

resolveCssColor

Resolves a CSS colour, such as a var() or light-dark(), to a value a canvas can paint with.

Usage

Call it in the browser, from afterNextRender, with the element you draw on, the expression and a fallback.

import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
import { resolveCssColor } from 'ngwr/utils';

@Component({
  selector: 'app-swatch',
  template: '<canvas #canvas width="240" height="48"></canvas>',
})
export class Swatch {
  private readonly canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas');

  constructor() {
    afterNextRender(() => {
      const canvas = this.canvas().nativeElement;
      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      ctx.fillStyle = resolveCssColor(canvas, 'var(--wr-color-primary)', '#3969e2');
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    });
  }
}
resolveCssColor(canvas, '#3969e2', '#000');
// 'rgb(57, 105, 226)'

resolveCssColor(canvas, 'light-dark(#ffffff, #0b1120)', '#fff');
// whichever side is in effect on the canvas

resolveCssColor(canvas, 'color-mix(in srgb, var(--wr-color-primary) 20%, transparent)', '#0000');
// 'color(srgb … / 0.2)'

resolveCssColor(canvas, 'var(--not-set-anywhere)', '#0f172a');
// '#0f172a' — the fallback

Redraw on a scheme switch

A resolved colour is a snapshot. watchColorScheme() calls back when the page's colour scheme changes, so a still canvas can draw again.

import { afterNextRender } from '@angular/core';
import { resolveCssColor, watchColorScheme } from 'ngwr/utils';

constructor() {
  afterNextRender(() => this.draw());
  // A canvas keeps the pixels it was given: draw again when the scheme switches.
  watchColorScheme(() => this.draw());
}

API

NameDescriptionTypeDefault
resolveCssColor(context, expression, fallback)Resolves expression against context to rgb(), rgba() or, for a mix, color(srgb …). Returns fallback when it does not parse or names a custom property that is not set.(context: Element, expression: string, fallback: string) => string—
watchColorScheme(callback, options?)Calls callback when the scheme <html> resolves to changes: WrTheme's inline color-scheme, a class or attribute on <html>, or the OS preference under light dark. Stops on destroy; returns a stop function. Does nothing on the server.(callback: (scheme: WrColorScheme) => void, options?: { injector?: Injector }) => () => void—

See also