js实现阳光
实现阳光效果的JavaScript方法
使用Canvas绘制阳光效果是一种常见的方式。以下是一个简单的实现方法:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
function drawSun(x, y, radius, rays) {
// 绘制太阳核心
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
const gradient = ctx.createRadialGradient(x, y, 0, x, y, radius);
gradient.addColorStop(0, 'rgba(255, 255, 0, 1)');
gradient.addColorStop(1, 'rgba(255, 200, 0, 0.8)');
ctx.fillStyle = gradient;
ctx.fill();
// 绘制光线
ctx.strokeStyle = 'rgba(255, 255, 0, 0.7)';
ctx.lineWidth = 3;
for(let i = 0; i < rays; i++) {
const angle = (i / rays) * Math.PI * 2;
const rayLength = radius * 2;
const endX = x + Math.cos(angle) * rayLength;
const endY = y + Math.sin(angle) * rayLength;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(endX, endY);
ctx.stroke();
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSun(canvas.width/2, canvas.height/2, 50, 12);
requestAnimationFrame(animate);
}
animate();
添加发光效果
使用CSS可以增强阳光的视觉效果:

canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
background: linear-gradient(to bottom, #87CEEB, #E0F7FA);
}
body {
margin: 0;
overflow: hidden;
}
实现动态阳光变化
修改动画函数实现阳光大小和亮度的变化:

let scale = 1;
let growing = true;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 动态变化
if(growing) {
scale += 0.005;
if(scale > 1.2) growing = false;
} else {
scale -= 0.005;
if(scale < 0.8) growing = true;
}
drawSun(canvas.width/2, canvas.height/2, 50 * scale, 12);
requestAnimationFrame(animate);
}
使用WebGL实现更逼真效果
对于更高级的阳光效果,可以考虑使用Three.js等WebGL库:
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建太阳光源
const sunGeometry = new THREE.SphereGeometry(1, 32, 32);
const sunMaterial = new THREE.MeshBasicMaterial({color: 0xffff00});
const sun = new THREE.Mesh(sunGeometry, sunMaterial);
scene.add(sun);
// 添加辉光效果
const sunLight = new THREE.PointLight(0xffff00, 1, 100);
sunLight.position.set(0, 0, 0);
scene.add(sunLight);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
sun.rotation.x += 0.01;
sun.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
性能优化建议
对于复杂场景,考虑以下优化措施:
- 使用requestAnimationFrame进行动画循环
- 对静态元素使用缓存
- 合理设置Canvas或WebGL的尺寸
- 避免在动画循环中创建新对象
这些方法可以根据具体需求进行调整和组合,创造出不同风格的阳光效果。






