DOM Text

/**
 * A DOM Text Game Object. It makes efficient innerText updates and can resize automatically.
 *
 * @class DOMText
 * @extends Phaser.GameObjects.DOMElement
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs.
 * @param {number} x - The horizontal position of this Game Object in the world.
 * @param {number} y - The vertical position of this Game Object in the world.
 * @param {string} element - The type of DOM element to create, e.g. 'div' or 'span'.
 * @param {string} style - The CSS style string to apply to the DOM element, e.g. 'color: red; font-size: 16px;'.
 * @param {string} innerText - The initial text content of the DOM element.
 * @param {boolean} [autoSize=true] - Whether to automatically resize this Game Object when the text changes.
 */
class DOMText extends Phaser.GameObjects.DOMElement {
    constructor(scene, x, y, element, style, innerText, autoSize = true) {
        // DOMElement() -> setElement(element, style, innerText) -> updateSize().
        super(scene, x, y, element, style, innerText);

        /**
         * Whether to automatically resize this Game Object when the text changes.
         *
         * Set this to `false` if you've given the DOM element a fixed size in CSS.
         *
         * @property {boolean} autoSize
         */
        this.autoSize = autoSize;

        /**
         * Whether the DOM node needs a text update this frame.
         *
         * @property {boolean} _dirty
         * @private
         */
        this._dirty = false;

        /**
         * The current text value.
         *
         * @property {string} _text
         * @private
         */
        this._text = innerText;
    }

    /**
     * The innerText content of this Game Object.
     *
     * @property {string} text
     */
    set text(value) {
        if (this._text !== value) {
            this._text = value;
            this._dirty = true;
        }
    }

    get text() {
        return this._text;
    }

    preRender() {
        super.preRender();

        if (this._dirty && this.node) {
            this.node.innerText = this._text;
            this._dirty = false;

            if (this.autoSize) {
                this.updateSize();
            }
        }
    }
}

/**
 * Adds a DOM Text Game Object to the Scene.
 *
 * Use `this.add.domText()`.
 *
 * @method Phaser.GameObjects.GameObjectFactory#domText
 */
Phaser.GameObjects.GameObjectFactory.register('domText', function (x, y, element, style, innerText, autoSize) {
    var gameObject = new DOMText(this.scene, x, y, element, style, innerText, autoSize);

    this.displayList.add(gameObject);

    return gameObject;
});
2 Likes