text.js

import * as PIXI from 'pixi.js';

/**
 * PIXI.Text를 조금 더 쉽게 사용하기 위해 제작된 클래스
 * @alias Text
 */
export default class Text {
  /**
   * PIXI.Text를 자체 생성하고 전달받은 Pixi에 등록시킨다.
   * <p>기본적으로 anchor는 0.5로 가운데를 기본값으로 한다.
   * @param {PIXI} pixi PIXI 오브젝트
   * @param {string} text 입력하고자 하는 텍스트
   * @param {object} option PIXI.Text와 동일한 옵션
   */
  constructor(pixi, text, option) {
    /**
     * @description 실제 PIXI.Text의 오브젝트
     * @type { PIXI.Text }
     */
    this.object = new PIXI.Text(text, option);
    this.object.anchor.set(0.5);
    pixi.stage.addChild(this.object);
  }

  /**
   * Text 위치 지정 함수
   * @param {number} x x 좌표
   * @param {number} y y 좌표
   * @memberof Text
   * @instance
   */
  setPosition(x, y) {
    this.object.x = x;
    this.object.y = y;
  }

  /**
   * Text 투명도 조절 함수
   * @param {number} alpha 투명도 값 0.0 ~ 1.0
   * @memberof Text
   * @instance
   */
  setAlpha(alpha) {
    this.object.alpha = alpha;
  }

  /**
   * Text 제거 함수
   * <p> 해당 텍스트를 PIXI 오브젝트에서 removeChild 해주고 제거한다.
   * @memberof Text
   * @instance
   */
  destroy() {
    this.object.parent.removeChild(this.object);
    this.object.destroy();
  }

  /**
   * Text 크기 지정 함수
   * @param {number} scale 배율
   * @memberof Text
   * @instance
   */
  setScale(scale) {
    this.object.scale.x = scale;
    this.object.scale.y = scale;
  }

  /**
   * Text의 색상을 배경에 따라 white/black 으로 지정해주는 함수
   * @param {array} backgroundRGB [r,g,b] 형식의 배경 rgb값
   * @memberof Text
   * @instance
   */
  setColorBasedOnBackground(backgroundRGB, bright, dark) {
    const brightColor = bright || 0xffffff;
    const darkColor = dark || 0x000000;
    const brightness = Math.round(((parseInt(backgroundRGB[0], 10) * 299)
      + (parseInt(backgroundRGB[1], 10) * 587)
      + (parseInt(backgroundRGB[2], 10) * 114)) / 1000);
    this.object.style.fill = brightness > 125 ? darkColor : brightColor;
  }
}