Search code examples
javascriptcachinghtml5-canvascreatejseaseljs

Copy Shape cache as Bitmap source image


I have an EaselJS Shape object that contains cached graphics instructions, which are really expensive. Every frame I draw more graphics into the cache using myShape.updateCache("source-overlay");, so they'll not need to be redrawn the next frame.

But I want to remove the oldest cached graphics after 1 second, so I thought about creating a buffer Bitmap object, copy the cache from myShape into buffer's image property, clear myShape current cache and continue drawing new graphics to it, then after 1 second clear the buffer.

Hard to explain, I know, but simplifying things up:

var myShape = new createjs.Shape();
var buffer = new createjs.Bitmap();

myShape.cache(0, 0, innerWidth, innerHeight);
stage.addChild(myShape, buffer);

function tick () {
    myShape.graphics.s("#F00").lt(Math.random() * 100, Math.random() * 100);
    myShape.updateCache("source-overlay");
    myShape.graphics.clear();
}
setInterval(function(){
    buffer.alpha = 1;
    buffer.image = myShape.getCacheDataURL();
    myShape.updateCache();
    createjs.Tween.get(buffer).to({alpha: 0}, 1000);
},1000);

The problem is that myShape's cache won't appear as buffer's source image. Why?


Solution

  • A quick solution from Grant Skinner for cloning a cache:

    var bmp = new createjs.Bitmap(shape.cacheCanvas)
    bmp.cache(x,y,w,h);
    var cache2 = bmp.cacheCanvas;
    

    Discussion here: https://github.com/CreateJS/EaselJS/issues/701#issuecomment-160349081