How to have multiple globalCompositeOperation

  canvas, html, javascript

My canvas is 512×256 pixels

Here is what I am trying to achieve :

  • Print a local image (image 1) on the canvas.
  • Fill this image with a specific color.
  • Print another local image(image 2) that should not overlap image 1.

So what I did is :

  • .drawImage(image1)
  • Create a rectangle of 512×256 ( ctx.rect(0, 0, 512, 256); )
  • ctx.globalCompositeOperation = "destination-in";
  • draw this rectangle ( ctx.fill() ) (with destination-in it should have for effect to fill the first image with the color of the rectangle)
  • ctx.globalCompositeOperation = "destination-out";
  • .drawImage(image2) (with destination-out it should make this image under the image 1)

But it doesn’t display anything.
I figured it was because we can’t have different globalCompositeOperation… But I’m sure it’s possible somehow, I found people talking about it and fixing the issue but they’re using specific code for their specific task and I simply don’t understand. I would love an example for my script :

    <script>
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var img1 = new Image();
    img1.onload = function () {
        ctx.drawImage(img1, 0, 0);
    };
    ctx.globalCompositeOperation = "destination-in";
    ctx.rect(0, 0, 512, 256);
    ctx.fillStyle = "green";
    ctx.fill()
    ctx.globalCompositeOperation = "destination-out";
    img2.onload = function () {
        ctx.drawImage(img2, 0, 0);
    };
    img1.src = "C:/Users/... file1.png" // replaced the path for this example
    img2.src = "C:/Users/... file2.png";
</script>

And here is my html body :

<body>    
<canvas id="canvas" width="512" height="256"></canvas>
</body>

Source: Ask Javascript Questions

LEAVE A COMMENT