1. 程式人生 > >three.js學習:三維空間下的直線

three.js學習:三維空間下的直線

參數 exc sce ner lan body 效果 .com htm

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參數,因此直線的顏色是根據頂點的顏色漸變的。

three.js學習:三維空間下的直線