This code snippet (below) contains 2 event listeners:
renderer.domElement.addEventListener("pointerdown", changeColor, false);
document.addEventListener("keydown", changeColor, false);
Both of these event listeners trigger a color change in a cube. However, when editing the input parameter in the GUI, the 'keydown' events also cause a color change, which should be avoided.
The issue seems to arise from using document.addEventListener
for the 'keydown' events. Changing it to
renderer.domElement.addEventListener
does not work.
How can I prevent 'keydown' events from triggering during GUI parameter edits?
Code
var renderer, controls, scene, camera;
var cube;
init();
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xb0b0b0);
// Camera
camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(300, 300, 300);
camera.up.set(0, 0, 1);
// Light
var ambientLight = new THREE.AmbientLight(0xcccccc, 0.2);
scene.add(ambientLight);
// Helpers
var helpers = new THREE.Group();
var grid = new THREE.GridHelper(200, 10);
grid.rotation.x = Math.PI / 2;
var axis = THREE.AxisHelper(100);
helpers.add(grid);
helpers.add(axis);
scene.add(helpers);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
// Event listeners
controls.addEventListener("change", render, false);
// Draw the cube
var cubeGeometry = new THREE.BoxGeometry(50, 50, 50);
var cubeMaterial = new THREE.MeshBasicMaterial({color: 0x000088});
cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
scene.add(cube);
// GUI
params = {
size: 50,
};
var gui = new dat.GUI();
gui.add(params, "size", 0.0, 100, 1);
// Listeners
renderer.domElement.addEventListener("pointerdown", changeColor, false);
document.addEventListener("keydown", changeColor, false);
// Render
render();
}
function changeColor(event) {
cube.material.color.set(Math.random() * 0xffffff);
cube.material.needsUpdate = true;
render();
}
function render() {
renderer.render(scene, camera);
}