Skip to content

Instantly share code, notes, and snippets.

@leonadler
Last active June 9, 2022 17:02
Show Gist options
  • Select an option

  • Save leonadler/19e6876f1c5e572532fa9c70f288a92c to your computer and use it in GitHub Desktop.

Select an option

Save leonadler/19e6876f1c5e572532fa9c70f288a92c to your computer and use it in GitHub Desktop.

Revisions

  1. leonadler revised this gist Jun 9, 2022. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions overlayColors.js
    Original file line number Diff line number Diff line change
    @@ -5,10 +5,10 @@
    * blendColors('255 0 0 / 20%', '60 60 40 / 30%', '128 96 44 / 60%')
    * // -> {r: 128, g: 84, b: 40, a: 0.7764705882352941}
    */
    function overlayColors(...colors){
    function overlayColors(...colors) {
    let canvas;
    if (typeof OffscreenCanvas === 'function') {
    canvas = = new OffscreenCanvas(1, 1);
    canvas = new OffscreenCanvas(1, 1);
    } else {
    canvas = document.createElement('canvas');
    canvas.width = canvas.height = 1;
  2. leonadler revised this gist Jun 9, 2022. No changes.
  3. leonadler created this gist Jun 9, 2022.
    25 changes: 25 additions & 0 deletions overlayColors.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    /**
    * Helper to test how alpha-transparent colors are layered in the browser.
    *
    * @example
    * blendColors('255 0 0 / 20%', '60 60 40 / 30%', '128 96 44 / 60%')
    * // -> {r: 128, g: 84, b: 40, a: 0.7764705882352941}
    */
    function overlayColors(...colors){
    let canvas;
    if (typeof OffscreenCanvas === 'function') {
    canvas = = new OffscreenCanvas(1, 1);
    } else {
    canvas = document.createElement('canvas');
    canvas.width = canvas.height = 1;
    }
    const ctx = canvas.getContext('2d');
    colors.forEach(col => {
    ctx.fillStyle = `rgb(${col})`;
    ctx.rect(0, 0, 1, 1)
    ctx.fill();
    });

    const [r,g,b,a] = ctx.getImageData(0,0,1,1).data;
    return {r, g, b, a: (a / 255) }
    }