欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

threejs:绘制一条直线

程序员文章站 2022-05-23 12:28:59
...

补充:renderer.setClearColor可以改变背景颜色 

	//创建场景
	var scene = new THREE.Scene();
	var scene = new THREE.Scene();
	//创建相机
	var camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000);
	//创建渲染器
	var renderer = new THREE.WebGLRenderer();
	//设置背景颜色
	renderer.setClearColor(0xffffff);

threejs:绘制一条直线

threejs:绘制一条直线
注意:只有canvasRender才能渲染线条宽度

threejs:绘制一条直线


<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>画一条线</title>
	<script type="text/javascript" src="three.js"></script>
	<script type="text/javascript" src="three.min.js"></script>
<style type="text/css">
	div#canvas-frame{
		border: none;
		cursor: pointer;
		width: 100%;
		height: 600px;
		background-color: gray;
	}
</style>
<script type="text/javascript">
	var renderer;
	function initThree(){
		width = document.getElementById('canvas-frame').clientWidth;
		height = document.getElementById('canvas-frame').clientHeight;
		renderer = new THREE.WebGLRenderer( {antialias:true} );//打开抗锯齿
		renderer.setSize(width,height);
		document.getElementById('canvas-frame').appendChild(renderer.domElement);
		renderer.setClearColor(0xfffffff,1.0);
	}

	var camera;
	function initCam(){
		camera = new THREE.PerspectiveCamera( 75,width/height,1,10000 );
		camera.position.x = 0;
		camera.position.y = 0;
		camera.position.z = 1000;
	}

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

	var light;
	function initLight(){
		light = new THREE.DirectionalLight( 0xff0000, 1.0 );
		light.position.set(100,100,200);
		scene.add(light);
	}

	var cube;
	function initObject(){
		var geometry = new THREE.Geometry();
		var material = new THREE.LineBasicMaterial({vertexColors:true});
		/*参数是元组形式,如果默认不使用顶点颜色,则是白色
		  {vertexColors:false,color:0xff0000}可以使线条变成红色
		*/
		var color1 = new THREE.Color(0x444444);
		var color2 = new THREE.Color(0xff0000);
		/*三维空间中的一个点由三个坐标表示,如果不定义
		  p1和p2都为零。下面的geometry,即几何体,是由顶点构成的
		  这儿传入两个顶点,构成了一条线,如果传入三个,可以构成
		  一个三角形
		*/
		var p1 = new THREE.Vector3(-300, 0, 0);
		var p2 = new THREE.Vector3(300, 0, 0);
		// var p3 = new THREE.Vector3(0, -100, 0);
		geometry.vertices.push(p1);
		geometry.vertices.push(p2);
		// geometry.vertices.push(p3);
		geometry.colors.push(color1,color2);//对应p1和p2的颜色,中间点使用颜色插值

		var line = new THREE.Line(geometry,material,THREE.LineSegments);
		//lineSegments表示各个点连接的方式,这儿是分段。也可以使用其他参数。
		scene.add(line);
	}

	function threeStart(){
		initThree();
		initCam();
		initScene();
		initLight();
		initObject();
		renderer.clear();
		renderer.render(scene,camera);
	}
</script>
</head>
<body οnlοad="threeStart();">
	<div id="canvas-frame"></div>
</body>
</html>

理解的都写在注释里了,不理解的还在学习中。

相关标签: 前端