Fix: stop media streams in p5.prototype.remove() by calling element.r… by Sanchit2662 · Pull Request #8547 · processing/p5.js

Summary

p5.prototype.remove() in src/core/main.js manually removes DOM nodes and event listeners from this._elements, but it does not call each element’s own remove() method.

Because of this, the media-specific cleanup inside p5.Element.prototype.remove() (in src/dom/dom.js) is skipped. When a sketch uses createCapture(), calling mySketch.remove() does not stop the underlying getUserMedia stream. The webcam/microphone remains active and hardware resources are not released.

The issue is caused by duplicated cleanup logic in main.js that does not include the p5.MediaElement media-stop branch.


Fix

The manual DOM + event listener cleanup loop in p5.prototype.remove() has been replaced with calls to each element’s own remove() method.

To avoid mutation issues (since element.remove() splices itself from _elements), iteration is performed over a shallow copy of the array.

By delegating cleanup to p5.Element.prototype.remove():

DOM nodes are removed as before

Event listeners are properly detached

_elements bookkeeping remains correct

Media elements now correctly stop active streams and release hardware devices

This change does not introduce new behavior — it ensures that existing element-level cleanup logic is consistently used during sketch teardown, preventing resource leaks while preserving existing functionality.