其他分享
首页 > 其他分享> > three.js学习:三维空间下的直线

three.js学习:三维空间下的直线

作者:互联网

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <script src="js/three.min.js"></script>
    <style>
        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            /*background-color: blue;*/
        }
    </style>
</head>
<body>
<canvas></canvas>
</body>
<script src="js/chapter2.1.js"></script>
</html>

 

chapter2.1.js

1、步骤概述:初始化渲染器 > 初始化相机 > 初始化场景 > 建立几何图形并添加到场景中 > 渲染

function threeStart() {
    initThree(); 
    initCamera();
    initScene();
    initObject();
    renderer.clear();
    renderer.render(scene, camera);
}
threeStart();

2、初始化渲染器

var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var renderer;
function initThree() {
    renderer = new THREE.WebGLRenderer({
        canvas : canvas,
        antialias : true
    });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(0xffffff, 1);
}

3、初始化相机

var camera;
function initCamera() {
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.x = 0;
    camera.position.y = 0;
    camera.position.z = 1000;
    camera.up.x = 0;
    camera.up.y = 1;
    camera.up.z = 0;
    camera.lookAt(0, 0, 0);
}

4、初始化场景

var scene;
function initScene () {
    scene = new THREE.Scene();
}

5、生成几何图行并添加到场景中

var line;
function initObject() {
    //定义两个顶点
    var p1 = new THREE.Vector3(-100, -100, 0);
    var p2 = new THREE.Vector3(100, 100, 0);

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial({vertexColors:THREE.VertexColors });
    geometry.vertices.push(p1);
    geometry.vertices.push(p2);

    var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0xFF0000 );
    geometry.colors.push(color1, color2);
    line = new THREE.Line(geometry, material, THREE.LineSegments);
    scene.add(line);
}

执行效果:

因为实例化材质的时候,用了vertexColors:THREE.VertexColors参数,因此直线的颜色是根据顶点的颜色渐变的。

 

标签:canvas,THREE,three,window,camera,三维空间,var,new,js
来源: https://www.cnblogs.com/wsfu/p/10357346.html