【问题标题】:How to center the text mesh in Three.js如何在 Three.js 中使文本网格居中
【发布时间】:2019-08-20 18:49:39
【问题描述】:

我目前正在使用Three.js 构建一个工具。 我想将 dots 与相应的 numbers(点数)放在一起。 下面的代码是我的实现方式。 (如果有更好的方法请教我)

为了对齐两个网格,我重新定位了它们,以便文本(数字)可以位于点的中心内。 但是,问题在于文本的位置是基于左侧的网格,而不是中心。因此,如果数字获得更多位数,它们就不会像我预期的那样对齐。

有没有更好的方法来对齐文本网格,以便它们可以位于圆的中心?

var totalDotCount = 0;
function addDotMeshToGroup(x, y) { // x,y coordinate
  ...
  // Dot
  var geometry = new THREE.CircleGeometry(0.4, 32);
  var material = new THREE.MeshBasicMaterial({color: 0xFFFF00});
  var dotMesh = new THREE.Mesh(geometry, material)

  // Number Text
  var textGeo = new THREE.TextGeometry(totalDotCount.toString(10), textParm);
  var textMesh = new THREE.Mesh(textGeo, material);

  // Relocation
  dotMesh.position.set(x, y, 0);
  textMesh.position.set(x - 0.2, y - 0.2, 0);

  totalDotCount += 1;
  ...
}

图01【预期】

图02【意外】

【问题讨论】:

    标签: three.js


    【解决方案1】:

    在这种特定情况下,将圆和数字建模为 3d 对象可能有点过头了。相反,您可以创建一个简单的平面并使用纹理向其添加圆圈和数字。可以使用 canvas-element 动态创建纹理,如下所示:

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    canvas.width = canvas.height = 256;
    
    // draw/fill the circle
    ctx.beginPath();
    ctx.arc(128, 128, 128, 0, 2 * Math.PI);
    ctx.fillStyle = 'yellow';
    ctx.fill();
    
    // draw the number
    ctx.fillStyle = 'black';
    ctx.font = '64px sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('12', 128, 128);
    
    // create mesh with texture
    const mesh = new Mesh(
      new PlaneGeometry(1,1),
      new MeshBasicMaterial({transparent: true, map: new CanvasTexture(canvas)})
    );
    

    【讨论】:

    • 非常感谢。对于我的情况,这实际上是一个更好的方法。
    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多