Skip to content

Instantly share code, notes, and snippets.

@leonadler
Last active June 9, 2022 17:02
Show Gist options
  • Save leonadler/19e6876f1c5e572532fa9c70f288a92c to your computer and use it in GitHub Desktop.
Save leonadler/19e6876f1c5e572532fa9c70f288a92c to your computer and use it in GitHub Desktop.
Helper to test how the browser blends overlayed semi-transparent colors
/**
* 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) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment