js实现led
LED 效果实现方法
使用 JavaScript 实现 LED 效果可以通过多种方式完成,以下是几种常见的方法:
HTML/CSS 结构
<div class="led" id="led"></div>
CSS 样式
.led {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: grey;
}
基础 JavaScript 控制

const led = document.getElementById('led');
let isOn = false;
function toggleLed() {
isOn = !isOn;
led.style.backgroundColor = isOn ? 'red' : 'grey';
}
// 每1秒切换一次状态
setInterval(toggleLed, 1000);
高级 LED 效果
RGB LED 实现
const colors = ['red', 'green', 'blue'];
let currentColor = 0;
function changeColor() {
led.style.backgroundColor = colors[currentColor];
currentColor = (currentColor + 1) % colors.length;
}
setInterval(changeColor, 500);
使用 Canvas 实现 LED 矩阵
HTML 结构

<canvas id="ledMatrix" width="300" height="100"></canvas>
JavaScript 代码
const canvas = document.getElementById('ledMatrix');
const ctx = canvas.getContext('2d');
const ledSize = 10;
const spacing = 5;
const rows = 5;
const cols = 20;
function drawLedMatrix() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const x = col * (ledSize + spacing);
const y = row * (ledSize + spacing);
const isActive = Math.random() > 0.7;
ctx.beginPath();
ctx.arc(x + ledSize/2, y + ledSize/2, ledSize/2, 0, Math.PI * 2);
ctx.fillStyle = isActive ? '#ff0000' : '#330000';
ctx.fill();
}
}
}
setInterval(drawLedMatrix, 100);
使用 CSS 动画增强效果
CSS 添加发光效果
.led.active {
box-shadow: 0 0 10px 5px rgba(255, 0, 0, 0.7);
animation: pulse 0.5s infinite alternate;
}
@keyframes pulse {
from { box-shadow: 0 0 5px 2px rgba(255, 0, 0, 0.7); }
to { box-shadow: 0 0 20px 10px rgba(255, 0, 0, 0.7); }
}
JavaScript 控制类切换
function toggleLed() {
led.classList.toggle('active');
}
这些方法可以根据具体需求进行组合和调整,实现从简单到复杂的各种 LED 效果。






