如何仅在单击特定元素时才执行功能?
How to execute a function only when a specific element is clicked?
我希望用户能够观察模型,并且在单击“立方体模式”按钮时能够在 space 中放置立方体。现在,我创建了一个在 three.js 网站上找到的脚本,它执行此操作,但我希望它仅在单击上述按钮时执行。
我创建了一个变量 let j = 1;
,如果单击此按钮,它会将其值更改为 2
。然后我想做这样的事情:if (j = 2) {// Execute function}
。 The image of my scene is here。我可以在我的函数中的什么地方插入这个条件?还是有更好的方法来执行此任务?
我的 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;
}
}
我希望用户能够观察模型,并且在单击“立方体模式”按钮时能够在 space 中放置立方体。现在,我创建了一个在 three.js 网站上找到的脚本,它执行此操作,但我希望它仅在单击上述按钮时执行。
我创建了一个变量 let j = 1;
,如果单击此按钮,它会将其值更改为 2
。然后我想做这样的事情:if (j = 2) {// Execute function}
。 The image of my scene is here。我可以在我的函数中的什么地方插入这个条件?还是有更好的方法来执行此任务?
我的 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;
}
}