Skip to content

Instantly share code, notes, and snippets.

@joeng03
Created June 21, 2020 08:34
Show Gist options
  • Save joeng03/a9c0c2299cf33c8ba649343aab0e1ec3 to your computer and use it in GitHub Desktop.
Save joeng03/a9c0c2299cf33c8ba649343aab0e1ec3 to your computer and use it in GitHub Desktop.
function move(element,direction,duration=1000){
var elStyle = window.getComputedStyle(element);
var x_coord= elStyle.getPropertyValue('left').replace("px", "");
var y_coord= elStyle.getPropertyValue('top').replace("px", "");
var x_frameDistance = direction[0]/ (duration / 10);
var y_frameDistance = direction[1] / (duration / 10);
function moveAFrame() {
elStyle = window.getComputedStyle(element);
x_coord = elStyle.getPropertyValue('left').replace("px","");
var x_newLocation = Number(x_coord) + x_frameDistance;
y_coord = elStyle.getPropertyValue('top').replace("px", "");
var y_newLocation = Number(y_coord) + y_frameDistance;
if(x_newLocation<=0||x_newLocation>=width){
x_frameDistance*=-1;
}
else if(y_newLocation<=0||y_newLocation>=height){
y_frameDistance*=-1;
}
else{
element.style['left'] = x_newLocation + "px";
element.style['top'] = y_newLocation + "px";
}
}
var movingFrames = setInterval(moveAFrame, 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment