当前位置:首页 > JavaScript

js实现光圈

2026-01-31 13:00:32JavaScript

实现光圈效果的JavaScript方法

在JavaScript中实现光圈效果可以通过Canvas或CSS结合动画来完成。以下是两种常见的方法:

Canvas实现光圈效果

js实现光圈

const canvas = document.getElementById('haloCanvas');
const ctx = canvas.getContext('2d');
let radius = 0;
const maxRadius = 100;

function drawHalo() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 创建径向渐变
  const gradient = ctx.createRadialGradient(
    canvas.width/2, canvas.height/2, radius * 0.7,
    canvas.width/2, canvas.height/2, radius
  );

  gradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)');
  gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');

  ctx.fillStyle = gradient;
  ctx.beginPath();
  ctx.arc(canvas.width/2, canvas.height/2, radius, 0, Math.PI * 2);
  ctx.fill();

  radius += 1;
  if (radius > maxRadius) radius = 0;

  requestAnimationFrame(drawHalo);
}

drawHalo();

CSS动画实现光圈效果

js实现光圈

<div class="halo"></div>

<style>
.halo {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  background: radial-gradient(
    circle, 
    rgba(255,255,255,0.8) 0%, 
    rgba(255,255,255,0) 70%
  );
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  70% {
    transform: scale(1.3);
    opacity: 0;
  }
  100% {
    transform: scale(0.8);
    opacity: 0;
  }
}
</style>

光圈效果增强技巧

调整颜色和透明度可以创建不同风格的光圈效果。对于更自然的效果,可以使用多层渐变:

// 多层光圈示例
function drawMultiHalo() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  for (let i = 0; i < 3; i++) {
    const currentRadius = radius + i * 20;
    const gradient = ctx.createRadialGradient(
      canvas.width/2, canvas.height/2, currentRadius * 0.6,
      canvas.width/2, canvas.height/2, currentRadius
    );

    gradient.addColorStop(0, `rgba(100, 200, 255, ${0.8 - i*0.2})`);
    gradient.addColorStop(1, 'rgba(100, 200, 255, 0)');

    ctx.fillStyle = gradient;
    ctx.beginPath();
    ctx.arc(canvas.width/2, canvas.height/2, currentRadius, 0, Math.PI * 2);
    ctx.fill();
  }

  radius += 0.5;
  if (radius > maxRadius) radius = 0;

  requestAnimationFrame(drawMultiHalo);
}

性能优化建议

对于需要频繁更新的光圈动画,考虑以下优化措施:

  • 使用requestAnimationFrame而不是setInterval
  • 尽量减少每帧绘制的操作数量
  • 对于静态光圈,可以预渲染为图像
  • 在CSS实现中,使用will-change: transform提升性能

这些方法可以根据具体需求进行调整,创建从简单到复杂的不同光圈视觉效果。

标签: 光圈js
分享给朋友:

相关文章

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <…

js 实现跳转

js 实现跳转

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

js实现轮播代码

js实现轮播代码

基础轮播实现 使用HTML、CSS和JavaScript创建一个简单的轮播效果。HTML部分定义轮播容器和图片元素。 <div class="carousel"> <div c…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…