Using space key to pan around
freenandes opened this issue · comments
Hi! I'm trying to set the space key as the one that triggers the panning functionality. It's a bigger key and i want my visitors to be able to select the text in the content that I'm writing.
I tried a lot of combinations, the one I thought would be the best would be this one:
panzoom(element, { beforeMouseDown: function(e) { const shouldIgnore = !(e.altKey || (e.code === 'Space')); return shouldIgnore; }, });
But it doesn't work either. What's the most appropriate way to do that with this library? Thanks
You need to check if space is pressed first. This is how I solved it:
let spacebarPressed = false;
const handleSpaceBarKeydown = (e: KeyboardEvent) => {
if (e.key === ' ' || e.code === 'Space') {
if (
document.body === e.target ||
document.getElementById('scene') === e.target
) {
e.stopPropagation();
e.preventDefault();
}
spacebarPressed = true;
}
};
const handleSpaceBarKeyup = (e: KeyboardEvent) => {
if (e.key === ' ' || e.code === 'Space') {
if (
document.body === e.target ||
document.getElementById('scene') === e.target
) {
e.stopPropagation();
e.preventDefault();
}
spacebarPressed = false;
}
};
document.removeEventListener('keydown', handleSpaceBarKeydown);
document.addEventListener('keydown', handleSpaceBarKeydown);
document.removeEventListener('keyup', handleSpaceBarKeyup);
document.addEventListener('keyup', handleSpaceBarKeyup);
const sceneElement = document.querySelector('.panzoom') as HTMLElement | null;
if (sceneElement) {
const { default: panzoom } = await import('panzoom');
// And pass it to panzoom
const instance = panzoom(sceneElement as HTMLElement, {
beforeMouseDown: () => {
const shouldIgnore = !spacebarPressed;
return shouldIgnore;
},
});
}