jquery.easypiechart.js 9.1 KB

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