js实现圆球
使用 Canvas 绘制圆球
通过 HTML5 Canvas API 可以动态绘制圆球。以下代码创建一个红色圆球:
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
使用 CSS 创建圆球
通过 CSS 的 border-radius 属性可以将元素变成圆形:

<div class="ball"></div>
<style>
.ball {
width: 100px;
height: 100px;
border-radius: 50%;
background: radial-gradient(circle at 30% 30%, #ff0000, #aa0000);
box-shadow: inset -10px -10px 20px rgba(0,0,0,0.5);
}
</style>
使用 SVG 绘制圆球
SVG 提供矢量图形支持,适合创建可缩放的圆球:

<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="red" />
<filter id="lighting">
<feGaussianBlur stdDeviation="3" />
</filter>
</svg>
3D 圆球效果
使用 CSS 3D 变换和光照效果增强立体感:
.sphere {
width: 150px;
height: 150px;
border-radius: 50%;
background: radial-gradient(circle at 30% 30%,
#fff, #f5f5f5 40%, #ddd 60%, #333 95%);
box-shadow:
inset 0 0 20px #fff,
inset 10px 0 30px rgba(255,255,255,0.4),
inset -20px 0 30px rgba(0,0,0,0.4);
}
动画效果实现
为圆球添加弹跳动画:
const ball = document.querySelector('.ball');
let position = 0;
let velocity = 0;
const gravity = 0.2;
function animate() {
velocity += gravity;
position += velocity;
if(position > 150) {
position = 150;
velocity *= -0.8;
}
ball.style.transform = `translateY(${position}px)`;
requestAnimationFrame(animate);
}
animate();






