如果在圆圈中找到点击的点,则打印适合的消息

时间:2013-12-13 17:17:50

标签: javascript jquery canvas

我有一个中心坐标(x1,y1)和两个圆的半径(r)。

我有另一个点A(x2,y2),它是鼠标点击的点。

我编写了一个函数,如果在圆圈内或外部找到A点,则会打印一条消息。

这是我的jsfiddle:

http://jsfiddle.net/alonshmiel/c4upM/22/

我想知道下一件事:

if the clicked pixel is inside the lightblue circle, print 1.
else if the clicked pixel is inside the gray circle, print 2.
else print 3.

我在函数中构建了这些圆圈:circleInArc

另外,我在javascript区域编写了函数:$('#canvas').on('click', function(event) {..}function isPointInsideCircle(center_x, center_y, radius, x, y) {..}。我在html区域中编写了另一个函数(如circleInArc)。

请帮助我,

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

回复较小圈子中的点击事件

  • 创建小的蓝色和灰色圆圈时,保存其x / y坐标和半径信息

  • 发生鼠标事件时,请使用pointInside测试查看鼠标是否在任一圈中。

演示:http://jsfiddle.net/m1erickson/nrXNh/

代码可能如下所示:

    // When a circle is created send back its x,y & radius
    // We use this info to later check if the mouse is inside this particular circle

    function circleInArc(fillColor,radianAngle){
        var x=cx+radius*Math.cos(radianAngle);
        var y=cy+radius*Math.sin(radianAngle);
        ctx.beginPath();
        ctx.arc(x,y,linewidth/2,0,Math.PI*2);
        ctx.closePath();
        ctx.fillStyle=fillColor;
        ctx.fill();
        return({x:x,y:y,radius:linewidth/2});
    }


    // save both circles x,y & radius in a javascript object when calling circleInArc

    var circle1=circleInArc("skyblue",PI*1.5);
    var circle2=circleInArc("lightgray",PI*1.25);


    // listen for mousedown events 
    // I use jquery, but you could substitute pure javascript if you prefer

    $("#canvas").mousedown(function(e){handleMouseDown(e);});


    // when a mousedown occurs, test both circles to see if the mouse is inside
    // then put up an alert with the results of the tests

    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // test circle1
      var dx=mouseX-circle1.x;
      var dy=mouseY-circle1.y;
      var rSquared=circle1.radius*circle1.radius;
      if(dx*dx+dy*dy<rSquared){
          alert("Clicked in circle#1");
          return;
      }

      // test circle2
      var dx=mouseX-circle2.x;
      var dy=mouseY-circle2.y;
      var rSquared=circle2.radius*circle2.radius;
      if(dx*dx+dy*dy<rSquared){
          alert("Clicked in circle#2");
          return;
      }

      // otherwise outside circles
      alert("Clicked outside circle#1 and circle#2");

    }