当前位置:首页 > JavaScript

js实现特效

2026-04-07 02:10:21JavaScript

实现基础动画效果

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

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

鼠标悬停交互

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

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 绘制动态粒子效果。基础结构:

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 场景:

js实现特效

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
分享给朋友:

相关文章

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整数…