当前位置:网站首页>Three. Introduction to JS learning notes 17: mouse control of 3D model rotation of JSON file
Three. Introduction to JS learning notes 17: mouse control of 3D model rotation of JSON file
2022-07-07 15:49:00 【Jiang Duoduo_ Mostly Harmless 】
Reference learning
https://blog.csdn.net/tuoxinquyu/article/details/72391797
One . Mouse control principle :
When the mouse is pressed, the horizontal coordinate of the current mouse clientX1, It is constantly triggered during the movement of the mouse onMouseMove event , Keep recording the current coordinates of the mouse clientX2, Subtract the last horizontal coordinate recorded from the current coordinate ,
And pay the current coordinate to the previous one clientX1, Calculate the difference between two coordinates clientX2-clientX1,
Divide the difference by a constant ( This constant can be adjusted according to your own needs ), Get the angle of rotation
Two . Core code :
function init() {
// load json Model , Put the model in group1 in
var loaderC1 = new THREE.ObjectLoader();
loaderC1.load("json/che0312.json", function(obj1) {
obj1.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.side = THREE.DoubleSide;
}
});
obj1.scale.multiplyScalar(50);
mesh1 = new THREE.Mesh();
mesh1.name="Me1";
mesh1.add(obj1);
group1.add(mesh1);
scene.add(group1);
renderer.render(scene, camera);
});
// Event monitoring
document.addEventListener( 'mousedown', onMouseDown, false );
document.addEventListener( 'mouseup', onMouseup, false );
}
// Mouse events
var rotateStart;
rotateStart = new THREE.Vector2();
function onMouseDown(event){
// Block browser default Events . What is the default event , For example, the browser's default right-click menu 、a Tag default connection jump
event.preventDefault();
mouseDown = true;
//clientX The event property returns the mouse pointer to the browser page when the event is triggered ( Or customer area ) The horizontal coordinates of . The client area refers to the current window .
mouseX = event.clientX;// The horizontal coordinate of the mouse pointer when the event is triggered
rotateStart.set( event.clientX, event.clientY );
document.addEventListener( 'mousemove', onMouseMove2, false );
}
function onMouseup(event){
// When the mouse is released
mouseDown = false;
// Remove the operation of mouse movement
document.removeEventListener("mousemove", onMouseMove2);
}
function onMouseMove2(event){
// If the mouse is not pressed , Termination operation
if(!mouseDown){
return;
}
//event.clientX Is the current move , Constantly recording mouse X coordinate .mouseX It is the mouse that records the starting point of rotation for the first time when the mouse is pressed X coordinate , With every move ,mouseX It is constantly updated to the coordinate point after the last move
var deltaX = event.clientX - mouseX;
mouseX = event.clientX;// I understand that , Every unit of distance is assigned , As the starting point of the next move
// In this way, the mouse can be pressed to the right or left , The model moves with it
rotateScene(deltaX);
}
// Set the model rotation speed , You can adjust it according to your own needs
function rotateScene(deltaX){
// Set the rotation direction to be opposite to the moving direction , So I added a minus sign . Without a minus sign is moving forward
// var deg = -deltaX/279;
var deg = deltaX/279;
//deg Set the radian of model rotation Accumulate on the basis of the original rotation
group1.rotation.y += deg;
render();
}
function render() {
renderer.render(scene, camera);
}
3、 ... and . Model rotation
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>threejs Mouse movement controls model rotation </title>
</head>
<body>
<script type="text/javascript" src="js/three.js"></script>
<!--<script src="http://jsrun.it/assets/a/q/3/W/aq3Wl" type="text/javascript"></script>-->
<!--<script src="js/CanvasRenderer.js"></script>
<script src="js/Projector.js"></script>
<script src="js/DDSLoader.js"></script>
<script src="js/MTLLoader.js"></script>-->
<script src="js/OBJLoader.js"></script>
<!-- <script src="js/jquery-2.1.1.min.js"></script>
<script src="https://raw.githack.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.js"></script> -->
<script>
var camera, scene, renderer, geometry, material, mesh, mesh1;
var pivot5, pivot6;
var group = new THREE.Group();
var group1 = new THREE.Group();
init();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(20, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(15,15,15);
// camera.lookAt(new THREE.Vector3(0,0,0));
camera.lookAt( scene.position );
// camera.position.z = 500;
// camera.position.y = 100;
scene.add(camera);
// Axis assist
var axes = new THREE.AxisHelper(500);
scene.add(axes);
// Rendering
renderer = new THREE.WebGLRenderer({
antialias: true });
renderer.setClearColor( 0xffffcc );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add ambient light
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
// Add directional rays
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
//json Model
var loaderC1 = new THREE.ObjectLoader();
loaderC1.load("json/che0312.json", function(obj1) {
obj1.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.side = THREE.DoubleSide;
}
});
obj1.scale.multiplyScalar(50);
mesh1 = new THREE.Mesh();
mesh1.name="Me1";
mesh1.add(obj1);
group1.add(mesh1);
scene.add(group1);
renderer.render(scene, camera);
});
// monitor
document.addEventListener( 'mousedown', onMouseDown, false );
document.addEventListener( 'mouseup', onMouseup, false );
}//init end
var rotateStart;
rotateStart = new THREE.Vector2();
/* Mouse movement control model rotation idea : When the mouse is pressed, the horizontal coordinate of the current mouse clientX1, It is constantly triggered during the movement of the mouse onMouseMove event , Keep recording the current coordinates of the mouse clientX2, Subtract the last horizontal coordinate recorded from the current coordinate , And pay the current coordinate to the previous one clientX1, Calculate the difference between two coordinates clientX2-clientX1, Divide the difference by a constant ( This constant can be adjusted according to your own needs ), Get the angle of rotation */
function onMouseDown(event){
event.preventDefault();
// When the mouse is pressed , Record the horizontal coordinates when the mouse is pressed
mouseDown = true;
mouseX = event.clientX;// The horizontal coordinate of the mouse pointer when starting the event
// When the mouse is pressed , Set the starting point of rotation as the coordinate of mouse click
rotateStart.set( event.clientX, event.clientY );
// When the mouse is held down , Conduct mousemove In operation , perform ononMouseMove2 function , That is to say
// Calculate the difference
document.addEventListener( 'mousemove', onMouseMove2, false );
}
function onMouseup(event){
// When the mouse is released
mouseDown = false;
// Remove the operation of mouse movement
document.removeEventListener("mousemove", onMouseMove2);
}
function onMouseMove2(event){
// If the mouse is not pressed , Termination operation
if(!mouseDown){
return;
}
//event.clientX Is the current move , Constantly recording mouse X coordinate .mouseX It is the mouse that records the starting point of rotation for the first time when the mouse is pressed X coordinate , With every move ,mouseX It is constantly updated to the coordinate point after the last move
var deltaX = event.clientX - mouseX;
mouseX = event.clientX;// I understand that , Every unit of distance is assigned , As the starting point of the next move
// In this way, the mouse can be pressed to the right or left , The model moves with it
rotateScene(deltaX);
}
// Set the model rotation speed , You can adjust it according to your own needs
function rotateScene(deltaX){
// Set the rotation direction to be opposite to the moving direction , So I added a minus sign . Without a minus sign is moving forward
// var deg = -deltaX/279;
var deg = deltaX/279;
//deg Set the radian of model rotation Accumulate on the basis of the original rotation
group1.rotation.y += deg;
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
Four . Multi axis rotation +2 A model
There is no single model selected , At present, the two can only be together , Try again in the next article
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>threejs Mouse movement controls model rotation </title>
</head>
<body>
<script type="text/javascript" src="js/three.js"></script>
<!--<script src="http://jsrun.it/assets/a/q/3/W/aq3Wl" type="text/javascript"></script>-->
<!--<script src="js/CanvasRenderer.js"></script>
<script src="js/Projector.js"></script>
<script src="js/DDSLoader.js"></script>
<script src="js/MTLLoader.js"></script>-->
<script src="js/OBJLoader.js"></script>
<!-- <script src="js/jquery-2.1.1.min.js"></script>
<script src="https://raw.githack.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.js"></script> -->
<script>
var camera, scene, renderer, geometry, material, mesh, mesh1, mesh2;
var pivot5, pivot6;
var group = new THREE.Group();
var group1 = new THREE.Group();
var group2 = new THREE.Group();
init();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(20, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(15,15,15);
camera.lookAt( 0,0,0 );
// camera.lookAt(new THREE.Vector3(0,0,0));
// camera.lookAt( scene.position );
// camera.position.z = 500;
// camera.position.y = 100;
scene.add(camera);
// Axis assist
var axes = new THREE.AxisHelper(500);
scene.add(axes);
// Rendering
renderer = new THREE.WebGLRenderer({
antialias: true });
renderer.setClearColor( 0xffffcc );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add ambient light
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
// Add directional rays
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
//json Model
var loaderC1 = new THREE.ObjectLoader();
loaderC1.load("json/che0312.json", function(obj1) {
obj1.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.side = THREE.DoubleSide;
}
});
obj1.scale.multiplyScalar(50);
mesh1 = new THREE.Mesh();
mesh1.name="Me1";
mesh1.add(obj1);
group1.add(mesh1);
scene.add(group1);
renderer.render(scene, camera);
});
var loaderC2 = new THREE.ObjectLoader();
loaderC2.load("json/che0312.json", function(obj2) {
obj2.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.side = THREE.DoubleSide;
}
});
obj2.scale.multiplyScalar(50);
mesh2 = new THREE.Mesh();
mesh2.name="Me2";
mesh2.add(obj2);
group2.add(mesh2);
scene.add(group2);
group2.position.set(5,0,0);
renderer.render(scene, camera);
});
// monitor
document.addEventListener( 'mousedown', onMouseDown, false );
document.addEventListener( 'mouseup', onMouseup, false );
}//init end
var rotateStart;
rotateStart = new THREE.Vector2();
/* Mouse movement control model rotation idea : When the mouse is pressed, the horizontal coordinate of the current mouse clientX1, It is constantly triggered during the movement of the mouse onMouseMove event , Keep recording the current coordinates of the mouse clientX2, Subtract the last horizontal coordinate recorded from the current coordinate , And pay the current coordinate to the previous one clientX1, Calculate the difference between two coordinates clientX2-clientX1, Divide the difference by a constant ( This constant can be adjusted according to your own needs ), Get the angle of rotation */
function onMouseDown(event){
event.preventDefault();
// When the mouse is pressed , Record the horizontal coordinates when the mouse is pressed
mouseDown = true;
mouseX = event.clientX;// The horizontal coordinate of the mouse pointer when starting the event
mouseY = event.clientY;
// When the mouse is pressed , Set the starting point of rotation as the coordinate of mouse click
rotateStart.set( event.clientX, event.clientY );
// When the mouse is held down , Conduct mousemove In operation , perform ononMouseMove2 function , That is to say
// Calculate the difference
document.addEventListener( 'mousemove', onMouseMove2, false );
}
function onMouseup(event){
// When the mouse is released
mouseDown = false;
// Remove the operation of mouse movement
document.removeEventListener("mousemove", onMouseMove2);
}
function onMouseMove2(event){
// If the mouse is not pressed , Termination operation
if(!mouseDown){
return;
}
//event.clientX Is the current move , Constantly recording mouse X coordinate .mouseX It is the mouse that records the starting point of rotation for the first time when the mouse is pressed X coordinate , With every move ,mouseX It is constantly updated to the coordinate point after the last move
var deltaX = event.clientX - mouseX;
var deltaY = event.clientY - mouseY;
mouseX = event.clientX;// I understand that , Every unit of distance is assigned , As the starting point of the next move
// In this way, the mouse can be pressed to the right or left , The model moves with it
mouseY = event.clientY;
rotateScene(deltaX,deltaY);
}
// Set the model rotation speed , You can adjust it according to your own needs
function rotateScene(deltaX,deltaY){
// Set the rotation direction to be opposite to the moving direction , So I added a minus sign . Without a minus sign is moving forward
// var deg = -deltaX/279;
var deg1 = deltaX/100;
var deg2 = deltaY/100;
//deg Set the radian of model rotation Accumulate on the basis of the original rotation
group1.rotation.y += deg1;
group1.rotation.x += deg2;
group1.rotation.z += deg2;
group2.rotation.y += deg1;
group2.rotation.x += deg2;
group2.rotation.z += deg2;
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
5、 ... and . The complete code of the reference case is reproduced
Reference cases come from :
https://blog.csdn.net/tuoxinquyu/article/details/72391797
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>threejs Mouse movement controls model rotation </title>
</head>
<body>
<script src="js/threejs/three.js"></script>
<!--<script src="http://jsrun.it/assets/a/q/3/W/aq3Wl" type="text/javascript"></script>-->
<script src="js/threejs/renderers/CanvasRenderer.js"></script>
<script src="js/threejs/renderers/Projector.js"></script>
<script src="js/threejs/DDSLoader.js"></script>
<script src="js/threejs/MTLLoader.js"></script>
<script src="js/threejs/OBJLoader.js"></script>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="https://raw.githack.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.js"></script>
<script>
var camera, scene, renderer, geometry, material, mesh;
var pivot5, pivot6;
init();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 500;
camera.position.y = 100;
scene.add(camera);
// Axis assist
var axes = new THREE.AxisHelper(500);
scene.add(axes);
renderer = new THREE.WebGLRenderer({
antialias: true });
renderer.setClearColor( 0xffffcc );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
// Add ambient light
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
// Add directional rays
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
// load obj 、 texture of material 、 Mapping
var onError = function ( xhr ) {
};
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var texture = new THREE.Texture();
var loader = new THREE.OBJLoader();
loader.setPath( 'models/' );
pivot5 = new THREE.Object3D();
// Import obj Model
loader.load( 'tree.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
// Enlarge the model 40 times
var n=40;
child.scale.x =n;
child.scale.y =n;
child.scale.z =n;
}
} );
pivot5.position.x = -100;
pivot5.position.z = 100;
object.position.x = 0;
object.position.z = 0;
object.position.y = 50;
//scene.add( object );
pivot5.add(object);
}, onProgress, onError );
// Import map
var cubemtlLoader = new THREE.MTLLoader();
cubemtlLoader.setPath( 'models/' );
pivot6 = new THREE.Object3D();
cubemtlLoader.load( 'cube.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'models/' );
objLoader.load( 'cube.obj', function ( object ) {
var n= 20;
object.scale.x =n;
object.scale.y =n;
object.scale.z =n;
// Modify the coordinate point of the rotation axis , The default is (0,0,0);
pivot6.position.x = 100;
pivot6.position.z = 100;
object.position.x = 0;
object.position.z = 0;
object.position.y = 100;
pivot6.add(object);
render();
}, onProgress, onError );
});
scene.add(pivot5);
scene.add(pivot6);
document.body.appendChild(renderer.domElement);
document.addEventListener( 'mousedown', onMouseDown, false );
document.addEventListener( 'mouseup', onMouseup, false );
}
var rotateStart;
rotateStart = new THREE.Vector2();
/* Mouse movement control model rotation idea : When the mouse is pressed, the horizontal coordinate of the current mouse clientX1, It is constantly triggered during the movement of the mouse onMouseMove event , Keep recording the current coordinates of the mouse clientX2, Subtract the last horizontal coordinate recorded from the current coordinate , And pay the current coordinate to the previous one clientX1, Calculate the difference between two coordinates clientX2-clientX1, Divide the difference by a constant ( This constant can be adjusted according to your own needs ), Get the angle of rotation */
function onMouseDown(event){
event.preventDefault();
mouseDown = true;
mouseX = event.clientX;// The horizontal coordinate of the mouse pointer when starting the event
rotateStart.set( event.clientX, event.clientY );
document.addEventListener( 'mousemove', onMouseMove2, false );
}
function onMouseup(event){
mouseDown = false;
document.removeEventListener("mousemove", onMouseMove2);
}
function onMouseMove2(event){
if(!mouseDown){
return;
}
var deltaX = event.clientX - mouseX;
mouseX = event.clientX;
rotateScene(deltaX);
}
// Set the model rotation speed , You can adjust it according to your own needs
function rotateScene(deltaX){
// Set the rotation direction to be opposite to the moving direction , So I added a minus sign
var deg = -deltaX/279;
//deg Set the radian of model rotation
pivot5.rotation.y += deg;
pivot6.rotation.y += deg;
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
边栏推荐
- LeetCode3_ Longest substring without duplicate characters
- Annexb and avcc are two methods of data segmentation in decoding
- [wechat applet] Chapter (5): basic API interface of wechat applet
- Steps to create P8 certificate and warehousing account
- Oracle控制文件丢失恢复归档模式方法
- 写一篇万字长文《CAS自旋锁》送杰伦的新专辑登顶热榜
- Oracle control file loss recovery archive mode method
- The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service
- 2. Heap sort "hard to understand sort"
- Runnable是否可以中断
猜你喜欢
【数字IC验证快速入门】23、SystemVerilog项目实践之AHB-SRAMC(3)(AHB协议基本要点)
Configure mongodb database in window environment
Vite path alias @ configuration
居然从408改考自命题!211华北电力大学(北京)
HW初级流量监控,到底该怎么做
Window环境下配置Mongodb数据库
MySQL bit type resolution
Do you know the relationship between the most important indicators of two strong wind control and the quality of the customer base
Super simple and fully automated generation super signature system (cloud Xiaoduo minclouds.com cloud service instance), free application in-house test app distribution and hosting platform, maintenan
Cocos creator collision and collision callback do not take effect
随机推荐
【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
Configure mongodb database in window environment
Gd32 F3 pin mapping problem SW interface cannot be burned
TS typescript type declaration special declaration field number is handled when the key key
【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)
How to deploy the super signature distribution platform system?
Three. JS introductory learning notes 04: external model import - no material obj model
After UE4 is packaged, mesh has no material problem
避坑:Sql中 in 和not in中有null值的情况说明
Iterator and for of.. loop
What are the safest securities trading apps
[original] all management without assessment is nonsense!
[quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)
Super signature principle (fully automated super signature) [Yun Xiaoduo]
Jacobo code coverage
Runnable是否可以中断
The "go to definition" in VS2010 does not respond or prompts the solution of "symbol not found"
Steps to create P8 certificate and warehousing account
Wechat applet 01
【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)