How to convert x,y coordinates to an angle?

前端 未结 6 830
暗喜
暗喜 2020-12-13 06:49

Microsoft provide an excellent SVG gradient maker so IE9 can also have \"CSS3\" gradients (click Custom).

I currently utilise their logic for my Fireworks and Dreamw

6条回答
  •  独厮守ぢ
    2020-12-13 07:23

    This function takes 2 elements and returns the degree between the middle of the elements.

    For example, I used it on a world map, to make the image of plane rotate in the direction of a city.

    function degFromTwoElements(el1,el2){
        var x1,x2,y1,y2,cx1,xy1,cx2,cy2,deltaX,deltaY,dx,dy,rad,deg,shortest,number;
        x1 = el1.position().left;
        y1 = el1.position().top;
        x2 = el2.position().left;
        y2 = el2.position().top;
        cx1 = x1 - (el1.width() / 2);
        cy1 = y1 - (el1.height() / 2);
        cx2 = x2 - (el2.width() / 2);
        cy2 = y2 - (el2.height() / 2);
    
        deltaX = cx2 - cx1;
        deltaY = cy2 - cy1;
        y1 = Math.sqrt((Math.abs(deltaY)*Math.abs(deltaY))+(Math.abs(deltaX)*(Math.abs(deltaX))));
        x1 = 0;
        dy = deltaY-y1;
        dx = deltaX-x1;
        rad = Math.atan2(dy, dx);
        deg = rad * (360 / Math.PI);
    
        shortest;
        number = Math.abs(deg);
        if ((360 - number ) < number){
            shortest = 360 - number;
            console.log('shorter degree: ' + shortest);
            return shortest;
        } 
        else console.log('Angle is: ' + deg);
        return deg;
    
    }
    

提交回复
热议问题