Cómo convertir coordenadas x,y a un ángulo?


Microsoft proporciona un excelente SVG gradient maker por lo que IE9 también puede tener gradientes "CSS3" (haga clic en Personalizado).

Actualmente utilizo su lógica para mis extensiones Fireworks y Dreamweaver para convertir degradados a SVG, pero solo sé cómo hacerlo para las direcciones estándar superior, inferior, izquierda y derecha. Si ingresa un ángulo, no hago la conversión, porque no estoy seguro de cómo convertiría x1, x2, y1, y2 a grados de ángulo CSS3.

El gradiente el generador proporciona valores como: x1="0%" y1="0%" x2="56.262833675564686%" y2="68.29999651227678%"

No soy muy bueno con las matemáticas o la trigonometría, así que ¿alguien podría ayudarme? También me gustaría usar las mismas matemáticas en un Sass mixin para hacer algo similar, si es posible.

Author: Matt Stow, 2013-04-14

6 answers

Si obtiene deltaX y deltaY de sus coordenadas, entonces Math.atan2 devuelve el arctangent del cociente de sus argumentos. El valor devuelto está en radianes.

var deltaX = x2 - x1;
var deltaY = y2 - y1;
var rad = Math.atan2(deltaY, deltaX); // In radians

Entonces puedes convertirlo a grados tan fácil como:

var deg = rad * (180 / Math.PI)

introduzca la descripción de la imagen aquí

Editar

Había algunos errores en mi respuesta inicial. Creo que en la respuesta actualizada se abordan todos los errores. Por favor, comente aquí si cree que hay un problema aquí.

 57
Author: Mohsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-22 22:46:40

La respuesta actualmente aceptada es incorrecta. En primer lugar, Math.tan está totalmente equivocado suspect sospecho que Mohsen quiso decir Math.atan y esto es solo un error tipográfico.

Sin embargo, como otras respuestas a esa respuesta indican, realmente debe usar Math.atan2(y,x) en su lugar. La tangente inversa regular solo devolverá valores entre-pi/2 y pi/2 (cuadrantes 1 y 4) porque la entrada es ambigua the la tangente inversa no tiene forma de saber si el valor de entrada pertenece al cuadrante 1 vs 3, o 2 vs 4.

Math.atan2, en el por otro lado, puede usar los valores xy dados para averiguar en qué cuadrante se encuentra y devolver el ángulo apropiado para cualquier coordenada en los 4 cuadrantes. Entonces, como otros han señalado, solo puede multiplicar por (180/Math.pi) para convertir radianes a grados, si es necesario.

 17
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-29 03:38:26

En lugar de usar Matemáticas.tan función Usted debe utilizar matemáticas.atan2:

Aquí hay un ejemplo de uso:

deltaX = x2 - x1;
deltaY = y2 - y1;
deg = Math.atan2(deltaY, deltaX)*180.0/Math.PI;

Y esto devolverá un grado de .

 2
Author: MNie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-08 23:42:19

Si estás en un Cuadrante

P1 = (X0,Y0)

P2 = (X1,Y1)

A = (X0-X1)

B = (Y0-Y2)

deltaX=((a)**2)**0.5
deltaY=((b)**2)**0.5
rad=math.atan2(deltaY, deltaX)
deg = rad * (360 / math.pi)
print deg

El grado será entre 0 ~ 180

 0
Author: 楊宇恩,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-11 18:21:15

var x,x1,x2,y,y1,y2;
var cells = 'cell0';
		var h,w;
		var cx,cy;
		var dx,dy;
		var derajat;
		var deg;
		var ang;
		var light;
		var control;
			function mouse_watch(event){
				x = event.clientX;
				y = event.clientY;
				cell_data(cells);
				koordinat(x2,y2);
				busur(derajat);
			}
			function koordinat(x2,y2){
				x2 = x-cx;
				y2 = y-cy;
				yk = y2;
				xk = x2;
			}
			function busur(derajat){

				y1 = Math.sqrt((Math.abs(yk)*Math.abs(yk))+(Math.abs(xk)*(Math.abs(xk))));
				x1 = 0;
				dy = yk-y1;
				dx = xk-x1;
				rad = Math.atan2(dy, dx);
				derajat = rad * (360 / Math.PI);
				cell = document.getElementById(cells);
				ang = cell.getElementsByClassName('angle0')[0];
				ang.style.transform = 'rotate('+derajat+'deg)';
				light = ang.getElementsByClassName('points')[0];
				light.style.height = y1+'px';
			}
			function cell_data(cells){
				cell = document.getElementById(cells);
				h = Number(cell.style.height.replace('px',''));
				w = Number(cell.style.width.replace('px',''));
				cy = Number(cell.style.top.replace('px',''))+h/2;
				cx = Number(cell.style.left.replace('px',''))+w/2;
			}
			.preview_engine{
				position: absolute;
				top: 0;
				left: 0;
				padding: 10px;
				background-color: #2E8AE6;
				color: white;
			}
			body{
				cursor: default;
				width: 100%;
				height: 100%;
				font-family: Arial;
				font-size: 12px;
			}
			.fieldwork{
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0px;
				left: 0px;
			}
			.cell{
				position: relative;
				transition : width 2s, height 2s, top 2s, left 2s;
				background-color: red;
			}
			.angle0{
				width: 200px;
				height: 200px;
				position: absolute;
				top: -75px;
				left: -75px;
				background-color: green;
				border-radius: 50%;
				opacity: 0.5;
				transition : width 2s, height 2s, top 2s, left 2s;
			}
			.points{
				width: 10px;
				height: 10px;
				position: absolute;
				left: 95px;
				top: 95px;
				background-color: red;
				border-radius: 1em;
				opacity: none;
			}
<div class="fieldwork" onmousemove="mouse_watch(event)">
<div class='cell' id="cell0" style="width:50px;height:50px;top:200px;left:400px;">
<div class="angle0">
<div class="points"></div>
</div>
</div>
</div>
 -1
Author: Black Side,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-29 03:15:38

Esta función toma 2 elementos y devuelve el grado entre el centro de los elementos.

Por ejemplo, lo usé en un mapa del mundo, para hacer que la imagen del plano gire en la dirección de una ciudad.

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;

}
 -1
Author: Alessandro Catania,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 15:35:49