FrossBlock
FrossBlock

Reputation: 51

Javascript multiple circular graphs

Ive made a working circular graph using javascript, and Ive run into a problem. The script fetches the id of the graph in order to work, but I would like multiple graphs.

So here is my question: How do I make the script compatible with multiple graphs? I tried fetching them by their class but that didnt seem to work.

Here is my code:

var el = document.getElementById('graph'); // get canvas

var options = {
    percent: el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 80,
    lineWidth: el.getAttribute('data-line') || 5,
    color: el.getAttribute('data-color') || 0,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
    percent = Math.min(Math.max(0, percent || 1), 1);
    ctx.beginPath();
    ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
    ctx.strokeStyle = color;
    ctx.lineCap = 'butt'; // butt, round or square
    ctx.lineWidth = lineWidth
    ctx.stroke();
};

drawCircle('#F7F7F7', options.lineWidth, 100 / 100);
drawCircle(options.color, options.lineWidth, options.percent / 100);

And this is the HTML:

<div class="chart" id="graph" 
    data-percent="92" 
    data-color="#1EA1FF" 
    data-size="110" data-line="3">
</div>

Thanks in advance.

Upvotes: 1

Views: 128

Answers (1)

Tyler Kiser
Tyler Kiser

Reputation: 921

You should be able to surround everything with a loop. You need to select all the elements with the same class into an array, then loop through that array. I also suggest setting the "el" variable inside the array, then you don't have to change your code:

var graphs = document.getElementsByClassName("chart");
for(var i = 0; i < graphs.length; i++)
{
   var el = graphs[i];
   //Now the rest of your code
   var options = ... 
}

"el" then becomes each element as the loop iterates.

Upvotes: 2

Related Questions