How to prevent the alpha-values to add together on html canvas

47 views Asked by At

If I set globalAlpha=0.5 and draw two rectangles that overlap, the overlapping area will be totally opaque:

image of two overlapping rectangles

Is there any way to prevent this behaviour? I just want everything to have an alpha value of 0.5. So the overlapping area should be of the same color and transparency as the rest.

I already tried to play around with globalCompositeOperation but it did not solve my problem.

Here is an live example: https://codesandbox.io/p/sandbox/alpha-adding-jylhmr

In short here is the needed code:

<!DOCTYPE html>
<html>
  <body onload="start()">
    <canvas style="border: 1pt solid black" id="canvas" width="300" height="300"></canvas>
    <script>
      let ctx = document.getElementById("canvas").getContext("2d");
      ctx.fillStyle = "red";
      ctx.gobalAlpha = 0.5;
      ctx.fillRect(0,0,200,200);
      ctx.fillRect(100,100,200,200);
    </script>
   </body>
</html>

It‘s not an option to fill both rectangles simultaniously because the rects will be filled by user interaction („click“).

0

There are 0 answers