0

I'm using an HTML canvas to draw shapes on, and I want to know the exact blending/compositing methods that is used for this. I created a test environment and I already got some weird values out of it:

function Color(r, g, b, a) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.a = a;
}

const canvas = document.getElementById('canvas');

const context = canvas.getContext('2d');

const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const color1 = new Color(60, 50, 40, 0.25);
const color2 = new Color(24, 10, 16, 0.75);

const getData = () => context.getImageData(0, 0, canvasWidth, canvasHeight).data;

function fill(color) {
    const { r, g, b, a } = color;
    context.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
    context.fillRect(0, 0, canvasWidth, canvasHeight);
}

const clear = () => context.clearRect(0, 0, canvasWidth, canvasHeight);

fill(color1);

const data1 = getData(); // (60, 52, 40, 64)

clear();

fill(color2);

const data2 = getData(); // (24, 9, 16, 191)

clear();

fill(color1);
fill(color2);

const data3 = getData(); // (27, 12, 18, 207)

First of all, it seems like filling the canvas with a color doesn't work properly, because some RGB values are off by a few. Also, I tried to find the blending function and found this article: https://drafts.fxtf.org/compositing-1/#blending. This doesn't seem to be working, because I would expect data3 to be (33, 22, 20, 207), but again, this is off. What is going on? I'm using VS Code and test using Google Chrome.

Edit: I did the calculation wrong and forgot to divide by a0. The expected value of data3 is still off though, I expect it to be (26.76923076923077, 13.076923076923077, 17.846153846153847, 207.1875). It is closer to the actual color, but still weird that it's off. I guess the main question now is, why are data1 and data2 off?

Alex Janse
  • 43
  • 6
  • If both colors are (semi-)transparent, the white from the clear canvas also "shines through". if you set color 1 to transparency 1, the results are closer to your desired values. – niorad Oct 26 '22 at 09:30

0 Answers0