Canvas How to - Handle mouse click event








Question

We would like to know how to handle mouse click event.

Answer


<!--  w w w . j  a  v  a 2  s. co  m-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
canvas {
  border: 1px solid red;
}
</style>
<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 () {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
        }
        img.src = "http://www.java2s.com/style/download.png";
        canvas.addEventListener("click", function (e) {
            console.log("!");
        });
}//]]>  
</script>
</head>
<body>
  <p>Click on image in the canvas to trigger the click event listener</p>
  <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

The code above is rendered as follows: