What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/Anna_123/pen/QbQqQb

/* Pie chart based on the pen by aaronlsilber (http://codepen.io/aaronlsilber/pen/IqrkL) which is based on an article by James Litten (http://html5.litten.com/graphing-data-in-the-html5-canvas-element-part-iv-simple-pie-charts/) */

/* Peak Chart Javascript
=====================================================================*/
var peakColors = ['rgb(236, 208, 120)', 'rgba(217, 91, 67, 0.7)', 'rgba(192, 41, 66, 0.7)', 'rgba(84, 36, 55, 0.7)', 'rgba(83, 119, 122, 0.7)', 'rgba(119, 146, 174, 0.7)'];

function drawPeakChart(canvasId) {
    var i, start, peakPoint,
        canvas = document.getElementById(canvasId),
        peakData = canvas.dataset.values.split(',').map(function(x) { return parseInt(x, 10) }),
        ctx = canvas.getContext('2d'),
        max = Math.max.apply(Math, peakData),
        plotBase = canvas.width / peakData.length,
        overlap = plotBase * .4;
        plotBase += canvas.width * .05;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (i = 0; i < peakData.length; i++) {
        start = i === 0 ? 0 : i * plotBase - i * overlap;
        peakPoint = canvas.height - Math.round(canvas.height * (peakData[i] / max));
        ctx.fillStyle = peakColors[i];
        ctx.beginPath();
        ctx.moveTo(start, canvas.height);
        ctx.lineTo(start + plotBase * .5, peakPoint);
        ctx.lineTo(start + plotBase, canvas.height);
        ctx.lineTo(start, canvas.height);
        ctx.fill();
    }
}

drawPeakChart('canPeak');
body {
  font: normal normal 400 1rem/1.5 "Segoe UI", "Helvetica Neue", "DejaVu Sans", Helvetica, Arial, sans-serif;
}
aside {
  float: left;
  margin-right: 100px;
}
.chart {
  margin-bottom:0;
  margin-top:0;
}
.vert > canvas, .vert > ol {
  display:inline-block
}
.horiz > li {
  display: inline;
  padding-right: 20px;
}
.legend {
  vertical-align:top;
  padding-left:15px;
  list-style: none;
}
.key {
  position:relative;
}
.key:before {
  content:"";
  position:absolute;
  top:35%;
  left:-15px;
  width:10px;
  height:10px;
}
.one:before{background:rgb(236, 208, 120)}
.two:before{background:rgba(217, 91, 67, 0.7)}
.three:before{background:rgba(192, 41, 66, 0.7)}
.four:before{background:rgba(84, 36, 55, 0.7)}
.five:before{background:rgba(83, 119, 122, 0.7)}
.six:before{background:rgba(119, 146, 174, 0.7)}
<aside class="chart">
  <canvas id="canPeak" width="300" height="200" data-values='40, 30, 20, 60, 10, 50'>
    This browser does not support HTML5 Canvas.
  </canvas>
  <ol class="legend horiz">
    <li class="key one">One</li>
    <li class="key two">Two</li>
    <li class="key three">Three</li>
    <li class="key four">Four</li>
    <li class="key five">Five</li>
    <li class="key six">Six</li>
  </ol>
</aside>

I am attempting to replicate the animated graph seen in this example: http://codepen.io/boars/pen/bnAfC, but despite my best efforts so far, I have been unsuccessful. Any assistance or advice would be much appreciated. Thank you! :-)

Answer №1

To incorporate an animation loop into the rendering of triangular bars, simply follow these steps:

var animationSteps = 60;
var animationStepCounter = 0;
var animation = setInterval(function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (i = 0; i < peakData.length; i++) {
        start = i === 0 ? 0 : i * plotBase - i * overlap;
        peakPoint = canvas.height - Math.round(canvas.height * (peakData[i] / max) * animationStepCounter / animationSteps);
        ctx.fillStyle = peakColors[i];
        ctx.beginPath();
        ctx.moveTo(start, canvas.height);
        ctx.lineTo(start + plotBase * .5, peakPoint);
        ctx.lineTo(start + plotBase, canvas.height);
        ctx.lineTo(start, canvas.height);
        ctx.fill();
    }

    if (animationStepCounter === animationSteps)
        clearInterval(animation);
    else
        animationStepCounter++;
}, 10);

This process involves redrawing the bars 60 times with a 10ms delay between each iteration, gradually increasing the height of the bars to reach their final height.

