MM86 MM86 - 5 months ago 10
Javascript Question

How to find out which part of the circle was clicked, using HTML5 canvas?

I am trying to create Simon game using HTML5 canvas and vanilla JavaScript. I am confused about the coordinate system in the arc() method. I have divided the circle into 4 quadrants and would like to alert the number of the quadrant clicked. But, I am not sure how to find out which part of the circle was clicked. https://jsfiddle.net/xawpLdys/1/

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;

var pads = [];

var angle = 2 * Math.PI / 4;
var color = ["green","red","blue","yellow"];
var Pads = function(x, y, radius, start, end) {
this.x = x;
this.y = y;
this.radius = radius;
this.start = start;
this.end = end;

};
function drawSimon(radius) {
for (var i = 0; i < 4; i++) {
context.beginPath();
context.moveTo(x, y);
context.arc(x, y, radius, i*angle, (i+1)*angle, false);
context.lineWidth = radius;
context.fillStyle = color[i];
context.fill();
context.lineWidth = 2;
context.strokeStyle = '#444';
context.stroke();
var pad = new Pads(x, y, radius, i*angle, (i+1)*angle);
pads.push(pad);
}

}

drawSimon(150);

$('#myCanvas').click(function (e) {

/*for (var i = 0; i < pads.length; i++) {
if (//condition matches) {
alert (i);
}
}*/
});

Answer

Try This

This example just translates the clicked e.pageX and e.pageY to normal quadrant system. And after some condition, you can determine which part has been clicked.

    $('#myCanvas').click(function (e) {
    var nx,ny;
    nx=-(x- e.pageX);
    ny=y- e.pageY;
        if (nx>0 && ny>0){
      alert('Yellow');
      }else if (nx<0 && ny>0){
      alert('Blue');
      }else if (nx>0 && ny<0){
      alert('Green');
      }else if (nx<0 && ny<0){
      alert('Red');
      }

    });

Here is the fiddle https://jsfiddle.net/xawpLdys/3/