MM86 MM86 - 1 year ago 81
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.

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.moveTo(x, y);
context.arc(x, y, radius, i*angle, (i+1)*angle, false);
context.lineWidth = radius;
context.fillStyle = color[i];
context.lineWidth = 2;
context.strokeStyle = '#444';
var pad = new Pads(x, y, radius, i*angle, (i+1)*angle);



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

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

Answer Source

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){
      }else if (nx<0 && ny>0){
      }else if (nx>0 && ny<0){
      }else if (nx<0 && ny<0){


Here is the fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download