Animation On Button-Press
Background image scrolling triggered by buttons, with inertia effect. Requires jQuery.
by the_voder
HTML
<div id="container">
<div id="inner"></div>
<div id="controls">
<button id="left-btn">Left</button>
<button id="right-btn">Right</button>
<button id="up-btn">Up</button>
<button id="down-btn">Down</button>
</div>
</div>
CSS
#container {
position: relative;
width: 90vw;
height: 50vh;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
background-image: url("https://hoyafilter.com/uploads/images/catalog/product/STARSCAPE/starscape_7.jpg?1572533966254");
}
#controls {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
JavaScript
/*
Background image scrolling triggered by buttons, with inertia effect.
Requires jQuery.
*/
$(document).ready(function() {
//////////////////////
// DEFINE VARIABLES //
//////////////////////
// Element to animate (jQuery selector)
// Must have a background image set in CSS, as it's the position of the BG image that is animated.
// This allows us to scroll the image indefinitely, as it will repeat.
// You might want to make sure your background image tiles seamlessly.
const $element = $("#container");
// Button elements (jQuery selectors)
const $btnLeft = $("#left-btn");
const $btnRight = $("#right-btn");
const $btnUp = $("#up-btn");
const $btnDown = $("#down-btn");
// Distance to move element over 1 second.
// Because of smoothing and frame-rate variation, this won't always be exactly correct
const distance = 10;
// Smoothing/inertia amount (must be less that 1)
const inertia = 0.95;
// Left/Top increment amount
// We set these on mousedown/up on our buttons to determine the distance animated
var leftIncrement = 0;
var topIncrement = 0;
// Initial backgroiund image Left/Top position.
// We had to do some processing here to get a usable number initially
// (getting rid of the '%' unit and turning a text string into a number).
// These variables will be updated as the element is animated
var currentLeft = parseFloat($element.css("background-position-x").replace("%", ""));
var currentTop = parseFloat($element.css("background-position-y").replace("%", ""));
//////////////////////////
// CALCULATE FRAME-RATE //
//////////////////////////
// Calculate frames per second.
// This allows us to change the distance moved over a frame, to keep the apparent speed of animation constant even when frame-rate changes.
// Source: https://thewebdev.info/2021/08/07/how-to-calculate-frames-per-second-in-the-canvas-using-javascripts-requestanimationframe-function/
var fps = 30;
var times = [];
const...