用 Three.js 绘制一个基本三角形

问题描述 投票:0回答:4

我正在尝试学习 Three.js 我想绘制一个基本的三角形,但是我的代码不起作用。

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 70, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 10;


var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.Geometry();
geometry.vertices= [new THREE.Vector3(2,1,0), new THREE.Vector3(1,3,0), new THREE.Vector3(3,4,0)]; 
geometry.faces = [new THREE.Face3(0,1,2)];
var mesh= new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ color: 0xffff00 }) );
scene.add(mesh);


renderer.render(scene, camera);

我哪里做错了?

javascript three.js
4个回答
10
投票

有脸

var geom = new THREE.Geometry();
var v1 = new THREE.Vector3(0, 0, 0);
var v2 = new THREE.Vector3(30, 0, 0);
var v3 = new THREE.Vector3(30, 30, 0);
var triangle = new THREE.Triangle(v1, v2, v3);
var normal = triangle.normal();
geom.vertices.push(triangle.a);
geom.vertices.push(triangle.b);
geom.vertices.push(triangle.c);
geom.faces.push(new THREE.Face3(0, 1, 2, normal));
var mesh = new THREE.Mesh(geom, new THREE.MeshNormalMaterial());
scene.add(mesh);

只是大纲

 var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-30, 2, 2));
geometry.vertices.push(new THREE.Vector3(2, 30, 2));
geometry.vertices.push(new THREE.Vector3(30, 2, 2));
geometry.vertices.push(new THREE.Vector3(-30, 2, 2));

var line = new THREE.Line(
  geometry,
  new THREE.LineBasicMaterial({ color: 0x00ff00 })
);
scene.add(line);

enter image description here


10
投票

有趣的是,找到更新的答案是多么困难,因为

Geometry
在 Three.js 的最新版本中已被弃用,我发现绘制平面三角形的方式是使用
Shape
原语。

const shape = new THREE.Shape();

const x = 0;
const y = 0;

shape.moveTo(x - 2, y - 2);
shape.lineTo(x + 2, y - 2);
shape.lineTo(x, y + 2);

const TriangleGeometry = new THREE.ShapeGeometry(shape);

基于 https://thirdjs.org/docs/index.html?q=ShapeGeometry#api/en/geometries/ShapeGeometry


5
投票

您必须小心将顶点添加到面上的顺序。如果顺序遵循顺时针顺序,则表面的法向量将指向下方。由于你的相机是从上方观察的,所以你不会看到三角形。如果顺序是逆时针,法线将指向您的相机。

如果你改变它就会起作用:

geometry.faces = [new THREE.Face3(0,1,2)];

致:

geometry.faces = [new THREE.Face3(1,0,2)];

您还可以使用参数侧,将其应用于脸部的两侧。

new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide };


4
投票

2023 年的答案。也适用于 3D 顶点坐标。

let vertices = new Float32Array([
    -1.0, -1.0, 1.0,    // vertex 1
    1.0, -1.0, 1.0,     // vertex 2
    1.0, 1.0, 1.0,      // vertex 3
]);

const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
const material = new THREE.MeshBasicMaterial({ color: 'red' });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

发布r150

© www.soinside.com 2019 - 2024. All rights reserved.