Situation: I'm using HTML5 drag-and-drop to place tiles in a game I'm writing. I'd like to add an effect where the two tiles that I'm about to drop a new tile between move slightly apart to indicate that this is where you're dropping (similar to the Mac OS dock).
My Approach: I have a flexbox
into which I'm dropping these tiles. I wrote a function that essentially returns one period of a sine wave and I'm using it to update the dropped tiles' right:
and top:
CSS properties (the tiles are position: relative;
) based on their original position relative to the mouse during drag
.
// Update occupant style for desired effect
occupants.forEach(function(occupant, index) {
$(occupant).css({'right' : -10 * nudgeSine(occupantsMouseOffset[index] * 10) + 'px',
'top' : -10 * Math.abs(nudgeSine(occupantsMouseOffset[index] * 10)) + 'px',
'opacity' : 1 - Math.abs(nudgeSine(occupantsMouseOffset[index])) });
});
// Function to return 1 period of a sine wave
function nudgeSine(x) {
if (x < -3.14159 || x > 3.14159) {
return 0;
} else {
return Math.sin(x);
}
}
Problem: In Chrome (but not in Firefox), at some mouse positions, which I can't find a pattern in, the tile is jumping back-and-forth. See the .gif below:
In Chrome (left) and in Firefox (right):
I even console.log
ged the element's calculated right:
property, and while it is shown jumping around on screen, it outputs as a constant value.
What I've Tried/Thought About:
- Even with the mouse stationary and
console.log(event.clientX)
outputting a constant value, the tile will jump around. - I thought
event.clientX
might be changing imperceptibly, so I'm basing my calculations onMath.trunc(event.clientX)
to no avail. - I am using
element.getBoundingClientRect()
in my calculations, which I'm not very familiar with, and I think it may be the root cause of my problem.
I made this CodePen, but wasn't able to completely replicate the issue. Still, I think someone may be able to spot what's happening.
Edit: I've put this up on a github page to fully replicate. This link may not work for future readers of the question, but I'll keep it up for the foreseeable future. To demonstrate the issue, view in Chrome and Firefox.
Thank you.