jquery.flot.pie.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. /* Flot plugin for rendering pie charts.
  2. Copyright (c) 2007-2014 IOLA and Ole Laursen.
  3. Licensed under the MIT license.
  4. The plugin assumes that each series has a single data value, and that each
  5. value is a positive integer or zero. Negative numbers don't make sense for a
  6. pie chart, and have unpredictable results. The values do NOT need to be
  7. passed in as percentages; the plugin will calculate the total and per-slice
  8. percentages internally.
  9. * Created by Brian Medendorp
  10. * Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars
  11. The plugin supports these options:
  12. series: {
  13. pie: {
  14. show: true/false
  15. radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
  16. innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
  17. startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
  18. tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
  19. offset: {
  20. top: integer value to move the pie up or down
  21. left: integer value to move the pie left or right, or 'auto'
  22. },
  23. stroke: {
  24. color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
  25. width: integer pixel width of the stroke
  26. },
  27. label: {
  28. show: true/false, or 'auto'
  29. formatter: a user-defined function that modifies the text/style of the label text
  30. radius: 0-1 for percentage of fullsize, or a specified pixel length
  31. background: {
  32. color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
  33. opacity: 0-1
  34. },
  35. threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
  36. },
  37. combine: {
  38. threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
  39. color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
  40. label: any text value of what the combined slice should be labeled
  41. }
  42. highlight: {
  43. opacity: 0-1
  44. }
  45. }
  46. }
  47. More detail and specific examples can be found in the included HTML file.
  48. */
  49. (function($) {
  50. // Maximum redraw attempts when fitting labels within the plot
  51. var REDRAW_ATTEMPTS = 10;
  52. // Factor by which to shrink the pie when fitting labels within the plot
  53. var REDRAW_SHRINK = 0.95;
  54. function init(plot) {
  55. var canvas = null,
  56. target = null,
  57. options = null,
  58. maxRadius = null,
  59. centerLeft = null,
  60. centerTop = null,
  61. processed = false,
  62. ctx = null;
  63. // interactive variables
  64. var highlights = [];
  65. // add hook to determine if pie plugin in enabled, and then perform necessary operations
  66. plot.hooks.processOptions.push(function(plot, options) {
  67. if (options.series.pie.show) {
  68. options.grid.show = false;
  69. // set labels.show
  70. if (options.series.pie.label.show === "auto") {
  71. if (options.legend.show) {
  72. options.series.pie.label.show = false;
  73. } else {
  74. options.series.pie.label.show = true;
  75. }
  76. }
  77. // set radius
  78. if (options.series.pie.radius === "auto") {
  79. if (options.series.pie.label.show) {
  80. options.series.pie.radius = 3 / 4;
  81. } else {
  82. options.series.pie.radius = 1;
  83. }
  84. }
  85. // ensure sane tilt
  86. if (options.series.pie.tilt > 1) {
  87. options.series.pie.tilt = 1;
  88. } else if (options.series.pie.tilt < 0) {
  89. options.series.pie.tilt = 0;
  90. }
  91. }
  92. });
  93. plot.hooks.bindEvents.push(function(plot, eventHolder) {
  94. var options = plot.getOptions();
  95. if (options.series.pie.show) {
  96. if (options.grid.hoverable) {
  97. eventHolder.unbind("mousemove").mousemove(onMouseMove);
  98. }
  99. if (options.grid.clickable) {
  100. eventHolder.unbind("click").click(onClick);
  101. }
  102. }
  103. });
  104. plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) {
  105. var options = plot.getOptions();
  106. if (options.series.pie.show) {
  107. processDatapoints(plot, series, data, datapoints);
  108. }
  109. });
  110. plot.hooks.drawOverlay.push(function(plot, octx) {
  111. var options = plot.getOptions();
  112. if (options.series.pie.show) {
  113. drawOverlay(plot, octx);
  114. }
  115. });
  116. plot.hooks.draw.push(function(plot, newCtx) {
  117. var options = plot.getOptions();
  118. if (options.series.pie.show) {
  119. draw(plot, newCtx);
  120. }
  121. });
  122. function processDatapoints(plot, series, datapoints) {
  123. if (!processed) {
  124. processed = true;
  125. canvas = plot.getCanvas();
  126. target = $(canvas).parent();
  127. options = plot.getOptions();
  128. plot.setData(combine(plot.getData()));
  129. }
  130. }
  131. function combine(data) {
  132. var total = 0,
  133. combined = 0,
  134. numCombined = 0,
  135. color = options.series.pie.combine.color,
  136. newdata = [],
  137. i,
  138. value;
  139. // Fix up the raw data from Flot, ensuring the data is numeric
  140. for (i = 0; i < data.length; ++i) {
  141. value = data[i].data;
  142. // If the data is an array, we'll assume that it's a standard
  143. // Flot x-y pair, and are concerned only with the second value.
  144. // Note how we use the original array, rather than creating a
  145. // new one; this is more efficient and preserves any extra data
  146. // that the user may have stored in higher indexes.
  147. if ($.isArray(value) && value.length === 1) {
  148. value = value[0];
  149. }
  150. if ($.isArray(value)) {
  151. // Equivalent to $.isNumeric() but compatible with jQuery < 1.7
  152. if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) {
  153. value[1] = +value[1];
  154. } else {
  155. value[1] = 0;
  156. }
  157. } else if (!isNaN(parseFloat(value)) && isFinite(value)) {
  158. value = [1, +value];
  159. } else {
  160. value = [1, 0];
  161. }
  162. data[i].data = [value];
  163. }
  164. // Sum up all the slices, so we can calculate percentages for each
  165. for (i = 0; i < data.length; ++i) {
  166. total += data[i].data[0][1];
  167. }
  168. // Count the number of slices with percentages below the combine
  169. // threshold; if it turns out to be just one, we won't combine.
  170. for (i = 0; i < data.length; ++i) {
  171. value = data[i].data[0][1];
  172. if (value / total <= options.series.pie.combine.threshold) {
  173. combined += value;
  174. numCombined++;
  175. if (!color) {
  176. color = data[i].color;
  177. }
  178. }
  179. }
  180. for (i = 0; i < data.length; ++i) {
  181. value = data[i].data[0][1];
  182. if (numCombined < 2 || value / total > options.series.pie.combine.threshold) {
  183. newdata.push(
  184. $.extend(data[i], { /* extend to allow keeping all other original data values
  185. and using them e.g. in labelFormatter. */
  186. data: [[1, value]],
  187. color: data[i].color,
  188. label: data[i].label,
  189. angle: value * Math.PI * 2 / total,
  190. percent: value / (total / 100)
  191. })
  192. );
  193. }
  194. }
  195. if (numCombined > 1) {
  196. newdata.push({
  197. data: [[1, combined]],
  198. color: color,
  199. label: options.series.pie.combine.label,
  200. angle: combined * Math.PI * 2 / total,
  201. percent: combined / (total / 100)
  202. });
  203. }
  204. return newdata;
  205. }
  206. function draw(plot, newCtx) {
  207. if (!target) {
  208. return; // if no series were passed
  209. }
  210. var canvasWidth = plot.getPlaceholder().width(),
  211. canvasHeight = plot.getPlaceholder().height(),
  212. legendWidth = target.children().filter(".legend").children().width() || 0;
  213. ctx = newCtx;
  214. // WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE!
  215. // When combining smaller slices into an 'other' slice, we need to
  216. // add a new series. Since Flot gives plugins no way to modify the
  217. // list of series, the pie plugin uses a hack where the first call
  218. // to processDatapoints results in a call to setData with the new
  219. // list of series, then subsequent processDatapoints do nothing.
  220. // The plugin-global 'processed' flag is used to control this hack;
  221. // it starts out false, and is set to true after the first call to
  222. // processDatapoints.
  223. // Unfortunately this turns future setData calls into no-ops; they
  224. // call processDatapoints, the flag is true, and nothing happens.
  225. // To fix this we'll set the flag back to false here in draw, when
  226. // all series have been processed, so the next sequence of calls to
  227. // processDatapoints once again starts out with a slice-combine.
  228. // This is really a hack; in 0.9 we need to give plugins a proper
  229. // way to modify series before any processing begins.
  230. processed = false;
  231. // calculate maximum radius and center point
  232. maxRadius = Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2;
  233. centerTop = canvasHeight / 2 + options.series.pie.offset.top;
  234. centerLeft = canvasWidth / 2;
  235. if (options.series.pie.offset.left === "auto") {
  236. if (options.legend.position.match("w")) {
  237. centerLeft += legendWidth / 2;
  238. } else {
  239. centerLeft -= legendWidth / 2;
  240. }
  241. if (centerLeft < maxRadius) {
  242. centerLeft = maxRadius;
  243. } else if (centerLeft > canvasWidth - maxRadius) {
  244. centerLeft = canvasWidth - maxRadius;
  245. }
  246. } else {
  247. centerLeft += options.series.pie.offset.left;
  248. }
  249. var slices = plot.getData(),
  250. attempts = 0;
  251. // Keep shrinking the pie's radius until drawPie returns true,
  252. // indicating that all the labels fit, or we try too many times.
  253. do {
  254. if (attempts > 0) {
  255. maxRadius *= REDRAW_SHRINK;
  256. }
  257. attempts += 1;
  258. clear();
  259. if (options.series.pie.tilt <= 0.8) {
  260. drawShadow();
  261. }
  262. } while (!drawPie() && attempts < REDRAW_ATTEMPTS)
  263. if (attempts >= REDRAW_ATTEMPTS) {
  264. clear();
  265. target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>");
  266. }
  267. if (plot.setSeries && plot.insertLegend) {
  268. plot.setSeries(slices);
  269. plot.insertLegend();
  270. }
  271. // we're actually done at this point, just defining internal functions at this point
  272. function clear() {
  273. ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  274. target.children().filter(".pieLabel, .pieLabelBackground").remove();
  275. }
  276. function drawShadow() {
  277. var shadowLeft = options.series.pie.shadow.left;
  278. var shadowTop = options.series.pie.shadow.top;
  279. var edge = 10;
  280. var alpha = options.series.pie.shadow.alpha;
  281. var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
  282. if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) {
  283. return; // shadow would be outside canvas, so don't draw it
  284. }
  285. ctx.save();
  286. ctx.translate(shadowLeft, shadowTop);
  287. ctx.globalAlpha = alpha;
  288. ctx.fillStyle = "#000";
  289. // center and rotate to starting position
  290. ctx.translate(centerLeft, centerTop);
  291. ctx.scale(1, options.series.pie.tilt);
  292. //radius -= edge;
  293. for (var i = 1; i <= edge; i++) {
  294. ctx.beginPath();
  295. ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
  296. ctx.fill();
  297. radius -= i;
  298. }
  299. ctx.restore();
  300. }
  301. function drawPie() {
  302. var startAngle = Math.PI * options.series.pie.startAngle;
  303. var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
  304. var i;
  305. // center and rotate to starting position
  306. ctx.save();
  307. ctx.translate(centerLeft, centerTop);
  308. ctx.scale(1, options.series.pie.tilt);
  309. //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
  310. // draw slices
  311. ctx.save();
  312. var currentAngle = startAngle;
  313. for (i = 0; i < slices.length; ++i) {
  314. slices[i].startAngle = currentAngle;
  315. drawSlice(slices[i].angle, slices[i].color, true);
  316. }
  317. ctx.restore();
  318. // draw slice outlines
  319. if (options.series.pie.stroke.width > 0) {
  320. ctx.save();
  321. ctx.lineWidth = options.series.pie.stroke.width;
  322. currentAngle = startAngle;
  323. for (i = 0; i < slices.length; ++i) {
  324. drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
  325. }
  326. ctx.restore();
  327. }
  328. // draw donut hole
  329. drawDonutHole(ctx);
  330. ctx.restore();
  331. // Draw the labels, returning true if they fit within the plot
  332. if (options.series.pie.label.show) {
  333. return drawLabels();
  334. } else return true;
  335. function drawSlice(angle, color, fill) {
  336. if (angle <= 0 || isNaN(angle)) {
  337. return;
  338. }
  339. if (fill) {
  340. ctx.fillStyle = color;
  341. } else {
  342. ctx.strokeStyle = color;
  343. ctx.lineJoin = "round";
  344. }
  345. ctx.beginPath();
  346. if (Math.abs(angle - Math.PI * 2) > 0.000000001) {
  347. ctx.moveTo(0, 0); // Center of the pie
  348. }
  349. //ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera
  350. ctx.arc(0, 0, radius, currentAngle, currentAngle + angle / 2, false);
  351. ctx.arc(0, 0, radius, currentAngle + angle / 2, currentAngle + angle, false);
  352. ctx.closePath();
  353. //ctx.rotate(angle); // This doesn't work properly in Opera
  354. currentAngle += angle;
  355. if (fill) {
  356. ctx.fill();
  357. } else {
  358. ctx.stroke();
  359. }
  360. }
  361. function drawLabels() {
  362. var currentAngle = startAngle;
  363. var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius;
  364. for (var i = 0; i < slices.length; ++i) {
  365. if (slices[i].percent >= options.series.pie.label.threshold * 100) {
  366. if (!drawLabel(slices[i], currentAngle, i)) {
  367. return false;
  368. }
  369. }
  370. currentAngle += slices[i].angle;
  371. }
  372. return true;
  373. function drawLabel(slice, startAngle, index) {
  374. if (slice.data[0][1] === 0) {
  375. return true;
  376. }
  377. // format label text
  378. var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
  379. if (lf) {
  380. text = lf(slice.label, slice);
  381. } else {
  382. text = slice.label;
  383. }
  384. if (plf) {
  385. text = plf(text, slice);
  386. }
  387. var halfAngle = ((startAngle + slice.angle) + startAngle) / 2;
  388. var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
  389. var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
  390. var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>";
  391. target.append(html);
  392. var label = target.children("#pieLabel" + index);
  393. var labelTop = (y - label.height() / 2);
  394. var labelLeft = (x - label.width() / 2);
  395. label.css("top", labelTop);
  396. label.css("left", labelLeft);
  397. // check to make sure that the label is not outside the canvas
  398. if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) {
  399. return false;
  400. }
  401. if (options.series.pie.label.background.opacity !== 0) {
  402. // put in the transparent background separately to avoid blended labels and label boxes
  403. var c = options.series.pie.label.background.color;
  404. if (c == null) {
  405. c = slice.color;
  406. }
  407. var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;";
  408. $("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>")
  409. .css("opacity", options.series.pie.label.background.opacity)
  410. .insertBefore(label);
  411. }
  412. return true;
  413. } // end individual label function
  414. } // end drawLabels function
  415. } // end drawPie function
  416. } // end draw function
  417. // Placed here because it needs to be accessed from multiple locations
  418. function drawDonutHole(layer) {
  419. if (options.series.pie.innerRadius > 0) {
  420. // subtract the center
  421. layer.save();
  422. var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
  423. layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
  424. layer.beginPath();
  425. layer.fillStyle = options.series.pie.stroke.color;
  426. layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
  427. layer.fill();
  428. layer.closePath();
  429. layer.restore();
  430. // add inner stroke
  431. layer.save();
  432. layer.beginPath();
  433. layer.strokeStyle = options.series.pie.stroke.color;
  434. layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
  435. layer.stroke();
  436. layer.closePath();
  437. layer.restore();
  438. // TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
  439. }
  440. }
  441. //-- Additional Interactive related functions --
  442. function isPointInPoly(poly, pt) {
  443. for (var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) {
  444. ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) ||
  445. (poly[j][1] <= pt[1] && pt[1] < poly[i][1])) &&
  446. (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) &&
  447. (c = !c);
  448. }
  449. return c;
  450. }
  451. function findNearbySlice(mouseX, mouseY) {
  452. var slices = plot.getData(),
  453. options = plot.getOptions(),
  454. radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius,
  455. x, y;
  456. for (var i = 0; i < slices.length; ++i) {
  457. var s = slices[i];
  458. if (s.pie.show) {
  459. ctx.save();
  460. ctx.beginPath();
  461. ctx.moveTo(0, 0); // Center of the pie
  462. //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here.
  463. ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false);
  464. ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false);
  465. ctx.closePath();
  466. x = mouseX - centerLeft;
  467. y = mouseY - centerTop;
  468. if (ctx.isPointInPath) {
  469. if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) {
  470. ctx.restore();
  471. return {
  472. datapoint: [s.percent, s.data],
  473. dataIndex: 0,
  474. series: s,
  475. seriesIndex: i
  476. };
  477. }
  478. } else {
  479. // excanvas for IE doesn;t support isPointInPath, this is a workaround.
  480. var p1X = radius * Math.cos(s.startAngle),
  481. p1Y = radius * Math.sin(s.startAngle),
  482. p2X = radius * Math.cos(s.startAngle + s.angle / 4),
  483. p2Y = radius * Math.sin(s.startAngle + s.angle / 4),
  484. p3X = radius * Math.cos(s.startAngle + s.angle / 2),
  485. p3Y = radius * Math.sin(s.startAngle + s.angle / 2),
  486. p4X = radius * Math.cos(s.startAngle + s.angle / 1.5),
  487. p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5),
  488. p5X = radius * Math.cos(s.startAngle + s.angle),
  489. p5Y = radius * Math.sin(s.startAngle + s.angle),
  490. arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]],
  491. arrPoint = [x, y];
  492. // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
  493. if (isPointInPoly(arrPoly, arrPoint)) {
  494. ctx.restore();
  495. return {
  496. datapoint: [s.percent, s.data],
  497. dataIndex: 0,
  498. series: s,
  499. seriesIndex: i
  500. };
  501. }
  502. }
  503. ctx.restore();
  504. }
  505. }
  506. return null;
  507. }
  508. function onMouseMove(e) {
  509. triggerClickHoverEvent("plothover", e);
  510. }
  511. function onClick(e) {
  512. triggerClickHoverEvent("plotclick", e);
  513. }
  514. // trigger click or hover event (they send the same parameters so we share their code)
  515. function triggerClickHoverEvent(eventname, e) {
  516. var offset = plot.offset();
  517. var canvasX = parseInt(e.pageX - offset.left);
  518. var canvasY = parseInt(e.pageY - offset.top);
  519. var item = findNearbySlice(canvasX, canvasY);
  520. if (options.grid.autoHighlight) {
  521. // clear auto-highlights
  522. for (var i = 0; i < highlights.length; ++i) {
  523. var h = highlights[i];
  524. if (h.auto === eventname && !(item && h.series === item.series)) {
  525. unhighlight(h.series);
  526. }
  527. }
  528. }
  529. // highlight the slice
  530. if (item) {
  531. highlight(item.series, eventname);
  532. }
  533. // trigger any hover bind events
  534. var pos = { pageX: e.pageX, pageY: e.pageY };
  535. target.trigger(eventname, [pos, item]);
  536. }
  537. function highlight(s, auto) {
  538. //if (typeof s == "number") {
  539. // s = series[s];
  540. //}
  541. var i = indexOfHighlight(s);
  542. if (i === -1) {
  543. highlights.push({ series: s, auto: auto });
  544. plot.triggerRedrawOverlay();
  545. } else if (!auto) {
  546. highlights[i].auto = false;
  547. }
  548. }
  549. function unhighlight(s) {
  550. if (s == null) {
  551. highlights = [];
  552. plot.triggerRedrawOverlay();
  553. }
  554. //if (typeof s == "number") {
  555. // s = series[s];
  556. //}
  557. var i = indexOfHighlight(s);
  558. if (i !== -1) {
  559. highlights.splice(i, 1);
  560. plot.triggerRedrawOverlay();
  561. }
  562. }
  563. function indexOfHighlight(s) {
  564. for (var i = 0; i < highlights.length; ++i) {
  565. var h = highlights[i];
  566. if (h.series === s) {
  567. return i;
  568. }
  569. }
  570. return -1;
  571. }
  572. function drawOverlay(plot, octx) {
  573. var options = plot.getOptions();
  574. var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
  575. octx.save();
  576. octx.translate(centerLeft, centerTop);
  577. octx.scale(1, options.series.pie.tilt);
  578. for (var i = 0; i < highlights.length; ++i) {
  579. drawHighlight(highlights[i].series);
  580. }
  581. drawDonutHole(octx);
  582. octx.restore();
  583. function drawHighlight(series) {
  584. if (series.angle <= 0 || isNaN(series.angle)) {
  585. return;
  586. }
  587. //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
  588. octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor
  589. octx.beginPath();
  590. if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) {
  591. octx.moveTo(0, 0); // Center of the pie
  592. }
  593. octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false);
  594. octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false);
  595. octx.closePath();
  596. octx.fill();
  597. }
  598. }
  599. } // end init (plugin body)
  600. // define pie specific options and their default values
  601. var options = {
  602. series: {
  603. pie: {
  604. show: false,
  605. radius: "auto", // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
  606. innerRadius: 0, /* for donut */
  607. startAngle: 3 / 2,
  608. tilt: 1,
  609. shadow: {
  610. left: 5, // shadow left offset
  611. top: 15, // shadow top offset
  612. alpha: 0.02 // shadow alpha
  613. },
  614. offset: {
  615. top: 0,
  616. left: "auto"
  617. },
  618. stroke: {
  619. color: "#fff",
  620. width: 1
  621. },
  622. label: {
  623. show: "auto",
  624. formatter: function(label, slice) {
  625. return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>";
  626. }, // formatter function
  627. radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
  628. background: {
  629. color: null,
  630. opacity: 0
  631. },
  632. threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow)
  633. },
  634. combine: {
  635. threshold: -1, // percentage at which to combine little slices into one larger slice
  636. color: null, // color to give the new slice (auto-generated if null)
  637. label: "Other" // label to give the new slice
  638. },
  639. highlight: {
  640. //color: "#fff", // will add this functionality once parseColor is available
  641. opacity: 0.5
  642. }
  643. }
  644. }
  645. };
  646. $.plot.plugins.push({
  647. init: init,
  648. options: options,
  649. name: "pie",
  650. version: "1.1"
  651. });
  652. })(jQuery);