Canvas How to - Handle onclick event








Question

We would like to know how to handle onclick event.

Answer


<!--from  w w  w  .  j  a  v  a2s. c om-->
Click to repaint canvas

<!DOCTYPE html>
<html>
<body>
<canvas id="drawing" width="600px" height="600px" onclick="resize()"></canvas>
<script type='text/javascript'>
var radius = 70;
var canvas,
    context,
    centerX,
    centerY;
window.onload = function() {
    canvas=document.getElementById("drawing");
    context=canvas.getContext("2d");
    centerX = canvas.width / 2;
    centerY = canvas.height / 2;
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
}
function resize () {
    context.beginPath();
    context.arc(centerX, centerY, radius * 2, 0, 2 * Math.PI, false);
    context.fillStyle= "#701be0"; // This changes the rectangle to blue
    context.fill();
}
</script>
</body>
</html>

The code above is rendered as follows: