jquery.easypiechart.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /**!
  2. * easyPieChart
  3. * Lightweight plugin to render simple, animated and retina optimized pie charts
  4. *
  5. * @license
  6. * @author Robert Fleischmann <rendro87@gmail.com> (http://robert-fleischmann.de)
  7. * @version 2.1.6
  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(['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. el.appendChild(canvas);
  29. if (typeof(G_vmlCanvasManager) !== 'undefined') {
  30. G_vmlCanvasManager.initElement(canvas);
  31. }
  32. var ctx = canvas.getContext('2d');
  33. canvas.width = canvas.height = options.size;
  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. ctx.lineWidth = 1;
  76. ctx.fillStyle = options.scaleColor;
  77. ctx.save();
  78. for (var i = 24; i > 0; --i) {
  79. if (i % 6 === 0) {
  80. length = options.scaleLength;
  81. offset = 0;
  82. } else {
  83. length = options.scaleLength * 0.6;
  84. offset = options.scaleLength - length;
  85. }
  86. ctx.fillRect(-options.size/2 + offset, 0, length, 1);
  87. ctx.rotate(Math.PI / 12);
  88. }
  89. ctx.restore();
  90. };
  91. /**
  92. * Request animation frame wrapper with polyfill
  93. * @return {function} Request animation frame method or timeout fallback
  94. */
  95. var reqAnimationFrame = (function() {
  96. return window.requestAnimationFrame ||
  97. window.webkitRequestAnimationFrame ||
  98. window.mozRequestAnimationFrame ||
  99. function(callback) {
  100. window.setTimeout(callback, 1000 / 60);
  101. };
  102. }());
  103. /**
  104. * Draw the background of the plugin including the scale and the track
  105. */
  106. var drawBackground = function() {
  107. if(options.scaleColor) drawScale();
  108. if(options.trackColor) drawCircle(options.trackColor, options.trackWidth || options.lineWidth, 1);
  109. };
  110. /**
  111. * Canvas accessor
  112. */
  113. this.getCanvas = function() {
  114. return canvas;
  115. };
  116. /**
  117. * Canvas 2D context 'ctx' accessor
  118. */
  119. this.getCtx = function() {
  120. return ctx;
  121. };
  122. /**
  123. * Clear the complete canvas
  124. */
  125. this.clear = function() {
  126. ctx.clearRect(options.size / -2, options.size / -2, options.size, options.size);
  127. };
  128. /**
  129. * Draw the complete chart
  130. * @param {number} percent Percent shown by the chart between -100 and 100
  131. */
  132. this.draw = function(percent) {
  133. // do we need to render a background
  134. if (!!options.scaleColor || !!options.trackColor) {
  135. // getImageData and putImageData are supported
  136. if (ctx.getImageData && ctx.putImageData) {
  137. if (!cachedBackground) {
  138. drawBackground();
  139. cachedBackground = ctx.getImageData(0, 0, options.size * scaleBy, options.size * scaleBy);
  140. } else {
  141. ctx.putImageData(cachedBackground, 0, 0);
  142. }
  143. } else {
  144. this.clear();
  145. drawBackground();
  146. }
  147. } else {
  148. this.clear();
  149. }
  150. ctx.lineCap = options.lineCap;
  151. // if barcolor is a function execute it and pass the percent as a value
  152. var color;
  153. if (typeof(options.barColor) === 'function') {
  154. color = options.barColor(percent);
  155. } else {
  156. color = options.barColor;
  157. }
  158. // draw bar
  159. drawCircle(color, options.lineWidth, percent / 100);
  160. }.bind(this);
  161. /**
  162. * Animate from some percent to some other percentage
  163. * @param {number} from Starting percentage
  164. * @param {number} to Final percentage
  165. */
  166. this.animate = function(from, to) {
  167. var startTime = Date.now();
  168. options.onStart(from, to);
  169. var animation = function() {
  170. var process = Math.min(Date.now() - startTime, options.animate.duration);
  171. var currentValue = options.easing(this, process, from, to - from, options.animate.duration);
  172. this.draw(currentValue);
  173. options.onStep(from, to, currentValue);
  174. if (process >= options.animate.duration) {
  175. options.onStop(from, to);
  176. } else {
  177. reqAnimationFrame(animation);
  178. }
  179. }.bind(this);
  180. reqAnimationFrame(animation);
  181. }.bind(this);
  182. };
  183. var EasyPieChart = function(el, opts) {
  184. var defaultOptions = {
  185. barColor: '#ef1e25',
  186. trackColor: '#f9f9f9',
  187. scaleColor: '#dfe0e0',
  188. scaleLength: 5,
  189. lineCap: 'round',
  190. lineWidth: 3,
  191. trackWidth: undefined,
  192. size: 110,
  193. rotate: 0,
  194. animate: {
  195. duration: 1000,
  196. enabled: true
  197. },
  198. easing: function (x, t, b, c, d) { // more can be found here: http://gsgd.co.uk/sandbox/jquery/easing/
  199. t = t / (d/2);
  200. if (t < 1) {
  201. return c / 2 * t * t + b;
  202. }
  203. return -c/2 * ((--t)*(t-2) - 1) + b;
  204. },
  205. onStart: function(from, to) {
  206. return;
  207. },
  208. onStep: function(from, to, currentValue) {
  209. return;
  210. },
  211. onStop: function(from, to) {
  212. return;
  213. }
  214. };
  215. // detect present renderer
  216. if (typeof(CanvasRenderer) !== 'undefined') {
  217. defaultOptions.renderer = CanvasRenderer;
  218. } else if (typeof(SVGRenderer) !== 'undefined') {
  219. defaultOptions.renderer = SVGRenderer;
  220. } else {
  221. throw new Error('Please load either the SVG- or the CanvasRenderer');
  222. }
  223. var options = {};
  224. var currentValue = 0;
  225. /**
  226. * Initialize the plugin by creating the options object and initialize rendering
  227. */
  228. var init = function() {
  229. this.el = el;
  230. this.options = options;
  231. // merge user options into default options
  232. for (var i in defaultOptions) {
  233. if (defaultOptions.hasOwnProperty(i)) {
  234. options[i] = opts && typeof(opts[i]) !== 'undefined' ? opts[i] : defaultOptions[i];
  235. if (typeof(options[i]) === 'function') {
  236. options[i] = options[i].bind(this);
  237. }
  238. }
  239. }
  240. // check for jQuery easing
  241. if (typeof(options.easing) === 'string' && typeof(jQuery) !== 'undefined' && jQuery.isFunction(jQuery.easing[options.easing])) {
  242. options.easing = jQuery.easing[options.easing];
  243. } else {
  244. options.easing = defaultOptions.easing;
  245. }
  246. // process earlier animate option to avoid bc breaks
  247. if (typeof(options.animate) === 'number') {
  248. options.animate = {
  249. duration: options.animate,
  250. enabled: true
  251. };
  252. }
  253. if (typeof(options.animate) === 'boolean' && !options.animate) {
  254. options.animate = {
  255. duration: 1000,
  256. enabled: options.animate
  257. };
  258. }
  259. // create renderer
  260. this.renderer = new options.renderer(el, options);
  261. // initial draw
  262. this.renderer.draw(currentValue);
  263. // initial update
  264. if (el.dataset && el.dataset.percent) {
  265. this.update(parseFloat(el.dataset.percent));
  266. } else if (el.getAttribute && el.getAttribute('data-percent')) {
  267. this.update(parseFloat(el.getAttribute('data-percent')));
  268. }
  269. }.bind(this);
  270. /**
  271. * Update the value of the chart
  272. * @param {number} newValue Number between 0 and 100
  273. * @return {object} Instance of the plugin for method chaining
  274. */
  275. this.update = function(newValue) {
  276. newValue = parseFloat(newValue);
  277. if (options.animate.enabled) {
  278. this.renderer.animate(currentValue, newValue);
  279. } else {
  280. this.renderer.draw(newValue);
  281. }
  282. currentValue = newValue;
  283. return this;
  284. }.bind(this);
  285. /**
  286. * Disable animation
  287. * @return {object} Instance of the plugin for method chaining
  288. */
  289. this.disableAnimation = function() {
  290. options.animate.enabled = false;
  291. return this;
  292. };
  293. /**
  294. * Enable animation
  295. * @return {object} Instance of the plugin for method chaining
  296. */
  297. this.enableAnimation = function() {
  298. options.animate.enabled = true;
  299. return this;
  300. };
  301. init();
  302. };
  303. $.fn.easyPieChart = function(options) {
  304. return this.each(function() {
  305. var instanceOptions;
  306. if (!$.data(this, 'easyPieChart')) {
  307. instanceOptions = $.extend({}, options, $(this).data());
  308. $.data(this, 'easyPieChart', new EasyPieChart(this, instanceOptions));
  309. }
  310. });
  311. };
  312. }));