Search code examples
javascriptraphaelgraphaeljustgage

Calculating a percentage with mouse position considering half-circle


I just tried to code some tricks on justGage (using Raphael JS code) to calculate percentages but I'm stuck on mathematical formula :( .

Here's the point : I have a div with 400px width that welcomes a svg justGage. I would like to make it filling following mouse clicking. For example, clicking on bottom right of the half-circle will fill it as if it was 100% filled. Clicking on bottom left, fill it at 0%. The issue is that I try to catch mouse position and use it to refresh the Gage, but working only on X axis is not following circle shape.

Here's my basic calculation :

    var parentOffset = $(this).offset(); 
    var relX = e.pageX - parentOffset.left;
    g1.refresh(Math.round((relX)/4));

And the whole code test fiddle.

Does anyone know a formula to really follow the circle shape ?


Solution

  • Since you have a strip which the clicks happen, you cannot rely on the x-coordinate in order to decide the precentage. The best option I could think of was using trigonometry to calculate the angle between the click and the center of the circle, before fitting it to your range 0-100 by this equation ((angel/Math.PI)*100).

    Below is a code snipplet that worked out for me.

    $(function(){
        $("#g1 path").click(function(e){
            var parent = $(this).parent();
            var height = parent.height();
            var width = parent.width();
            var center = {'x': width/2, 'y':(height-60)};
            var angle = Math.atan2(-(e.pageY - center['y']), center['x'] - e.pageX);
            g1.refresh(Math.round((angle/Math.PI)*100));  
        });
    })