lithiumdesign
lithiumdesign

Reputation: 95

Scale Text from it's Center

I'm very new to Canvas and easeljs and I'm trying to get text to scale in from it's center. I'm able to center the text correctly on the Canvas, but I'm not sure how to handle the scaling in the Tween.

I'm pretty sure I need to set the regx/regy, but I'm not sure exactly where and what I should have that set to.

I've made a quick jsfiddle here without any regx/regy setting, and you can see the text scales from the top-left. https://jsfiddle.net/1woLdrqt/10/

If anyone can point me in the right direction I'd be forever grateful!!

Thanks!!

<canvas id="canvas" style="display: block; background-color: #123; width: 300px; height: 200px;" width="300" height="200"></canvas>
<button id="zoomIn">Zoom In</button>
<button id="zoomOut">Zoom Out</button>

var stage = new createjs.Stage("canvas");
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", stage);

var text = new createjs.Text("hello", "900 36px Ariel", "#fff");
text.name = "myText";

var b = text.getBounds();

text.x = ( ($("#canvas").width() / 2) - (b.width / 2) ); 
text.y = ( ($("#canvas").height() / 2) - (b.height / 2) );

stage.addChild(text);

$("#zoomIn").click(function() {
    var x = stage.getChildByName("myText");
    var b = x.getBounds();

    createjs.Tween.get(x)
    .to({
        scaleX: 2,
        scaleY: 2,
    }, 2000);
});

$("#zoomOut").click(function() {
    var x = stage.getChildByName("myText");
    var b = x.getBounds();

    createjs.Tween.get(x)
    .to({
        scaleX: 1,
        scaleY: 1,
    }, 2000);
});

Upvotes: 1

Views: 457

Answers (2)

Lanny
Lanny

Reputation: 11294

Further to the answer by @Konrad, you can set the "textAlign" to "center". This is handy because if you change the text, it will flow out from the center horizontally, instead of the left. There is no equivalent for vertical text alignment (textBaseline is not quite the same), so the bounds/regY approach is good too.

Upvotes: 1

Konrad Kalemba
Konrad Kalemba

Reputation: 1229

Your thought is right. Setting regX and regY is the best approach to solve the problem. EaselJS's documentation defines these properties pretty clearly. As showed in examples provided in their descriptions you want them to be set to 50% of text's width (regX) and height (regY) dimensions.

Here is the implementation of the above in your code (JsFiddle):

var b = text.getBounds();

text.regX = b.width / 2;
text.regY = b.height / 2;

// We also don't need to correct the initial position anymore as the origin point of the text is now in its center. 
text.x = ($("#canvas").width() / 2); // - (b.width / 2)
text.y = ($("#canvas").height() / 2); // - (b.height / 2)

Upvotes: 1

Related Questions