What Is The Best Way To Remove/delete A Function Object Once Instantiated/drawn To Canvas?
Solution 1:
A lot of canvas libraries solve this problem by keeping an array of objects that are in the canvas scene. Every time the animate()
function is called, it loops through the list of objects and calls update()
for each one (I'm using the names you're using for simplicity).
This allows you to control what is in the scene by adding or removing objects from the array. Once objects are removed from the array, they will no longer be updated (and will get trash collected if there are no other references hanging around).
Here's an example:
const sceneObjects = [];
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
// Update every object in the scene
sceneObjects.forEach(obj => obj.update());
}
// Elsewhere...
function foo() {
// Remove an object
sceneObjects.pop();
// Add a different object
sceneObjects.push(new Circle(2, 2, 0, 1, 1, 2));
}
It's not uncommon to take this a step further by creating a Scene
or Canvas
class/object that keeps the list of scene objects and gives an interface for other parts of the program to use (for example, Scene.add(myNewCircle)
or Scene.remove(myOldCircle)
).
Post a Comment for "What Is The Best Way To Remove/delete A Function Object Once Instantiated/drawn To Canvas?"