html5-canvasglobalcompositeoperation

Canvas globalCompositeOperation source-in and destination-in not working with multiple source and destination


HTML5 Canvas globalCompositeOperation values source-in and destination-in are not working with multiple source and destination images. The operation results in blank canvas. All other values of globalCompositeOperation works..

<!DOCTYPE html>
<html>
<body >
<canvas id="myCanvas" width="512" height="512"></canvas>
<script>
var c=document.getElementById('myCanvas');
var ctx=c.getContext('2d');
ctx.fillStyle='blue';
ctx.fillRect(10,10,50,50);
ctx.fillRect(100,100,50,50);
ctx.globalCompositeOperation='source-in';
ctx.beginPath();
ctx.fillStyle='red';
ctx.arc(50,50,30,0,2*Math.PI);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle='red';
ctx.arc(110,110,30,0,2*Math.PI);
ctx.fill();
ctx.closePath();
</script>
</body>
</html>

Let me know if there is something wrong with the way I'm doing or is it a bug? Thanks..


Solution

  • Each subsequent call to fill() is a new composite operation. In your case the last arc does not intersect with the current drawings and will result in a blank composite.

    You need to draw all elements that you want included in the composite operation before calling fill(). Example:

    var c=document.getElementById('myCanvas');
    var ctx=c.getContext('2d');
    ctx.fillStyle='blue';
    ctx.fillRect(10,10,50,50);
    ctx.fillRect(100,100,50,50);
    
    ctx.globalCompositeOperation='source-in';
    
    ctx.fillStyle='red';
    ctx.beginPath();
    ctx.arc(50,50,30,0,2*Math.PI);
    ctx.arc(110,110,30,0,2*Math.PI);
    ctx.fill();