当前位置:网站首页>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>
边栏推荐
- Syntax of generator function (state machine)
- MySQL bit type resolution
- 一大波开源小抄来袭
- How to deploy the super signature distribution platform system?
- VS2005 strange breakpoint is invalid or member variable value cannot be viewed
- 【数字IC验证快速入门】18、SystemVerilog学习之基本语法5(并发线程...内含实践练习)
- How to build your own super signature system (yunxiaoduo)?
- Oracle控制文件丢失恢复归档模式方法
- 从 1.5 开始搭建一个微服务框架链路追踪 traceId
- [quick start of Digital IC Verification] 25. AHB sramc of SystemVerilog project practice (5) (AHB key review, key points refining)
猜你喜欢
【微信小程序】Chapter(5):微信小程序基础API接口
【數字IC驗證快速入門】20、SystemVerilog學習之基本語法7(覆蓋率驅動...內含實踐練習)
居然从408改考自命题!211华北电力大学(北京)
[deep learning] semantic segmentation experiment: UNET network /msrc2 dataset
有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
unnamed prototyped parameters not allowed when body is present
AB package details in unity (super detail, features, packaging, loading, manager)
How to release NFT in batches in opensea (rinkeby test network)
Webgl texture
When opening the system window under UE4 shipping, the problem of crash is attached with the plug-in download address
随机推荐
Super signature principle (fully automated super signature) [Yun Xiaoduo]
2.Golang基础知识
Ida Pro reverse tool finds the IP and port of the socket server
Getting started with webgl (1)
[wechat applet] Chapter (5): basic API interface of wechat applet
Function: JS Click to copy content function
[target detection] yolov5 Runtong voc2007 data set
居然从408改考自命题!211华北电力大学(北京)
AB package details in unity (super detail, features, packaging, loading, manager)
Use of SVN
Vertex shader to slice shader procedure, varying variable
A wave of open source notebooks is coming
【数字IC验证快速入门】26、SystemVerilog项目实践之AHB-SRAMC(6)(APB协议基本要点)
Async and await
LeetCode1_ Sum of two numbers
无线传感器网络--ZigBee和6LoWPAN
[quick start of Digital IC Verification] 26. Ahb-sramc of SystemVerilog project practice (6) (basic points of APB protocol)
Please supervise the 2022 plan
When opening the system window under UE4 shipping, the problem of crash is attached with the plug-in download address
一大波开源小抄来袭