import * as THREE from "three";

export default class PureTextLabel extends THREE.Mesh {
  constructor(text, point, fontsize = 12, color = "#000000", id) {
    let res = 2;
    const width = 168 * res;
    const height = 50 * res;
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;

    let fontFamily = "Arial";
    let fs = fontsize * res;
    var context = canvas.getContext("2d");
    context.fillStyle = "transparent";
    context.rect(0, 0, width, height);
    context.fill();
    let fontStyle = "normal " + fs + "px " + fontFamily;
    // console.log("fontStyle", fontStyle);
    context.font = fontStyle;
    context.fillStyle = color;
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(text, width / 2, height / 2);
    const canvas_map = new THREE.Texture(canvas);
    canvas_map.colorSpace = THREE.SRGBColorSpace;
    canvas_map.needsUpdate = true;
    canvas_map.anisotropy = 4;

    const g = new THREE.PlaneGeometry(1.5, 0.44);
    g.rotateX(-Math.PI / 2);

    // const texture = new THREE.CanvasTexture(canvas_map);

    const m = new THREE.MeshBasicMaterial({
      map: canvas_map,
      transparent: true, // 允许材质透明
    });
    super(g, m);
    if (id) {
      this.uuid = id;
    }
    const p = new THREE.Vector3().copy(point);
    this.userData = {
      id: this.uuid,
      text: text,
      color: color,
      pos: p.toArray(),
      fontsize: fontsize,
    };
    this.position.copy(p);
    this.name = "pureText_" + text;
  }
}
