js实现阳光
以下是几种用JavaScript实现阳光/光照效果的常见方法,可根据具体需求选择:
使用CSS滤镜和动画
通过CSS的brightness和drop-shadow滤镜结合动画实现阳光照射效果:

const sun = document.createElement('div');
sun.style.cssText = `
position: absolute;
width: 100px; height: 100px;
background: radial-gradient(circle, yellow, transparent 70%);
filter: brightness(1.5) drop-shadow(0 0 10px gold);
animation: pulse 2s infinite alternate;
`;
document.body.appendChild(sun);
// 动态添加CSS关键帧
const style = document.createElement('style');
style.textContent = `
@keyframes pulse {
from { transform: scale(1); opacity: 0.8; }
to { transform: scale(1.2); opacity: 1; }
}
`;
document.head.appendChild(style);
Canvas绘制阳光光晕
利用Canvas的径向渐变和合成模式创建更复杂的光照效果:
const canvas = document.createElement('canvas');
canvas.width = 300; canvas.height = 300;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const gradient = ctx.createRadialGradient(150, 150, 0, 150, 150, 150);
gradient.addColorStop(0, 'rgba(255,255,0,1)');
gradient.addColorStop(0.7, 'rgba(255,200,0,0.5)');
gradient.addColorStop(1, 'rgba(255,150,0,0)');
ctx.globalCompositeOperation = 'lighter';
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(150, 150, 150, 0, Math.PI * 2);
ctx.fill();
WebGL实现动态光照
使用Three.js等库创建3D阳光效果:

import * as THREE from 'three';
const scene = new THREE.Scene();
const light = new THREE.PointLight(0xffccaa, 1, 100);
light.position.set(10, 10, 10);
scene.add(light);
// 添加辉光效果
const sprite = new THREE.TextureLoader().load('glow.png');
const glow = new THREE.SpriteMaterial({
map: sprite,
color: 0xffcc66,
transparent: true,
blending: THREE.AdditiveBlending
});
const sunSprite = new THREE.Sprite(glow);
sunSprite.scale.set(5, 5, 1);
scene.add(sunSprite);
光线追踪模拟
通过光线步进算法模拟真实阳光(性能要求较高):
// 在片段着色器中实现的光线追踪示例
const shaderCode = `
uniform vec3 sunDirection;
void main() {
vec3 lightDir = normalize(sunDirection);
float intensity = max(0.0, dot(lightDir, vec3(0,1,0)));
vec3 color = mix(vec3(0.1), vec3(1.0,0.9,0.7), intensity);
gl_FragColor = vec4(color, 1.0);
}
`;
实现选择建议:
- 简单UI效果推荐CSS方案
- 游戏或交互式场景建议Canvas/WebGL
- 需要物理精确模拟时考虑光线追踪
- 移动端注意性能优化






