javascriptcreatejs

createjs removed all existing info on canvas?


I am trying to verify that this happens no matter what, and there's no way to bypass it. It seems pretty silly to me that createjs uses this architecture. But I noticed that creating a stage from an existing canvas element removes all shapes, writings, etc from the canvas? Code is below:

html:

<canvas id="canvas" width="800" height="400"></canvas>

js:

var canv = document.getElementById("canvas");
var stage = new createjs.Stage(canv);
var ctx = canv.getContext('2d');
ctx.beginPath();
ctx.arc(50,50,10,0,2*Math.PI);
ctx.stroke();
createjs.Ticker.addEventListener("tick", tick);//circle created is overwritten here!!!?! Why createjs!?
//stage.update();
createjs.MotionGuidePlugin.install();

var shape1 = new createjs.Shape();
shape1.graphics.f("#000000").dc(0,0,10);


var path1 = new createjs.Shape();
path1.graphics.beginStroke("#ff0000").mt(0,0).qt(50,100,100,0);

stage.addChild(path1, shape1);

createjs.Tween.get(shape1).to({guide:{ path:[0,0, 50,100, 100,0] }},2000, createjs.Ease.cubicInOut);


function tick(event) {
    stage.update();
}

Is this something that cannot be bypassed? It seems silly to me that createjs wouldn't just actually use the existing element unerased. If not, what is the point in passing in an element in the first place, why doesn't it just create a canvas element, and give you the ID? Anyways, if this is how it's going to be, unfortunately, I am going to have to go somewhere else. Sad, because createjs seemed pretty useful.


Solution

  • CreateJS uses a retained graphics mode, that is, it stores the state and redraws it each time. This is because the canvas is basically a big Bitmap with drawing commands – clearing the stage is the only way to remove the previous state.

    But good news! There are lots of ways to get around these limitations if you want to blend CreateJS content with other content, or even make additive drawing effects.

    The first is easy, which is setting autoClear. This will prevent the clear, and just draw the new contents over the old one.

    stage.autoClear = false;
    

    The second is a bit tougher, but great for instances where you want to mix CreateJS content with other libraries or effects. You can basically use the other canvas as the source to a Bitmap you include in CreateJS:

    // Create a child for CreateJS referencing the other canvas
    var bmp = new createjs.Bitmap(otherCanvas);
    
    // Add it at the bottom (or top or wherever) in your new CreateJS canvas
    stage.addChildAt(bmp, 0);
    

    This is a great approach because it lets you put your content wherever you want, edit it separately, etc.

    If you have a different case this doesn't cover, let me know and I can try to make a recommendation!

    Cheers.