Canvas How to - Click to clear rectangle








Question

We would like to know how to click to clear rectangle.

Answer


<!--   w  ww  .j av a2s. c  o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var canvas = document.getElementById("test");
    var context = canvas.getContext('2d');
    context.fillStyle = 'rgba(255, 0, 0, 0.1)';
    context.fillRect(0, 0, 40, 40);
    context.beginPath();
    context.rect(0, 0, 20, 20);
    context.clip();
    $("input").click(function(){
        context.clearRect(10, 10, 20, 20);
    });
});//]]>  
</script>
</head>
<body>
    <canvas id="test"></canvas>
    <input type="button" value="Clear rect">
</body>
</html>

The code above is rendered as follows: