Navigation Menu

Skip to content

adactio/Canvas-Sparkline

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 

Repository files navigation

Canvas Sparklines

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:

  1. canvas_id: The ID of a canvas element.
  2. data: An array of numeric values.
  3. endpoint: A Boolean value.
  4. color: A string value.
  5. 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.

Usage

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

Licence

Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication

http://creativecommons.org/publicdomain/zero/1.0/

About

Create a sparkline in a canvas element.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published