Files
2025-04-30 20:20:13 +02:00

95 lines
2.5 KiB
JavaScript

(()=>{var api = new ModuleApi();
// Configuration with default values
var config = {
amplitude: 50,
frequency: 1,
speed: 1,
color: '#4287f5',
lineWidth: 3
};
// Get DOM elements
var container = api.dom();
var canvas = container.querySelector('#sineCanvas');
var ctx = canvas.getContext('2d');
// Animation variables
var animationId;
var startTime = Date.now();
// Initialize the canvas
function initCanvas() {
var rect = container.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
}
// Draw the sine wave
function drawSineWave() {
if (!ctx)
return;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set line style
ctx.strokeStyle = config.color;
ctx.lineWidth = config.lineWidth;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// Draw the wave
var now = Date.now();
var elapsed = (now - startTime) / 1000;
var timeOffset = elapsed * config.speed;
ctx.beginPath();
// Start from the left side of the canvas
var centerY = canvas.height / 2;
for (var x = 0; x <= canvas.width; x++) {
// Calculate the y position for each x point along the sine wave
var xValue = (x / canvas.width) * Math.PI * 2 * config.frequency;
var sineValue = Math.sin(xValue + timeOffset);
var y = centerY + sineValue * config.amplitude;
if (x === 0) {
ctx.moveTo(x, y);
}
else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
// Request the next frame
animationId = requestAnimationFrame(drawSineWave);
}
// Start the animation
function startAnimation() {
if (animationId) {
cancelAnimationFrame(animationId);
}
startTime = Date.now();
animationId = requestAnimationFrame(drawSineWave);
}
// Handle window resize
function handleResize() {
initCanvas();
drawSineWave();
}
// Setup property listeners
api.onPropertyUpdate('amplitude', function (value) {
config.amplitude = value;
});
api.onPropertyUpdate('frequency', function (value) {
config.frequency = value;
});
api.onPropertyUpdate('speed', function (value) {
config.speed = value;
});
api.onPropertyUpdate('color', function (value) {
config.color = value;
});
api.onPropertyUpdate('lineWidth', function (value) {
config.lineWidth = value;
});
// Handle resize events
api.onResize(function () {
handleResize();
});
// Initialize
window.addEventListener('load', function () {
initCanvas();
startAnimation();
});
})();