javascript canvas detect click on shape

2020-02-23 08:48发布

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!

5条回答
叼着烟拽天下
2楼-- · 2020-02-23 09:25

bigGreen is not in the HTML, so $("#bigGreen") selects nothing. You can't put a click function on things like JavaScript functions; since they don't exist in the DOM, how could you click one? You should replace #bigGreen with #canvas, since "canvas" is your HTML element.

I forked your fiddle to show this here.

Edit: If you want to see that the user clicked on a particular circle, you use the canvas click event, and then, you determine which circle was clicked by the coordinates passed into the click event.

查看更多
聊天终结者
3楼-- · 2020-02-23 09:27

You can try jcanvas

http://projects.calebevans.me/jcanvas/docs/mouseEvents/

// Click the star to make it spin
$('canvas').drawPolygon({
  layer: true,
  fillStyle: '#c33',
  x: 100, y: 100,
  radius: 50,
  sides: 5,
  concavity: 0.5,
  click: function(layer) {
    // Spin star
    $(this).animateLayer(layer, {
      rotate: '+=144'
    });
  }
});
查看更多
做自己的国王
4楼-- · 2020-02-23 09:42

You can now use hit regions in Chrome and Firefox:

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility#Hit_regions

ctx.beginPath();
ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
ctx.fill();
ctx.addHitRegion({id: "bigGreen"});

and add a callback

canvas.onclick = function (event)
{
    if (event.region) {
        alert('You clicked ' + event.region);
    }
}

or just use one of the many canvas APIs:

http://www.fabricjs.com/

http://www.createjs.com/easeljs

http://www.paperjs.org

etc...

查看更多
一纸荒年 Trace。
5楼-- · 2020-02-23 09:43

Canvas API function isPointInPath() can be used to assist with hit detection. This function can at least tell if mouse coordinates are within a complex shape without doing sophisticated math yourself. May work for simple shapes as well but my use case was for on a bezier curve path. However, you need to either incorporate this function in your drawing logic to test while paths are open or keep an array of Path2d objects to test against. I redraw on onClick handler and pass in mouse coords from event args, but I think I could have kept an array of Path2d objects instead.

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath

查看更多
冷血范
6楼-- · 2020-02-23 09:50

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/

查看更多
登录 后发表回答