Is it possible to change the background as I move the sun across the screen?

Recently, I developed a page that allows users to drag an image of the sun in an arc. The sun transitions from a bright sun to a darker version and eventually into a moon as it moves along the arc. Now, my goal is to have the background image also transition seamlessly.

I am seeking advice on how to smoothly fade the current sky background image into a tiled night sky image (similar to the one provided below) when the sun reaches the halfway point of its arc.

https://i.sstatic.net/8kI2q.gif

To visualize what I'm describing, you can check out the interactive demonstration at .

var width = 300,
  sun = $("#sun"),
  dark = $("#dark_sun"),
  moon = $("#moon"),
  total = $(window).width()
firstOfThree = (total / 3) * 0,
  secondOfThree = (total / 3) * 1,
  thirdOfThree = (total / 3) * 2;

// Drag functionality

// CSS styling for elements
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<img id="moon" src="http://i.imgur.com/VmFEwrH.png">
<img id="dark_sun" src="http://i.imgur.com/f3UFHb7.png">
<img id="sun" src="http://i.imgur.com/DGkZYZQ.png">

Answer №1

Implement fixed layers with opacity transition.

The getOpacity function receives two parameters, Z (percentage) and the index of the div, using them (along with the element count) to compute opacity while ensuring each .bg is fully displayed at some point during dragging. The function determines and returns the values through the cosine operation.

opacity = A*Math.cos(P*0 + Z*Math.PI - (index*Math.PI)/L) + V

I have generated a visual representation here on desmos.com and included a code snippet to simplify understanding of its functionality.

$(function(){

    var bg = $(".bg"),
        drag = $(".drag"),
        sun = $("#sun"),
        csel = '#container'; // container selector

    _init();

    // hoistorzs

    function _init(){
        onDrag();
        sun.css({
            opacity:1
          })
          .draggable({
            axis: "x",
            containment: csel,
            drag:onDrag
        });
    }
  
    function getOpacity(Z,index){
        Z = 1 - Math.min(Math.max(0,Z),1); // ensure 0 < x < 1
        var len = bg.length;
        var A = 1,
            P = 1,
            V = -A + 1,
            x = 0, // we require y at x=zero
            L = len - 1, // resolves fencepost error calculating arc indices
            opacity = A*Math.cos(P*0 + Z*Math.PI - (index*Math.PI)/L) + V; // ranges from 0 to 1;
        return opacity;
    }

    function onDrag(){
        var len = bg.length,
            total = $(csel).width(),
            min=sun.width()/2+8,
            max=total-min,
            x = sun.offset().left + (min),
            p = (x-min)/(max-min),
            w = sun.width(),
            heightPct = Math.pow((total >> 1) - x, 2) / Math.pow(total >> 1, 2),
            rounded = Math.round(heightPct * 30) + "%";

        bg.each(function(i){
            var op = getOpacity(p,i);
            $(this).css({
                opacity:op
            });
        });
      
        drag.each(function(i){
            var op = getOpacity(p,i);
            $(this).css({
                opacity:op > .5 ? 1 : 0,
                left: sun.css("left"),
                top: sun.css("top"),
                marginTop: rounded
            });
          
        })
    }
})
#container{
  width:100%;
  height:100%;  
}
img.drag {
  position: absolute;
  opacity:-1;
  height:30%;
  bottom:10%;
  transition:opacity 1s;
}
div.bg {
  width:100%;
  height:100%;
  position:fixed;
  top:0;
  left:0;
  background-repeat: repeat;
  background-size:cover;
  animation: mymove 40s linear infinite;
}
@keyframes mymove {
  from { background-position: 0 0; }
  to { background-position: 300px 0; }
}
<div id="container">
  <!-- ADD AS MANY IMAGE AS YOU LIKE HERE IN REVERSE ORDER -->
  
  <!-- NIGHT -->
  <div class="bg" id="night" style="background-image:url(http://i.imgur.com/JK3hIxi.gif);"></div>
  <img class="drag" id="moon" src="http://i.imgur.com/VmFEwrH.png">

  <!-- EVENING -->
  <div class="bg" id="evening" style="background-image:url(http://i.imgur.com/9UqDlgv.png)"></div>
  <img class="drag" id="dark_sun" src="http://i.imgur.com/f3UFHb7.png">
  
  <!-- DAY -->
  <div class="bg" id="day" style="background-image:url(http://i.imgur.com/aZty7Mq.png)"></div>
  <img class="drag" id="sun" src="http://i.imgur.com/DGkZYZQ.png">  

