簡體   English   中英

如何僅在單擊特定元素時才執行功能?

[英]How to execute a function only when a specific element is clicked?

我希望用戶能夠觀察模型,並在單擊“立方體模式”按鈕時能夠在空間中放置立方體。 現在,我創建了一個我在three.js 網站上找到的腳本,它執行此操作,但我希望它僅在單擊上述按鈕時執行。 我創建了一個變量let j = 1; 如果單擊此按鈕,它將將其值更改為2 然后我想做這樣的事情: if (j = 2) {// Execute function} 我的場景的圖像在這里 我可以在我的函數中的什么位置插入這個條件? 還是有更好的方法來執行此任務? 我的 JavaScript 函數:

 import './style_proba.css' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'; import { PCDLoader } from 'three/examples/jsm/loaders/PCDLoader' let camera, controls, scene, renderer; let plane; let pointer, raycaster, isShiftDown = false; let rollOverMesh, rollOverMaterial; let cubeGeo, cubeMaterial; const objects = []; let cubeBtn = document.getElementById("cubeBtn"); init(); //render(); // remove when using next line for animation loop (requestAnimationFrame) animate(); function init() { let j = 1; // This will be a variable that change its value according to the clicked button console.log(j) if (cubeBtn.onclick = function(){ console.log("IVA"); j = 2; console.log(j) }); scene = new THREE.Scene(); scene.background = new THREE.Color(0xcccccc); // scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 ); renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setPixelRatio(window.devicePixelRatio / 2); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); camera.position.set(0, 0, 100); // controls controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled controls.dampingFactor = 0.05; controls.screenSpacePanning = false; controls.maxDistance = 1000; controls.maxPolarAngle = Math.PI / 2; // PCD load const loader = new PCDLoader(); loader.load('./material/Pointcloud_Atrium_5cm.pcd', function point(points) { console.log(points.geometry.position) points.geometry.center(); //points.geometry.rotateZ(10); points.rotation.x = Math.PI; points.rotation.z = -0.02; points.scale.x = 6; points.scale.y = 6; points.scale.z = 6; points.position.y = 10; scene.add(points); render(); animate(); }) // lights const dirLight1 = new THREE.DirectionalLight(0xffffff); dirLight1.position.set(1, 1, 1); scene.add(dirLight1); const dirLight2 = new THREE.DirectionalLight(0x002288); dirLight2.position.set(- 1, - 1, - 1); scene.add(dirLight2); const ambientLight = new THREE.AmbientLight(0x222222); scene.add(ambientLight); // roll-over helpers let boxFace = 10; const rollOverGeo = new THREE.BoxGeometry(boxFace, boxFace, boxFace); rollOverMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, opacity: 0.5, transparent: true }); rollOverMesh = new THREE.Mesh(rollOverGeo, rollOverMaterial); scene.add(rollOverMesh); // raycaster = new THREE.Raycaster(); pointer = new THREE.Vector2(); // const planeGeometry = new THREE.PlaneGeometry(150, 250); plane = new THREE.Mesh(planeGeometry, new THREE.MeshBasicMaterial({ visible: false })); scene.add(plane); plane.rotateX(-Math.PI/2) plane.position.setY(-20) objects.push(plane); // eventListeners document.addEventListener('pointermove', onPointerMove); document.addEventListener('click', click); document.addEventListener('keydown', onDocumentKeyDown); document.addEventListener('keyup', onDocumentKeyUp); document.addEventListener("click", onImageLoad); } // Functions function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function onPointerMove(event) { pointer.set((event.clientX / window.innerWidth) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1); raycaster.setFromCamera(pointer, camera); const intersects = raycaster.intersectObjects(objects, false); if (intersects.length > 0) { const intersect = intersects[0]; rollOverMesh.position.copy(intersect.point).add(intersect.face.normal); rollOverMesh.position.divideScalar(10).floor().multiplyScalar(10).addScalar(5); } } function click(event) { pointer.set((event.clientX / window.innerWidth) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1); raycaster.setFromCamera(pointer, camera); const intersects = raycaster.intersectObjects(objects, false); if (intersects.length > 0) { const intersect = intersects[0]; // delete cube if (isShiftDown) { if (intersect.object !== plane) { scene.remove(intersect.object); objects.splice(objects.indexOf(intersect.object), 1); } // create cube } else{ // cubes cubeGeo = new THREE.BoxGeometry(10, 10, 10); cubeMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff }) const voxel = new THREE.Mesh(cubeGeo, cubeMaterial); voxel.position.copy(intersect.point).add(intersect.face.normal); voxel.position.divideScalar(30).floor().multiplyScalar(30).addScalar(15); scene.add(voxel); objects.push(voxel); } // animate(); } } // Functions for SHIFT key press (the first is press and the second release) function onDocumentKeyDown(event) { switch (event.keyCode) { case 16: isShiftDown = true; break; } } function onDocumentKeyUp(event) { switch (event.keyCode) { case 16: isShiftDown = false; break; } } function render() { renderer.render(scene, camera); } function animate() { requestAnimationFrame(animate); controls.update(); render(); }
 <!DOCTYPE html> <html lang="en"> <head> <title>My project</title> <link rel="stylesheet" href="style_proba.css"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <div class="container"></div> </head> <body> <div class="header"> <h1>Header</h1> <p>Resize the browser window to see the responsive effect.</p> </div> <div class="row"> <div class="column"> <h2>Main Content</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p> </div> </div> <ul> <li><a class="active" href="#home">Home</a></li> <li><a href="#Panoramic Tour">Panoramic Tour</a></li> <li><a id="cubeBtn" href="#Insert Cubes">Insert Cubes</a></li> <li><a href="#Photos">Photos</a></li> <li><a href="#Audios">Audios</a></li> <li><a href="#Videos">Videos</a></li> </ul> <div id="canvas" class="canvas"> <script type="module" src="./main.js"></script> </div> </body> </html>

好吧,您可以嘗試這樣的事情

<button onclick='myfunction'></button>

你可以在這里定義函數

let j=1;

let myfunction=()=>{
  if (j===2){
    Secondfunction()
  }
  else {
    j=+1;
    // or j=1+1;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM