【问题标题】:Center text in a container (EaselJS)在容器中居中文本(EaselJS)
【发布时间】:2013-11-08 15:50:10
【问题描述】:

我是 EaselJS 的新手,我正在尝试创建一个带有居中文本的彩色容器。这是我的代码:

var width = 100, height = 100;
canvas.width = width + 10;
canvas.height = height + 10;
var container = new c.Container();
container.x = 10;
container.y = 10;
container.setBounds(0, 0, width, height);

var rect = new c.Shape();
rect.graphics.beginFill('#6e7e8e').drawRect(0, 0, width, height);
container.addChild(rect);

var text = new c.Text();
text.set({
    text: 'hello',
    textAlign: 'center'
});
container.addChild(text);
stage.addChild(container);
stage.update();

由于某种原因,文本不在容器中居中,但有一半文本在容器外。我的代码有什么问题?

【问题讨论】:

    标签: javascript canvas easeljs createjs


    【解决方案1】:

    您的文本以添加的 x 位置为中心水平居中(在您的情况下为 x=0),这就是它在容器外一半的原因。如果您想在容器中居中放置文本,则必须自己定义位置:

    text.set({
        text: 'hello',
    });
    var b = text.getBounds();
    text.x = (width/2) - (b.width/2); 
    text.y = (height/2) - (b.height/2);
    

    【讨论】:

    • 你不想要 text.x = (width / 2) - (b.width / 2) 吗?
    • @Mister D.,如果文本“居中”和“右”对齐,如何更新文本的点击区域?
    猜你喜欢
    • 1970-01-01
    • 2014-02-18
    • 2012-12-04
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 2016-10-07
    相关资源
    最近更新 更多