javascript 做一个动态旋转的3D球
时间: 2023-10-07 17:06:05 浏览: 55
好的,以下是一个使用JavaScript实现动态旋转的3D球的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>3D球</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var radius = 100; // 球的半径
var centerX = canvas.width / 2; // 球心坐标 X
var centerY = canvas.height / 2; // 球心坐标 Y
var angleX = 0; // 绕 X 轴旋转角度
var angleY = 0; // 绕 Y 轴旋转角度
var angleZ = 0; // 绕 Z 轴旋转角度
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(angleZ);
ctx.rotate(angleY);
ctx.rotate(angleX);
ctx.beginPath();
for (var i = 0; i < 360; i += 10) {
var x = radius * Math.cos(i * Math.PI / 180);
var y = radius * Math.sin(i * Math.PI / 180);
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.restore();
angleX += 0.01;
angleY += 0.02;
angleZ += 0.03;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
```
这个示例代码会在浏览器中绘制一个白色的3D球,球会不断地绕 X、Y、Z 轴旋转,形成动态旋转的效果。你可以根据自己的需要调整球的半径、旋转角度等参数,来实现自己想要的效果。