Home > Blockchain >  How to make a move animation which can move an image from current place to where the user clicks
How to make a move animation which can move an image from current place to where the user clicks

Time:01-10

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
})

CodePudding user response:

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.

CodePudding user response:

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}, ${dY})` },
  ], {
    duration: 3000 // should be linked to distance - 3px in 3s is **SLOW**
  }
);
  •  Tags:  
  • Related