This won’t be much of a tutorial, but this is a glimpse into my initial attempt to add layers to a drawing app. This is the first time I’ve really thought keeping a state would be useful, so that’s probably the direction I’ll be moving in the future. For now, however, I’ve written some workarounds just to get it started.
Step 1 is to initiate an array of layers and add the default layer:
Most layers will be raster layers, so that’s the only type I’ll focus on for now. We create a layer object with a unique canvas, as well as coordinate and opacity information, and of course the layer’s name.
Now the onscreen canvas potentially represents multiple offscreen canvases, so we need to draw each layer whenever the onscreen canvas gets re-rendered, such as when undoing actions.
For the DOM, create a container and whenever a layer is added or in the future, when changes are made such as changing the order of layers, we create the innerHTML. This is where using state would be a much better solution, but when things are still so simple, this functions:
To relate the DOM to the layers object, we can just use the index since the DOM is drawn according to the index anyway. This might be a problem later when layers can be removed but are still part of the layers object to keep actions reversible.
This does nothing yet, just shows how to relate the DOM to the layers object.
Adding layers has led me to question the command pattern that I’ve been using for undo/redo functionality, so it’s likely I’ll revisit that topic in a future blogpost.