1.5 Patterns and Promises
Today I reworked how patterns are loaded and stored.
By patterns, I mean complex objects that can be used in place of a colour for any stroke or fill. This includes CanvasGradients and CanvasPattern - which can be created from images, existing canvas drawings, and many, many other sources.
Before, patterns were synchronously loaded at the same time the code is loaded, where CanvasPattern from images were forced to use images stored in the form of dataURIs. This was not a scalable solution since storing 100 different images in code is crazy for anyone that wants to use some, but not all of the patterns. The load time would’ve also been atrocious.
The new method uses Javascript’s Promise mechanism to lazily load patterns as you need them, and makes it extremely easy to create a new pattern. For example, to create a new repeating pattern from an image:
Draw waits until all the necessary and unloaded patterns have been loaded before drawing. This means if you added 100 patterns, but are only using 1 of them, you only load the 1 you’re using and don’t end up wasting bandwidth and time loading the ones you haven’t used yet.
One consequence of making draw asynchronous is the exports that it returns might also have to be dealt with asynchronously. This can be done using:
However, this is only if you actually need the exports.
Pattern Varieties
In addition to links, you can also pass in functions for producing patterns. For example, to create a washed out jeans pattern, where there’s more wear near the knees and center of the pants, you can create a gradient:
The factory method will be given ctx and ex (exports including draw points). Methods that take only ctx will be statically cached (meaning we actually cache the produced pattern since we can create it with any context), but methods that also require exports will be dynamically cached (since we need to know the exports each time).