当前位置:首页 > JavaScript

js实现特效

2026-04-07 02:10:21JavaScript

实现基础动画效果

使用 requestAnimationFrame 实现平滑动画,适合连续渲染场景。示例代码:

function animate() {
  element.style.left = (parseInt(element.style.left) + 1) + 'px';
  requestAnimationFrame(animate);
}
animate();

鼠标悬停交互

通过 mouseentermouseleave 事件触发样式变化。示例:

js实现特效

element.addEventListener('mouseenter', () => {
  element.style.transform = 'scale(1.2)';
});
element.addEventListener('mouseleave', () => {
  element.style.transform = 'scale(1)';
});

滚动视差效果

监听 scroll 事件,调整不同图层移动速度。关键代码:

window.addEventListener('scroll', () => {
  const scrollY = window.scrollY;
  background.style.transform = `translateY(${scrollY * 0.5}px)`;
  foreground.style.transform = `translateY(${scrollY * 0.2}px)`;
});

Canvas 粒子系统

利用 Canvas 绘制动态粒子效果。基础结构:

js实现特效

const ctx = canvas.getContext('2d');
function drawParticle(x, y, radius) {
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.fill();
}
// 粒子更新逻辑需结合 requestAnimationFrame

SVG 路径动画

通过修改 stroke-dashoffset 实现描边动画:

const path = document.querySelector('path');
const length = path.getTotalLength();
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length;

// 动画触发后逐渐减少 offset
function animatePath() {
  path.style.strokeDashoffset -= 5;
  if (offset > 0) requestAnimationFrame(animatePath);
}

WebGL 3D 效果

使用 Three.js 库快速创建 3D 场景:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);

// 添加立方体并动画旋转
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

function animate() {
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
  requestAnimationFrame(animate);
}
animate();

标签: 特效js
分享给朋友:

相关文章

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue-r…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。 &…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

vue实现动画特效

vue实现动画特效

Vue 实现动画特效的方法 Vue 提供了多种方式实现动画特效,主要通过内置组件和第三方库结合 CSS 或 JavaScript 完成。以下是常见的实现方法: 使用 Vue 内置过渡组件 Vue 的…

js 实现日历

js 实现日历

实现日历的基本思路 日历的核心功能是展示日期,并允许用户进行日期选择或导航。JavaScript 可以动态生成日历的 HTML 结构,并处理用户交互逻辑。 基础日历结构 日历通常包含头部(显示月份和…