Adding Layers to A Drawing App, pt. 2
In part 1, we rendered the layers to the DOM, and now we’re going to make it so the layers can be rearranged and interacted with from the DOM.
The important lines here are the ones setting each layer element to
draggable: true and associating the actual layer object with the layer element on line 1669 by assigning it to a new property of the layer element. I called it
layerObj but you could call it anything.
Now we’re going to use drag events to change the order of the layers.
dragstart we can pass the index of the layer object being dragged through the drag events using
e.dataTransfer.setData. The other way is to set a global variable, but I find this way nicer since it means one less global variable to keep track of, and in this project there are already so many. The box shadow line is a stylistic choice. Hover events don’t trigger while the drag events are happening so we can simulate them by changing the css of elements that the dragged layer passes over. We’ll use the
dragleave for that while
dragover is simply prevented from triggering.
Doing this stops the normal hover css from working at all, but it doesn’t matter because the all the layer elements will be re-rendered once we stop dragging.
Dropping the layer onto another element, we can get the targeted layer object from the event and using
e.dataTransfer.getData we can get the index of the dragged layer. Splicing the dragged layer into a new position in the layers array, we get the index from the layers array rather than just using i, because they won’t always be the same. Only layers not flagged as removed are rendered to the DOM, but those layers will still be part of the layers array.