Unleash the artistic magic with canvas animation that breath

I have a JSON file containing multiple points that need to be drawn gradually. I came across a helpful tutorial on this topic, but it only covers drawing a single line. What I'm looking to achieve is sequentially drawing several lines with different starting points. Below is the structure of the JSON file:

{
  "data": [
    {
      "line": {
        "color": "#96c23b",
        "points": [
          {
            "x": 1,
            "y": 2
          },
          {
            "x": 2,
            "y": 3
          },
          {
            "x": 4,
            "y": 5
          },
          {
            "x": 7,
            "y": 8
          }
        ],
        "width": 2.0
      },
      "type": "line",
      "line_id": "1"
    },
    {
      "line": {
        "color": "#DF5453",
        "points": [
          {
            "x": 33,
            "y": 34
          },
          {
            "x": 34,
            "y": 35
          },
          {
            "x": 38,
            "y": 39
          },
          {
            "x": 40,
            "y": 42
          },
          {
            "x": 45,
            "y": 46
          }
        ],
        "width": 5.0
      },
      "type": "line",
      "line_id": "2"
    }
  ]
}

The speed at which the lines are drawn is not a concern for me.

I am able to parse the JSON and draw the lines in canvas without animation using the following jQuery code:

var points_list =  {"data":[
  {"line":{"color":"#96c23b","points":[{"x":1,"y":2},{"x":2,"y":3},{"x":4,"y":5},{"x":7,"y":8}],"width":2.0},"type":"line","line_id":"1"},
  {"line":{"color":"#DF5453","points":[{"x":33,"y":34},{"x":34,"y":35},{"x":38,"y":39},{"x":40,"y":42},{"x":45,"y":46}],"width":5.0},"type":"line","line_id":"2"}
]}

function drawLines() {
    var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");

    $.each(points_list.data, function (key, value) {
        var info = value.line;
        var color = info.color;
        var width = info.width;
        var points = info.points;

        context.beginPath();
        context.moveTo(points[0].x, points[0].y);
        context.lineWidth = width;
        context.strokeStyle = color;
        context.fillStyle = color;

        for (var p = 1; p < points.length; p++) {
            context.lineTo(points[p].x, points[p].y);
        }
        context.stroke();
    });
}

Answer №1

Illustrated here is a method to track the positions of outerList and innerList using variables in a dynamic manner. The outerlist (points_list.data) is observed through lineIndexB while the innerList (points_list.data.line.points) is monitored via lineIndexA.

Upon each invocation of the drawLines function, the subsequent line segment gets drawn followed by an incrementation of the lineIndexA variable. If a particular line segment is completed, then lineIndexB is incremented accordingly.

This implementation leverages the setTimeout function for animation functionality, with potential for conversion to requestAnimationFrame seamlessly.

var points_list =  {"data":[
  {"line":{"color":"#96c23b","points":[{"x":1,"y":2},{"x":2,"y":3},{"x":4,"y":5},{"x":7,"y":8}],"width":2.0},"type":"line","line_id":"1"},
  {"line":{"color":"#DF5453","points":[{"x":33,"y":34},{"x":34,"y":35},{"x":38,"y":39},{"x":40,"y":42},{"x":45,"y":46}],"width":5.0},"type":"line","line_id":"2"}
]};

var lineIndexA = 1;
var lineIndexB = 0;

var canvas = document.getElementById("canvas");
canvas.width = 500;
canvas.height = 500;
var context = canvas.getContext("2d");

function drawLines() {
   
var value = points_list.data[lineIndexB];
  var info = value.line;
  var color = info.color;
  var width = info.width;
  var points = info.points;

  context.beginPath();
  context.moveTo(points[lineIndexA-1].x, points[lineIndexA-1].y);
  context.lineWidth = width;
  context.strokeStyle = color;
  context.fillStyle = color;
  context.lineTo(points[lineIndexA].x, points[lineIndexA].y);        
  context.stroke();
    
  lineIndexA = lineIndexA + 1;
  if (lineIndexA>points.length-1) {
  lineIndexA = 1;
    lineIndexB = lineIndexB + 1;
  }
        
  //stop the animation if the last line is exhausted...
  if (lineIndexB>points_list.data.length-1) return;
    
  setTimeout(function() {
    drawLines()
                }, 1000);
}

drawLines();
<canvas id="canvas"></canvas>

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

GraphicsMagick operations causing files to become blank

Currently, I am executing the following code: gm(jpgName).setFormat('jpg') .resize(160,158) .compress('JPEG') .write(fs.createWriteStream(jpgName),function(err){ if(err){ console.log(err,jpgName); res.send( ...

The prop passed from parent to child encountered an error - the specified type is not valid

Among the plethora of questions on this site, none seem to align with my specific code dilemma as I venture into the realm of React JS for the first time. My project involves creating a dice application where I've established separate classes for numb ...

Obtaining ResponseText from server without invoking servlet using xmlhttprequest in Internet Explorer (Any release)

When making a xmlhttprequest to call a servlet, I am facing different behaviors in Firefox and IE. In Firefox, everything is working fine, but in IE, the request only triggers sometimes when clicking the refresh button. Additionally, sometimes the respon ...

Redux, Retrieving the entire state rather than just the specified state

Experiencing a strange issue with react-redux. I am receiving all the state data instead of just the specific state that was passed. Here is the code snippet: Action.js import socketIOClient from 'socket.io-client' const DATA_URL = "LINK TO AP ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

Detecting Memory Leaks in a Node.js/Express.js Application

I've been dealing with memory problems in my Express.js web app lately. It keeps crashing with the following error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory Initially, when I launch the service, the memory u ...

Update the button label using data from a JSON source

While I am iterating through my JSON data, I want to dynamically set the button title based on the JSON property title. How can I achieve this? func getDataFromJSON(){ //Calling getCollectionViewData from the RestParser class RestParser.sharedInst ...

Having troubles with my Expo XDE project

I am currently using Expo XDE to run an app and encountered the following warning: Screenshot of Expo XDE warning Clicking on the link in the warning takes you to the Expo documentation. Upon inspecting it, I suspect that the issue might be related to my ...

Passport is implementing multistrategies for multiple authentications simultaneously

After configuring Passport.js to utilize multiple strategies, I encountered an issue: passport.authenticate(['bearer', 'facebook-token', 'google-token', 'linkedin-token'],function(err, user, info) ... Although it i ...

Error Message: Google Sheets Script encountered an issue while trying to align the cell content to the center using `

I seem to be encountering an issue with this particular script where it consistently generates the error mentioned in the title. Title: cell.setHorizontalAlignment(SpreadsheetApp.HorizontalAlignment.CENTER) function CustomFont() { // var spreadsheet ...

Retrieve the HTML of the chosen option within the parent form utilizing vanilla JavaScript, not the document object

I have a HTML form that is repeated multiple times on a webpage. In order to avoid targeting every specific field name of each form, I am creating a general-use JavaScript script that detects where it was triggered and obtains the values of the fields (tra ...

$emit functionality within a promise

I am facing an issue with event orders in my application. I have a method for fetching data and another one to open a modal with that data, but the problem is that the modal is rendered before getting the data, resulting in the previous result briefly appe ...

Observing modifications in the database is possible after executing the setInterval function

I am using a JavaScript function that runs every 4 seconds with setInterval. Once this function is executed for the first time, it calls an ajax request and changes a column value in the database. I want to know how I can check if this value has been succe ...

Verifying Age through Date of Birth

I'm currently seeking a way to validate a date of birth field that is entered as text in a dd/mm/yyyy format using jQuery Masked Input. I want to ensure the correct format is used by also utilizing the dateITA:true additional methods for validation. ...

An error occurred while processing the response: java.lang.IllegalStateException: Parsing error - expected object but received string at the beginning of the document

Currently working on implementing user authentication in Android. When passing the username and password, an error is appearing. The API seems to be functioning correctly. Any help or suggestions would be greatly appreciated. Here is the specific error me ...

Scripting issues detected in Safari and Microsoft Edge browsers

I recently finished developing an AngularJs Application that works flawlessly on Google Chrome and Mozilla Firefox. However, upon testing it on Safari and IE-11, I encountered errors in the console. One particular piece of code that causes issues is used ...

display JSON data beautifully on a webpage using Express

I am trying to display a large JavaScript object in a visually appealing format on my browser window using Express. I have experimented with using res.json() and res.send() with pretty print enabled in Express, but it seems that this method only works fo ...

Toggle the mute and unmute feature for a participant in an AWS Chime meeting

Hello everyone! I'm looking for details on the AWS Chime SDK (amazon-chime-sdk-js). Is it possible with the Amazon Chime SDK for 3 participants (Anna, John, and Lenny) in a meeting room to have Anna ignore Lenny's microphone and only hear John, ...

Eliminating empty lines from a textarea using jQuery

I have exhaustively attempted every solution I could find both here and on Google, but none of them seem to be working for my issue. Just to clarify, my goal is to eliminate any empty lines from a text area. This is what I have tried so far: <textare ...