当前位置:网站首页>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>
边栏推荐
- webgl_ Enter the three-dimensional world (2)
- Yunxiaoduo software internal test distribution test platform description document
- Introduction of mongod management database method
- [quick start of Digital IC Verification] 22. Ahb-sramc of SystemVerilog project practice (2) (Introduction to AMBA bus)
- OpenGL common functions
- Basic knowledge sorting of mongodb database
- After UE4 is packaged, mesh has no material problem
- XMIND frame drawing tool
- UE4 exports the picture + text combination diagram through ucanvasrendertarget2d
- 【数字IC验证快速入门】25、SystemVerilog项目实践之AHB-SRAMC(5)(AHB 重点回顾,要点提炼)
猜你喜欢
【微信小程序】Chapter(5):微信小程序基础API接口
LeetCode2_ Add two numbers
【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
unnamed prototyped parameters not allowed when body is present
15. Using the text editing tool VIM
20th anniversary of agile: a failed uprising
[quick start of Digital IC Verification] 24. AHB sramc of SystemVerilog project practice (4) (AHB continues to deepen)
[deep learning] image hyperspectral experiment: srcnn/fsrcnn
numpy--疫情数据分析案例
Use cpolar to build a business website (2)
随机推荐
webgl_ Enter the three-dimensional world (2)
Basic knowledge sorting of mongodb database
Yunxiaoduo software internal test distribution test platform description document
[quick start for Digital IC Validation] 26. Ahb - sramc (6) for system verilog project practice (Basic Points of APB Protocol)
Detailed explanation of unity hot update knowledge points and introduction to common solution principles
Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
Jacobo code coverage
Use cpolar to build a business website (2)
Matlab experience summary
[Lanzhou University] information sharing of postgraduate entrance examination and re examination
nodejs package. JSON version number ^ and~
Database exception resolution caused by large table delete data deletion
Syntax of generator function (state machine)
2022 all open source enterprise card issuing network repair short website and other bugs_ 2022 enterprise level multi merchant card issuing platform source code
【数字IC验证快速入门】25、SystemVerilog项目实践之AHB-SRAMC(5)(AHB 重点回顾,要点提炼)
Learn good-looking custom scroll bars in 1 minute
Introduction of mongod management database method
Function: JS Click to copy content function
【Markdown语法高级】让你的博客更精彩(四:设置字体样式以及颜色对照表)