three.js CSS3DRenderer如何控制字体大小

时间:2019-12-09 07:14:21

标签: javascript css three.js

我想使用threejs的CSS3DRenderer在3d视图中呈现文本, 但我无法控制字体大小,我尝试通过css设置font-size: 1px,但它仍然很大。 我也尝试将scale设置为css3dobject,但是我不知道如何计算比例。 谢谢!

这是我的代码:https://codepen.io/hungtcs/pen/xxbZOQV

import { CSS3DRenderer, CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer';
import { Scene, PerspectiveCamera, Mesh, PlaneGeometry, MeshPhongMaterial, Color, DoubleSide, NoBlending, WebGLRenderer, MeshBasicMaterial, GridHelper } from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

export class CSS3DDemo {
  private scene: Scene;
  private camera: PerspectiveCamera;
  private css3DRenderer: CSS3DRenderer;
  private webGLRenderer: WebGLRenderer;
  private controls: OrbitControls;

  constructor() {
    this.scene = new Scene();
    this.camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 500);
    this.webGLRenderer = new WebGLRenderer();
    this.css3DRenderer = new CSS3DRenderer();
    this.controls = new OrbitControls(this.camera, this.css3DRenderer.domElement);

    this.webGLRenderer.setSize(window.innerWidth, window.innerHeight);
    this.webGLRenderer.setClearColor(0xFFFFFF);
    this.css3DRenderer.setSize(window.innerWidth, window.innerHeight);
    this.css3DRenderer.domElement.style.position = 'absolute';
    this.css3DRenderer.domElement.style.top = '0px';
    this.css3DRenderer.domElement.style.left = '0px';

    this.camera.position.set(0, 0, 10);

    const div = window.document.createElement('div');
    div.innerHTML = `this is content`;
    div.style.width = '10px';
    div.style.height = '10px';
    // div.style.background = 'lightblue';
    const object = new CSS3DObject(div);
    object.position.set(0, 0, 0);
    this.scene.add(object);

    const planeGeometry = new PlaneGeometry(10, 10);
    const planeMesh = new Mesh(planeGeometry, new MeshBasicMaterial({ color: 0xFF0000, side: DoubleSide }));
    planeMesh.position.copy(object.position);
    this.scene.add(planeMesh);

    this.scene.add(this.camera);
    this.scene.add(new GridHelper(100, 100));
    window.document.body.appendChild(this.webGLRenderer.domElement);
    window.document.body.appendChild(this.css3DRenderer.domElement);
    this.render();
  }

  private render() {
    window.requestAnimationFrame(() => this.render());
    this.css3DRenderer.render(this.scene, this.camera);
    this.webGLRenderer.render(this.scene, this.camera);
    this.controls.update();
  }

}

1 个答案:

答案 0 :(得分:0)

CSS3DObject遵循CSS规则。如果要更改字体大小,只需更改div的样式:

div.style.width = '10px';
div.style.height = '10px';
div.style.fontSize = '0.5px';

要记住的是,使用CSS3DRenderer,1px是3D空间中的1个世界单位。因此,您可能需要缩小3D对象或将摄像机移回。