user1590534 user1590534 - 5 months ago 41
Javascript Question

javascript canvas detect click on shape

I have a problem with the click function in javascript. This is my code:

var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext('2d');

BigCircle = function(x, y, color, circleSize) {
ctx.shadowBlur = 10;
ctx.shadowColor = color;
ctx.beginPath();
ctx.arc(x, y, circleSize, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
};

var bigGreen = new BigCircle(1580, 800, '#5eb62b', 180);

function init() {
$("#bigGreen").click(function(e){
alert("test");
});
}
$(document).ready(function() {
init();
});


But the click event is not working! Does anybody know why? Thank you so much in advance!

Answer

without seeing your html this question is a little bit unclear, it seems you would like to draw something on a canvas and use jquery to add click events for the circle, this isn't possible.

you can use jquery to get the click event ON the canvas and from the cursor position you can calculate if the user clicked the circle or not, but jquery won't help you here you have to do the math yourself.

jquery does only work for dom elements.

BigCircle = function(ctx,x, y, color, circleSize) {
    ctx.beginPath();
    ctx.arc(x, y, circleSize, 0, Math.PI * 2, true);
    ctx.fillStyle=color
    ctx.fill();
    ctx.closePath();
    this.clicked=function(){
      ctx.fillStyle='#ff0000'
      ctx.fill();
    }
};

function init() {
  var canvas = document.getElementsByTagName("canvas")[0];
  var ctx = canvas.getContext('2d');
  var bigGreen = new BigCircle(ctx,50, 50, '#5eb62b', 50);
  $('#canvas').click(function(e){
    var x = e.clientX
      , y = e.clientY          
    if(Math.pow(x-50,2)+Math.pow(y-50,2) < Math.pow(50,2))   
      bigGreen.clicked()
  })    
}


$(document).ready(function() {
    init();   
});

‚Äč

jsfiddle is here http://jsfiddle.net/yXVrk/1/

Comments