</div>

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

if the input field is empty, eliminate the class

Within the code snippet, a function is present which performs the following actions. It searches for an email in the input field, then converts the email to an md5 hash, and finally generates a Gravatar URL that is inserted into a class using fadeIn(); ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

Unable to display an image element in fullscreen within a modal that is already fullscreen

I am facing an issue with my modal that is designed to occupy the full width and height of a browser. Inside this modal, there is an image enclosed within a div along with some other elements. My goal is to make the image go full screen in the browser, aki ...

I'm looking for a way to showcase tasks in Fullcalendar that don't have a set end date

Is there a way to display a task in the full calendar when the task has a start date but no defined end date, such as a promotion that lasts until stock runs out? I would like the timeline for this type of task to extend indefinitely. However, since such ...

Exploring different options for parsing HTML content and extracting text from strings that do not contain HTML/XML tags

When looking at this particular solution for stripping HTML tags from a string, the process involves passing the string to rvest::read_html() in order to generate an html_document object. Subsequently, this object is input into rvest::html_text() to obtai ...

Troubleshooting multiple element visibility problems with jQuery

Please take a look at the code snippet below. $(document).ready(function(){ $(".like-btn").hover(function() { var rowid = $(this).attr("data-rowid"); $(".reaction-box[data-rowid='" + rowid + "']").fadeIn(100, function() { $(".reaction ...

Positioning a Three.js static CSS2DObject with respect to the camera's perspective

I am currently working on a unique program visualizer that utilizes Three.js to showcase various aspects of a program to the user. One crucial feature of this visualizer is allowing users to click on specific objects to view additional information about th ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

Retrieving nested array elements in MongoDB using parent ID element (JavaScript)

Suppose I have a MongoDB collection structured as follows: _id: ObjectId(" <a objectid> ") id: " <a userid> " __v: 0 subscribedTo: Object Regardless of whether or not Mongoose is being used, how can I execute a query to acc ...

Is there a way to showcase interactive HTML content similar to an ePub or eBook without the need to convert the HTML into ePub

Looking to enhance the mobile reading experience with a responsive design similar to popular ebook readers like Kindle or iBooks? Want to break long articles into full-screen sections for easy navigation on small devices? Consider using dynamic HTML to ada ...

How can one manage styling choices in R Markdown while creating a PDF document?

Currently, I am utilizing R Markdown within the RStudio platform to produce documentation. When selecting the "Knit HTML" option, my output appears satisfactory. The ability to modify styling options and apply CSS Files directly is a beneficial feature. ...

Trap mistakes while utilizing async/await

Within my Express application, I have a register function for creating new users. This function involves creating the user in Auth0, sending an email, and responding to the client. I am looking to handle errors from Auth0 or Postmark individually and send ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

Text field in React's material-ui causes the screen to shake

I am encountering an issue with a simple React code that includes a Material-UI Textfield. Whenever I try to enter data into the text field, the screen shakes. Additionally, when I click outside of the box after entering data, the screen shakes again. Ca ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Leveraging jQuery to determine the overall number of images within the specified <id>

Within a single div, I have included several images using the code <img src= etc I am looking to determine the total count of images contained within that div. Additionally, I aim to store the ID of each image in MySQL using PHP... Appreciate any assi ...

Activating the Submission of a File in a JQuery Form Plugin

Currently, I am using the JQuery Form Plugin to facilitate file uploads on my website. Instead of using a standard submit button, I would prefer to have a div element trigger the submission process. Here is the code I have attempted: $(document).on(&apo ...

Preserve numerous inputs in local storage

Hope your day is going well. I've been attempting to save multiple inputs by parsing localStorage into JSON using a 'for' loop, but unfortunately, nothing is being saved. The error message in the CONSOLE reads: "Uncaught SyntaxError: Unexpe ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...