Canvas How to - Erase the existing image with Composite destination-out








Question

We would like to know how to erase the existing image with Composite destination-out.

Answer


<!--from  w w  w  .j  a  v  a  2 s .  c om-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
    start();
}
img.src = "http://www.java2s.com/style/download.png";
function start() {
    ctx.drawImage(img, 0, 0);
    ctx.globalCompositeOperation = "destination-out";
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(300, 300);
    ctx.moveTo(300, 0);
    ctx.lineTo(0, 300);
    ctx.lineWidth = 30;
    ctx.fillStyle = "blue";
    ctx.stroke();
}
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

The code above is rendered as follows: