当前位置:网站首页>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>
边栏推荐
- MongoD管理数据库的方法介绍
- Detailed explanation of unity hot update knowledge points and introduction to common solution principles
- MongoDB数据库基础知识整理
- 【数字IC验证快速入门】24、SystemVerilog项目实践之AHB-SRAMC(4)(AHB继续深入)
- How to deploy the super signature distribution platform system?
- TS as a general cache method
- LeetCode1_ Sum of two numbers
- Postman generate timestamp, future timestamp
- The difference between full-time graduate students and part-time graduate students!
- LeetCode2_ Add two numbers
猜你喜欢
Typescript release 4.8 beta
Streaming end, server end, player end
LeetCode2_ Add two numbers
Three. JS introductory learning notes 00: coordinate system, camera (temporarily understood)
Configure mongodb database in window environment
[wechat applet] Chapter (5): basic API interface of wechat applet
Use cpolar to build a business website (2)
Monthly observation of internet medical field in May 2022
【数字IC验证快速入门】22、SystemVerilog项目实践之AHB-SRAMC(2)(AMBA总线介绍)
[quick start of Digital IC Verification] 19. Basic grammar of SystemVerilog learning 6 (thread internal communication... Including practical exercises)
随机推荐
The difference between full-time graduate students and part-time graduate students!
Webgl texture
Window环境下配置Mongodb数据库
[quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
[deep learning] image hyperspectral experiment: srcnn/fsrcnn
Postman generate timestamp, future timestamp
【微信小程序】Chapter(5):微信小程序基础API接口
[quick start of Digital IC Verification] 20. Basic grammar of SystemVerilog learning 7 (coverage driven... Including practical exercises)
Learn good-looking custom scroll bars in 1 minute
The significance of XOR in embedded C language
Syntax of generator function (state machine)
Vite path alias @ configuration
Starting from 1.5, build a microservice framework link tracking traceid
Super signature principle (fully automated super signature) [Yun Xiaoduo]
【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)
Three. JS introductory learning notes 0: illustration of how webgl and threejs work
Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
有钱人买房就是不一样
How to release NFT in batches in opensea (rinkeby test network)
Please supervise the 2022 plan