+ 5

How I make manual animation in JavaScript using onscreen buttons?

I want to make an animation in JS using onscreen buttons to move object up,down,left,right.

18th Jun 2019, 4:26 AM
CodeBoyMF
CodeBoyMF - avatar
1 Respuesta
+ 3
There are many ways to smoothly animate the movement of objects on a page. I'll mention a couple recommendations for the two cases you might have: Case 1: If the object you're moving is an HTML element(not just a part of an HTML canvas drawing), use CSS's transition property and having JavaScript just set the final positions. This will achieve the animation with minimal code. Your CSS could look like this: #your-element { position: fixed; /* Position in a way that relies on top, left properties. "absolute" is likely to work for you too. */ left: 0; top: 0; /* Whatever you want for an initial position. */ transition: top 1s, left 1s; /* Smoothly animate any changes to the element's position (top, left) over a 1 second interval. */ } Your JavaScript could look like this assuming you included jQuery: $('#your-down-button').click(function() { // This will be called when your down button is clicked. // Set an inline style for the top CSS property. // Higher top values correspond with pushing the element lower in the page. $('#your-element').css({ 'top': '100px' }); }); Case 2: If your object is part of a canvas drawing, you can use requestAnimationFrame. setTimeout and setInterval can do the trick if you actually want a slower interval and a choppy effect instead of a smooth animation but most-likely requestAnimationFrame is best for you. This gives you a function that is called very often(usually 60 times per second). You can use this to update your drawing with the object in different positions.
18th Jun 2019, 11:36 AM
Josh Greig
Josh Greig - avatar