DOM-to-Canvas using D3
This example shows a canvas scenegraph implemented using custom namespaced DOM elements, where moving the mouse appends `custom:circle` elements that grow and fade over two seconds. A timer continuously redraws the canvas by iterating over the DOM children, mapping each element’s attributes to Canvas API calls like `beginPath` and `arc`. The code uses D3 v3’s `d3.select`, `d3.event`, `d3.timer`, and `d3.ns.prefix` to manage the custom namespace and transitions, demonstrating an alternative to SVG for customized rendering scenarios.
AI-generated descriptionMouseover to draw circles!
This is a quick proof-of-concept example demonstrating how to create a canvas scenegraph in the DOM using custom namespaced elements. The scenegraph in this example consists of a simple container sketch element and a number of child circle elements:
The browser ignores these elements because they exist in our "custom" namespace. To render them, we use a timer that iterates over the child elements and draws them to a canvas element.
Why do this? Well, if you wanted your own custom representation tailored to a specific application or domain, you can! This example demonstrates how to use the DOM to implement your own element hierarchy and render it to canvas. If you're designing a general-purpose graphical representation, though, I recommend using SVG instead. For comparison, see the original OMG Particles! example.
Implementation note: I'd prefer to use DOM Mutation Events to listen for changes to our custom elements, but browsers seem a bit sluggish in reporting them, particularly when elements are removed. If you have a slow-moving scene, you could probably get away with using mutation events rather than a timer that runs continuously. Alternatively, you could improve this example by stopping the timer after extended periods of activity.