RGraph.drawing.poly.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // version: 2014-06-26
  2. /**
  3. * o--------------------------------------------------------------------------------o
  4. * | This file is part of the RGraph package. RGraph is Free Software, licensed |
  5. * | under the MIT license - so it's free to use for all purposes. If you want to |
  6. * | donate to help keep the project going then you can do so here: |
  7. * | |
  8. * | http://www.rgraph.net/donate |
  9. * o--------------------------------------------------------------------------------o
  10. */
  11. /**
  12. * Having this here means that the RGraph libraries can be included in any order, instead of you having
  13. * to include the common core library first.
  14. */
  15. // Define the RGraph global variable
  16. RGraph = window.RGraph || {isRGraph: true};
  17. RGraph.Drawing = RGraph.Drawing || {};
  18. /**
  19. * The constructor. This function sets up the object. It takes the ID (the HTML attribute) of the canvas as the
  20. * first argument, then the coordinates of the coords of the shape
  21. *
  22. * @param string id The canvas tag ID
  23. * @param number coords The coordinates of the shape
  24. */
  25. RGraph.Drawing.Poly = function (id, coords)
  26. {
  27. var tmp = RGraph.getCanvasTag(id);
  28. // Get the canvas and context objects
  29. this.id = tmp[0];
  30. this.canvas = tmp[1];
  31. this.context = this.canvas.getContext ? this.canvas.getContext("2d", {alpha: (typeof id === 'object' && id.alpha === false) ? false : true}) : null;
  32. this.colorsParsed = false;
  33. this.canvas.__object__ = this;
  34. this.coords = coords;
  35. this.coordsText = [];
  36. this.original_colors = [];
  37. this.firstDraw = true; // After the first draw this will be false
  38. /**
  39. * This defines the type of this shape
  40. */
  41. this.type = 'drawing.poly';
  42. /**
  43. * This facilitates easy object identification, and should always be true
  44. */
  45. this.isRGraph = true;
  46. /**
  47. * This adds a uid to the object that you can use for identification purposes
  48. */
  49. this.uid = RGraph.CreateUID();
  50. /**
  51. * This adds a UID to the canvas for identification purposes
  52. */
  53. this.canvas.uid = this.canvas.uid ? this.canvas.uid : RGraph.CreateUID();
  54. /**
  55. * This does a few things, for example adding the .fillText() method to the canvas 2D context when
  56. * it doesn't exist. This facilitates the graphs to be still shown in older browser (though without
  57. * text obviously). You'll find the function in RGraph.common.core.js
  58. */
  59. //RGraph.OldBrowserCompat(this.context);
  60. /**
  61. * Some example background properties
  62. */
  63. this.properties =
  64. {
  65. 'chart.linewidth': 1,
  66. 'chart.strokestyle': 'black',
  67. 'chart.fillstyle': 'red',
  68. 'chart.events.click': null,
  69. 'chart.events.mousemove': null,
  70. 'chart.tooltips': null,
  71. 'chart.tooltips.override': null,
  72. 'chart.tooltips.effect': 'fade',
  73. 'chart.tooltips.css.class': 'RGraph_tooltip',
  74. 'chart.tooltips.event': 'onclick',
  75. 'chart.tooltips.highlight': true,
  76. 'chart.highlight.stroke': 'rgba(0,0,0,0)',
  77. 'chart.highlight.fill': 'rgba(255,255,255,0.7)',
  78. 'chart.shadow': false,
  79. 'chart.shadow.color': 'rgba(0,0,0,0.2)',
  80. 'chart.shadow.offsetx': 3,
  81. 'chart.shadow.offsety': 3,
  82. 'chart.shadow.blur': 5
  83. }
  84. /**
  85. * A simple check that the browser has canvas support
  86. */
  87. if (!this.canvas) {
  88. alert('[DRAWING.POLY] No canvas support');
  89. return;
  90. }
  91. /**
  92. * Create the dollar object so that functions can be added to them
  93. */
  94. this.$0 = {};
  95. /**
  96. * Translate half a pixel for antialiasing purposes - but only if it hasn't beeen
  97. * done already
  98. */
  99. if (!this.canvas.__rgraph_aa_translated__) {
  100. this.context.translate(0.5,0.5);
  101. this.canvas.__rgraph_aa_translated__ = true;
  102. }
  103. // Short variable names
  104. var RG = RGraph;
  105. var ca = this.canvas;
  106. var co = ca.getContext('2d');
  107. var prop = this.properties;
  108. var jq = jQuery;
  109. var pa = RG.Path;
  110. var win = window;
  111. var doc = document;
  112. var ma = Math;
  113. /**
  114. * "Decorate" the object with the generic effects if the effects library has been included
  115. */
  116. if (RG.Effects && typeof RG.Effects.decorate === 'function') {
  117. RG.Effects.decorate(this);
  118. }
  119. /**
  120. * A setter method for setting properties.
  121. *
  122. * @param name string The name of the property to set
  123. * @param value mixed The value of the property
  124. */
  125. this.set =
  126. this.Set = function (name, value)
  127. {
  128. name = name.toLowerCase();
  129. /**
  130. * This should be done first - prepend the property name with "chart." if necessary
  131. */
  132. if (name.substr(0,6) != 'chart.') {
  133. name = 'chart.' + name;
  134. }
  135. prop[name] = value;
  136. return this;
  137. };
  138. /**
  139. * A getter method for retrieving graph properties. It can be used like this: obj.Get('chart.strokestyle');
  140. *
  141. * @param name string The name of the property to get
  142. */
  143. this.get =
  144. this.Get = function (name)
  145. {
  146. /**
  147. * This should be done first - prepend the property name with "chart." if necessary
  148. */
  149. if (name.substr(0,6) != 'chart.') {
  150. name = 'chart.' + name;
  151. }
  152. return prop[name.toLowerCase()];
  153. };
  154. /**
  155. * Draws the shape
  156. */
  157. this.draw =
  158. this.Draw = function ()
  159. {
  160. /**
  161. * Fire the onbeforedraw event
  162. */
  163. RG.FireCustomEvent(this, 'onbeforedraw');
  164. /**
  165. * Parse the colors. This allows for simple gradient syntax
  166. */
  167. if (!this.colorsParsed) {
  168. this.parseColors();
  169. // Don't want to do this again
  170. this.colorsParsed = true;
  171. }
  172. /**
  173. * Stop this growing uncntrollably
  174. */
  175. this.coordsText = [];
  176. /**
  177. * DRAW THE SHAPE HERE
  178. */
  179. var obj = this;
  180. pa(this, ['b','fu',function (obj){if (prop['chart.shadow'])
  181. {
  182. co.shadowColor = prop['chart.shadow.color'];
  183. co.shadowOffsetX = prop['chart.shadow.offsetx'];
  184. co.shadowOffsetY = prop['chart.shadow.offsety'];
  185. co.shadowBlur = prop['chart.shadow.blur'];
  186. }},'fu',function (obj)
  187. {
  188. co.strokeStyle=prop['chart.strokestyle'];
  189. co.fillStyle=prop['chart.fillstyle'];
  190. obj.DrawPoly();
  191. },'lw',prop['chart.linewidth'],'f',prop['chart.fillstyle'], 'fu', function ()
  192. {
  193. RG.NoShadow(obj);
  194. }, 's',prop['chart.strokestyle']]);
  195. /**
  196. * Turn off shadow again
  197. */
  198. RG.NoShadow(this)
  199. /**
  200. * This installs the event listeners
  201. */
  202. RG.InstallEventListeners(this);
  203. /**
  204. * Fire the onfirstdraw event
  205. */
  206. if (this.firstDraw) {
  207. RG.fireCustomEvent(this, 'onfirstdraw');
  208. this.firstDrawFunc();
  209. this.firstDraw = false;
  210. }
  211. /**
  212. * Fire the ondraw event
  213. */
  214. RG.FireCustomEvent(this, 'ondraw');
  215. return this;
  216. };
  217. /**
  218. * The getObjectByXY() worker method
  219. */
  220. this.getObjectByXY = function (e)
  221. {
  222. if (this.getShape(e)) {
  223. return this;
  224. }
  225. };
  226. /**
  227. * Draw the Poly but doesn't stroke or fill - that's left to other functions
  228. */
  229. this.drawPoly =
  230. this.DrawPoly = function ()
  231. {
  232. var coords = this.coords;
  233. pa(this, ['b','m',coords[0][0], coords[0][1]]);
  234. // Draw lines to subsequent coords
  235. for (var i=1,len=coords.length; i<len; ++i) {
  236. co.lineTo(coords[i][0],coords[i][1]);
  237. }
  238. // Close the path and stroke/fill it with whatever the current fill/stroke styles are
  239. pa(this, ['lw', prop['chart.linewidth'], 'c','f',co.fillStyle, 's',co.strokeStyle]);
  240. };
  241. /**
  242. * Not used by the class during creating the graph, but is used by event handlers
  243. * to get the coordinates (if any) of the selected bar
  244. *
  245. * @param object e The event object
  246. */
  247. this.getShape = function (e)
  248. {
  249. var coords = this.coords;
  250. var mouseXY = RGraph.getMouseXY(e);
  251. var mouseX = mouseXY[0];
  252. var mouseY = mouseXY[1];
  253. // Should redraw the poly but not stroke or fill it and then use isPointInPath() to test it
  254. // DON'T USE PATH OBJECT HERE
  255. co.beginPath();
  256. co.strokeStyle = 'rgba(0,0,0,0)';
  257. co.fillStyle = 'rgba(0,0,0,0)';
  258. this.DrawPoly();
  259. if (co.isPointInPath(mouseX, mouseY)) {
  260. return {
  261. 0: this, 1: this.coords, 2: 0,
  262. 'object': this, 'coords': this.coords, 'index': 0, 'tooltip': prop['chart.tooltips'] ? prop['chart.tooltips'][0] : null
  263. };
  264. }
  265. return null;
  266. };
  267. /**
  268. * This function positions a tooltip when it is displayed
  269. *
  270. * @param obj object The chart object
  271. * @param int x The X coordinate specified for the tooltip
  272. * @param int y The Y coordinate specified for the tooltip
  273. * @param objec tooltip The tooltips DIV element
  274. */
  275. this.positionTooltip = function (obj, x, y, tooltip, idx)
  276. {
  277. var canvasXY = RGraph.getCanvasXY(obj.canvas);
  278. var width = tooltip.offsetWidth;
  279. var height = tooltip.offsetHeight;
  280. // Set the top position
  281. tooltip.style.left = 0;
  282. tooltip.style.top = (y - height - 7) + 'px';
  283. // By default any overflow is hidden
  284. tooltip.style.overflow = '';
  285. // The arrow
  286. var img = new Image();
  287. img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAFCAYAAACjKgd3AAAARUlEQVQYV2NkQAN79+797+RkhC4M5+/bd47B2dmZEVkBCgcmgcsgbAaA9GA1BCSBbhAuA/AagmwQPgMIGgIzCD0M0AMMAEFVIAa6UQgcAAAAAElFTkSuQmCC';
  288. img.style.position = 'absolute';
  289. img.id = '__rgraph_tooltip_pointer__';
  290. img.style.top = (tooltip.offsetHeight - 2) + 'px';
  291. tooltip.appendChild(img);
  292. /**
  293. * Reposition the tooltip if at the edges:
  294. */
  295. // LEFT edge
  296. if (x - (width / 2) < 10) {
  297. tooltip.style.left = (canvasXY[0] + x - (width * 0.1)) - 8.5+ 'px';
  298. img.style.left = ((width * 0.1) - 8.5) + 'px';
  299. // RIGHT edge
  300. } else if ((x + (width / 2)) > doc.body.offsetWidth) {
  301. tooltip.style.left = x - (width * 0.9) + 'px';
  302. img.style.left = ((width * 0.9) - 8.5) + 'px';
  303. // Default positioning - CENTERED
  304. } else {
  305. tooltip.style.left = x - (width / 2) + 'px';
  306. img.style.left = ((width * 0.5) - 8.5) + 'px';
  307. }
  308. };
  309. /**
  310. * Each object type has its own Highlight() function which highlights the appropriate shape
  311. *
  312. * @param object shape The shape to highlight
  313. */
  314. this.highlight =
  315. this.Highlight = function (shape)
  316. {
  317. // Evidentally this is necessary
  318. co.fillStyle = prop['chart.fillstyle'];
  319. // Add the new highlight
  320. if (prop['chart.tooltips.highlight']) {
  321. pa(this, ['b','fu', function (obj){obj.DrawPoly();},'f',prop['chart.highlight.fill'],'s',prop['chart.highlight.stroke']]);
  322. }
  323. };
  324. /**
  325. * This allows for easy specification of gradients
  326. */
  327. this.parseColors = function ()
  328. {
  329. // Save the original colors so that they can be restored when the canvas is reset
  330. if (this.original_colors.length === 0) {
  331. this.original_colors['chart.fillstyle'] = RG.array_clone(prop['chart.fillstyle']);
  332. this.original_colors['chart.strokestyle'] = RG.array_clone(prop['chart.strokestyle']);
  333. this.original_colors['chart.highlight.stroke'] = RG.array_clone(prop['chart.highlight.stroke']);
  334. this.original_colors['chart.highlight.fill'] = RG.array_clone(prop['chart.highlight.fill']);
  335. }
  336. var func = this.parseSingleColorForGradient;
  337. /**
  338. * Parse various properties for colors
  339. */
  340. prop['chart.fillstyle'] = func(prop['chart.fillstyle']);
  341. prop['chart.strokestyle'] = func(prop['chart.strokestyle']);
  342. prop['chart.highlight.stroke'] = func(prop['chart.highlight.stroke']);
  343. prop['chart.highlight.fill'] = func(prop['chart.highlight.fill']);
  344. };
  345. /**
  346. * This parses a single color value
  347. */
  348. this.parseSingleColorForGradient = function (color)
  349. {
  350. if (!color) {
  351. return color;
  352. }
  353. if (typeof color === 'string' && color.match(/^gradient\((.*)\)$/i)) {
  354. var parts = RegExp.$1.split(':');
  355. // Create the gradient
  356. var grad = co.createLinearGradient(0,0,ca.width,0);
  357. var diff = 1 / (parts.length - 1);
  358. grad.addColorStop(0, RG.trim(parts[0]));
  359. for (var j=1,len=parts.length; j<len; ++j) {
  360. grad.addColorStop(j * diff, RG.trim(parts[j]));
  361. }
  362. }
  363. return grad ? grad : color;
  364. };
  365. /**
  366. * Using a function to add events makes it easier to facilitate method chaining
  367. *
  368. * @param string type The type of even to add
  369. * @param function func
  370. */
  371. this.on = function (type, func)
  372. {
  373. if (type.substr(0,2) !== 'on') {
  374. type = 'on' + type;
  375. }
  376. this[type] = func;
  377. return this;
  378. };
  379. /**
  380. * This function runs once only
  381. * (put at the end of the file (before any effects))
  382. */
  383. this.firstDrawFunc = function ()
  384. {
  385. };
  386. /**
  387. * Objects are now always registered so that the chart is redrawn if need be.
  388. */
  389. RG.Register(this);
  390. };