Trying to manage 10.000 simple shapes on a <canvas>
, I experimented with caching as a replacement for redrawing. Much to my surprise:
- Using
ImageData
andcanvas.{get|put}Image
seems terribly slow. - Caching patterns with
canvas.createPattern
is nearly as quick as redrawing. - Caching an entire canvas for each shape is even quicker than redrawing.
For some reason, however, some canvases break during caching. After some lookups, at irregular intervals (every 2-5 cache lookups), a canvas is retrieved that causes an
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
to be thrown. I am using the same code for caching the different objects, so I think the problem is not the caching, but rather the number of canvas
objects.
Maybe it is also of interest that I am animating the shapes to (0,0), reducing their size as well to nothing. Errors do happen even when the rectangle is 6x3px big, for example, so it should not be about sizing.
Any idea? If no immediate idea comes up, I'll simplify the code for posting. Thanks, nobi
Trying to manage 10.000 simple shapes on a <canvas>
, I experimented with caching as a replacement for redrawing. Much to my surprise:
- Using
ImageData
andcanvas.{get|put}Image
seems terribly slow. - Caching patterns with
canvas.createPattern
is nearly as quick as redrawing. - Caching an entire canvas for each shape is even quicker than redrawing.
For some reason, however, some canvases break during caching. After some lookups, at irregular intervals (every 2-5 cache lookups), a canvas is retrieved that causes an
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
to be thrown. I am using the same code for caching the different objects, so I think the problem is not the caching, but rather the number of canvas
objects.
Maybe it is also of interest that I am animating the shapes to (0,0), reducing their size as well to nothing. Errors do happen even when the rectangle is 6x3px big, for example, so it should not be about sizing.
Any idea? If no immediate idea comes up, I'll simplify the code for posting. Thanks, nobi
Share Improve this question asked Sep 19, 2013 at 14:55 virtualnobivirtualnobi 1,1802 gold badges12 silver badges37 bronze badges 2- 3 This might give you some input: lists.w3.org/Archives/Public/public-whatwg-archive/2013Mar/… For us to be able to pin-point the error you should provide a "working" example as a fiddle. – user1693593 Commented Sep 19, 2013 at 18:47
- @Ken-AbdiasSoftware thanks for providing the link! Perfect hit! – virtualnobi Commented Sep 20, 2013 at 7:55
2 Answers
Reset to default 13In my case I have seen this error becase of zero canvas area: if width*height = 0, then such canvases give this error during drawImage.
Ken is perfectly right - although I have seen the error when the rectangle should still be 6x3, the error did not appear anymore when I animated the rectangles to size (1,1) instead of (0,0).