diff --git a/packages/draw/draw.mjs b/packages/draw/draw.mjs index 910ac08c..4e84878f 100644 --- a/packages/draw/draw.mjs +++ b/packages/draw/draw.mjs @@ -30,13 +30,20 @@ export const getDrawContext = (id = 'test-canvas', options) => { }; let animationFrames = {}; +function stopAnimationFrame(id) { + if (animationFrames[id] !== undefined) { + cancelAnimationFrame(animationFrames[id]); + delete animationFrames[id]; + } +} +function stopAllAnimations() { + Object.keys(animationFrames).forEach((id) => stopAnimationFrame(id)); +} Pattern.prototype.draw = function (callback, { id = 'std', from, to, onQuery, ctx } = {}) { if (typeof window === 'undefined') { return this; } - if (animationFrames[id]) { - cancelAnimationFrame(animationFrames[id]); - } + stopAnimationFrame(id); ctx = ctx || getDrawContext(); let cycle, events = []; @@ -69,9 +76,7 @@ Pattern.prototype.onFrame = function (id, fn, offset = 0) { if (typeof window === 'undefined') { return this; } - if (animationFrames[id]) { - cancelAnimationFrame(animationFrames[id]); - } + stopAnimationFrame(id); const animate = () => { const t = getTime() + offset; const haps = this.queryArc(t, t); @@ -85,7 +90,7 @@ Pattern.prototype.onFrame = function (id, fn, offset = 0) { export const cleanupDraw = (clearScreen = true) => { const ctx = getDrawContext(); clearScreen && ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.width); - Object.values(animationFrames).forEach((id) => cancelAnimationFrame(id)); + stopAllAnimations(); if (window.strudelScheduler) { clearInterval(window.strudelScheduler); } diff --git a/packages/webaudio/scope.mjs b/packages/webaudio/scope.mjs index 309b4ab7..e4b856f3 100644 --- a/packages/webaudio/scope.mjs +++ b/packages/webaudio/scope.mjs @@ -91,10 +91,13 @@ function clearScreen(smear = 0, smearRGB = `0,0,0`, ctx = getDrawContext()) { */ Pattern.prototype.fscope = function (config = {}) { let id = config.id ?? 1; - return this.analyze(id).draw(() => { - clearScreen(config.smear, '0,0,0', config.ctx); - analysers[id] && drawFrequencyScope(analysers[id], config); - }); + return this.analyze(id).draw( + () => { + clearScreen(config.smear, '0,0,0', config.ctx); + analysers[id] && drawFrequencyScope(analysers[id], config); + }, + { id }, + ); }; /** @@ -113,10 +116,13 @@ Pattern.prototype.fscope = function (config = {}) { */ Pattern.prototype.tscope = function (config = {}) { let id = config.id ?? 1; - return this.analyze(id).draw(() => { - clearScreen(config.smear, '0,0,0', config.ctx); - analysers[id] && drawTimeScope(analysers[id], config); - }); + return this.analyze(id).draw( + () => { + clearScreen(config.smear, '0,0,0', config.ctx); + analysers[id] && drawTimeScope(analysers[id], config); + }, + { id }, + ); }; Pattern.prototype.scope = Pattern.prototype.tscope;