Search code examples
javascriptcanvaspathfill

Make canvas object's drawn path transparent?


I need some help with this code. There is a blue square (it is supposed to be,) but it's path is blue too!

body{
  overflow-y:hidden;
  overflow-x:hidden;
}
canvas{
  background:url("https://img0.etsystatic.com/038/0/6965312/il_340x270.545626074_sflg.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onkeydown="move(event.keyCode)">
<script>
var X = 80;
var Y = 20;
function move(keyCode){
  myCanvas.fillStyle = "transperant";
  myCanvas.fillRect(X, Y, 50, 50);
  if(keyCode == 39){
    X += 5;
  }
  if(keyCode == 37){
    X -= 5;
  }
  if(keyCode == 40){
    Y += 5;
  }
  if(keyCode == 38){
    Y -= 5;
  }
  myCanvas.fillStyle = "blue";
  myCanvas.fillRect(X, Y, 50,50);
}
</script>
<canvas id="C1" width="900px" height="900px">Uhh, what?!?!</canvas>
<script>
myElement = document.getElementById("C1");
myCanvas = myElement.getContext("2d");
myCanvas.fillStyle = "transperant";
myCanvas.fillRect(80, 20, 50, 50);
  </script>
</body>

How do you make the path transparent/clear? I tried fillPath, but that didn't work. Maybe I was using it wrong. Please give me some help? Please also include source/example.


Solution

  • Use compositing to make new drawings "erase" existing pixels.

    The compositing mode that "erases" is destination-out

    Example code:

    // set compositing to use any new drawings 
    // to "erase" existing drawings
    ctx.globalCompositeOperation='destination-out';
    
    // draw something
    // the canvas will become transparent inside that drawing
    ctx.fillRect(100,100,100,100);
    
    // reset compositing to default
    ctx.globalCompositeOperation='source-over';
    

    Example code and a Demo:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    var img=new Image();
    img.onload=start;
    img.src="https://img0.etsystatic.com/038/0/6965312/il_340x270.545626074_sflg.jpg";
    function start(){
    
      canvas.width=img.width;
      canvas.height=img.height;
      ctx.drawImage(img,0,0);
    
      // set compositing to use any new drawings 
      // to "erase" existing drawings
      ctx.globalCompositeOperation='destination-out';
    
      // draw something
      // the canvas will become transparent inside that drawing
      ctx.fillRect(100,100,100,100);
    
      // reset compositing to default
      ctx.globalCompositeOperation='source-over'; 
    
    }
    body{ background-color: purple; }
    canvas{border:1px solid red;}
    <canvas id="canvas" width=300 height=300></canvas>