我使用react-three-renderer(npm,github)来构建一个three.js的场景。
我尝试使用<sprite>
和<spriteMaterial>
制作一个始终面向相机的标签,就像在stemkoski's example中一样。
但是,我无法显示标签并正确设置其坐标。我在Sprite-Label-Test处有一个最低限度可验证的完整示例。下载它,运行npm install
,然后打开_dev / public / home.html。
我的目标是将文字显示在我预期的位置,但正如您所见,它只是黑暗。为了证明精灵在相机的视野中,我把一个盒子放在同一个位置。要查看它从render方法中取消注释并重新gulp。
这是我的档案。它有两个主要组件,componentDidMount
方法,其中为精灵创建文本,以及render
方法。
var React = require('react');
var React3 = require('react-three-renderer');
var THREE = require('three');
var ReactDOM = require('react-dom');
class Simple extends React.Component {
constructor(props, context) {
super(props, context);
// construct the position vector here, because if we use 'new' within render,
// React will think that things have changed when they have not.
this.cameraPosition = new THREE.Vector3(0, 0, 100);
}
componentDidMount() {
var text = "Hello world";
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var metrics = context.measureText( text );
var textWidth = metrics.width;
context.font = "180px arial Bold";
context.fillStyle = "rgba(255,0,0,1)";
context.strokeStyle = "rgba(255,0,0,1)";
context.lineWidth = 4;
context.fillText( text, 0, 0);
var texture = new THREE.Texture(canvas)
texture.needsUpdate = true;
this.spriteMaterial.map = texture;
this.spriteMaterial.useScreenCoordinates = false;
}
render() {
const width = window.innerWidth; // canvas width
const height = window.innerHeight; // canvas height
var position = new THREE.Vector3(0, 0, 10);
var scale = new THREE.Vector3(1,1,1);
return (<React3
mainCamera="camera" // this points to the perspectiveCamera which has the name set to "camera" below
width={width}
height={height}
>
<scene>
<perspectiveCamera
name="camera"
fov={75}
aspect={width / height}
near={0.1}
far={1000}
position={this.cameraPosition}
/>
<sprite position={position} scale={scale} ref={(sprite) => this.sprite = sprite}>
<spriteMaterial ref={(spriteMaterial) => this.spriteMaterial = spriteMaterial}></spriteMaterial>
</sprite>
{/*<mesh position={position}>
<boxGeometry
width={10}
height={10}
depth={10}
/>
<meshBasicMaterial
color={0x00ff00}
/>
</mesh>*/}
</scene>
</React3>);
}
}
ReactDOM.render(<Simple/>, document.querySelector('.root-anchor'));
我做错了什么?如何在使用var position = new THREE.Vector3(0, 0, 10);
行建立的位置显示精灵文本标签?提前谢谢。
答案 0 :(得分:6)
<canvas>
上绘制的文字固定在左下角。因此,在(0,0)处绘制文本甚至不可见。它完全在画布外面(如下面的白色所示):
- context.fillText( text, 0, 0);
+ context.fillText( text, 0, 18);
这就是@df在line 147上设置绘图位置时使用fontsize
的原因。
另外,你的相机并没有看任何东西。 React-Three允许将此作为<perspectiveCamera/>
的属性。
+ lookAt={this.cameraLook}
我针对您的MVCE存储库打开了pull request。