1. 常用的Math用法
Math.random() //0-1 的随机数
Math.round() //四舍五入取整
Math.ceil() //向上取整
Math.floor() //向下取整
Math.abs() //绝对值
Math.max(num1,num2....) //比较最大值
Math.min(num1,num2....) //比较最小值
Math.PI //π 3.1415926 - 3.1415927
Math.pow(x,y) //x的y次方
Math.sqrt() //开平方
Math.sin
Math.cos
Math.tan
注:
常用弧度来表示角度
eg: b=c*sin(x); //x表示一个度数。用弧度表示角度 (2*Math.PI/360)*x;
2.案例
a.做一个六边形
var z = 150 / Math.tan((2 * Math.PI / 360) * 30);
for (var i = 0; i < 6; i++) {
box.innerHTML += '<div style="transform-origin: center center '+(-z)+'px;transform: translateZ('+z+'px) rotateY('+(i*60)+'deg);background:'+randomColor()+';"></div>';
}
//随机色(用16进制颜色值表示)
function randomColor() {
var str = "0123456789abcdef"
var color = '#';
for (var i = 0; i < 6; i++) {
//每一次都随机一个0-15下标
color += str.charAt((Math.random() * 15));
}
return color;
}
</script>
效果:
b.抛物线案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0
}
div:nth-of-type(1) {
600px;
height: 2px;
background: red;
position: absolute;
top: 300px;
}
div:nth-of-type(2) {
2px;
height: 600px;
background: blue;
position: absolute;
left: 300px;
}
span {
display: block;
2px;
height: 2px;
position: absolute;
border-radius: 1px;
background: red;
}
</style>
</head>
<body>
<div></div>
<div></div>
<script>
for(var x= -300; x<=300;x++) {
var y = 0.01 * Math.pow(x,2);
document.write('<span style="left:' +(x+300)+ 'px;top:' +(y+300)+'px;"></span>');
}
</script>
</body>
</html>
显示效果: