当前位置:首页 > JavaScript

js实现圆球

2026-03-14 05:22:29JavaScript

使用 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);
}

动画效果实现

为圆球添加弹跳动画:

js实现圆球

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();

标签: 圆球js
分享给朋友:

相关文章

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…

js实现下拉菜单

js实现下拉菜单

使用HTML和CSS创建基础结构 HTML部分需要包含一个触发下拉的按钮和隐藏的下拉菜单内容: <div class="dropdown"> <button class="dr…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…