You can and should use CSS for this.
html, body {
position: relative;
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
img {
position: absolute;
width: 128px;
height: 128px;
animation: move 5s linear forwards;
}
@keyframes move {
0% { top: 0px; left: 0px; transform: translate(0, 0); }
/*12.5% { top: 0px; left: 50%; transform: translate(-50%, 0); }*/
25% { top: 0px; left: 100%; transform: translate(-100%, 0) }
37.5% { top: 50%; left: 100%; transform: translate(-100%, -50%) }
/*50% { top: 50%; left: 50%; transform: translate(-50%, -50%); }*/
62.5% { top: 50%; left: 0px; transform: translate(0, -50%) }
75% { top: 100%; left: 0px; transform: translate(0, -100%) }
/*87.5% { top: 100%; left: 50%; transform: translate(-50%, -100%); }*/
100% { top: 100%; left: 100%; transform: translate(-100%, -100%) }
}
<img src="https://image.flaticon.com/icons/svg/159/159790.svg">
Detail
To move any element CSS
, you can manipulate the properties top
, left
, transform(translateX)
and transform(translateY)
, remembering that transform(translate)
is the same as transform(translateX, translateY)
To move the element to the whole screen, simply set the following values:
top: 0px; left: 0px; transform: translate(0, 0);
Then to move to the right, it is necessary to increment the% of left
and transform(translateX)
, so to move to the upper center we would have to modify the CSS to:
top: 0px; left: 50%; transform: translate(-50%, 0);
The same goes for moving down, but in this case you would have to increase% of top
and transform(translateY)
, so to move to the middle of the left side we would have to modify CSS to:
top: 50%; left: 0px; transform: translate(0, -50%);
Finally, you can increment the two values at the same time, the last example would move the image to the center of the screen:
top: 50%; left: 50%; transform: translate(-50%, -50%);
Remember that to work correctly, the element must have the property position: fixed
or position: absolute
(in the case of absolute
, the parent must fill the entire screen).