Home > Software engineering >  transparent circle on opaque canvas
transparent circle on opaque canvas

Time:12-28

I'm trying to draw a transparent circle on the HTML Canvas. Here is the code:


    const canvas = document.querySelector('#canvas');
    let ctx = canvas.getContext('2d');
    
    
    canvas.width = 700;
    canvas.height = 700;
    ctx.beginPath();
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.globalCompositeOperation = 'destination-out';
    ctx.clearRect(50, 50, 200, 200);
    ctx.beginPath();
    ctx.fillRect(50, 50, 200, 200);
    ctx.moveTo(350, 150);
    ctx.beginPath();
    ctx.arc(350, 150, 80, 0, 2 * Math.PI, false);
    ctx.closePath();
    ctx.fill();

I was able to make the rectangle transparent with globalCompositeOperation set to destination-out but it failed to make the circle fully transparent. Here is what MDN says about destination-out operation,

The existing content is kept where it doesn't overlap the new shape.

The circle has still some opaque color applied to it. How to make it fully transparent? Here is the live demo.

Unable to understand what's wrong with the code. Any help would be appreciated.

CodePudding user response:

You are using too many beginpath methods, but this isn't the issue.

The fully transparent rectangle is created by the clearRect and not by the fillRect method.

So you should set fillStyle to white and then the code works.

const canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');

canvas.width = 700;
canvas.height = 700;
  ctx.beginPath();
    ctx.fillStyle = 'rgba(0, 0, 0, .5)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'rgba(255, 255, 255, 1)';
    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillRect(50, 50, 200, 200);
    ctx.moveTo(350, 150);
    ctx.arc(350, 150, 80, 0, 2 * Math.PI, false);
    ctx.fill();
  ctx.closePath();
body {
  background-color: skyblue;
    position: relative;
}

img, #canvas {
    position: absolute;
}
<body>
    <img src="https://images.unsplash.com/photo-1635315850978-44cd0b237006?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1770&q=80" alt="">
  <canvas id="canvas"></canvas>
</body>

  • Related