用three.js制作一个三角形

时间:2024-05-23 10:33:14
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <script src="../js/three.js"></script>
 7 </head>
 8 <body οnlοad="main()">
 9 <script>
10     function initTHREE(){
11         width = window.innerWidth;
12         height = window.innerHeight;
13         renderer = new THREE.WebGLRenderer({
14             antialias:true
15         });
16         renderer.setSize(width,height);
17         renderer.setClearColor("white",1.0);
18         document.body.appendChild(renderer.domElement);
19     }
20     function initCamera(){
21         camera = new THREE.PerspectiveCamera(45,width/height,1,1000);
22         camera.position.z = 30;
23 
24     }
25     function initScene(){
26         scene = new THREE.Scene();
27     }
28     function initGeometry(){
29         geometry = new THREE.Geometry();
30         var material = new THREE.LineBasicMaterial({vertexColors:true});
31 //        var p1 = new THREE.Vector3(-10,0,0);
32 //        var p2 = new THREE.Vector3(10,0,0);
33 //        var p3 = new THREE.Vector3(0,10,0);
34 //        var color1 = new THREE.Color(0xff0000);
35 //
36 //        var color2 = new THREE.Color(0xff0000);
37 //        var color3 = new THREE.Color(0xff0000);
38 //        geometry.vertices.push(p1,p2,p3,p1);
39 //        geometry.colors.push(color1,color2,color3,color1);
40         /*LineStrip表示绘制线的时候会按照你几何体push进去的点的顺序进行绘制,如上会是p1->p2->p3->p1
41             其中你的点有多少个,就必须有多少个color值,color值可以为之前定义过的color
42         */
43 //        var triangle = new THREE.Line(geometry,material,THREE.LineStrip);
44         var p1 = new THREE.Vector3(-10,0,0);
45         var p2 = new THREE.Vector3(10,0,0);
46         var p3 = new THREE.Vector3(0,10,0);
47         var color1 = new THREE.Color(0xff0000);
48         var color2 = new THREE.Color(0xff0000);
49         var color3 = new THREE.Color(0xff0000);
50         geometry.vertices.push(p1,p2,p2,p3,p3,p1);
51         geometry.colors.push(color1,color2,color3,color1,color1,color1);
52         /*
53             LinePieces表示每相邻的两个点连成一条线,其中相邻的两个点是由我们自己定义的,如上面的代码
54             p1->p2   p2->p3  p3->p1
55             这样,三条线连起来就是一个三角形,注意,颜色要和点相对应
56          */
57         var triangle = new THREE.Line(geometry,material,THREE.LinePieces);
58         scene.add(triangle);
59     }
60     function main(){
61         initTHREE();
62         initCamera();
63         initScene();
64         initGeometry();
65         //会按照上方我们定义的renderer.setClearColor来清除画布,如果不重复渲染的话,那么这个函数可要可不要
66          renderer.clear();
67         renderer.render(scene,camera);
68     }
69 </script>
70 </body>
71 </html>

 用three.js制作一个三角形