Issue with the svg animation not properly "executing"

Hello everyone! This is my debut post, and usually I can find solutions by browsing the community. However, this time I am in need of some assistance. I have crafted an "SVG" file that includes animations depicting the different cycles of a day over a 24-hour period. I have managed to utilize NPM bundles for calculating the time cycles and determining the duration of each "time period" between the SVG gradients.

The snippet of code looks like this:

<linearGradient
id="skyGradient"
gradientTransform="rotate(90)"
>
<stop offset="50%">
<animate 
attributeName="stop-color"
begin="39420s"
keyTimes="0;0.19517361111111112;0.21341435185185184;0.23157407407407407;0.2471875;0.2479398148148148;0.4997337962962963;0.7515277777777778;0.7522800925925925;0.7678935185185185;0.7860648148148148;0.8043055555555556;1"
values="black;rgb(0,0,0);rgb(2,15,23);rgb(8,33,48);rgb(46,125,185);rgb(145,193,243);rgb(145,193,243);rgb(46,125,185);rgb(46,125,185);rgb(24,75,106);rgb(10,41,59);rgb(2,15,23);black"
calcMode="linear"
dur="86400s">
</animate>
</stop>
</linearGradient>

This is just a portion of the SVG linearGradient, with two more similar sections following the same code structure.

Code available here: https://jsfiddle.net/2148whup/

What do I expect from this setup?

When a visitor lands on the page, I am aware of the current time in seconds of their specific location's day. For instance, if it's June 17, 2023, at 9:30 am EDT, I can calculate the total seconds elapsed since midnight and determine the corresponding percentage where the animation should ideally start based on keyTimes and progress until completion (if the user stays on the site throughout the day). Despite going through https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animate thoroughly, I'm encountering difficulties rendering the animation, even after manual adjustments to the generated code.

In my "test" code, I've tried using color codes in RGB or Hex formats but without success. Once I manage to resolve this issue, I plan to work on implementing JavaScript to automatically update/regenerate keyTimes for another 24-hour loop cycle if necessary.

Answer №1

For a smooth animation like this with complex calculations involved, JavaScript would provide a more efficient solution for updating the DOM. In this scenario, I use the 'gradientTransform' attribute to simulate the change in time of day through a gradient effect. The gradient is refreshed every minute in this script.

const gradient = document.getElementById('g1');

function updateGradient(){
  let now = new Date();
  let dayBegin = new Date();
  dayBegin.setMilliseconds(0);
  dayBegin.setSeconds(0);
  dayBegin.setMinutes(0);
  dayBegin.setHours(0);
  let delta = (now - dayBegin) / (1000*60*60*24);
  gradient.setAttribute('gradientTransform', `translate(${delta * 100 - 50} 0)`);
  setTimeout(updateGradient, 60*1000);
}

updateGradient();
<svg viewBox="0 0 100 50" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="g1" gradientUnits="userSpaceOnUse"
      gradientTransform="translate(-50 0)">
      <stop offset="0%" stop-color="orange" />
      <stop offset="40%" stop-color="orange" />
      <stop offset="60%" stop-color="green" />
      <stop offset="100%" stop-color="green" />
    </linearGradient>
  </defs>
  <rect width="100" height="50" fill="url(#g1)"/>
</svg>

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

Access another key within an object

Here's a code snippet from my module: exports.yeah = { hallo: { shine: "was", yum: this.hallo.shine } } In the above code, I'm attempting to reference the shine property in yum: this.hallo.shine However, when I run the script, ...

"What is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

How to maintain the focus within a jQuery dialog box

Exploring the world of jQuery dialog, I'm eager to incorporate it into my latest side project. My goal is to enhance accessibility by adding tabindex to the divs within the dialog for easy tab navigation. However, I encountered an issue where the focu ...

Combining two observable entities

Utilizing Angular 4 and rxjs, the objective is to fetch data from two distinct servers in JSON format, merge this data, and exhibit it in a list by associating the list with an observable array. **Word Search Component TypeScript File:** @Component( ...

Retrieving server information using AJAX in React

I've been attempting to utilize an AJAX call in order to fetch server data for my React Components. However, I'm encountering difficulties when it comes to displaying it with React as I keep receiving this error: Uncaught TypeError: Cannot read ...

Remove checked rows in a table with a single click

I have created a table with a list and checkboxes next to each element. There is also a Delete button that I want to connect to the delete operation. Here is the code for the Delete button: <tr id="deleteproject" > <td wi ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

Implementing asynchronous file reading with module.exports in Node.js

Apologies in advance for what may seem like a basic question, but I'm delving into the inner workings of node and need help with a particular issue: I am trying to send an object or file from fs.readFile using require and module.exports. So far, this ...

From converting Javascript code to PHP and using the innerHTML function for deletion

I'm currently working on implementing a script and could use some assistance with two specific issues that I'm struggling to resolve. The main goal is to enable users to create a running route and then store the route in a database using coordina ...

Why does the selectedItems in the AngularJS grid keep coming back as undefined?

Is there a specific reason why the angularjs grid in my sample isn't displaying the selectedItems properly? Every time I attempt to reference the selectedItems, it returns "undefined." I have tested this in both Chrome and IE with identical outcomes. ...

What are some ways to replicate the experience of a lengthy document loading?

I am interested in conducting tests on JavaScript code that runs both before and after the document is fully loaded. Is there a way to purposely delay my document's loading process (for instance, by 10 seconds) so I can easily observe the effects occ ...

What is the best way to align a series of divs vertically within columns?

Struggling to find the right words to ask this question has made it difficult for me to locate relevant search results. However, I believe a picture is worth a thousand words so...https://i.stack.imgur.com/LfPMO.png I am looking to create multiple columns ...

Splitting the express instance and routes into two separate server files

Currently, I am in the process of developing a middleware that can run two server files within the same instance while keeping the routes separate. Allow me to elaborate with examples: Directory Structure: /common-server /routers /routes.js /ap ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

What could be causing my div link to redirect to different content instead of the intended destination?

When creating a div to provide information about a course, including the price and a "Take Class" button that links to the purchase page, I encountered an issue where the link extends beyond the intended area. @import url(https://fonts.googleapis.com/cs ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example: function onExit(){ localStorage.setItem("my_object","'" + JSON.stringify(object) + "'"); } When retrieving this data from localStorage, it may loo ...

Connecting an AngularJS directive to a controller

I'm in the process of learning AngularJS directives and facing a challenge. Here's the JSFiddle link to an example I'm working on: https://jsfiddle.net/7smor9o4/ In the example, my expectation is for the vm.alsoId variable to match the valu ...