Search code examples
javascriptjqueryhtmlgeometryjcanvas

How to set text in center of curve shape with jCanvas?


I'm drawing "map" with jCanvas using drawLine method and need to put house number in center of the curve shape (it can has random number of angles).

Also please note, that all objects are draggable and text must be draggable with it.

Or how can I calculate center of object, which can has random number of angles?


Solution

  • I wrote a function that solved my problem. As var points you must send svg polygon points.

    function getcenter(points, index)
    {
        if (typeof points!="undefined") 
        {
            var pairs = [];
            pairs = points.split(" ");
            
            
    
            var first = true;
            var min; var max;
            
            for(var i=0;i<pairs.length;i++)
            {
                var list = pairs[i].split(',');
                
                if(first===true)
                {
                    first = false;
                    min = max = list[index];
                }
                else
                {
                    if(list[index]<min) min = list[index];
                    if(list[index]>max) max = list[index];
                }
            }
            
    
            min = parseInt(min);
            max = parseInt(max);
    
            var result = (min+max)/2;
    
            return result;
        }
        else return false;
    };