首页 > 解决方案 > 无法在 Ext.draw.Container 构造函数中添加精灵

问题描述

我正在尝试创建一个头像类,当在应用程序的不同部分使用时,它的大小可以不同。基本头像如下:

Ext.define('Avatar', {
    extend: 'Ext.draw.Container',
    width: 60,
    height: 60,
    sprites: [{
        type: 'circle',
        fillStyle: '#79BB3F',
        r: 30,
        x: 30,
        y: 30
    }, {
        type: 'text',
        x: 30,
        y: 30,
        text: 'AU',
        textAlign: 'center',
        textBaseline: 'middle',
        fontSize: 30
    }]
});

https://fiddle.sencha.com/#view/editor&fiddle/2ks4

为了能够制作可变大小的头像,我重写了构造函数并在那里添加了精灵,然后我可以用变量替换固定大小:

Ext.define('Avatar', {
    extend: 'Ext.draw.Container',
    width: 60,
    height: 60,
    constructor: function() {
        var me = this;
        Ext.apply(me, {
            width: 30, // Changing component size works, ...
            height: 30,
            sprites: [{ // but sprites do not work!
                type: 'circle',
                fillStyle: '#79BB3F',
                r: 30,
                x: 30,
                y: 30
            }, {
                type: 'text',
                x: 30,
                y: 30,
                text: 'AU',
                textAlign: 'center',
                textBaseline: 'middle',
                fontSize: 30
            }]
        });
        me.callParent(arguments);
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/2kv1

可以通过构造函数改变头像大小;添加精灵不起作用。我怎样才能让它工作?

标签: javascriptextjs

解决方案


改写 initComponent:

initComponent: function() {

    var sprites =[{
        type: 'circle',
        fillStyle: '#79BB3F',
        r: 30,
        x: 30,
        y: 30
    }, {
        type: 'text',
        x: 30,
        y: 30,
        text: 'AU',
        textAlign: 'center',
        textBaseline: 'middle',
        fontSize: 30
    }];

   this.setSprites(sprites);

}

推荐阅读