You have the flexibility to adjust the number of iterations or the timing interval to alter the speed and smoothness of the animation as desired.


Explore this code on CodePen: http://codepen.io/anon/pen/MwQOVG

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 encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...

What causes the NavBar to show and hide within a specific range?

Recently, I encountered a perplexing issue with my navbar. It functions correctly except for one strange behavior that has left me baffled. Why does the menu appear when I adjust the width to 631px, but disappear at 600px? And vice versa – why does it wo ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

I've been struggling with my Create React app for the past two days, and it just won

When trying to create a React project using the command `npx create-react-app reactproject`, I encountered an error: npm ERR! code ENOENT npm ERR! syscall spawn C:\Users\SUJITKUMAR\Desktop npm ERR! path D:\WebDev\React npm ERR! ...

Is it possible to exclude specific URLs from CSRF protection in sails.js?

I am currently integrating Stripe with my sails.js server and need to disable CSRF for specific URLs in order to utilize Stripe's webhooks effectively. Is there a way to exempt certain URLs from CSRF POST requirements within sails.js? I have searched ...

Using AngularJS to differentiate between desktop and mobile devices, as well as determine if the connection is wifi or not

After some research on SO, I couldn't find similar Q&A about detecting connection types rather than just if a connection exists or not. The goal of my website is to automatically play a video clip based on the user's device and network statu ...

What is the best way to implement an undo-list using arrays?

My current project involves creating a paint program in JavaScript, and I am aiming to implement an undo function rather than just an eraser. How can I store events in an array and then enable the deletion of each event individually? I have a dropdown men ...

Are background images covering hidden text detrimental to accessibility?

Is there a way to display images of text instead of actual text for my menu? I have implemented spans within each menu link. These spans have specific dimensions, block display properties, the text is indented to be hidden, and the background image is set ...

Embrace the power of React using curly brackets!

Today, I made the decision to dive into learning React. Typically, I use Brackets for my coding environment. The first step I took was adding the necessary sources to my HTML code. <html> <head> <link rel="stylesheet" href="styl ...

When using the Infinite Scroll React component, only a single new set of objects is loaded as you scroll down, and the loading

My React component is designed to load 6 images at a time as the page is scrolled down, creating an infinite scroll effect similar to what YouTube and Reddit now use. Currently, when the page loads, it shows the initial 6 images correctly. However, as I c ...

How can I use a button to save all changes made in a JqGrid checkbox column simultaneously?

In my jqgrid, there is a column named 'asistencia' which displays data from a database as checkboxes. These checkboxes are pre-checked based on the property formatoptions: {disabled : false}. I would like to implement a 'save' button th ...

What is the process for showing a table based on a selected value?

I could use some help - I am working on a <select> element with 4 different options in the form of <option>. What I want to achieve is to have tables that are initially not visible, and then when an option is clicked, the corresponding table wi ...

I have been working on creating a hangman game, and although I have figured out the logic behind it, I am experiencing an issue where it is not functioning properly. After inspect

I am currently working on a basic hangman game using only HTML and JavaScript. I have the logic in place, but it doesn't seem to be functioning correctly. When I inspected the element, it showed an error saying 'undefined toUppercase.' As a ...

How can you prioritize one CSS file over another?

To avoid repetition, I wish to have all the classes, tags, and ids from css.css take precedence over bootstrap.min.css, without duplicating any from bootstrap.min.css. <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/css.css ...

When a specific item is selected from a drop-down menu, text boxes and drop-downs will dynamically appear and change

In the current version of my code, there is a single drop-down menu with three options for the user to select from. If "Complete" is chosen, a text box should appear. If "Abandon" or "Transfer" is selected, a separate drop-down menu needs to be displayed. ...

Guide to incorporating flash into a form similar to the method used on http://www.mediafire.com

I'm looking to integrate a flash upload feature into my index file, but I'm not sure how to do it. Here is the link to the flash uploader: . I want it to work similar to how uploading works on when you click on UPLOAD. Thank you for any assistan ...

Access the HTML file from a different directory

I have a directory called "myWebsite". Within this directory, there is a file named "index.html" and another subdirectory named "other". Inside the "other" directory, there are CSS files, JS files, and "page2.ht ...

Tips on transforming button-controlled tab pages in Bootstrap 2 to Bootstrap 3

I am currently in the process of upgrading my website from Bootstrap 2 to Bootstrap 3, and I have encountered an issue with a specific control that consists of multiple sets of tab pages controlled by toggle buttons. Here is an example of the functional c ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...