js实现灯泡
使用HTML和JavaScript实现灯泡效果
通过HTML创建灯泡的基本结构,使用CSS设置灯泡样式,JavaScript控制灯泡的开关状态。

<!DOCTYPE html>
<html>
<head>
<style>
.bulb {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: gray;
margin: 20px;
}
.bulb.on {
background-color: yellow;
box-shadow: 0 0 20px yellow;
}
</style>
</head>
<body>
<div class="bulb" id="bulb"></div>
<button onclick="toggleBulb()">开关</button>
<script>
function toggleBulb() {
const bulb = document.getElementById('bulb');
bulb.classList.toggle('on');
}
</script>
</body>
</html>
使用Canvas绘制动态灯泡
通过Canvas绘制更复杂的灯泡效果,包括发光动画。

<canvas id="bulbCanvas" width="200" height="200"></canvas>
<button onclick="toggleCanvasBulb()">开关</button>
<script>
const canvas = document.getElementById('bulbCanvas');
const ctx = canvas.getContext('2d');
let isOn = false;
function drawBulb(state) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制灯泡
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = state ? 'yellow' : 'gray';
ctx.fill();
// 发光效果
if (state) {
const gradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 70);
gradient.addColorStop(0, 'rgba(255, 255, 0, 0.8)');
gradient.addColorStop(1, 'rgba(255, 255, 0, 0)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
}
function toggleCanvasBulb() {
isOn = !isOn;
drawBulb(isOn);
}
// 初始绘制
drawBulb(false);
</script>
使用CSS动画实现闪烁效果
为灯泡添加CSS动画实现闪烁效果,模拟真实灯泡。
<style>
.bulb-animated {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: gray;
margin: 20px;
transition: all 0.3s ease;
}
.bulb-animated.on {
background-color: yellow;
box-shadow: 0 0 20px yellow;
animation: flicker 0.5s infinite alternate;
}
@keyframes flicker {
0% { opacity: 1; }
50% { opacity: 0.8; }
100% { opacity: 1; }
}
</style>
<div class="bulb-animated" id="animatedBulb"></div>
<button onclick="toggleAnimatedBulb()">开关</button>
<script>
function toggleAnimatedBulb() {
const bulb = document.getElementById('animatedBulb');
bulb.classList.toggle('on');
}
</script>
响应物理交互的灯泡
通过监听鼠标移动实现灯泡随光标亮度变化的效果。
<div class="bulb-physics" id="physicsBulb"></div>
<style>
.bulb-physics {
width: 150px;
height: 150px;
border-radius: 50%;
background-color: gray;
margin: 20px;
transition: all 0.1s ease;
}
</style>
<script>
const physicsBulb = document.getElementById('physicsBulb');
document.addEventListener('mousemove', (e) => {
const x = e.clientX;
const y = e.clientY;
const rect = physicsBulb.getBoundingClientRect();
const centerX = rect.left + rect.width/2;
const centerY = rect.top + rect.height/2;
const distance = Math.sqrt(
Math.pow(x - centerX, 2) +
Math.pow(y - centerY, 2)
);
const maxDistance = 300;
let brightness = 1 - Math.min(distance/maxDistance, 1);
physicsBulb.style.backgroundColor = `rgb(255, 255, ${Math.floor(255 * (1 - brightness))})`;
physicsBulb.style.boxShadow = `0 0 ${brightness * 30}px yellow`;
});
</script>






