Reputation: 364
I have an image, I want to move the image from its current place(where it is initially placed) to another place where user clicks. I mean, when user clicks on anywhere in the Html page, the image should move there and I need to make this a move animation so that the image should move from its current place to another place in 3 seconds(for example). How can I do that? Can vanilla JavaScript
or jQuery
help to do it? I just want to make this animation anyway but React
does not work in my laptop efficiently so please answer in jQuery
or in plain JavaScript
.
In my html page:
<img src="./wolf.png" alt="wolf" style="width:3%;" id="wolf">
In my css file:
#wolf {
animation-name: move;
animation-duration: 3s;
animation-fill-mode: forwards;
}
@keyframes move {
/*
Need help
*/
}
In .js file:
$(document).ready(function() {
// Need help
})
Upvotes: 1
Views: 802
Reputation: 854
On https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API we learn that a DOMelement has an animate method.
var dX = 150, dY = 50; // TODO: proper distance between current and target location
document.getElementById("wolf").animate(
[
{ transform: `translate(${dX}px, ${dY}py)` },
], {
duration: 3000 // should be linked to distance - 3px in 3s is **SLOW**
}
);
To make the duration depend on the distance you need to designate which distance should take those three seconds (or whatever) and then calculate the travel distance. Pythagoras showed us how. Here's a jsfiddle that does all that - enjoy: https://jsfiddle.net/flowtron/0qkuvtd7/
At the core there are the following calculations:
// once on pageload:
screendiagonal = Math.sqrt( screen.width * screen.width + screen.height * screen.height ); // Pythagoras
// every move - what are the X and Y distances to travel?
let delta = { x: targetCoord.x - pos.x, y: targetCoord.y - pos.y };
let curdur = ( Math.sqrt(delta.x*delta.x+delta.y*delta.y) / screendiagonal ) * 3000; // Pythagoras - travel distance in time relative to screendiagonal
This is so that the diagonal of the screen would take three seconds.
Upvotes: 1
Reputation: 674
To find out where the mouse cursor is on click of user, you can use
document.onclick= function(event) {
pointerX = event.pageX;
pointerY = event.pageY;
}
console.log('Cursor at: '+pointerX+', '+pointerY);
You can combine this with translate in element.style.translate and move element from current position to where user has clicked.
Upvotes: 1