如何用背景图片创建 PIXI.text

how to create PIXI.text with background image

我正在使用 PIXI,我想添加一些带有背景图片的文本对象。

var text = new PIXI.Text('my custom text',
    {
      font : '12px Arial',
      fill : 0x666666,
      align : 'center',
      cacheAsBitmap: true, // for better performance
      height: 57,
      width: 82
    });

stage.addChild(text);

PIXI.texture 是向该文本添加背景图像(如气球)的唯一方法吗?

如果是这样,请使用以下代码:

var texture = PIXI.Texture.fromImage("balloon");
text.setTexture(texture);

我收到这个错误:

Uncaught TypeError: Cannot set property 'x' of null

我做错了什么?

您不能在文本对象上设置背景图像。但是您可以轻松地将文本对象添加为 Sprite 的子对象。

NOTE: Texture 存储了表示图像的信息,但不能直接添加到显示列表中。您应该改用 PIXI.Sprite。

//Create the background Image
var sprite = PIXI.Sprite.fromImage('balloon');
sprite.position.x = 100;
sprite.position.y = 100;
stage.addChild(sprite);

//Add text as a child of the Sprite
var text = new PIXI.Text('my custom text',
    {
      font : '12px Arial',
      fill : 0x666666,
      align : 'center',
      cacheAsBitmap: true, // for better performance
      height: 57,
      width: 82
    });    
sprite.addChild(text);

您可以像这样居中对齐所有内容:

sprite.anchor.x = sprite.anchor.y = 0.5;
text.anchor.x = text.anchor.y = 0.5;