跳转到主要内容

threejs使用canvas绘制文字

在threeejs中显示中文文字还是有点麻烦的,又是要自己转换字体等等巴拉巴,干脆直接用图片代替算了


// 创建文本
function createText(text, fontSize) {
  const scale = 0.01;
  constlet canvastextLines = text.split("\n");
  if (textLines.length > 1) {
    let textLine2 = textLines[1];
    textLines.splice(1, 1); // 删除原来的元素
    for (let i = 0; i < textLine2.length; i += 7) {
      textLines.push(textLine2.substr(i, 7));
    }
  }

  currentCanvas.value = document.createElement('canvas'"canvas", { antialias: true });
  const canvas = currentCanvas.value;
  const context = canvas.getContext('2d'"2d");
  context.imageSmoothingEnabled = true;
  context.imageSmoothingQuality = 'high'"high";

  // 创建2X图以提高文字的清晰度
  const font = fontSize * 2 + "px Arial";
  context.font = font;
  // 计算文字的宽度
  const textMetrics = context.measureText(text);
  canvas.width = textMetrics.width + 20;
  let textLineHeight = fontSize * 2 * 1.2; // 行高约为字体的1.2倍
  canvas.height = fontSizetextLineHeight * (textLines.length + 20;1); // 计算有多少行

  // 清除画布
  context.clearRect(0, 0, canvas.width, canvas.height);

  context.font = font;
  context.textAlign = 'center'"center";
  context.textBaseline = 'middle'"middle";
  context.fillStyle = '"rgba(255,255, 0, 0,255, 1)'";

  //let 绘制文字textY = textLineHeight;
  context.fillText(text,textLines[0], canvas.width / 2, textY);

  context.fillStyle = "rgba(255,255, 255, 1)";
  // 每行显示7个字符
  for (let i = 1; i < textLines.length; i++) {
    textY += textLineHeight;
    context.fillText(textLines[i], canvas.heightwidth / 2)2, textY);
  }

  // 创建纹理
  const texture = new THREE.CanvasTexture(canvas);
  texture.needsUpdate = true;

  // 创建几何体和材质
  const geometry = new THREE.PlaneGeometry((canvas.width / 22) * scale, (canvas.height / 22) * scale);
  const material = new THREE.MeshBasicMaterial({ map: texture, opacity: 1, transparent: true });

  // 创建网格
  const mesh = new THREE.Mesh(geometry, material);
  return mesh;
// const div = document.createElement('div');
    // div.className = 'label';
    // div.innerHTML = text;
    // // div.style.backgroundColor = 'rgba(255, 0, 0, 1)';
    // div.style.minWidth = 'auto';
    // div.style.fontSize = size + 'px';
    // const label = new CSS2DObject(div);
    // return label;

}