-
Notifications
You must be signed in to change notification settings - Fork 0
/
oscilloscope.js
252 lines (210 loc) · 7.41 KB
/
oscilloscope.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// oscilloscope.js
let animationFrameId;
let oscilloscopeParams = {};
let time = 0;
let charge = 0.0001;
let current = 0.001;
let dataPoints = [];
let timeData = [];
let canvas, ctx;
// Toggle states for plotting
let showCurrent = true;
let showVoltage = true;
let showPower = true;
// Function to update oscilloscope parameters from script.js
function updateOscilloscopeParameters(params) {
console.log('Updating oscilloscope parameters:', params);
oscilloscopeParams = params;
// No need to reset simulation here; it will be called separately if needed
}
// Initialize the oscilloscope
function initOscilloscope() {
canvas = document.getElementById('oscilloscope');
console.log('Initializing oscilloscope...');
if (!canvas) {
console.error('Canvas element with id "oscilloscope" not found.');
return;
}
ctx = canvas.getContext('2d');
if (!ctx) {
console.error('Failed to get 2D context from canvas.');
return;
}
console.log('Canvas and context initialized.');
// Resize canvas to fit container
resizeCanvas();
// Handle window resize
window.addEventListener('resize', resizeCanvas);
// Start the simulation
resetSimulation();
}
// Function to resize the canvas responsively
function resizeCanvas() {
if (!canvas.parentElement) return;
const parentWidth = canvas.parentElement.clientWidth;
canvas.width = parentWidth - 50; // Adjust for padding/margin
canvas.height = parentWidth * 0.6; // Maintain aspect ratio
console.log(`Canvas resized to ${canvas.width}x${canvas.height}`);
}
// Reset the simulation
function resetSimulation() {
cancelAnimationFrame(animationFrameId);
time = 0;
charge = 0.0001;
current = 0.001;
dataPoints = [];
timeData = [];
simulate();
}
// Simulation loop using Euler's method
function simulate() {
if (!oscilloscopeParams || Object.keys(oscilloscopeParams).length === 0) {
// Parameters not set yet, wait for script.js to set them
animationFrameId = requestAnimationFrame(simulate);
return;
}
const { inductanceBase, inductanceVariationPercent, omega_p, capacitance, resistance, dt, maxDataPoints } = oscilloscopeParams;
// Apply Euler's method
const deltaL = (inductanceVariationPercent / 100) * inductanceBase;
const inductance = inductanceBase + deltaL * Math.sin(omega_p * time);
const dCurrent = (-resistance * current - charge / capacitance) / inductance;
// Update current and charge
current += dCurrent * dt;
charge += current * dt;
// Calculate voltage across the capacitor
const voltage = charge / capacitance;
// Calculate power
const power = current * current * resistance;
// Store current, voltage, and power for plotting
dataPoints.push({ current, voltage, power });
timeData.push(time);
if (dataPoints.length > maxDataPoints) {
dataPoints.shift();
timeData.shift();
}
// Draw oscilloscope
drawOscilloscope();
// Increment time
time += dt;
// Continue simulation
animationFrameId = requestAnimationFrame(simulate);
}
// Function to draw the oscilloscope plot
function drawOscilloscope() {
if (!ctx) {
console.error('Canvas context is undefined.');
return;
}
// Clear canvas
ctx.fillStyle = 'black'; // Set background color to black
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw zero line
ctx.strokeStyle = '#888';
ctx.beginPath();
ctx.moveTo(0, canvas.height / 2);
ctx.lineTo(canvas.width, canvas.height / 2);
ctx.stroke();
// Determine scaling for current, voltage, and power
const quantitiesToShow = [];
if (showCurrent) quantitiesToShow.push('current');
if (showVoltage) quantitiesToShow.push('voltage');
if (showPower) quantitiesToShow.push('power');
const allValues = quantitiesToShow.flatMap(q => dataPoints.map(point => point[q]));
const maxAmplitude = Math.max(...allValues.map(Math.abs)) || 1;
const yScale = (canvas.height / 2) / maxAmplitude;
// Draw each waveform
quantitiesToShow.forEach(quantity => {
let color;
switch (quantity) {
case 'current':
color = 'lime';
break;
case 'voltage':
color = 'yellow';
break;
case 'power':
color = 'red';
break;
}
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i < dataPoints.length; i++) {
const x = (i / (oscilloscopeParams.maxDataPoints - 1)) * canvas.width;
const y = (canvas.height / 2) - (dataPoints[i][quantity] * yScale);
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
});
// Draw dynamic axis labels
const maxTime = timeData.length > 0 ? timeData[timeData.length - 1] : 0;
drawAxisLabels(maxAmplitude, maxTime);
// Draw legend
drawLegend();
}
// Function to draw dynamic axis labels directly on the canvas
function drawAxisLabels(maxAmplitude, maxTime) {
if (!ctx) {
console.error('Canvas context is undefined.');
return;
}
ctx.fillStyle = 'white';
ctx.font = '12px Arial';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
// Y-axis labels
for (let i = -2; i <= 2; i++) {
let y = canvas.height / 2 - (i * (canvas.height / 4));
let amplitudeValue = (i * maxAmplitude / 2).toFixed(2);
ctx.fillText(`${amplitudeValue}`, 5, y);
}
// X-axis labels at the bottom
ctx.textAlign = 'center';
ctx.textBaseline = 'alphabetic';
for (let i = 0; i <= 4; i++) {
let x = (canvas.width / 4) * i;
let timeValue = (maxTime * (i / 4)).toFixed(3);
ctx.fillText(`${timeValue} s`, x, canvas.height - 5);
}
}
// Function to draw legend
function drawLegend() {
let items = [];
if (showCurrent) items.push({ color: 'lime', label: 'Current (A)' });
if (showVoltage) items.push({ color: 'yellow', label: 'Voltage (V)' });
if (showPower) items.push({ color: 'red', label: 'Power (W)' });
const legendHeight = items.length * 15 + 10;
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(10, 10, 120, legendHeight);
ctx.font = '12px Arial';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
items.forEach((item, index) => {
ctx.fillStyle = item.color;
ctx.fillText(`— ${item.label}`, 20, 15 + index * 15);
});
}
// Initialize the oscilloscope on DOMContentLoaded
document.addEventListener('DOMContentLoaded', () => {
initOscilloscope();
// Handle toggle switches
const toggleCurrentCheckbox = document.getElementById('toggleCurrent');
const toggleVoltageCheckbox = document.getElementById('toggleVoltage');
const togglePowerCheckbox = document.getElementById('togglePower');
toggleCurrentCheckbox.addEventListener('change', () => {
showCurrent = toggleCurrentCheckbox.checked;
});
toggleVoltageCheckbox.addEventListener('change', () => {
showVoltage = toggleVoltageCheckbox.checked;
});
togglePowerCheckbox.addEventListener('change', () => {
showPower = togglePowerCheckbox.checked;
});
});
// Expose functions to global scope
window.resetSimulation = resetSimulation;
window.updateOscilloscopeParameters = updateOscilloscopeParameters;