trackball是three.js的一个组件,需要额外的引入文件,文件的地址是在官方下载的案例examples/js/controls/trackballcontrols.js。只需要和案例里面一样设置相关的属性,并在实例化的时候讲相机传入。就可以实现交互效果。本文主要给大家介绍关于three.js如何用轨迹球插件,也就是trackball增加对模型的交互功能的相关资料,需要的朋友们下面来一起看看吧。
可以实现的效果:
鼠标按住左键可以旋转模型
鼠标按住右键拖拽可以移动模型
鼠标滚轮可以缩放模型
案例代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<style type="text/css">
html, body {
margin: 0;
height: 100%;
}
canvas {
display: block;
}
</style>
</head>
<body onload="draw();">
</body>
<script src="build/three.js"></script>
<script src="examples/js/controls/trackballcontrols.js"></script>
<script>
var renderer;
function initrender() {
renderer = new three.webglrenderer({antialias:true});
renderer.setsize(window.innerwidth, window.innerheight);
document.body.appendchild(renderer.domelement);
}
var camera;
function initcamera() {
camera = new three.perspectivecamera(45, window.innerwidth/window.innerheight, 1, 10000);
camera.position.set(0, 0, 400);
}
var scene;
function initscene() {
scene = new three.scene();
}
var light;
function initlight() {
scene.add(new three.ambientlight(0x404040));
light = new three.directionallight(0xffffff);
light.position.set(1,1,1);
scene.add(light);
}
function initmodel() {
var map = new three.textureloader().load(examples/textures/uv_grid_sm.jpg);
var material = new three.meshlambertmaterial({map:map});
var cube = new three.mesh(new three.boxgeometry(100, 200, 100, 1, 1, 1), material);
scene.add(cube);
}
//用户交互插件 鼠标左键按住旋转,右键按住平移,滚轮缩放
var controls;
function initcontrols() {
controls = new three.trackballcontrols( camera );
//旋转速度
controls.rotatespeed = 5;
//变焦速度
controls.zoomspeed = 3;
//平移速度
controls.panspeed = 0.8;
//是否不变焦
controls.nozoom = false;
//是否不平移
controls.nopan = false;
//是否开启移动惯性
controls.staticmoving = false;
//动态阻尼系数 就是灵敏度
controls.dynamicdampingfactor = 0.3;
//未知,占时先保留
//controls.keys = [ 65, 83, 68 ];
controls.addeventlistener( 'change', render );
}
function render() {
renderer.render( scene, camera );
}
//窗口变动触发的函数
function onwindowresize() {
camera.aspect = window.innerwidth / window.innerheight;
camera.updateprojectionmatrix();
controls.handleresize();
render();
renderer.setsize( window.innerwidth, window.innerheight );
}
function animate() {
//更新控制器
controls.update();
render();
requestanimationframe(animate);
}
function draw() {
initrender();
initscene();
initcamera();
initlight();
initmodel();
initcontrols();
animate();
window.onresize = onwindowresize;
}
</script>
</html>
相关推荐:
两种js实现小球抛物线轨迹运动的方法
以上就是three.js用trackball插件增加对模型的交互功能的详细内容。