如何在 Three.js 中居中文本网格 [英] How to center the text mesh in Three.js

查看:42
本文介绍了如何在 Three.js 中居中文本网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently building a tool with Three.js. I would like to put dots with corresponding numbers (dot count). Below code is how I implemented. (Please teach me if there are better ways)

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

To align two meshes, I relocated them so that the text (number) can be inside the center of the dot. However, the problem is that the position of the text is based on meshes left side, not the center. So that if the numbers gain more digits, they wouldn't align as I expected.

是否有更好的方法来对齐文本网格,使其位于圆心?

Is there a better way to align text mesh so that they can be on the center of the circle?

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 [意外]

推荐答案

在这种特定情况下,将圆和数字建模为 3d 对象可能有点矫枉过正.相反,您可以创建一个简单的平面并使用纹理为其添加圆圈和数字.可以使用画布元素即时创建纹理,如下所示:

In this specific case, modelling the circle and numbers as 3d-objects is probably a bit overkill. Instead, you can create a simple plane and add the circle and number to it using a texture. Textures can be created on the fly using a canvas-element, something like this:

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)})
);

这篇关于如何在 Three.js 中居中文本网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