HTML5 Canvas Shape Caching Performance Tip
If you have a complex shape with many drawing operations, or if you're applying filters, you can improve performance by caching the shape. When you cache a shape, Konva will draw it onto an internal canvas buffer. After that, instead of redrawing the shape every time, Konva will simply use the cached version.
This is particularly useful for:
- Complex shapes with many drawing operations
- Shapes with filters
- Shapes that don't change often but need to be redrawn frequently
To cache a shape, simply call the cache()
method. You can clear the cache with clearCache()
.
How caching works?
When you call the cache()
method on a shape, Konva:
- Creates an internal canvas buffer
- Draws the shape onto this buffer
- Stores this buffer for future use
After caching, instead of redrawing the shape every time it needs to be displayed, Konva simply uses the cached version from the buffer. This is much faster than redrawing the shape repeatedly.
Guidelines
- Don't cache simple shapes without filters. It may be faster to render it dirrectly, then from cached version.
- Every cached node creates several canvas buffers. So don't overuse it, as it will consume a lot of memory.
- It is better to cache groups of shapes, then to cache each shape individually.
- Remember to always measure performance with and without caching to see the actual difference.
Below is a demo showing the performance difference between cached and non-cached complex shapes:
Instructions:
- Click anywhere on the stage to add 1000 more circles
- Toggle the checkbox to enable/disable caching
- Watch the FPS counter to see the performance difference
- The group of circles rotates continuously
- Vanilla
- React
- Vue