This is a little snippet of JavaScript that will take an array of numeric values (in any range) and plot those values as a sparkline.
The sparkline
function takes five parameters:
canvas_id
: The ID of a canvas element.data
: An array of numeric values.endpoint
: A Boolean value.color
: A string value.style
: A string value, either 'line' or 'bar'.
If endpoint
is set to true
then the sparkline will mark the final value with a red dot.
If color
is not set, the sparkline will default to 50% transparent black.
If style
is not set, the sparkline will default to 'line'.
The demo.html
shows a few examples. The distribution of the values is determined by the dimensions of the canvas element. So it doesn't matter if the data
array contains values that are larger than the pixel dimensions of the canvas element: the script will normalise the values to fit.
Place your canvas element wherever you want it to appear in your document:
<canvas id="mycanvas" width="90" height="18"></canvas>
You can link to the sparkline.js
file at the end of your HTML document and then call the function afterwards:
<script src="sparkline.js"></script>
<script>
sparkline ('mycanvas', [145, 123, 121, 78, 23, 9, 23, 24, 25, 89, 35, 124, 78, 98], true);
</script>
Or you can inline the sparkline
function at the bottom of your document (to avoid the extra HTTP request):
<script>
var sparkline = function(canvas_id, data, endpoint, color, style) {
...
};
sparkline('mycanvas', [145, 123, 121, 78, 23, 9, 23, 24, 25, 89, 35, 124, 78, 98], true, 'rgba(0,0,255,.5)','line');
</script>
You can see the script in action on member profiles on the website The Session e.g. http://thesession.org/members/1