Dotting seems to lag a little when there are many pixels to render.
It seems that the nested for loop that is run when render()
is called is the main culprit of the lag.
I believe optimization will be achievable if we separate the Dotting component into many layers, thus Separation of Concerns
First, we could have a grid layer. This layer will show the grids of the pixels.
Instead of running a nested for loop for this grid layer, we could simply change the grid when there is a change in data, and use canvas transform
api to better the performance.
Below that grid layer, we can have an interaction layer. This layer will be used for the pixels the user is interacting with her mouse. We can render the this.strokedPixels
just by running a for loop in this.strokedPixels
and render them in the οΏ½interaction layer. Once the user moves her mouse outside of the canvas element or has triggered a mouseup, then this layer will be empty and the changes will be applied to the layer below, the data layer.
Below the interaction layer, we can have the data layer. This layer is the layer that will show the pixel data. This is the only part where we will need to run a nested for loop. However, the nested for loop will be only run once when the data has changed. If there are no changes in the data and the user is simply panning and zooming, we can use the canvas transform
api to better the performance.
Below the data layer, we can have a background layer. This layer will show the background of Dotting. This will be the easiest layer to implement.
Having four layers, the grid layer, the interaction layer, the data layer, and the background layer will be enough to optimize the performance. But for user customization we can also add a custom layer, the layer at the bottom, where users can manipulate the canvas. This can be a feature that users would want because some users would like to place an image behind the pixel grid canvas and draw it.
Also, having these multiple layers can lessen the complexity of our canvas logic since it will separate each feature into smaller parts. This will enhance the readability of our current code!