Skip to content

Removing p5 instance before _setupDone causes canvas element to linger #6311

@donaldzhu

Description

@donaldzhu

Most appropriate sub-area of p5.js?

  • Accessibility
  • Color
  • Core/Environment/Rendering
  • Data
  • DOM
  • Events
  • Image
  • IO
  • Math
  • Typography
  • Utilities
  • WebGL
  • Build Process
  • Unit Testing
  • Internalization
  • Friendly Errors
  • Other (specify if possible)

p5.js version

1.7.0

Web browser and version

Chrome 114.0.5735.198

Operating System

OS 12.5.1

Steps to reproduce this

Steps:

  1. Create p5 Instance
  2. Remove instance before _setupDone.
  3. Check DOM to find an orphaned canvas element, despite the p5 instance controlling it has been removed.

Snippet:

const sketch = new p5(p => {
  p.setup = () => {
    p.createCanvas(200, 200)
    console.log('Setup called.')
  }
})

console.log(sketch._setupDone, sketch.canvas)
console.log(document.querySelector("canvas"))
sketch.remove()
// added timeout to allow canvas to be appended after the sketch is removed
setTimeout(() => console.log(document.querySelector("canvas")), 1000)

Essentially, when remove is called on p5 instance, it only checks if there is already an existing canvas. If there is, remove it from the DOM. But in the case where the canvas element hasn't been created yet, it simply skips the canvas removal down the line. I am not too familiar with the rendering pipeline, but there could be a flag on pInst that skips further initialization of the DOM element once remove has been called.

It was problematic for me when using p5 with react, when there are rapid initializing and removal of p5 instances where the canvas isn't created in time to be removed from the DOM.

A codepen replicating the issue:
https://codepen.io/DonaldZhu/pen/LYXMmeJ

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions