-2

I'm trying to make the circle I've made in canvas have an onclick event. I tried the following with no success. If anyone can offer some pointers, that would be great.

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<div id="type"></div>
<canvas id="ctx2" width="500" height="500" style="border: solid 1px;"></canvas>
<script>
var ctx = document.getElementById("ctx2").getContext("2d");
//var message = 'Hello John, this is your canvas.';
//ctx.fillStyle = 'red';
//ctx.font = '30px Arial';
//ctx.opacity = 0;
//ctx.fillText(message,50,50);

ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();
ctx.onclick = displayDate(); // This is what I used (stack overflow)

function displayDate() {
    document.getElementById("type").innerHTML = Date();
}

document.getElementById("type").innerHTML = typeof ctx


</script>
</body>
</html>
JohnSeuss
  • 51
  • 9
  • An onclick event can only be attached to an element that exists in the DOM. Anything drawn to a canvas does not exist in the DOM, it's just graphics. One way to do this is to attach your onclick to the entire canvas and then determine if the location clicked is within your circle. – Tibrogargan Apr 09 '16 at 07:02

3 Answers3

1

You need to add the event listener to the canvas and then check if the "click" event coordinates lie within the circular area that you created. jsFiddle example: https://jsfiddle.net/aL2epngo/

 var circle = {x:100,y:75, r:50};

function displayDate() {
    document.getElementById("type").innerHTML = Date();
}

 function checkBoundaries(x,y){
     var clicked = false;
     if(x >=circle.x - circle.r && x <= circle.x+circle.r){
       if(y >= circle.y- circle.r && y <= circle.y+circle.r){
         clicked = true;
       }
     }
     return clicked;
 }  

 function clickHandler(e){

     var canvas = document.getElementsByTagName("canvas")[0];
     var x = e.pageX ? e.pageX:  e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      var y = e.pageY ? e.pageY:  e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      x -= canvas.offsetLeft;
      y -= canvas.offsetTop;

      if( checkBoundaries(x,y) ){
        displayDate()
      }

 }
nick
  • 1,197
  • 11
  • 16
0

I used this to make a map of the positions in a call center and clicking on position i get different actions.

Here's an example:

HTML:

<script src="https://raw.githubusercontent.com/DmitryBaranovskiy/raphael/master/raphael-min.js"></script>
<div id="test"></div>

JAVASCRIPT:

var canvas = Raphael('test', 500, 500);
var rect = canvas.rect(50,50,50,50);
rect.attr('fill', 'red');
rect.click(function(test){alert('test');});

https://jsfiddle.net/g5gL1j02/

edisonmecaj
  • 1,062
  • 1
  • 9
  • 20
-1

you can used

ctx.addEventListener('click', function(event) {
     displayDate();
},false);

//or
canvas.addEventListener("mousedown",function(){
      displayDate();
},false)

if you satisfied then vote for me

Rajiv
  • 78
  • 10