js实现led
LED 效果的实现方法
在 JavaScript 中实现 LED 效果可以通过多种方式,以下是几种常见的实现方法:
使用 CSS 和 JavaScript 结合
通过 CSS 定义 LED 样式,JavaScript 控制状态变化:
.led {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #ccc;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.led.on {
background-color: #f00;
box-shadow: 0 0 10px #f00;
}
const led = document.querySelector('.led');
setInterval(() => {
led.classList.toggle('on');
}, 1000);
使用 Canvas 绘制动态 LED
利用 Canvas API 可以实现更复杂的 LED 效果:
const canvas = document.getElementById('ledCanvas');
const ctx = canvas.getContext('2d');
let isOn = false;
function drawLed() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(50, 50, 40, 0, Math.PI * 2);
ctx.fillStyle = isOn ? '#f00' : '#400';
ctx.fill();
ctx.shadowBlur = isOn ? 20 : 0;
ctx.shadowColor = '#f00';
}
setInterval(() => {
isOn = !isOn;
drawLed();
}, 500);
七段数码管实现
模拟七段数码管显示数字:
function drawSegment(ctx, segments, x, y, size, color) {
const segCoords = [
[[0, 0], [1, 0]], // a
[[1, 0], [1, 1]], // b
[[1, 1], [1, 2]], // c
[[0, 2], [1, 2]], // d
[[0, 1], [0, 2]], // e
[[0, 0], [0, 1]], // f
[[0, 1], [1, 1]] // g
];
ctx.strokeStyle = color;
ctx.lineWidth = size / 10;
segments.forEach((seg, i) => {
if (seg) {
ctx.beginPath();
const [start, end] = segCoords[i];
ctx.moveTo(x + start[0] * size, y + start[1] * size);
ctx.lineTo(x + end[0] * size, y + end[1] * size);
ctx.stroke();
}
});
}
// 数字0-9对应的段亮灭情况
const digitSegments = [
[1, 1, 1, 1, 1, 1, 0], // 0
[0, 1, 1, 0, 0, 0, 0], // 1
// ...其他数字
];
使用 WebGL 实现高级 LED 效果
对于需要高性能或3D效果的LED展示,可以考虑使用WebGL:
// 初始化WebGL上下文
const gl = canvas.getContext('webgl');
// 创建着色器程序
const vertexShaderSource = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0, 1);
}
`;
const fragmentShaderSource = `
precision mediump float;
uniform vec3 color;
void main() {
float dist = distance(gl_PointCoord, vec2(0.5));
float intensity = smoothstep(0.5, 0.4, dist);
gl_FragColor = vec4(color * intensity, 1.0);
}
`;
// 编译着色器并创建程序...
性能优化技巧
- 对于大量LED实例,考虑使用对象池技术复用DOM元素
- Canvas绘制时使用requestAnimationFrame替代setInterval
- WebGL实现时注意批处理绘制调用
- 对于静态LED显示,可以使用CSS滤镜提高视觉效果
交互功能扩展
为LED添加交互功能:
document.querySelectorAll('.led').forEach(led => {
led.addEventListener('click', function() {
this.classList.toggle('on');
});
});
以上方法可以根据具体需求选择使用,CSS方法适合简单场景,Canvas适合动态效果,WebGL适合高性能需求。







