easypiechart.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /**!
  2. * easyPieChart
  3. * Lightweight plugin to render simple, animated and retina optimized pie charts
  4. *
  5. * @license Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
  6. * @author Robert Fleischmann <rendro87@gmail.com> (http://robert-fleischmann.de)
  7. * @version 2.1.3
  8. **/
  9. (function(root, factory) {
  10. if(typeof exports === 'object') {
  11. module.exports = factory(require('jquery'));
  12. }
  13. else if(typeof define === 'function' && define.amd) {
  14. define('EasyPieChart', ['jquery'], factory);
  15. }
  16. else {
  17. factory(root.jQuery);
  18. }
  19. }(this, function($) {
  20. /**
  21. * Renderer to render the chart on a canvas object
  22. * @param {DOMElement} el DOM element to host the canvas (root of the plugin)
  23. * @param {object} options options object of the plugin
  24. */
  25. var CanvasRenderer = function(el, options) {
  26. var cachedBackground;
  27. var canvas = document.createElement('canvas');
  28. if (typeof(G_vmlCanvasManager) !== 'undefined') {
  29. G_vmlCanvasManager.initElement(canvas);
  30. }
  31. var ctx = canvas.getContext('2d');
  32. canvas.width = canvas.height = options.size;
  33. el.appendChild(canvas);
  34. // canvas on retina devices
  35. var scaleBy = 1;
  36. if (window.devicePixelRatio > 1) {
  37. scaleBy = window.devicePixelRatio;
  38. canvas.style.width = canvas.style.height = [options.size, 'px'].join('');
  39. canvas.width = canvas.height = options.size * scaleBy;
  40. ctx.scale(scaleBy, scaleBy);
  41. }
  42. // move 0,0 coordinates to the center
  43. ctx.translate(options.size / 2, options.size / 2);
  44. // rotate canvas -90deg
  45. ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI);
  46. var radius = (options.size - options.lineWidth) / 2;
  47. if (options.scaleColor && options.scaleLength) {
  48. radius -= options.scaleLength + 2; // 2 is the distance between scale and bar
  49. }
  50. // IE polyfill for Date
  51. Date.now = Date.now || function() {
  52. return +(new Date());
  53. };
  54. /**
  55. * Draw a circle around the center of the canvas
  56. * @param {strong} color Valid CSS color string
  57. * @param {number} lineWidth Width of the line in px
  58. * @param {number} percent Percentage to draw (float between -1 and 1)
  59. */
  60. var drawCircle = function(color, lineWidth, percent) {
  61. percent = Math.min(Math.max(-1, percent || 0), 1);
  62. var isNegative = percent <= 0 ? true : false;
  63. ctx.beginPath();
  64. ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, isNegative);
  65. ctx.strokeStyle = color;
  66. ctx.lineWidth = lineWidth;
  67. ctx.stroke();
  68. };
  69. /**
  70. * Draw the scale of the chart
  71. */
  72. var drawScale = function() {
  73. var offset;
  74. var length;
  75. var i = 24;
  76. ctx.lineWidth = 1
  77. ctx.fillStyle = options.scaleColor;
  78. ctx.save();
  79. for (var i = 24; i > 0; --i) {
  80. if (i%6 === 0) {
  81. length = options.scaleLength;
  82. offset = 0;
  83. } else {
  84. length = options.scaleLength * .6;
  85. offset = options.scaleLength - length;
  86. }
  87. ctx.fillRect(-options.size/2 + offset, 0, length, 1);
  88. ctx.rotate(Math.PI / 12);
  89. }
  90. ctx.restore();
  91. };
  92. /**
  93. * Request animation frame wrapper with polyfill
  94. * @return {function} Request animation frame method or timeout fallback
  95. */
  96. var reqAnimationFrame = (function() {
  97. return window.requestAnimationFrame ||
  98. window.webkitRequestAnimationFrame ||
  99. window.mozRequestAnimationFrame ||
  100. function(callback) {
  101. window.setTimeout(callback, 1000 / 60);
  102. };
  103. }());
  104. /**
  105. * Draw the background of the plugin including the scale and the track
  106. */
  107. var drawBackground = function() {
  108. options.scaleColor && drawScale();
  109. options.trackColor && drawCircle(options.trackColor, options.lineWidth, 1);
  110. };
  111. /**
  112. * Clear the complete canvas
  113. */
  114. this.clear = function() {
  115. ctx.clearRect(options.size / -2, options.size / -2, options.size, options.size);
  116. };
  117. /**
  118. * Draw the complete chart
  119. * @param {number} percent Percent shown by the chart between -100 and 100
  120. */
  121. this.draw = function(percent) {
  122. // do we need to render a background
  123. if (!!options.scaleColor || !!options.trackColor) {
  124. // getImageData and putImageData are supported
  125. if (ctx.getImageData && ctx.putImageData) {
  126. if (!cachedBackground) {
  127. drawBackground();
  128. cachedBackground = ctx.getImageData(0, 0, options.size * scaleBy, options.size * scaleBy);
  129. } else {
  130. ctx.putImageData(cachedBackground, 0, 0);
  131. }
  132. } else {
  133. this.clear();
  134. drawBackground();
  135. }
  136. } else {
  137. this.clear();
  138. }
  139. ctx.lineCap = options.lineCap;
  140. // if barcolor is a function execute it and pass the percent as a value
  141. var color;
  142. if (typeof(options.barColor) === 'function') {
  143. color = options.barColor(percent);
  144. } else {
  145. color = options.barColor;
  146. }
  147. // draw bar
  148. drawCircle(color, options.lineWidth, percent / 100);
  149. }.bind(this);
  150. /**
  151. * Animate from some percent to some other percentage
  152. * @param {number} from Starting percentage
  153. * @param {number} to Final percentage
  154. */
  155. this.animate = function(from, to) {
  156. var startTime = Date.now();
  157. options.onStart(from, to);
  158. var animation = function() {
  159. var process = Math.min(Date.now() - startTime, options.animate);
  160. var currentValue = options.easing(this, process, from, to - from, options.animate);
  161. this.draw(currentValue);
  162. options.onStep(from, to, currentValue);
  163. if (process >= options.animate) {
  164. options.onStop(from, to);
  165. } else {
  166. reqAnimationFrame(animation);
  167. }
  168. }.bind(this);
  169. reqAnimationFrame(animation);
  170. }.bind(this);
  171. };
  172. var EasyPieChart = function(el, opts) {
  173. var defaultOptions = {
  174. barColor: '#ef1e25',
  175. trackColor: '#f9f9f9',
  176. scaleColor: '#dfe0e0',
  177. scaleLength: 5,
  178. lineCap: 'round',
  179. lineWidth: 3,
  180. size: 110,
  181. rotate: 0,
  182. animate: 1000,
  183. easing: function (x, t, b, c, d) { // more can be found here: http://gsgd.co.uk/sandbox/jquery/easing/
  184. t = t / (d/2);
  185. if (t < 1) {
  186. return c / 2 * t * t + b;
  187. }
  188. return -c/2 * ((--t)*(t-2) - 1) + b;
  189. },
  190. onStart: function(from, to) {
  191. return;
  192. },
  193. onStep: function(from, to, currentValue) {
  194. return;
  195. },
  196. onStop: function(from, to) {
  197. return;
  198. }
  199. };
  200. // detect present renderer
  201. if (typeof(CanvasRenderer) !== 'undefined') {
  202. defaultOptions.renderer = CanvasRenderer;
  203. } else if (typeof(SVGRenderer) !== 'undefined') {
  204. defaultOptions.renderer = SVGRenderer;
  205. } else {
  206. throw new Error('Please load either the SVG- or the CanvasRenderer');
  207. }
  208. var options = {};
  209. var currentValue = 0;
  210. /**
  211. * Initialize the plugin by creating the options object and initialize rendering
  212. */
  213. var init = function() {
  214. this.el = el;
  215. this.options = options;
  216. // merge user options into default options
  217. for (var i in defaultOptions) {
  218. if (defaultOptions.hasOwnProperty(i)) {
  219. options[i] = opts && typeof(opts[i]) !== 'undefined' ? opts[i] : defaultOptions[i];
  220. if (typeof(options[i]) === 'function') {
  221. options[i] = options[i].bind(this);
  222. }
  223. }
  224. }
  225. // check for jQuery easing
  226. if (typeof(options.easing) === 'string' && typeof(jQuery) !== 'undefined' && jQuery.isFunction(jQuery.easing[options.easing])) {
  227. options.easing = jQuery.easing[options.easing];
  228. } else {
  229. options.easing = defaultOptions.easing;
  230. }
  231. // create renderer
  232. this.renderer = new options.renderer(el, options);
  233. // initial draw
  234. this.renderer.draw(currentValue);
  235. // initial update
  236. if (el.dataset && el.dataset.percent) {
  237. this.update(parseFloat(el.dataset.percent));
  238. } else if (el.getAttribute && el.getAttribute('data-percent')) {
  239. this.update(parseFloat(el.getAttribute('data-percent')));
  240. }
  241. }.bind(this);
  242. /**
  243. * Update the value of the chart
  244. * @param {number} newValue Number between 0 and 100
  245. * @return {object} Instance of the plugin for method chaining
  246. */
  247. this.update = function(newValue) {
  248. newValue = parseFloat(newValue);
  249. if (options.animate) {
  250. this.renderer.animate(currentValue, newValue);
  251. } else {
  252. this.renderer.draw(newValue);
  253. }
  254. currentValue = newValue;
  255. return this;
  256. }.bind(this);
  257. init();
  258. };
  259. $.fn.easyPieChart = function(options) {
  260. return this.each(function() {
  261. var instanceOptions;
  262. if (!$.data(this, 'easyPieChart')) {
  263. instanceOptions = $.extend({}, options, $(this).data());
  264. $.data(this, 'easyPieChart', new EasyPieChart(this, instanceOptions));
  265. }
  266. });
  267. };
  268. }));