简体   繁体   English

javascript canvas检测点击形状

[英]javascript canvas detect click on shape

I have a problem with the click function in javascript.我在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!非常感谢您!

You can now use hit regions in Chrome and Firefox: 您现在可以在Chrome和Firefox中使用点击区域:

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility#Hit_regions 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: 或者只使用众多canvas API中的一个:

http://www.fabricjs.com/ http://www.fabricjs.com/

http://www.createjs.com/easeljs http://www.createjs.com/easeljs

http://www.paperjs.org http://www.paperjs.org

etc... 等等...

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. 没有看到你的HTML这个问题有点不清楚,似乎你想在画布上画一些东西并使用jquery为圆圈添加点击事件,这是不可能的。

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在画布上获取click事件,从光标位置你可以计算出用户是否点击了这个圆圈,但是jquery对你没有帮助,你必须自己做数学运算。

jquery does only work for dom elements. jquery只适用于dom元素。

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/ jsfiddle在这里http://jsfiddle.net/yXVrk/1/

Canvas API function isPointInPath () can be used to assist with hit detection. Canvas API函数isPointInPath ()可用于协助命中检测。 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. 也可以用于简单的形状,但我的用例是在bezier曲线路径上。 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. 但是,您需要在绘图逻辑中合并此函数以在路径打开时进行测试,或者保留要测试的Path2d对象数组。 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. 我重写onClick处理程序并从事件args传入鼠标坐标,但我想我可以保留一个Path2d对象数组。

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

bigGreen is not in the HTML, so $("#bigGreen") selects nothing. bigGreen不在HTML中,因此$(“#bigGreen”)不会选择任何内容。 You can't put a click function on things like JavaScript functions; 你不能在JavaScript函数之类的东西上放置一个click函数; since they don't exist in the DOM, how could you click one? 因为它们不存在于DOM中,你怎么能点击一个呢? You should replace #bigGreen with #canvas, since "canvas" is your HTML element. 您应该将#bigGreen替换为#canvas,因为“canvas”是您的HTML元素。

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. 编辑 :如果要查看用户单击特定圆,则使用画布单击事件,然后确定通过单击事件传递的坐标单击了哪个圆。

You can try jcanvas 你可以尝试jcanvas

http://projects.calebevans.me/jcanvas/docs/mouseEvents/ 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'
    });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM