Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic transition from one color to another.

Here is a snapshot showing a few frames of the animation: svg animation
Despite exploring various techniques, I have yet to discover an optimal solution.
I attempted implementing it using CSS keyframes:

    $.keyframe.define([{
      name: 'shift',
      ...
      ...
      
    }]);
    $('.ledbar').playKeyframe({
        name: 'shift',
        duration: "4s",
        timingFunction: 'linear',
        delay: 0,
        direction: 'reverse',
        fillMode: 'forwards',

      });

The orange part should move over the green areas of the svg. Each rectangle in the svg was designed to be incrementally 6px further than the previous one. However, due to the smooth transition between keyframes, the animation flickers. Transitioning the animation step by step might resolve this issue, but I'm unsure how to execute this effectively.

Hence, my query revolves around achieving a linear color shift within the svg to another color. I've explored options like svg masks without success.

If you find it helpful, here is the svg file:

    <?xml version="1.0" encoding="utf-8"?>
...
...
</svg>

Answer №1

One creative method involves using an animated linear gradient.

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="403.5px" height="13px" viewBox="0 0 403.5 13" enable-background="new 0 0 403.5 13" xml:space="preserve">
<defs>
  <linearGradient id="orange-grad" gradientUnits="userSpaceOnUse">
    <stop offset="0" stop-color="orange"/<
    <stop offset="0" stop-color="orange">
      <animate attributeName="offset" attributeType="XML"
               begin="0s" dur="5s" fill="freeze" from="0" to="1" />
    </stop>
    <stop offset="0" stop-color="#80A993">
      <animate attributeName="offset" attributeType="XML"
               begin="0s" dur="5s" fill="freeze" from="0" to="1" />
    </stop>
    <stop offset="1" stop-color="#80A993"/>
  </linearGradient>
</defs>
<g fill="url(#orange-grad)">
    <path d="M0.017,0L1.5,0.002L1.484,13H0L0.017,0z"/>
    <path d="M6.017,0L7.5,0.002L7.484,13H6L6.017,0z"/>
    <path d="M12.017,0L13.5,0.002L13.484,13H12L12.017,0z"/>
    ...
    (Additional path elements are present in the SVG)
</g>
</svg>

Update: Technique for manual activation and direction change

This updated approach uses a different technique to create the graph by employing a clipping path and moving an orange rectangle behind the clip. To meet the request of the original poster, functionality has been added to trigger and alter the animation direction with mouseover actions on buttons.

In this example, vanilla Javascript is utilized along with a timeout function for the animation. For smoother performance under heavier page loads, switching to window.requestAnimationFrame() can be considered.

var graphPosition = 0;
var graphStep = 6;
var graphRunning = false;

var orangeRect = document.getElementById("orange");


document.getElementById("forwards").addEventListener("mouseenter", function() {
  graphStep = 6;
  startGraphRunning();
});

document.getElementById("backwards").addEventListener("mouseenter", function() {
  graphStep = -6;
  startGraphRunning();
});



function startGraphRunning()
{
  // Avoid redundant operation if already running
  if (graphRunning) return;

  graphRunning = true;

  // Initiate the initial step of animation
  animationStep();
}


