Math 对象用于执行数学任务。
Math对象里有自己封装的方法
<script>
console.log(Math.PI);//圆周率
console.log(Math.abs(-1));//取绝对值
console.log(Math.ceil(2.45));//向上取整
console.log(Math.floor(2.45));//向下取整
console.log(Math.round(4.56));//四舍五入
console.log(Math.max(1,3,5));//取最大值
console.log(Math.min(1,3,5));//取最小值
console.log(Math.random()*10);//随机数 0-1范围
console.log(Math.sin(45));//sin函数
console.log(Math.cos(78));//cos函数
console.log(Math.tan(60));//tan函数
console.log(Math.asin(45));//asin函数
console.log(Math.pow(2,3));//次幂,2的3次幂
</script>
输出结果:
案例
小球以sin轨迹运动
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
html,body{
width: 100%;
height: 100%;
}
#ball{
width: 50px;
height: 50px;
position: absolute;
top: 350px;
left: 0;
background-color: #70bcdb;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="ball">
</div>
<script>
var ball=document.getElementById("ball");
var time;
var x=0;
var y=0;
time = setInterval(function () {
var top = Math.sin(x) * 50;
var left = y;
y = y + 1;
x = 0.04 * y;
ball.style.left = left + "px";
ball.style.top = (top + 350) + "px";
}, 1);
</script>
</body>
</html>