Javascript javascript画布检测点击形状

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12625766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:53:07  来源:igfitidea点击:

javascript canvas detect click on shape

javascriptfunctioneventscanvasclick

提问by user1590534

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

我对 javascript 中的点击功能有问题。这是我的代码:

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!

但是点击事件不起作用!有人知道为什么吗?非常感谢您!

回答by RobotEyes

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:

或者只使用众多画布 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...

等等...

回答by supernova

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 在画布上获取单击事件,并从光标位置计算用户是否单击了圆圈,但 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/

回答by Boog

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.

Canvas API 函数isPointInPath() 可用于辅助命中检测。这个函数至少可以判断鼠标坐标是否在一个复杂的形状内,而无需自己进行复杂的数学运算。也可能适用于简单的形状,但我的用例是用于贝塞尔曲线路径。但是,您需要将此函数合并到绘图逻辑中以在路径打开时进行测试,或者保留一组 Path2d 对象以进行测试。我重绘 onClick 处理程序并从事件参数传入鼠标坐标,但我认为我可以保留一组 Path2d 对象。

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

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

回答by Ed Bayiates

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.

bigGreen 不在 HTML 中,因此 $("#bigGreen") 不选择任何内容。你不能在 JavaScript 函数之类的东西上放置点击函数;既然它们不存在于 DOM 中,你怎么能点击一个?您应该用#canvas 替换#bigGreen,因为“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.

编辑:如果您想看到用户单击了特定的圆,您可以使用画布单击事件,然后通过传递给单击事件的坐标确定单击了哪个圆。

回答by Kld

You can try jcanvas

你可以试试jcanvas

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

http://projects.calebvans.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'
    });
  }
});