<html>
<head>
<script type="text/javascript" src="libs/three.js"></script>
<script type="text/javascript" src="libs/OBJLoader.js"></script>
<script type="text/javascript">
var scene = null
var camera = null
var renderer = null
var mesh = null
var id = null
function init() {
renderer = new THREE.WebGLRenderer({//渲染器
canvas: document.getElementById('mainCanvas')//画布
})
renderer.setClearColor(0x000000)//画布颜色
scene = new THREE.Scene()//创建场景
camera = new THREE.OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100)//正交投影照相机
camera.position.set(15, 25, 25)//相机位置
camera.lookAt(new THREE.Vector3(0, 2, 0))//lookAt()设置相机所看的位置
scene.add(camera)//把相机添加到场景中
var loader = new THREE.OBJLoader()//在init函数中,创建loader变量,用于导入模型
loader.load('libs/port.obj', function(obj) {//第一个表示模型路径,第二个表示完成导入后的回调函数,一般我们需要在这个回调函数中将导入的模型添加到场景中
obj.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.side = THREE.DoubleSide
}
})
mesh = obj//储存到全局变量中
scene.add(obj)//将导入的模型添加到场景中
})
var light = new THREE.DirectionalLight(0xffffff)//光源颜色
light.position.set(20, 10, 5)//光源位置
scene.add(light)//光源添加到场景中
id = setInterval(draw, 20)//每隔20s重绘一次
}
function draw() {//们在重绘函数中让茶壶旋转:
renderer.render(scene, camera)//调用WebGLRenderer的render函数刷新场景
mesh.rotation.y += 0.01//添加动画
if (mesh.rotation.y > Math.PI * 2) {
mesh.rotation.y -= Math.PI * 2
}
}
</script>
</head>
<body onload="init()">
<canvas id="mainCanvas" width="800px" height="600px" ></canvas>
</body>
</html>
three.js创建地图的方法:
1.定义html页面
<!DOCTYPE html>
<html>
<head>
<title>Three.js Step Tutorial</title>
<style>
body {
margin: 0px
background-color: #fff
overflow: hidden
}
</style>
</head>
<body>
<script src="js/three.min.js"></script>
<script src="js/three-tut.js"></script>
</body>
</html>
2、编写动画脚本anotation.js
var camera定义相机
var scene定义场景画布
var renderer定义渲染入口
var mesh定义恢复
init()初始化画布
animate()开始动画
函数定义
function init() {
scene = new THREE.Scene()
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000)
var light = new THREE.DirectionalLight( 0xffffff )
light.position.set( 0, 1, 1 ).normalize()
scene.add(light)
var geometry = new THREE.CubeGeometry( 10, 10, 10)
var material = new THREE.MeshPhongMaterial( { ambient: 0x050505, color: 0x0033ff, specular: 0x555555, shininess: 30 } )
mesh = new THREE.Mesh(geometry, material )
mesh.position.z = -50
scene.add( mesh )
renderer = new THREE.WebGLRenderer()
renderer.setSize( window.innerWidth, window.innerHeight )
document.body.appendChild( renderer.domElement )
window.addEventListener( 'resize', onWindowResize, false )
render()
}
function animate() {
mesh.rotation.x += .04
mesh.rotation.y += .02
render()
requestAnimationFrame( animate )
}
function render() {
renderer.render( scene, camera )
}
形状变换
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize( window.innerWidth, window.innerHeight )
render()
}
3、运行以上程序,效果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)