js实现信号波图
使用Canvas绘制信号波图
在JavaScript中,可以使用Canvas API来绘制信号波图。以下是一个简单的实现示例:
const canvas = document.getElementById('waveCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
function drawSineWave() {
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = '#0095DD';
for (let x = 0; x < width; x++) {
const y = height/2 + Math.sin(x * 0.05) * 50;
if (x === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
}
drawSineWave();
使用Web Audio API生成音频信号
Web Audio API可以用来生成和处理音频信号,并可视化波形:

const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioContext.createOscillator();
const analyser = audioContext.createAnalyser();
oscillator.connect(analyser);
analyser.connect(audioContext.destination);
oscillator.type = 'sine';
oscillator.frequency.value = 440;
analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
function drawWaveform() {
requestAnimationFrame(drawWaveform);
analyser.getByteTimeDomainData(dataArray);
ctx.fillStyle = 'rgb(200, 200, 200)';
ctx.fillRect(0, 0, width, height);
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgb(0, 0, 0)';
ctx.beginPath();
const sliceWidth = width * 1.0 / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = dataArray[i] / 128.0;
const y = v * height / 2;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
x += sliceWidth;
}
ctx.lineTo(width, height/2);
ctx.stroke();
}
oscillator.start();
drawWaveform();
使用第三方库实现高级波形
使用Wave.js等第三方库可以更简单地实现信号波图:

import Wave from 'wave.js';
const wave = new Wave({
container: document.getElementById('wave-container'),
color: '#4285F4',
progress: 0.5,
height: 100,
amplitude: 40,
speed: 0.15,
frequency: 2
});
wave.animate();
响应式信号波图实现
创建响应式信号波图,可以监听窗口大小变化并重绘:
function resizeCanvas() {
canvas.width = window.innerWidth * 0.8;
canvas.height = window.innerHeight * 0.3;
drawSineWave();
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
添加交互功能
为信号波图添加鼠标交互功能,允许用户改变波形参数:
let frequency = 0.05;
let amplitude = 50;
canvas.addEventListener('mousemove', (e) => {
frequency = e.clientX / width * 0.1;
amplitude = e.clientY / height * 100;
drawSineWave();
});
这些方法提供了从基础到高级的信号波图实现方式,可以根据具体需求选择合适的方案。Canvas API适合自定义程度高的场景,Web Audio API适合音频相关的可视化,而第三方库可以快速实现复杂效果。






