初识Three.js

生成一个三角形

参考链接


<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>My first three.js app</title>
    <style>
        body { margin: 0; }
    </style>
</head>

<body>
    <script type="module">
        // 引入three.js
        import * as THREE from 'https://unpkg.com/three/build/three.module.js';

        // Our Javascript will go here.
        // 创建一个渲染器
        const renderer = new THREE.WebGLRenderer();
        // 设置渲染器的大小
        renderer.setSize( window.innerWidth, window.innerHeight );
        // 将渲染器的实际渲染元素(也就是canvas)添加到body中
        document.body.appendChild( renderer.domElement );

        // 创建一个相机(透视相机)
        const camera = new THREE.PerspectiveCamera( 20, window.innerWidth / window.innerHeight, 1, 500 );
        // 设置相机的初始位置
        camera.position.set( 0, 0, 100 );
        // 设置相机的朝向(这里也就是上100的高度看向原点)
        camera.lookAt( 0, 0, 0 );

        // 创建一个场景
        const scene = new THREE.Scene();

        // 创建线条基本材质
        const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
        const points = [];
        points.push( new THREE.Vector3( - 10, 0, 0 ) ); // 三角形的左下角
        points.push( new THREE.Vector3( 0, 10, 0 ) );   // 三角形的顶点
        points.push( new THREE.Vector3( 10, 0, 0 ) );   // 三角形的右下角
        points.push( new THREE.Vector3( -10, 0, 0 ) );  // 回到三角形的左下角

        // 通过点创建线条
        // BufferGeometry 用于创建一个无顶点索引的几何体对象
        const geometry = new THREE.BufferGeometry().setFromPoints( points );
        // 通过线条基本材质和线条几何体创建线条
        const line = new THREE.Line( geometry, material );
        // 将线条添加到场景中
        scene.add( line );
        // 渲染场景
        renderer.render( scene, camera );
    </script>
</body>

</html>
posted @ 2023-05-04 11:00  脆皮鸡  阅读(42)  评论(0)    收藏  举报