SVG polyline animation that persists seamlessly

In my TypeScript code, I have implemented a function that creates a polyline based on 4 different points (x1y1, xCy1, xCy1, x2y2), where Xc represents the half distance between x1 and x2 on a plane. This polyline does not form a circular shape.

private createPolyline(points: Array<[number, number]>): SVGPolylineElement {
    let polyline: SVGPolylineElement = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
    let pointsAttr: string = points.map(point => point.join(',')).join(' ');

    polyline.setAttribute('points', pointsAttr);
    polyline.setAttribute('stroke', 'green');
    polyline.setAttribute('stroke-width', '2');
    polyline.setAttribute('fill', 'none');

    polyline.setAttribute('stroke-dasharray', '25');
    polyline.setAttribute('stroke-dashoffset', '40');
    polyline.style.animation = 'dash 5s linear infinite';

    return polyline;
}

My goal is to create a constantly flowing dashed line effect. The current method achieves this, but the animation resets after 5 seconds and restarts from the beginning.

Is there a way to make this animation continuously infinite?

Answer №1

There are two choices available.

  1. Opt for a sufficiently high animation delay and set the stroke-dashoffset value. For instance, 3000 seconds and 24000. It's as simple as that. Refer to the example below.

  2. Alternatively, take control by using requestAnimationFrame to continually increase the stroke-dashoffset value. Check out Creating a infinite forward SVG animation with CSS and JavaScript for detailed instructions on this approach.

function createPolyline(points) {
  let polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
  let pointsAttr = points.map(point => point.join(',')).join(' ');

  polyline.setAttribute('points', pointsAttr);
  polyline.setAttribute('stroke', 'lightgreen');
  polyline.setAttribute('stroke-width', '2');
  polyline.setAttribute('fill', 'none');

  polyline.setAttribute('stroke-dasharray', '25');
  polyline.setAttribute('stroke-dashoffset', '24000');
  polyline.style.animation = 'dash 3000s linear infinite';

  return polyline;
}

var poly = createPolyline([
  [50, 0],
  [21, 90],
  [98, 35],
  [2, 35],
  [79, 90],
  [50, 0]
])
document.querySelector("#mySomething").append(poly)
body {
  background: black;
}

@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<svg id="mySomething" viewBox="-10 -10 240 240" xmlns="http://www.w3.org/2000/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

Utilizing ng-change in an AngularJS directive with isolated scope to transition towards a component-based architecture. Let's evolve our approach

I've been struggling to get ng-change to trigger in my directive with an isolated scope. I'm working on transitioning from ng-controller to a more component-based architecture, but it's turning out to be more difficult than I anticipated. I ...

Retrieve the package.json file for a specific package by making an HTTP request to public repositories

I’ve been searching online but haven’t found a satisfying answer to my question yet. My main objective is to generate a dependency tree for a particular npmjs library of a specific version, like retrieving the dependency tree for the angular library v ...

Exploring the Scope of LocalStorage in Javascript

I've recently begun working with local storage and encountered some scope issues. Whenever I try to console.log(test), the second if statement returns undefined. What am I missing here? This is my current code; $("document").ready(function(){ ...

Increasing variable in angular template (nested ng-repeat)

I am facing a similar situation as described in the example below, and I need to generate a serial number for each row independently for each mark record. Here is the Java script Object structure: $scope.childsList = [ { id:12346, ...

Tips for properly implementing an enum in TypeScript when using the React useState hook

What's the correct way to utilize my useState hook? I have this enum type: export enum Status { PENDING = 'pending', SUCCESS = 'success', ERROR = 'error', } And the useState hook: const [isValid, setIsValid] = use ...

Tips for extracting and utilizing the values of multiple checked checkboxes in a jQuery datatable

When a button is clicked, I am trying to retrieve the selected values of multiple rows from the datatables. However, with my current code below, I am only able to get the value of the first selected row. function AssignVendor() { var table = $(assig ...

Using jQuery and Ajax to fade in content after all images and other assets have finished loading

I've encountered an issue with loading pages via ajax for users with custom URLs. For example, a profile is usually found at http://example.com/users/Dan, but if a user has a custom URL like http://example.com/DansCustomURL, I need to fetch their desi ...

Tips for integrating Google Analytics with React

In my react application, I have various pages: Main Service Contact Profile (private) etc.. To monitor user activity using Google Analytics, I came across the react-ga library which serves the purpose well. However, I find myself having to initialize G ...

Each time I refresh the page, the user data disappears and I have to login

Hello there, I am currently utilizing Express for backend authentication and these are the sign in functions/controllers implemented on the front end. export const signInUser = async credentials => { console.log('this is for the signInUser&apos ...

Smoothly scroll through parallax backgrounds

I've implemented a feature where an element moves in relation to scrolling using jQuery: $('#object').css('transform','translateY('+($(window).scrollTop()*.4)+'px)'); Here's the CSS: #object { width: ...

What is causing the search filter in the App.js code to malfunction?

After fetching a list of names from an array using the Fetch method, I attempted to implement a search filter by adding the resetData() method in my componentDidMount. Unfortunately, this resulted in an error as shown here: https://i.stack.imgur.com/1Z7kx. ...

What is the process for updating the dropdown list value based on the radio button that has been selected?

Is there a way to retrieve the value of a radio button and utilize it in the where clause? <input type="radio" name="radiobtn" value = "Yes" onclick="GetLockIn();" >Yes <input type="radio" name="radiobtn" value = "No" onclick="Ge ...

Delete an item from an array based on its index within the props

I am attempting to remove a specific value by its index in the props array that was passed from another component. const updatedData = [...this.props.data].splice([...this.props.data].indexOf(oldData), 1); const {tableData, ...application} = oldData; this ...

What is the best way to retrieve content from a different website using javascript in an asp.net environment?

Currently working on a web application in asp.net where I want to provide users with a JavaScript code that allows them to fetch content from my website and display it on their own website. To handle user requests on my website, I have implemented a gener ...

Is there a way to stop text from wrapping between words and punctuation marks using CSS or jQuery?

There is a paragraph containing some text. One issue I am facing is that punctuation at the end of a word may get wrapped to the next line, as shown here: This is the sentence, This is a new line Is there a way to fix this using CSS or jQuery? ...

What is the best way to enable a child category on a treeview within a Vue component?

I am working with two vue components. The first component (parent component) looks like this: <template> ... <ul class="filter-category" v-for="list in categories"> <list-category :data="list" :category-id="category ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

Call upon the prototype method of the parent class

"I'm having trouble understanding a piece of my code: //constructor function Widget (options) { }; //return the string Widget.prototype._addEditFormString = function (val) { return "<in ...

When errors occur while printing HTML through an Ajax request, it can hinder the functionality of other JavaScript code

I recently conducted an interesting experiment on my website. The concept involved sending an AJAX request to a PHP file, which then retrieved a random website by using various random words for search queries on Google. The retrieved website content was th ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...