当前位置:网站首页>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>
边栏推荐
- Do not use memset to clear floating-point numbers
- The significance of XOR in embedded C language
- A wave of open source notebooks is coming
- webgl_ Graphic transformation (rotation, translation, zoom)
- Points for attention in porting gd32 F4 series programs to gd32 F3 series
- 【数字IC验证快速入门】19、SystemVerilog学习之基本语法6(线程内部通信...内含实践练习)
- 【数字IC验证快速入门】26、SystemVerilog项目实践之AHB-SRAMC(6)(APB协议基本要点)
- 银行需要搭建智能客服模块的中台能力,驱动全场景智能客服务升级
- Annexb and avcc are two methods of data segmentation in decoding
- There is a cow, which gives birth to a heifer at the beginning of each year. Each heifer has a heifer at the beginning of each year since the fourth year. Please program how many cows are there in the
猜你喜欢
[quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
Cocos uses custom material to display problems
Three. JS introductory learning notes 05: external model import -c4d into JSON file for web pages
无线传感器网络--ZigBee和6LoWPAN
Async and await
使用cpolar建立一个商业网站(2)
HW初级流量监控,到底该怎么做
【兰州大学】考研初试复试资料分享
[quick start for Digital IC Validation] 26. Ahb - sramc (6) for system verilog project practice (Basic Points of APB Protocol)
15. Using the text editing tool VIM
随机推荐
Starting from 1.5, build a microservice framework link tracking traceid
从 1.5 开始搭建一个微服务框架链路追踪 traceId
Matlab experience summary
What is Base64?
C Alibaba cloud OSS file upload, download and other operations (unity is available)
leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)
Getting started with webgl (2)
Learn good-looking custom scroll bars in 1 minute
Monthly observation of internet medical field in May 2022
Three. JS introductory learning notes 05: external model import -c4d into JSON file for web pages
全日制研究生和非全日制研究生的区别!
写一篇万字长文《CAS自旋锁》送杰伦的新专辑登顶热榜
Webgl texture
Simple understanding and application of TS generics
Mesh merging under ue4/ue5 runtime
webgl_ Enter the three-dimensional world (1)
Vertex shader to slice shader procedure, varying variable
Create lib Library in keil and use lib Library
How to release NFT in batches in opensea (rinkeby test network)
Use cpolar to build a business website (2)