Master the art of line animations with D3.JS

Recently delving into D3 and I have a query regarding the animation of lines. I have been able to animate circles with the following code snippet:

var data = d3.range(100).map(function() {
    return new agent(
        0,
        0,
        (Math.random()-0.5)*.05,
        (Math.random()-0.5)*.05,
        'rgb(255, 0, 213)');
});

var circles = canvas.selectAll('circle')
        .data(data)
        .enter().append('circle')
        .attr('cx', function(d) {
            return d.x;
        })
        .attr('cy', function(d) {
            return d.y;
        })
        .attr('r', 5)
        .attr('fill', function(d) {
            return d.color;
        });

circles.attr('transform', function(d) {
    return 'translate(' + d.x + ',' + d.y + ')';
});

I am particularly interested in the last 3 lines - is there an equivalent way to apply translate to lines?

Answer №1

There are multiple ways to animate lines in D3, for example:

Modifying the data

svg.select(".line")
    .duration(animationLength)
    .attr("d", valueline(lineData))

valueline represents a d3.svg.line() function.

Animating line fill from start to end using stroke-dashoffset

var lineGraph = svg.append("path")
    .attr("class", "line")
    .attr("d", lineFunction(lineData))
    .attr("stroke-dasharray", 200 + " " + 200)
    .attr("stroke-dashoffset", 200)
    .attr("fill", "none")
    .transition()
    .duration(animationLength)
    .ease("linear")
    .attr("stroke-dashoffset", 0);

Using transform to move the line

svg.select(".line")
    .duration(animationLength)
    .attr("transform", "translate(" + 100 * Math.random() + "," + 100 * Math.random() + ")");

var animationLength = 2000;
var lineData = [{
    "x": 1,
    "y": 5
}, {
    "x": 20,
    "y": 20
}, {
    "x": 40,
    "y": 10
}, {
    "x": 60,
    "y": 40
}, {
    "x": 80,
    "y": 5
}, {
    "x": 100,
    "y": 60
}];
var lineFunction = d3.svg.line()
    .x(function (d) {
        return d.x;
    })
    .y(function (d) {
        return d.y;
    })
    .interpolate("linear");

var valueline = d3.svg.line()
    .x(function (d) {
        return d.x * (Math.random() + 0.5);
    })
    .y(function (d) {
        return d.y * (Math.random() + 0.5);
    });

var svg = d3.select("#line")
    .append("svg")
    .attr("width", 200)
    .attr("height", 200);

var lineGraph = svg.append("path")
    .attr("class", "line")
    .attr("d", lineFunction(lineData))
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .attr("stroke-dasharray", 200 + " " + 200)
    .attr("stroke-dashoffset", 200)
    .attr("fill", "none")
    .transition()
    .duration(animationLength)
    .ease("linear")
    .attr("stroke-dashoffset", 0);

svg = d3.select("body").transition();

svg.select(".line")
    .delay(animationLength)
    .duration(animationLength)
    .attr("d", valueline(lineData))
    .attr("transform", "translate(" + 100 * Math.random() + "," + 100 * Math.random() + ")");
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="line"></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

Troubleshooting a Node.js server issue with a two-dimensional array

I am currently facing an issue with submitting a form that contains two-dimensional array fields on a post request in node.js. The problem lies in the fact that the server side is receiving a one-dimensional array with all the values combined. Below is an ...

There is a JSON issue present, with half of the variables being undefined

Having an issue with my JSON as it throws me an undefined error. What's puzzling is that it recognizes my first variable without any problem. Below are the codes for better understanding: JSON {"Comics":[ {"comic" : { "src":"Pictures/Comic ...

Modifying computed object in Vue: A step-by-step guide

My issue involves a simple selection of months: <select v-model="month" v-on:change="dateChanged('month', month)"> <option v-for="(month, index) in months" :value="index">{{ month }}</option> </select> The primary da ...

AngularJS factory with local storage functionality

As a newcomer to IonicFrameWork, I decided to try out their "starter tab" template and made some tweaks to the functionality of deleting and bookmarking items from a factory. In my books.js file where the factory is defined, here's a snippet of what ...

The JavaScript React Slider fails to hide the next arrow button when there are no images displayed on the screen

What I am trying to achieve is the display of a certain number of images inside a div according to the screen size. Currently, I have managed to hide the previous button when currentIndex != 0. However, I am facing difficulty in hiding the next button when ...

Internet Explorer 11 Freezes Unexpectedly with Dynamic SVG Components

Lately, I developed a unique SVG Icon control for the new html application at my workplace. However, our quality department started noticing that IE 11 would intermittently "crash" while using the application after its implementation. I'm not convinc ...

How can I unselect a radio button by double clicking on it?

I am in need of a specific feature: When a user clicks on a radio button that is already checked, I want it to become unchecked. I've attempted to implement this code but unfortunately, it has not been successful. $(document).on('mouseup' ...

What is the best way to transfer variables and functions between JavaScript and Python seamlessly?

I am in the process of building a website using HTML, CSS, and JavaScript, and I am in need of an AI-powered chatbot. I have a Python file that contains the necessary logic for the chatbot (AI, NLTK). Inside the Python file, there is a function called "res ...

Can Node.js handle parsing this as JSON?

Attempting to parse a small API that returns somewhat invalid JSON. Trying the following approach: var request = require('request'), url = 'urlhere'; request({ url: url }, function(error, response, body) { ...

Can different classes be assigned as "dragenter" targets?

Is it possible to apply the Jquery "dragenter" event to multiple targets or classes simultaneously? I tried this approach, but it doesn't seem to be working: $('.list').on('dragenter','.class1, .class2', function(e) { ...

The HTML elements in my JSX code seem to constantly shift around whenever I resize my webpage

Using react.js, I'm currently developing a website that appears like this before resizing: pre-resize_screenshot_website However, upon vertical or diagonal resizing, the layout becomes distorted especially in the 'availability search bar' ...

How can state values be transferred between components?

I have come across various answers on different platforms but haven't been able to achieve the desired results. That's why I am reaching out with this question. So, my question is related to 3 files named: App.js, SignUp.js, and Welcome.js. My ...

jqueryajax function returns a boolean value upon completion

Recently, I developed a container method to handle an ajax request: function postRating(formData) { $.ajax({ type: "POST", url: '/api/ratings', data: formData }) .done(function () { return true ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Invoke a jQuery method in a dynamic manner

Is it possible to achieve the following? var todo = "text"; $this.eval(todo).split(/\b[\s,\.-:;]*/).length; The desired function is: $this.text().split(/\b[\s,\.-:;]*/).length; I'm struggling to find a solution... Ca ...

Using Jquery to retrieve the window size and dynamically apply it to a div's CSS, adjusting it accordingly when the

Hey there! I'm trying to create a full-screen div, but unfortunately CSS doesn't seem to do the trick in this case. JavaScript/jQuery is my only option. My plan is to dynamically set the size of the div based on the browser window's dimensi ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...

What's causing the malfunction in this JavaScript function for capitalizing the first letter?

My React component includes a select box where users can choose one of four "severity" labels, all of which must be in lowercase due to API requirements. Here is the select box... <select id="logs-select" onChange={this.handleSeverityChange} value={thi ...