graphics.js

import * as PIXI from 'pixi.js';
import Utility from './utility';

/**
 * PIXI.Graphics를 조금 더 쉽게 사용하기 위해 제작된 클래스
 * @alias Graphics
 */
export default class Graphics {
  /**
   * @description PIXI.Graphics를 자체 생성하고 전달받은 Pixi에 등록시킨다.
   * @param {PIXI} pixi PIXI 오브젝트
   */
  constructor(pixi) {
    /**
     * @description 실제 PIXI.Graphics의 오브젝트
     * @type { PIXI.Graphics }
     */
    this.object = new PIXI.Graphics();

    /**
     * @description PIXI.Graphics에서 쓰일 색상 0x000000 (16진수)
     * @type { number }
     */
    this.color = 0x000000;

    /**
     * @description PIXI.Graphics에서 쓰일 투명도 0.0 ~ 1.0
     * @type { number }
     */
    this.alpha = 1;
    pixi.stage.addChild(this.object);
  }

  /**
   * Graphics.drawRect의 사용을 간략화
   * @param {number} x x 좌표
   * @param {number} y y 좌표
   * @param {number} width 가로 길이
   * @param {number} height 세로 길이
   * @memberof Graphics
   * @instance
   */
  drawRect(x, y, width, height) {
    this.object.beginFill(this.color, this.alpha);
    this.object.drawRect(x, y, width, height);
    this.object.endFill();
  }

  /**
   * Graphics 상호작용 적용여부
   * @param {boolean} value 적용여부
   * @memberof Graphics
   * @instance
   */
  setInteractive(value) {
    this.object.interactive = value;
  }

  /**
   * Graphics 색상 변경
   * @param {array} rgb  [r,g,b] 형식의 rgb값
   * @memberof Graphics
   * @instance
   */
  setColor(rgb) {
    this.color = Utility.rgb2hex(rgb);
    this.colorRGB = rgb;
  }

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

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