In order to understand how caching a DisplayObject
works in EaselJS, we take the example of an imaginary canvas area so that the cached elements get rendered into it and each time you need to update the target shape, you call the cache
method again.
You can see the definition of the cache
method inside the DisplayObject
class in the following piece of code:
cache (x, y, width, height, [scale=1])
Draws the display object into a new canvas, which is then used for subsequent draws. For complex content that does not change frequently (ex. a Container with many children that do not move, or a complex vector Shape), this can provide for much faster rendering because the content does not need to be re-rendered each tick. The cached display object can be moved, rotated, faded, etc freely, however if its content changes, you must manually update the cache by calling
updateCache()
orcache()
again. You must specify the cache area via the x, y, w, and h parameters. This defines the rectangle that will be rendered and cached using this display object's coordinates.
This has been taken from:
http://www.createjs.com/Docs/EaselJS/classes/DisplayObject.html#method_cache
As you can see, the cache
method accepts four mandatory and one optional parameter. The first and second parameters define the coordinate
of the cache area; the third and fourth parameters define the width and height of the cache area. Using the last parameter, you can define the scale of shape inside the cache area. By default it is set as 1
, but you can change it.
Now it's time to see an example of using the cache
method in EaselJS. The following piece of code uses the cache
method to render a circle into a canvas element:
var shape = new createjs.Shape(); shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25); shape.cache(-25, -25, 50, 50);
In the first line, we created a shape using the Shape
class, filled it with red color, and then rendered it at (0, 0)
with a radius of 25
. In the third line, you will notice the use of the cache
method. In this line, a cache area is created at -25
, -25
with a width and height of 50
.
The complete source code and result is as follows:
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> <title>Cache method in EaselJS</title> <script type='text/javascript' src='createjs.js'></script> <script type='text/javascript'> window.onload=function() { var canvas = document.getElementById("testCanvas"); var stage = new createjs.Stage(canvas); var shape = new createjs.Shape(); shape.graphics.beginFill("#ff0000").drawCircle(0, 0, 25); shape.cache(-25, -25, 50, 50); stage.addChild(shape); stage.update(); } </script> </head> <body> <canvas id="testCanvas" width="400" height="100" style="border: 1px solid black;"></canvas> </body> </html>
The above source code is the completed example of using the cache method in EaselJS. The result of this source code is as shown in the following screenshot:
3.15.137.75