Я могу отобразить THREE.TubeGeometry фигуру следующим образом Поэтапно дисплей Three.js TubeGeometry
код ниже, ссылка на jsbin
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.js"></script>
<script>
// global variables
var renderer;
var scene;
var camera;
var geometry;
var control;
var count = 0;
var animationTracker;
init();
drawSpline();
function init()
{
// create a scene, that will hold all our elements such as objects, cameras and lights.
scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
// create a render, sets the background color and the size
renderer = new THREE.WebGLRenderer();
renderer.setClearColor('lightgray', 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
// position and point the camera to the center of the scene
camera.position.x = 0;
camera.position.y = 40;
camera.position.z = 40;
camera.lookAt(scene.position);
// add the output of the renderer to the html element
document.body.appendChild(renderer.domElement);
}
function drawSpline(numPoints)
{
var numPoints = 100;
// var start = new THREE.Vector3(-5, 0, 20);
var start = new THREE.Vector3(-5, 0, 20);
var middle = new THREE.Vector3(0, 35, 0);
var end = new THREE.Vector3(5, 0, -20);
var curveQuad = new THREE.QuadraticBezierCurve3(start, middle, end);
var tube = new THREE.TubeGeometry(curveQuad, numPoints, 0.5, 20, false);
var mesh = new THREE.Mesh(tube, new THREE.MeshNormalMaterial({
opacity: 0.9,
transparent: true
}));
scene.add(mesh);
renderer.render(scene, camera);
}
</script>
</body>
</html>
Однако, я хотел бы дисплей постепенно, как в дуге, которая загружается, так что она начинается как начальная точка, рисуется постепенно и, наконец, выглядит позади дуги по завершении.
Я приложил некоторое усилие и смог сделать это, сохранив все точки/координаты, покрытые дугой, и нарисовал линии между последовательными координатами, чтобы я чувствовал «дуговую нагрузку постепенно». Однако есть ли лучший способ достичь этого? Это ссылка на jsbin
Добавление кода здесь, а
<!DOCTYPE html>
<html>
<head>
<title>Incremental Spline Curve</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r75/three.js"></script>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<script>
// global variables
var renderer;
var scene;
var camera;
var splineGeometry;
var control;
var count = 0;
var animationTracker;
// var sphereCamera;
var sphere;
var light;
function init() {
// create a scene, that will hold all our elements such as objects, cameras and lights.
scene = new THREE.Scene();
// create a camera, which defines where we're looking at.
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
// create a render, sets the background color and the size
renderer = new THREE.WebGLRenderer();
// renderer.setClearColor(0x000000, 1.0);
renderer.setClearColor(0xffffff, 1);
renderer.setSize(window.innerWidth, window.innerHeight);
// position and point the camera to the center of the scene
camera.position.x = 0;
camera.position.y = 40;
camera.position.z = 40;
camera.lookAt(scene.position);
// add the output of the renderer to the html element
document.body.appendChild(renderer.domElement);
// //init for sphere
// sphereCamera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 1000);
// sphereCamera.position.y = -400;
// sphereCamera.position.z = 400;
// sphereCamera.rotation.x = .70;
sphere = new THREE.Mesh(new THREE.SphereGeometry(0.8,31,31), new THREE.MeshLambertMaterial({
color: 'yellow',
}));
light = new THREE.DirectionalLight('white', 1);
// light.position.set(0,-400,400).normalize();
light.position.set(0,10,10).normalize();
//get points covered by Spline
getSplineData();
}
//save points in geometry.vertices
function getSplineData() {
var curve = new THREE.CubicBezierCurve3(
new THREE.Vector3(-5, 0, 10),
new THREE.Vector3(0, 20, 0),
new THREE.Vector3(0, 20, 0),
new THREE.Vector3(2, 0, -25)
);
splineGeometry = new THREE.Geometry();
splineGeometry.vertices = curve.getPoints(50);
animate();
}
//scheduler loop
function animate() {
if(count == 50)
{
cancelAnimationFrame(animationTracker);
return;
}
//add line to the scene
drawLine();
renderer.render(scene, camera);
// renderer.render(scene, sphereCamera);
count += 1;
// camera.position.z -= 0.25;
// camera.position.y -= 0.25;
animationTracker = requestAnimationFrame(animate);
}
function drawLine() {
var lineGeometry = new THREE.Geometry();
var lineMaterial = new THREE.LineBasicMaterial({
color: 0x0000ff
});
console.log(splineGeometry.vertices[count]);
console.log(splineGeometry.vertices[count+1]);
lineGeometry.vertices.push(
splineGeometry.vertices[count],
splineGeometry.vertices[count+1]
);
var line = new THREE.Line(lineGeometry, lineMaterial);
scene.add(line);
}
// calls the init function when the window is done loading.
window.onload = init;
</script>
<body>
</body>
</html>
недостаток: недостаток делает это выше способ является то, что, в конце концов, я рисую линию между последовательными точками , и поэтому я теряю много эффектов, возможных в TubeGeometry, таких как толщина, прозрачность и т. д.
Пожалуйста, предложите мне альтернативный способ получения плавной инкрементной нагрузки для TubeGeometry.
большое спасибо, это здорово. Я потратил некоторое время, пытаясь понять это и смог настроиться по своему вкусу (скрипку в качестве следующего комментария). У меня было несколько вопросов. Q1.I понимает nMax = geometry.attributes.position.count Что такое nMax? Моя геометрия была преобразована в 24576 точек? Определяют ли эти точки геометрию, которую я хочу нарисовать? В вашей скрипке, points.length == 18 и nMax == 245762. Q2.Вы отмечаете, что вы назначили nStep 90, потому что 30 лиц * 3 вершины/лица. Я этого не понял, твоя скрипка выглядит как тонкая кишка, я не вижу 30 лиц. :) – PepperBoy
Моя скрипка: http://jsbin.com/taqareyeqi/edit?html,js,output – PepperBoy
Дружественный совет: Изучите и поймите 'BufferGeometry'. Было бы полезно для вас это сделать. Также изучите скрипку, чтобы вы понимали каждую ее линию. (1) 'nMax' = общее количество вершин (позиций) в геометрии буфера. 'points' - временный массив, используемый для определения кривой. (2) 'nStep' теперь много дополнительных вершин для рисования каждого кадра. В этом случае каждый кадр отображает 30 дополнительных граней. (2b) Лица крошечные. Их очень много. :) – WestLangley