"Learn the technique of animating SVG paths with JavaScript, a step beyond traditional HTML filling

I am looking to animate SVG path elements with JavaScript instead of HTML. I have come across numerous articles discussing how to achieve this through JavaScript and jQuery by manipulating the attributes.

Some helpful links I found: Fill color SVG path with animation Animate SVG path via JavaScript

Is there anyone who knows how to apply these techniques to the following path? Although it currently works fine in HTML, I would like to be able to control the duration of the animation.

<svg width="300" height="300">
        <defs>
    <linearGradient id="left-to-right">
      <stop offset="0" stop-color="#ff0000">
        <animate dur="2s" attributeName="offset" opacity= 0.1 fill="freeze" from="0" to="1" />
      </stop>
      <stop offset="0" stop-color="#fff" stop-opacity="0.1">
        <animate dur="2s" attributeName="offset" opacity="0.1" fill="freeze" from="0" to="1" />
      </stop>
    </linearGradient>
  </defs>
         <path id="myPath"
d="M 280 210 Q 237 144 180 140 Q 120 144 80 210 L 280 210 "
stroke="black" fill="url(#left-to-right)" />
      </svg>
      

The issue is that the JavaScript code is not functioning as expected.

$(function(){
  
    $(this).animate(
      {
        textIndent: 1,
      }, {
        duration: 3000,
step: function ( now, fx ) {
                var from = 0,
                  to = 700,
                    r = from + to * ( now - fx.start ) / ( fx.end - fx.start );
                
                $("#left-to-right").attr( "from", 0);
                $("#left-to-right").attr( "to", 1);
  },
        complete: function () {
          $("#myPath").attr("fill", "url(#left-to-right)");
        }
      }
    );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg width="300" height="300">
        <defs>
    <linearGradient id="left-to-right">
      <stop offset="0" stop-color="#ff0000">
        <animate dur="2s" attributeName="offset" opacity= 0.1 fill="freeze" from="0" to="1" />
      </stop>
    </linearGradient>
  </defs>
         <path id="myPath"
d="M 280 210 Q 237 144 180 140 Q 120 144 80 210 L 280 210 "
stroke="black" fill="url(#left-to-right)" />
      </svg>

What changes do I need to make to the JavaScript code, particularly in relation to the 'now', 'fx' values, and attributes, in order for the animation to work correctly as it does in the current HTML version?

Answer №1

If you're looking to incorporate javascript for animating the gradient, there's no longer a need for the <animate> element.

// Define all the stops
let ss = document.querySelectorAll("#left-to-right stop");
let start = null;
let progress = 0;// Track animation progress
let duration = 2000; // Set duration to 2 seconds in milliseconds
let rid = null;// Request Animation ID

function Frame(timestamp) {
  rid = window.requestAnimationFrame(Frame);

  if (!start) start = timestamp;
  progress = timestamp - start;
  
  if (progress <= duration) {
   // Reset the offset attribute for each stop
    ss.forEach(s => {
      s.setAttributeNS(null, "offset", progress / duration);
    });
  }
  // If the animation is complete, cancel it
  if (progress >= duration){window.cancelAnimationFrame(rid)}
}

Frame();
<svg width="300" height="300">
    <defs>
    <linearGradient id="left-to-right">
      <stop offset="0" stop-color="#ff0000"></stop>
      <stop offset="0" stop-color="#fff" ></stop>
    </linearGradient>
  </defs>
  <path id="myPath" d="M 280 210 Q 237 144 180 140 Q 120 144 80 210 L 280 210" stroke="black" fill="url(#left-to-right)" />
</svg>

I trust you'll find this information valuable.

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

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...

I'm having trouble displaying my button after using the jQuery show method on it following it being hidden. What could be causing this issue?

I'm dealing with a situation on my page where 3 buttons trigger different grid sizes when clicked. However, the issue arises when I hide these buttons off-screen using $('.button').hide();. When the user clicks on text <p onclick="diffRes ...

Automatically complete a text box upon page initialization

My objective is to automatically populate three text boxes on page load by using the function initializeFormForDebugging(). Although I have successfully achieved this using the style section of my program, I am now required to call them within a function ...

Implementing a for loop within a scrolling function

How do I multiply functions inside the scroll loop? This is what I currently have: $(window).scroll(function() { b1Center = $("#block-1").offset().top - ($(window).height() - divHeight) / 2; b1Bottom = $("#block-1").offset().top - $(window).height(); b1T ...

Several queries for directions on Google Maps are resulting in the same response being returned for all requests

I've been experimenting with the Google Maps Directions service to retrieve three different travel methods for the same route (driving, walking, and bicycling). Despite successfully iterating through the array of methods and setting them in the respec ...

Retrieving information from an AJAX callback

Is there a way to extract the URLs from PHP data? Here is an example script that may help you achieve this: PHP $query = 'SELECT * FROM picture LIMIT 3'; $result = mysql_query($query); while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) { ...

Extract all links from an external website

I'm attempting to extract all the URLs from a webpage using jQuery so that I can later use them with $.get(). If these URLs were located on the same page as the script, retrieving them would be easy by doing something like var links = document.getEle ...

How do I alter the post title font size with a child theme?

After updating my theme, I noticed that the H1 for my Posts titles in the "Next Posts" section changed to H4 unexpectedly. How can I revert it back to how it was before? I've attempted fixing it without success. If you need a visual reference, you ca ...

I am looking to show images based on the number chosen from the dropdown menu in CodeIgniter

When a number is selected from the dropdown menu, I want to display images accordingly. The options in the dropdown are 9, 12, and 18. Here is the code snippet for my view page: <form action="<?php echo base_url();?>roxcontrol/numberdisplay" id=" ...

AngularJS - issue with directive functionality on dynamically inserted classes

Check out this plnkr - I've got a button that toggles the class toggled on the body element. I've also developed a directive to trigger an alert when the toggled class is applied to the body element, but for some reason it's not working. H ...

Attempting to simulate the behavior of nfcManager by utilizing the nfcManager.start() function in react native testing library

In the process of developing my Android app, I encountered a need to read NFC tags. To accomplish this task, I decided to utilize the react-native-nfc-manager library. However, during my implementation, I faced two perplexing issues that have left me stump ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

JavaScript - combining elements of an array of time

I've encountered a challenge where I need to calculate the total time duration from an array that contains time durations like ['00:30', '01:30', '03:00', '04:30']. The code snippet I'm using for this task ...

Step-by-step guide on deleting an entire row from a PHP webpage

I have removed a row from the database, but now I need to also remove it from the interface on my PHP page. Any suggestions or assistance would be greatly appreciated. Here is a snippet of mypage.php: <tr> <td><?php echo $row[' ...

What is the best way to send $(this) to a function?

Here is my code snippet: $(document).ready(function(){ var hCount = 0, eCount = 0, nCount = 0, mCount = 0; $("#head").click(function() { var pPos = calculatePosition(hCount); $(this).animate({left:pPos+"px"}, ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

What is the process of querying both a collection and a subcollection in Firebase using AngularFire?

I have a structure in my firebase database that looks like this: /profiles/{uid}/displayName /email /otherAttribues /roles/{roleName}/someAttribute /someOtherAttribute The reason ...

Adjust the baseline of the text within the <li> element by moving it 2 pixels upwards

My webpage menu is set up with inline lis within a ul. Each li has a colored border and contains an a element. I want to change the color of the text inside the a element and move it 2 pixels up when hovering over it without affecting the li border. How ...

Out of the blue, the CSS functionality in my React app completely ceased to

I've been developing this website using React and Material UI, and I chose to implement standard CSS for styling. However, after closing my code editor and reopening it, some parts of the CSS do not seem to be loading properly. I'm completely puz ...

A comprehensive guide on personalizing Bootstrap 4 tooltips to suit your specific needs

I would like to customize the tooltip in Bootstrap 4 based on the screenshot provided below: https://i.stack.imgur.com/wg4Wu.jpg <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta chars ...