Search code examples
javascripthtml5-canvas

transparent circle on opaque canvas


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.


Solution

  • You are using beginpath methods but the directives you use aren't paths.

    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 = 600;
    canvas.height = 400;
        ctx.fillStyle = 'rgba(0, 0, 0, .5)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.globalCompositeOperation = 'destination-out';
        ctx.fillStyle = 'rgba(255, 255, 255, 1)';
        ctx.fillRect(25, 25, 150, 150);
        ctx.arc(275, 100, 60, 0, 2 * Math.PI, false);
        ctx.fill();
    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="" width=600 height=390>
      <canvas id="canvas"></canvas>
    </body>