Search code examples
cachingbitmapcreatejseaseljsundo-redo

How to draw to a cacheCanvas from a source other than the cached object in EaselJS / CreateJS?


I have a Shape that is cached and a Bitmap made from the shape's cacheCanvas. I now want to draw another Bitmap to the cacheCanvas or more particular, another Bitmap's cacheCanvas to the shape's cacheCanvas. I tried bitmap2.draw(shape.cacheCanvas) and it did not work - even though draw() says it receives a ctx and I think the shape's cacheCanvas is a ctx. It is giving me a drawImage is not a function error.

The reason I am doing this is for a drawing tool's undo functionality. I draw in the shape and blit with sourceover to a Bitmap for display and to a thumbnail Bitmap as there are multiple layers. On pressup I store a new Bitmap from the shape's cacheCanvas and cache it to remember the undo state. These give me the drawings at each pressup. To undo, I want to clear the drawing and cache it without sourceover and then draw the undo Bitmap into the shape's cache canvas. This keeps the relationship between the original shape, the original Bitmap and the thumb Bitmap. It is drawing to the shape's cacheCanvas that is the problem. Is there a way? Thanks!!

ADDED - I think I found a work-around. I can start with a Container with a Shape in it. Then blit the container to the Bitmap. Then when I want to go back to a certain stored Bitmap, I can clear the shape graphic and add the Bitmap to the container - blit that and remove the stored Bitmap. It would still be interesting to know if there is a way to write to a cacheCanvas with something other than the cached object.


Solution

  • Drawing to a cache canvas is not enough, you have to make sure to update the stage that is drawing it.

    Another approach to give you more control is to just wrap your cacheCanvas in another Stage. This lets you add content to it with the same control as the EaselJS stage. Note that it will clear the caches original contents when you update it, so its not a perfect solution. https://jsfiddle.net/lannymcnie/8yczqt05/

    var stage2 = new createjs.Stage(s.cacheCanvas);
    stage2.autoClear = false; // Keep the current cache. Just for this demo
    var s2 = new createjs.Shape();
    s2.graphics.f("blue").dc(50,50,50);
    stage2.addChild(s2);
    stage2.update();
    

    If you are making an undo/redo system you might consider a more robust solution, instead of relying on a Shape's cache. It sounds like you are already exploring a Container for the cache, hope you find success with that.

    Cheers!