atan2()

Baseline 2023
Newly available

Since March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

CSS 函数 atan2() 为三角函数,返回介于 -infinityinfinity 之间的两值的反正切值。此函数接受两个参数,返回表示介于 -180deg180deg 之间的 <angle> 的弧度数。

语法

css
/* 两个 <number> 值 */
transform: rotate(atan2(3, 2));

/* 两个 <dimension> 值 */
transform: rotate(atan2(1rem, -0.5rem));

/* 两个 <percentage> 值 */
transform: rotate(atan2(20%, -30%));

/* 其他值 */
transform: rotate(atan2(pi, 45));
transform: rotate(atan2(e, 30));

参数

atan2(y, x) 函数接受以逗号分隔的两值作为其参数。每值可为 <number><dimension><percentage>。两值须为同一类型,但若均为 <dimension>,则其单位可以不同(例:atan2(100px, 5vw) 为有效表达式)。

y

点的纵坐标。为解析为 <number><dimension><percentage> 的计算式。

x

点的横坐标。为解析为 <number><dimension><percentage> 的计算式。

返回值

对于所给两值 xy,函数 atan2(y, x) 计算并返回正半横轴与从原点到点 (x, y) 的射线的夹角(<angle>)。

形式语法

<atan2()> = 
atan2( <calc-sum> , <calc-sum> )

<calc-sum> =
<calc-product> [ [ '+' | '-' ] <calc-product> ]*

<calc-product> =
<calc-value> [ [ '*' | '/' ] <calc-value> ]*

<calc-value> =
<number> |
<dimension> |
<percentage> |
<calc-keyword> |
( <calc-sum> )

<calc-keyword> =
e |
pi |
infinity |
-infinity |
NaN

示例

旋转元素

由于 atan2() 函数返回 <angle>,故可用于旋转(rotate)元素。

HTML

html
<div class="box box-1"></div>
<div class="box box-2"></div>
<div class="box box-3"></div>
<div class="box box-4"></div>
<div class="box box-5"></div>

CSS

css
div.box {
  width: 100px;
  height: 100px;
  background: linear-gradient(orange, red);
}
div.box-1 {
  transform: rotate(atan2(3, 2));
}
div.box-2 {
  transform: rotate(atan2(3%, -2%));
}
div.box-3 {
  transform: rotate(atan2(-1, 0.5));
}
div.box-4 {
  transform: rotate(atan2(1, 0.5));
}
div.box-5 {
  transform: rotate(atan2(1rem, -0.5rem));
}

结果

规范

Specification
CSS Values and Units Module Level 4
# trig-funcs

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
atan2()

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

参见