function animationStep()
{
  // Calculate new position of orange rectangle
  var  newPos = graphPosition += graphStep;
  if (newPos < 0 || newPos > 408)
  {
    // Halt animation upon reaching minimum or maximum positions
    graphRunning = false;
  }
  else
  {
    // Update x position of orange rect
    graphPosition = newPos;
    // Positioning logic based on desired edge location of rectangle
    orangeRect.setAttribute("x", graphPosition - orangeRect.width.baseVal.value);
  }

  // Keep animation active by calling this function after 50ms if still running
  if (graphRunning)
    setTimeout(animationStep, 50);
}
div {
  display: inline-block;
  padding: 10px;
  background-color: #eee;
  border: solid 1px black;
  margin: 20px 20px 0 0;
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="403.5px" height="13px" viewBox="0 0 403.5 13" enable-background="new 0 0 403.5 13" xml:space="preserve">
<defs>
  <clipPath id="graph">
    <path d="M0.017,0L1.5,0.002L1.484,13H0L0.017,0z"/>
    <path d="M6.017,0L7.5,0.002L7.484,13H6L6.017,0z"/>
    <path d="M12.017,0L13.5,0.002L13.484,13H12L12.017,0z"/>
    ...
    (Additional path elements are present in the clipping path definition)
  </mask>
</defs>

<g clip-path="url(#graph)">
  <rect x="0" y="0" width="408" height="13" fill="green"/>
  <rect x="-408" y="0" width="408" height="13" fill="orange" id="orange"/>
</g>

</svg>

<br />
<div id="forwards">Forwards</div>
<div id="backwards">Backwards</div>

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

ReactJS not updating when multiple checkboxes are selected

Struggling to resolve an issue with this component. I encounter an error when trying to select multiple items using checkboxes. Oddly enough, another one of my components with the same code has no error. Please take a look at my code below, any help is gre ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

I am struggling to make my table adapt to different screen sizes and become

Here is an example of a table: <TABLE class=vysledky > <TR class=podtrzeni> <TD width="39" height="19">Order <br /> League</TD> <TD width="39" height="19">Order <br /> Team</TD> <TD width="3 ...

Method for creating a randomized layout grid in MaterialUI where each row contains a total of three columns

In the process of developing a React application that interacts with the reddit api and oAuth. Utilizing MaterialUI, I am currently experimenting with the Component to create a 3 column grid of images with dynamically generated column widths, maxing out a ...

How can I show a tooltip in vuetify when a button is disabled?

I am currently using the button and tooltip components in my Vuetify project. I am trying to find a way to only display the tooltip when the button is disabled, but I'm having trouble figuring out how to do it correctly. Right now, the tooltip only a ...

What is the best way to implement the settimeout method in react?

I need assistance on how to effectively utilize the setTimeout() method in my code. Specifically, I am looking to trigger a click event on an element after a certain delay and execute a function afterwards. Here is the current implementation of my code: ...

Utilizing AMD Modules and TypeScript to Load Bootstrap

I am attempting to incorporate Bootstrap into my project using RequireJS alongside typescript AMD modules. Currently, my requireJS configuration looks like this: require.config({ shim: { bootstrap: { deps: ["jquery"] } }, paths: { ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

I'm looking to adjust the position of an image inside a div without affecting the position of the entire div

When creating a horizontal navigation bar with an image, I encountered an issue where the image link did not align with the rest of the links on the navigation bar. I wanted to drop it down by a pixel or two without affecting the position of the other link ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

Contact form malfunctions with problematic Ajax functionality

I am facing issues with my ajax contact form. When I try to submit the form, I receive a "Please fill in all fields" message even though all fields are filled out. Here is my current form code: <form method="get" action="mail.php"> <inp ...

What is causing my JS/JQuery code to only function in the console of a web browser?

I am having trouble with the $(element).scroll(function(){}); function. When I put it into a js file, it does not work properly, but when I enter it directly into the console (just the scroll func), it works fine. My goal is to implement scrolling paginat ...

PHP query Ajax navigation

UPDATED I have made progress with processing both menus in "process.php" and displaying the queries in index.php. process.php <?php $menu1 = $_POST["menu1"]; $menu2 = $_POST["menu2"]; if($menu1 == 0) { $sql = "SELECT * FROM Language WHERE ID = " ...

How to achieve smooth transitions in CSS3 with dynamic height changes?

Currently, I am in the process of designing a unique layout. The main challenge lies in toggling between two classes for a div element, one of which has a height of 0px. To achieve this, I have successfully utilized CSS3 animations that effectively scale t ...

Similar to tabpanel's ._hide() function, how can this be implemented in C#?

Even though I feel like I've tackled this issue in the past, I can't seem to locate a resolution anywhere... In my situation, there are 3 tabs within an ajax TabContainer and two CheckBoxes located outside of it. All 3 tabs are visible unless bo ...

Is there a way to enable Tail Recursion Optimization in TypeScript?

const isPositive = (n: number) => n > 0; function fitsIn(dividend: number, divisor: number, count: number, accum: number): number { if (accum + divisor > dividend) { return count; } return ...

Having difficulty retrieving JSON data using Jquery

After receiving a JSON string as a response from the server, I encountered an issue when trying to access the objects within the response, only to receive an "undefined" message. Here is the AJAX request being made: $.ajax({ url: 'somefi ...

Updating a nested object within an array in a ReactJs component

I am struggling with updating a nested object within an array in the state of my React application. My goal is to determine if an item already exists in the state based on its name. Here's what I'm aiming for: Add an item to the cart. If th ...

Issue with bottom margins or padding

I am a beginner and I have noticed some black space at the bottom of my page. Unfortunately, using margin-bottom to remove it doesn't work as expected. When scrolling down, there is this pesky black space that I want to get rid of. Any help would be a ...

A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this: //main.js import "./vue-extensions/prototypes"; ...