RGraph.drawing.xaxis.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 and the Y coordinate of the axes as the second
  21. *
  22. * @param string id The canvas tag ID
  23. * @param number y The Y coordinate
  24. */
  25. RGraph.Drawing.XAxis = function (id, y)
  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.canvas.__object__ = this;
  33. this.y = y;
  34. this.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.xaxis';
  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.gutter.left': 25,
  66. 'chart.gutter.right': 25,
  67. 'chart.labels': null,
  68. 'chart.labels.position': 'section',
  69. 'chart.colors': ['black'],
  70. 'chart.title.color': null, // Defaults to same as chart.colors
  71. 'chart.text.color': null, // Defaults to same as chart.colors
  72. 'chart.text.font': 'Arial',
  73. 'chart.text.size': 10,
  74. 'chart.align': 'bottom',
  75. 'chart.numlabels': 5,
  76. 'chart.scale.visible': true,
  77. 'chart.scale.formatter': null,
  78. 'chart.scale.decimals': 0,
  79. 'chart.scale.invert': false,
  80. 'chart.scale.zerostart': true,
  81. 'chart.units.pre': '',
  82. 'chart.units.post': '',
  83. 'chart.title': '',
  84. 'chart.numticks': null,
  85. 'chart.hmargin': 0,
  86. 'chart.linewidth': 1,
  87. 'chart.noendtick.left': false,
  88. 'chart.noendtick.right': false,
  89. 'chart.noxaxis': false,
  90. 'chart.max': null,
  91. 'chart.min': 0,
  92. 'chart.tooltips': null,
  93. 'chart.tooltips.effect': 'fade',
  94. 'chart.tooltips.css.class':'RGraph_tooltip',
  95. 'chart.tooltips.event': 'onclick',
  96. 'chart.events.click': null,
  97. 'chart.events.mousemove': null,
  98. 'chart.xaxispos': 'bottom',
  99. 'chart.yaxispos': 'left'
  100. }
  101. /**
  102. * A simple check that the browser has canvas support
  103. */
  104. if (!this.canvas) {
  105. alert('[DRAWING.XAXIS] No canvas support');
  106. return;
  107. }
  108. /**
  109. * Create the dollar object so that functions can be added to them
  110. */
  111. this.$0 = {};
  112. /**
  113. * Translate half a pixel for antialiasing purposes - but only if it hasn't beeen
  114. * done already
  115. */
  116. if (!this.canvas.__rgraph_aa_translated__) {
  117. this.context.translate(0.5,0.5);
  118. this.canvas.__rgraph_aa_translated__ = true;
  119. }
  120. var RG = RGraph;
  121. var ca = this.canvas;
  122. var co = ca.getContext('2d');
  123. var prop = this.properties;
  124. var jq = jQuery;
  125. var pa = RG.Path;
  126. var win = window;
  127. var doc = document;
  128. var ma = Math;
  129. /**
  130. * "Decorate" the object with the generic effects if the effects library has been included
  131. */
  132. if (RG.Effects && typeof RG.Effects.decorate === 'function') {
  133. RG.Effects.decorate(this);
  134. }
  135. /**
  136. * A setter method for setting graph properties. It can be used like this: obj.Set('chart.strokestyle', '#666');
  137. *
  138. * @param name string The name of the property to set
  139. * @param value mixed The value of the property
  140. */
  141. this.set =
  142. this.Set = function (name, value)
  143. {
  144. name = name.toLowerCase();
  145. /**
  146. * This should be done first - prepend the property name with "chart." if necessary
  147. */
  148. if (name.substr(0,6) != 'chart.') {
  149. name = 'chart.' + name;
  150. }
  151. /**
  152. * Make the tickmarks align if labels are specified
  153. */
  154. if (name == 'chart.labels' && !prop['chart.numxticks']) {
  155. prop['chart.numxticks'] = value.length;
  156. }
  157. prop[name] = value;
  158. return this;
  159. };
  160. /**
  161. * A getter method for retrieving graph properties. It can be used like this: obj.Get('chart.strokestyle');
  162. *
  163. * @param name string The name of the property to get
  164. */
  165. this.get =
  166. this.Get = function (name)
  167. {
  168. /**
  169. * This should be done first - prepend the property name with "chart." if necessary
  170. */
  171. if (name.substr(0,6) != 'chart.') {
  172. name = 'chart.' + name;
  173. }
  174. return prop[name.toLowerCase()];
  175. };
  176. /**
  177. * Draws the rectangle
  178. */
  179. this.draw =
  180. this.Draw = function ()
  181. {
  182. /**
  183. * Fire the onbeforedraw event
  184. */
  185. RG.FireCustomEvent(this, 'onbeforedraw');
  186. /**
  187. * Stop this growing uncntrollably
  188. */
  189. this.coordsText = [];
  190. /**
  191. * Some defaults
  192. */
  193. this.gutterLeft = prop['chart.gutter.left'];
  194. this.gutterRight = prop['chart.gutter.right'];
  195. if (!prop['chart.text.color']) prop['chart.text.color'] = prop['chart.colors'][0];
  196. if (!prop['chart.title.color']) prop['chart.title.color'] = prop['chart.colors'][0];
  197. /**
  198. * Parse the colors. This allows for simple gradient syntax
  199. */
  200. if (!this.colorsParsed) {
  201. this.parseColors();
  202. // Don't want to do this again
  203. this.colorsParsed = true;
  204. }
  205. // DRAW X AXIS HERE
  206. this.DrawXAxis();
  207. /**
  208. * This installs the event listeners
  209. */
  210. RG.InstallEventListeners(this);
  211. /**
  212. * Fire the onfirstdraw event
  213. */
  214. if (this.firstDraw) {
  215. RG.fireCustomEvent(this, 'onfirstdraw');
  216. this.firstDrawFunc();
  217. this.firstDraw = false;
  218. }
  219. /**
  220. * Fire the ondraw event
  221. */
  222. RG.FireCustomEvent(this, 'ondraw');
  223. return this;
  224. };
  225. /**
  226. * The getObjectByXY() worker method
  227. */
  228. this.getObjectByXY = function (e)
  229. {
  230. if (this.getShape(e)) {
  231. return this;
  232. }
  233. };
  234. /**
  235. * Not used by the class during creating the graph, but is used by event handlers
  236. * to get the coordinates (if any) of the selected shape
  237. *
  238. * @param object e The event object
  239. */
  240. this.getShape = function (e)
  241. {
  242. var mouseXY = RG.getMouseXY(e);
  243. var mouseX = mouseXY[0];
  244. var mouseY = mouseXY[1];
  245. if ( mouseX >= this.gutterLeft
  246. && mouseX <= (ca.width - this.gutterRight)
  247. && mouseY >= this.y - (prop['chart.align'] == 'top' ? (prop['chart.text.size'] * 1.5) + 5 : 0)
  248. && mouseY <= (this.y + (prop['chart.align'] == 'top' ? 0 : (prop['chart.text.size'] * 1.5) + 5))
  249. ) {
  250. var x = this.gutterLeft;
  251. var y = this.y;
  252. var w = ca.width - this.gutterLeft - this.gutterRight;
  253. var h = 15;
  254. return {
  255. 0: this, 1: x, 2: y, 3: w, 4: h, 5: 0,
  256. 'object': this, 'x': x, 'y': y, 'width': w, 'height': h, 'index': 0, 'tooltip': prop['chart.tooltips'] ? prop['chart.tooltips'][0] : null
  257. };
  258. }
  259. return null;
  260. };
  261. /**
  262. * This function positions a tooltip when it is displayed
  263. *
  264. * @param obj object The chart object
  265. * @param int x The X coordinate specified for the tooltip
  266. * @param int y The Y coordinate specified for the tooltip
  267. * @param objec tooltip The tooltips DIV element
  268. */
  269. this.positionTooltip = function (obj, x, y, tooltip, idx)
  270. {
  271. var coordX = obj.gutterLeft;
  272. var coordY = obj.y;
  273. var coordW = ca.width - obj.gutterLeft - obj.gutterRight;
  274. var coordH = prop['chart.text.size'] * 1.5;
  275. var canvasXY = RG.getCanvasXY(ca);
  276. var width = tooltip.offsetWidth;
  277. var height = tooltip.offsetHeight;
  278. // Set the top position
  279. tooltip.style.left = 0;
  280. tooltip.style.top = canvasXY[1] + this.y - height - 5 + (prop['chart.align'] == 'top' ? ((prop['chart.text.size'] * 1.5) / 2) * -1 : ((prop['chart.text.size'] * 1.5) / 2)) + 'px';
  281. // By default any overflow is hidden
  282. tooltip.style.overflow = '';
  283. // The arrow
  284. var img = new Image();
  285. img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAFCAYAAACjKgd3AAAARUlEQVQYV2NkQAN79+797+RkhC4M5+/bd47B2dmZEVkBCgcmgcsgbAaA9GA1BCSBbhAuA/AagmwQPgMIGgIzCD0M0AMMAEFVIAa6UQgcAAAAAElFTkSuQmCC';
  286. img.style.position = 'absolute';
  287. img.id = '__rgraph_tooltip_pointer__';
  288. img.style.top = (tooltip.offsetHeight - 2) + 'px';
  289. tooltip.appendChild(img);
  290. // Reposition the tooltip if at the edges:
  291. // LEFT edge
  292. if ((canvasXY[0] + coordX + (coordW / 2) - (width / 2)) < 10) {
  293. tooltip.style.left = (canvasXY[0] + coordX - (width * 0.1)) + (coordW / 2) + 'px';
  294. img.style.left = ((width * 0.1) - 8.5) + 'px';
  295. // RIGHT edge
  296. } else if ((canvasXY[0] + coordX + (coordW / 2) + (width / 2)) > (doc.body.offsetWidth - 10) ) {
  297. tooltip.style.left = canvasXY[0] + coordX - (width * 0.9) + (coordW / 2) + 'px';
  298. img.style.left = ((width * 0.9) - 8.5) + 'px';
  299. // Default positioning - CENTERED
  300. } else {
  301. tooltip.style.left = (canvasXY[0] + coordX + (coordW / 2) - (width * 0.5)) + 'px';
  302. img.style.left = ((width * 0.5) - 8.5) + 'px';
  303. }
  304. };
  305. /**
  306. * Each object type has its own Highlight() function which highlights the appropriate shape
  307. *
  308. * @param object shape The shape to highlight
  309. */
  310. this.highlight =
  311. this.Highlight = function (shape)
  312. {
  313. // When showing tooltips, this method can be used to highlight the X axis
  314. };
  315. /**
  316. * This allows for easy specification of gradients
  317. */
  318. this.parseColors = function ()
  319. {
  320. // Save the original colors so that they can be restored when the canvas is reset
  321. if (this.original_colors.length === 0) {
  322. this.original_colors['chart.colors'] = RG.array_clone(prop['chart.colors']);
  323. }
  324. /**
  325. * Parse various properties for colors
  326. */
  327. //this.properties['chart.title.color'] = this.parseSingleColorForGradient(this.properties['chart.title.color']);
  328. //this.properties['chart.text.color'] = this.parseSingleColorForGradient(this.properties['chart.text.color']);
  329. prop['chart.colors'][0] = this.parseSingleColorForGradient(prop['chart.colors'][0]);
  330. };
  331. /**
  332. * This parses a single color value
  333. */
  334. this.parseSingleColorForGradient = function (color)
  335. {
  336. if (!color) {
  337. return color;
  338. }
  339. if (typeof color === 'string' && color.match(/^gradient\((.*)\)$/i)) {
  340. var parts = RegExp.$1.split(':');
  341. // Create the gradient
  342. var grad = co.createLinearGradient(prop['chart.gutter.left'],0,ca.width - prop['chart.gutter.right'],0);
  343. var diff = 1 / (parts.length - 1);
  344. grad.addColorStop(0, RG.trim(parts[0]));
  345. for (var j=1,len=parts.length; j<len; ++j) {
  346. grad.addColorStop(j * diff, RG.trim(parts[j]));
  347. }
  348. }
  349. return grad ? grad : color;
  350. };
  351. /**
  352. * The function that draws the X axis
  353. */
  354. this.drawXAxis =
  355. this.DrawXAxis = function ()
  356. {
  357. var gutterLeft = prop['chart.gutter.left'];
  358. var gutterRight = prop['chart.gutter.right'];
  359. var x = this.gutterLeft;
  360. var y = this.y;
  361. var min = prop['chart.min'];
  362. var max = prop['chart.max'];
  363. var labels = prop['chart.labels'];
  364. var labels_position = prop['chart.labels.position'];
  365. var color = prop['chart.colors'][0];
  366. var title_color = prop['chart.title.color'];
  367. var label_color = prop['chart.text.color'];
  368. var width = ca.width - this.gutterLeft - this.gutterRight;
  369. var font = prop['chart.text.font'];
  370. var size = prop['chart.text.size'];
  371. var align = prop['chart.align'];
  372. var numlabels = prop['chart.numlabels'];
  373. var formatter = prop['chart.scale.formatter'];
  374. var decimals = Number(prop['chart.scale.decimals']);
  375. var invert = prop['chart.scale.invert'];
  376. var scale_visible = prop['chart.scale.visible'];
  377. var units_pre = prop['chart.units.pre'];
  378. var units_post = prop['chart.units.post'];
  379. var title = prop['chart.title'];
  380. var numticks = prop['chart.numticks'];
  381. var hmargin = prop['chart.hmargin'];
  382. var linewidth = prop['chart.linewidth'];
  383. var noleftendtick = prop['chart.noendtick.left'];
  384. var norightendtick = prop['chart.noendtick.right'];
  385. var noxaxis = prop['chart.noxaxis'];
  386. var xaxispos = prop['chart.xaxispos'];
  387. var yaxispos = prop['chart.yaxispos'];
  388. if (RG.is_null(numticks)) {
  389. if (labels && labels.length) {
  390. numticks = labels.length;
  391. } else if (!labels && max != 0) {
  392. numticks = 10;
  393. } else {
  394. numticks = numlabels;
  395. }
  396. }
  397. /**
  398. * Set the linewidth
  399. */
  400. co.lineWidth = linewidth + 0.001;
  401. /**
  402. * Set the color
  403. */
  404. co.strokeStyle = color;
  405. if (!noxaxis) {
  406. /**
  407. * Draw the main horizontal line
  408. */
  409. pa(co, ['b','m',x, Math.round(y),'l',x + width, Math.round(y),'s',co.strokeStyle]);
  410. /**
  411. * Draw the axis tickmarks
  412. */
  413. co.beginPath();
  414. for (var i=(noleftendtick ? 1 : 0); i<=(numticks - (norightendtick ? 1 : 0)); ++i) {
  415. co.moveTo(Math.round(x + ((width / numticks) * i)), xaxispos == 'center' ? (align == 'bottom' ? y - 3 : y + 3) : y);
  416. co.lineTo(Math.round(x + ((width / numticks) * i)), y + (align == 'bottom' ? 3 : -3));
  417. }
  418. co.stroke();
  419. }
  420. /**
  421. * Draw the labels
  422. */
  423. co.fillStyle = label_color;
  424. if (labels) {
  425. /**
  426. * Draw the labels
  427. */
  428. numlabels = labels.length;
  429. var h = 0;
  430. var l = 0;
  431. var single_line = RG.MeasureText('Mg', false, font, size);
  432. // Measure the maximum height
  433. for (var i=0,len=labels.length; i<len; ++i) {
  434. var dimensions = RG.MeasureText(labels[i], false, font, size);
  435. var h = Math.max(h, dimensions[1]);
  436. var l = Math.max(l, labels[i].split('\r\n').length);
  437. }
  438. for (var i=0,len=labels.length; i<len; ++i) {
  439. RG.Text2(this,{'font': font,
  440. 'size': size,
  441. 'x': labels_position == 'edge' ? ((((width - hmargin - hmargin) / (labels.length - 1)) * i) + gutterLeft + hmargin) : ((((width - hmargin - hmargin) / labels.length) * i) + ((width / labels.length) / 2) + gutterLeft + hmargin),
  442. 'y':align == 'bottom' ? y + 3 : y - 3 - h + single_line[1],
  443. 'text':String(labels[i]),
  444. 'valign': align == 'bottom' ? 'top' : 'bottom',
  445. 'halign':'center',
  446. 'tag': 'labels'
  447. });
  448. }
  449. /**
  450. * No specific labels - draw a scale
  451. */
  452. } else if (scale_visible){
  453. if (max === null) {
  454. alert('[DRAWING.XAXIS] If not specifying axis.labels you must specify axis.max!');
  455. }
  456. // yaxispos
  457. if (yaxispos == 'center') {
  458. width /= 2;
  459. var additionalX = width;
  460. } else {
  461. var additionalX = 0;
  462. }
  463. for (var i=0; i<=numlabels; ++i) {
  464. // Don't show zero if the chart.scale.zerostart option is false
  465. if (i == 0 && !prop['chart.scale.zerostart']) {
  466. continue;
  467. }
  468. var original = (((max - min) / numlabels) * i) + min;
  469. var hmargin = prop['chart.hmargin'];
  470. var text = String(typeof(formatter) == 'function' ? formatter(this, original) : RG.number_format(this, original.toFixed(decimals), units_pre, units_post));
  471. if (invert) {
  472. var x = ((width - hmargin - ((width - hmargin - hmargin) / numlabels) * i)) + gutterLeft + additionalX;
  473. } else {
  474. var x = (((width - hmargin - hmargin) / numlabels) * i) + gutterLeft + hmargin + additionalX;
  475. }
  476. RG.Text2(this,{'font': font,
  477. 'size': size,
  478. 'x': x,
  479. 'y': align == 'bottom' ? y + 3 : y - 3,
  480. 'text':text,
  481. 'valign':align == 'bottom' ? 'top' : 'bottom',
  482. 'halign':'center',
  483. 'tag': 'scale'
  484. });
  485. }
  486. /**
  487. * If the Y axis is in the center - this draws the left half of the labels
  488. */
  489. if (yaxispos == 'center') {
  490. for (var i=0; i<numlabels; ++i) {
  491. var original = (((max - min) / numlabels) * (numlabels - i)) + min;
  492. var hmargin = prop['chart.hmargin'];
  493. var text = String(typeof(formatter) == 'function' ? formatter(this, original) : RG.number_format(this, original.toFixed(decimals), units_pre, units_post));
  494. if (invert) {
  495. var x = ((width - hmargin - ((width - hmargin - hmargin) / numlabels) * i)) + gutterLeft;
  496. } else {
  497. var x = (((width - hmargin - hmargin) / numlabels) * i) + gutterLeft + hmargin;
  498. }
  499. RG.Text2(this, {'font':font,
  500. 'size':size,
  501. 'x':x,
  502. 'y':align == 'bottom' ? y + size + 2 : y - size - 2,'text':'-' + text,
  503. 'valign':'center',
  504. 'halign':'center',
  505. 'tag': 'scale'
  506. });
  507. }
  508. }
  509. }
  510. /**
  511. * Draw the title for the axes
  512. */
  513. if (title) {
  514. var dimensions = RG.MeasureText(title, false, font, size + 2);
  515. co.fillStyle = title_color
  516. RG.Text2(this,{'font': font,
  517. 'size': size + 2,
  518. 'x': (ca.width - this.gutterLeft - this.gutterRight) / 2 + this.gutterLeft,
  519. 'y': align == 'bottom' ? y + dimensions[1] + 10 : y - dimensions[1] - 10,
  520. 'text': title,
  521. 'valign': 'center',
  522. 'halign':'center',
  523. 'tag': 'title'
  524. });
  525. }
  526. };
  527. /**
  528. * Using a function to add events makes it easier to facilitate method chaining
  529. *
  530. * @param string type The type of even to add
  531. * @param function func
  532. */
  533. this.on = function (type, func)
  534. {
  535. if (type.substr(0,2) !== 'on') {
  536. type = 'on' + type;
  537. }
  538. this[type] = func;
  539. return this;
  540. };
  541. /**
  542. * This function runs once only
  543. * (put at the end of the file (before any effects))
  544. */
  545. this.firstDrawFunc = function ()
  546. {
  547. };
  548. /**
  549. * Objects are now always registered so that the chart is redrawn if need be.
  550. */
  551. RG.Register(this);
  552. };