0
点赞
收藏
分享

微信扫一扫

three.js之创建坐标系网格

登高且赋 2022-08-22 阅读 101

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

canvas {
width: 100%;
height: 100%
}

div#canvas-frame {
border: none;
cursor: pointer;
width: 100%;
height: 600px;
background-color: #EEEEEE;
}
</style>
</head>
<body>
<div id="canvas-frame"></div>
<script src="../static/three.js-master/build/three.js"></script>
<script>

var renderer; // 渲染器, 声明变量

function initThree() {

renderer = new THREE.WebGLRenderer(); // 创建一个渲染器
renderer.setSize(window.innerWidth, window.innerHeight); // 设置宽度高度
document.getElementById('canvas-frame').appendChild(renderer.domElement); //添加到画布canvas-frame里面
renderer.setClearColor(0xFFFFFF, 1.0); // 设置背景色和透明度
}


var camera; // 摄像机

function initCamera() {
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500); // 创建一个透视摄像机
camera.position.set(0, 500, 0); // 设置摄像机坐标
camera.up.x = 0;
camera.up.y = 0;
camera.up.z = 1;
camera.lookAt(0, 0, 0);
}


var scene; // 场景

function initScene() {
scene = new THREE.Scene(); // 创建场景
}

var light;

function initLight() {
light = new THREE.DirectionalLight(0xFF0000, 1.0, 0); // THREE.DirectionalLight平行光可以看作距离很远的光
light.position.set(100, 100, 200); // 坐标
scene.add(light); // 添加到场景中
}


function initObject() {
var geometry = new THREE.Geometry(); // geometry为三维空间中的点集同点集闭合后的各个面的集合
// 在x轴上定义两个点p1(-500,0,0),p2(500,0,0)。
geometry.vertices.push(new THREE.Vector3(-200, 0, 0));
geometry.vertices.push(new THREE.Vector3(200, 0, 0));
// 思路:我们要画一个网格的坐标,那么我们就应该找到线的点。把网格虚拟成正方形,在正方形边界上找到几个等分点,用这些点两两连接,就能够画出整个网格来。
for (var i = 0; i <= 8; i++) {
// 这两个点决定了x轴上的一条线段,将这条线段复制20次,分别平行移动到z轴的不同位置,就能够形成一组平行的线段。
// 同理,将p1p2这条线先围绕y轴旋转90度,然后再复制20份,平行于z轴移动到不同的位置,也能形成一组平行线。
// 经过上面的步骤,就能够得到坐标网格了。
var linex = new THREE.Line(geometry, new THREE.LineBasicMaterial({color: 0x000000, opacity: 0.2}));
linex.position.z = (i * 50) - 200;
scene.add(linex);

var liney = new THREE.Line(geometry, new THREE.LineBasicMaterial({color: 0x000000, opacity: 0.2}));
liney.position.x = (i * 50) - 200;
liney.rotation.y = 90 * Math.PI / 180; // 将线旋转90度
scene.add(liney);

}
}


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

threeStart();

</script>
</body>
</html>

 附带three.js代码

three.js之创建坐标系网格_html



举报

相关推荐

0 条评论