RGraph.drawing.xaxis.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /**
  2. * o------------------------------------------------------------------------------o
  3. * | This file is part of the RGraph package - you can learn more at: |
  4. * | |
  5. * | http://www.rgraph.net |
  6. * | |
  7. * | This package is licensed under the RGraph license. For all kinds of business |
  8. * | purposes there is a small one-time licensing fee to pay and for non |
  9. * | commercial purposes it is free to use. You can read the full license here: |
  10. * | |
  11. * | http://www.rgraph.net/license |
  12. * o------------------------------------------------------------------------------o
  13. */
  14. /**
  15. * Having this here means that the RGraph libraries can be included in any order, instead of you having
  16. * to include the common core library first.
  17. */
  18. if (typeof(RGraph) == 'undefined') RGraph = {};
  19. if (typeof(RGraph.Drawing) == 'undefined') RGraph.Drawing = {};
  20. /**
  21. * The constructor. This function sets up the object. It takes the ID (the HTML attribute) of the canvas as the
  22. * first argument and the Y coordinate of the axes as the second
  23. *
  24. * @param string id The canvas tag ID
  25. * @param number y The Y coordinate
  26. */
  27. RGraph.Drawing.XAxis = function (id, y)
  28. {
  29. this.id = id;
  30. this.canvas = document.getElementById(typeof id === 'object' ? id.id : id);
  31. this.context = this.canvas.getContext('2d');
  32. this.canvas.__object__ = this;
  33. this.y = y;
  34. this.coords = [];
  35. this.coordsText = [];
  36. /**
  37. * This defines the type of this shape
  38. */
  39. this.type = 'drawing.xaxis';
  40. /**
  41. * This facilitates easy object identification, and should always be true
  42. */
  43. this.isRGraph = true;
  44. /**
  45. * This adds a uid to the object that you can use for identification purposes
  46. */
  47. this.uid = RGraph.CreateUID();
  48. /**
  49. * This adds a UID to the canvas for identification purposes
  50. */
  51. this.canvas.uid = this.canvas.uid ? this.canvas.uid : RGraph.CreateUID();
  52. /**
  53. * This does a few things, for example adding the .fillText() method to the canvas 2D context when
  54. * it doesn't exist. This facilitates the graphs to be still shown in older browser (though without
  55. * text obviously). You'll find the function in RGraph.common.core.js
  56. */
  57. RGraph.OldBrowserCompat(this.context);
  58. /**
  59. * Some example background properties
  60. */
  61. this.properties =
  62. {
  63. 'chart.gutter.left': 25,
  64. 'chart.gutter.right': 25,
  65. 'chart.labels': null,
  66. 'chart.labels.position': 'section',
  67. 'chart.colors': ['black'],
  68. 'chart.title.color': null, // Defaults to same as chart.colors
  69. 'chart.text.color': null, // Defaults to same as chart.colors
  70. 'chart.text.font': 'Arial',
  71. 'chart.text.size': 10,
  72. 'chart.align': 'bottom',
  73. 'chart.numlabels': 5,
  74. 'chart.scale.visible': true,
  75. 'chart.scale.formatter': null,
  76. 'chart.scale.decimals': 0,
  77. 'chart.scale.invert': false,
  78. 'chart.scale.zerostart': true,
  79. 'chart.units.pre': '',
  80. 'chart.units.post': '',
  81. 'chart.title': '',
  82. 'chart.numticks': null,
  83. 'chart.hmargin': 0,
  84. 'chart.linewidth': 1,
  85. 'chart.noendtick.left': false,
  86. 'chart.noendtick.right': false,
  87. 'chart.noxaxis': false,
  88. 'chart.max': null,
  89. 'chart.min': 0,
  90. 'chart.tooltips': null,
  91. 'chart.tooltips.effect': 'fade',
  92. 'chart.tooltips.css.class':'RGraph_tooltip',
  93. 'chart.tooltips.event': 'onclick',
  94. 'chart.events.click': null,
  95. 'chart.events.mousemove': null,
  96. 'chart.xaxispos': 'bottom',
  97. 'chart.yaxispos': 'left'
  98. }
  99. /**
  100. * A simple check that the browser has canvas support
  101. */
  102. if (!this.canvas) {
  103. alert('[DRAWING.XAXIS] No canvas support');
  104. return;
  105. }
  106. /**
  107. * Create the dollar object so that functions can be added to them
  108. */
  109. this.$0 = {};
  110. /**
  111. * Translate half a pixel for antialiasing purposes - but only if it hasn't beeen
  112. * done already
  113. */
  114. if (!this.canvas.__rgraph_aa_translated__) {
  115. this.context.translate(0.5,0.5);
  116. this.canvas.__rgraph_aa_translated__ = true;
  117. }
  118. ///////////////////////////////// SHORT PROPERTIES /////////////////////////////////
  119. var RG = RGraph;
  120. var ca = this.canvas;
  121. var co = ca.getContext('2d');
  122. var prop = this.properties;
  123. //////////////////////////////////// METHODS ///////////////////////////////////////
  124. /**
  125. * A setter method for setting graph properties. It can be used like this: obj.Set('chart.strokestyle', '#666');
  126. *
  127. * @param name string The name of the property to set
  128. * @param value mixed The value of the property
  129. */
  130. this.Set = function (name, value)
  131. {
  132. name = name.toLowerCase();
  133. /**
  134. * This should be done first - prepend the property name with "chart." if necessary
  135. */
  136. if (name.substr(0,6) != 'chart.') {
  137. name = 'chart.' + name;
  138. }
  139. /**
  140. * Make the tickmarks align if labels are specified
  141. */
  142. if (name == 'chart.labels' && !prop['chart.numxticks']) {
  143. prop['chart.numxticks'] = value.length;
  144. }
  145. prop[name] = value;
  146. return this;
  147. }
  148. /**
  149. * A getter method for retrieving graph properties. It can be used like this: obj.Get('chart.strokestyle');
  150. *
  151. * @param name string The name of the property to get
  152. */
  153. this.Get = function (name)
  154. {
  155. /**
  156. * This should be done first - prepend the property name with "chart." if necessary
  157. */
  158. if (name.substr(0,6) != 'chart.') {
  159. name = 'chart.' + name;
  160. }
  161. return prop[name.toLowerCase()];
  162. }
  163. /**
  164. * Draws the rectangle
  165. */
  166. this.Draw = function ()
  167. {
  168. /**
  169. * Fire the onbeforedraw event
  170. */
  171. RG.FireCustomEvent(this, 'onbeforedraw');
  172. /**
  173. * Some defaults
  174. */
  175. this.gutterLeft = prop['chart.gutter.left'];
  176. this.gutterRight = prop['chart.gutter.right'];
  177. if (!prop['chart.text.color']) prop['chart.text.color'] = prop['chart.colors'][0];
  178. if (!prop['chart.title.color']) prop['chart.title.color'] = prop['chart.colors'][0];
  179. /**
  180. * Parse the colors. This allows for simple gradient syntax
  181. */
  182. if (!this.colorsParsed) {
  183. this.parseColors();
  184. // Don't want to do this again
  185. this.colorsParsed = true;
  186. }
  187. // DRAW X AXIS HERE
  188. this.DrawXAxis();
  189. /**
  190. * This installs the event listeners
  191. */
  192. RG.InstallEventListeners(this);
  193. /**
  194. * Fire the ondraw event
  195. */
  196. RG.FireCustomEvent(this, 'ondraw');
  197. return this;
  198. }
  199. /**
  200. * The getObjectByXY() worker method
  201. */
  202. this.getObjectByXY = function (e)
  203. {
  204. if (this.getShape(e)) {
  205. return this;
  206. }
  207. }
  208. /**
  209. * Not used by the class during creating the graph, but is used by event handlers
  210. * to get the coordinates (if any) of the selected shape
  211. *
  212. * @param object e The event object
  213. */
  214. this.getShape = function (e)
  215. {
  216. var mouseXY = RG.getMouseXY(e);
  217. var mouseX = mouseXY[0];
  218. var mouseY = mouseXY[1];
  219. if ( mouseX >= this.gutterLeft
  220. && mouseX <= (ca.width - this.gutterRight)
  221. && mouseY >= this.y - (prop['chart.align'] == 'top' ? (prop['chart.text.size'] * 1.5) + 5 : 0)
  222. && mouseY <= (this.y + (prop['chart.align'] == 'top' ? 0 : (prop['chart.text.size'] * 1.5) + 5))
  223. ) {
  224. var x = this.gutterLeft;
  225. var y = this.y;
  226. var w = ca.width - this.gutterLeft - this.gutterRight;
  227. var h = 15;
  228. return {
  229. 0: this, 1: x, 2: y, 3: w, 4: h, 5: 0,
  230. 'object': this, 'x': x, 'y': y, 'width': w, 'height': h, 'index': 0, 'tooltip': prop['chart.tooltips'] ? prop['chart.tooltips'][0] : null
  231. };
  232. }
  233. return null;
  234. }
  235. /**
  236. * This function positions a tooltip when it is displayed
  237. *
  238. * @param obj object The chart object
  239. * @param int x The X coordinate specified for the tooltip
  240. * @param int y The Y coordinate specified for the tooltip
  241. * @param objec tooltip The tooltips DIV element
  242. */
  243. this.positionTooltip = function (obj, x, y, tooltip, idx)
  244. {
  245. var coordX = obj.gutterLeft;
  246. var coordY = obj.y;
  247. var coordW = ca.width - obj.gutterLeft - obj.gutterRight;
  248. var coordH = prop['chart.text.size'] * 1.5;
  249. var canvasXY = RG.getCanvasXY(ca);
  250. var width = tooltip.offsetWidth;
  251. var height = tooltip.offsetHeight;
  252. // Set the top position
  253. tooltip.style.left = 0;
  254. 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';
  255. // By default any overflow is hidden
  256. tooltip.style.overflow = '';
  257. // The arrow
  258. var img = new Image();
  259. img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAFCAYAAACjKgd3AAAARUlEQVQYV2NkQAN79+797+RkhC4M5+/bd47B2dmZEVkBCgcmgcsgbAaA9GA1BCSBbhAuA/AagmwQPgMIGgIzCD0M0AMMAEFVIAa6UQgcAAAAAElFTkSuQmCC';
  260. img.style.position = 'absolute';
  261. img.id = '__rgraph_tooltip_pointer__';
  262. img.style.top = (tooltip.offsetHeight - 2) + 'px';
  263. tooltip.appendChild(img);
  264. // Reposition the tooltip if at the edges:
  265. // LEFT edge
  266. if ((canvasXY[0] + coordX + (coordW / 2) - (width / 2)) < 10) {
  267. tooltip.style.left = (canvasXY[0] + coordX - (width * 0.1)) + (coordW / 2) + 'px';
  268. img.style.left = ((width * 0.1) - 8.5) + 'px';
  269. // RIGHT edge
  270. } else if ((canvasXY[0] + coordX + (width / 2)) > document.body.offsetWidth) {
  271. tooltip.style.left = canvasXY[0] + coordX - (width * 0.9) + (coordW / 2) + 'px';
  272. img.style.left = ((width * 0.9) - 8.5) + 'px';
  273. // Default positioning - CENTERED
  274. } else {
  275. tooltip.style.left = (canvasXY[0] + coordX + (coordW / 2) - (width * 0.5)) + 'px';
  276. img.style.left = ((width * 0.5) - 8.5) + 'px';
  277. }
  278. }
  279. /**
  280. * Each object type has its own Highlight() function which highlights the appropriate shape
  281. *
  282. * @param object shape The shape to highlight
  283. */
  284. this.Highlight = function (shape)
  285. {
  286. // When showing tooltips, this method can be used to highlight the X axis
  287. }
  288. /**
  289. * This allows for easy specification of gradients
  290. */
  291. this.parseColors = function ()
  292. {
  293. /**
  294. * Parse various properties for colors
  295. */
  296. //this.properties['chart.title.color'] = this.parseSingleColorForGradient(this.properties['chart.title.color']);
  297. //this.properties['chart.text.color'] = this.parseSingleColorForGradient(this.properties['chart.text.color']);
  298. prop['chart.colors'][0] = this.parseSingleColorForGradient(prop['chart.colors'][0]);
  299. }
  300. /**
  301. * This parses a single color value
  302. */
  303. this.parseSingleColorForGradient = function (color)
  304. {
  305. if (!color) {
  306. return color;
  307. }
  308. if (color.match(/^gradient\((.*)\)$/i)) {
  309. var parts = RegExp.$1.split(':');
  310. // Create the gradient
  311. var grad = co.createLinearGradient(prop['chart.gutter.left'],0,ca.width - prop['chart.gutter.right'],0);
  312. var diff = 1 / (parts.length - 1);
  313. grad.addColorStop(0, RG.trim(parts[0]));
  314. for (var j=1,len=parts.length; j<len; ++j) {
  315. grad.addColorStop(j * diff, RG.trim(parts[j]));
  316. }
  317. }
  318. return grad ? grad : color;
  319. }
  320. /**
  321. * The function that draws the X axis
  322. */
  323. this.DrawXAxis = function ()
  324. {
  325. var gutterLeft = prop['chart.gutter.left'];
  326. var gutterRight = prop['chart.gutter.right'];
  327. var x = this.gutterLeft;
  328. var y = this.y;
  329. var min = prop['chart.min'];
  330. var max = prop['chart.max'];
  331. var labels = prop['chart.labels'];
  332. var labels_position = prop['chart.labels.position'];
  333. var color = prop['chart.colors'][0];
  334. var title_color = prop['chart.title.color'];
  335. var label_color = prop['chart.text.color'];
  336. var width = ca.width - this.gutterLeft - this.gutterRight;
  337. var font = prop['chart.text.font'];
  338. var size = prop['chart.text.size'];
  339. var align = prop['chart.align'];
  340. var numlabels = prop['chart.numlabels'];
  341. var formatter = prop['chart.scale.formatter'];
  342. var decimals = Number(prop['chart.scale.decimals']);
  343. var invert = prop['chart.scale.invert'];
  344. var scale_visible = prop['chart.scale.visible'];
  345. var units_pre = prop['chart.units.pre'];
  346. var units_post = prop['chart.units.post'];
  347. var title = prop['chart.title'];
  348. var numticks = prop['chart.numticks'];
  349. var hmargin = prop['chart.hmargin'];
  350. var linewidth = prop['chart.linewidth'];
  351. var noleftendtick = prop['chart.noendtick.left'];
  352. var norightendtick = prop['chart.noendtick.right'];
  353. var noxaxis = prop['chart.noxaxis'];
  354. var xaxispos = prop['chart.xaxispos'];
  355. var yaxispos = prop['chart.yaxispos'];
  356. if (RG.is_null(numticks)) {
  357. if (labels && labels.length) {
  358. numticks = labels.length;
  359. } else if (!labels && max != 0) {
  360. numticks = 10;
  361. } else {
  362. numticks = numlabels;
  363. }
  364. }
  365. /**
  366. * Set the linewidth
  367. */
  368. co.lineWidth = linewidth + 0.001;
  369. /**
  370. * Set the color
  371. */
  372. co.strokeStyle = color;
  373. if (!noxaxis) {
  374. /**
  375. * Draw the main horizontal line
  376. */
  377. co.beginPath();
  378. co.moveTo(x, Math.round(y));
  379. co.lineTo(x + width, Math.round(y));
  380. co.stroke();
  381. /**
  382. * Draw the axis tickmarks
  383. */
  384. co.beginPath();
  385. for (var i=(noleftendtick ? 1 : 0); i<=(numticks - (norightendtick ? 1 : 0)); ++i) {
  386. co.moveTo(Math.round(x + ((width / numticks) * i)), xaxispos == 'center' ? (align == 'bottom' ? y - 3 : y + 3) : y);
  387. co.lineTo(Math.round(x + ((width / numticks) * i)), y + (align == 'bottom' ? 3 : -3));
  388. }
  389. co.stroke();
  390. }
  391. /**
  392. * Draw the labels
  393. */
  394. co.fillStyle = label_color;
  395. if (labels) {
  396. /**
  397. * Draw the labels
  398. */
  399. numlabels = labels.length;
  400. var h = 0;
  401. var l = 0;
  402. var single_line = RG.MeasureText('Mg', false, font, size);
  403. // Measure the maximum height
  404. for (var i=0,len=labels.length; i<len; ++i) {
  405. var dimensions = RG.MeasureText(labels[i], false, font, size);
  406. var h = Math.max(h, dimensions[1]);
  407. var l = Math.max(l, labels[i].split('\r\n').length);
  408. }
  409. for (var i=0,len=labels.length; i<len; ++i) {
  410. RGraph.Text2(this,{'font': font,
  411. 'size': size,
  412. '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),
  413. 'y':align == 'bottom' ? y + 3 : y - 3 - h + single_line[1],
  414. 'text':String(labels[i]),
  415. 'valign': align == 'bottom' ? 'top' : 'bottom',
  416. 'halign':'center',
  417. 'tag': 'labels'
  418. });
  419. }
  420. /**
  421. * No specific labels - draw a scale
  422. */
  423. } else if (scale_visible){
  424. if (!max) {
  425. alert('[DRAWING.XAXIS] If not specifying axis.labels you must specify axis.max!');
  426. }
  427. // yaxispos
  428. if (yaxispos == 'center') {
  429. width /= 2;
  430. var additionalX = width;
  431. } else {
  432. var additionalX = 0;
  433. }
  434. for (var i=0; i<=numlabels; ++i) {
  435. // Don't show zero if the chart.scale.zerostart option is false
  436. if (i == 0 && !prop['chart.scale.zerostart']) {
  437. continue;
  438. }
  439. var original = (((max - min) / numlabels) * i) + min;
  440. var hmargin = prop['chart.hmargin'];
  441. var text = String(typeof(formatter) == 'function' ? formatter(this, original) : RG.number_format(this, original.toFixed(decimals), units_pre, units_post));
  442. if (invert) {
  443. var x = ((width - hmargin - ((width - hmargin - hmargin) / numlabels) * i)) + gutterLeft + additionalX;
  444. } else {
  445. var x = (((width - hmargin - hmargin) / numlabels) * i) + gutterLeft + hmargin + additionalX;
  446. }
  447. RG.Text2(this,{'font': font,
  448. 'size': size,
  449. 'x': x,
  450. 'y': align == 'bottom' ? y + 3 : y - 3,
  451. 'text':text,
  452. 'valign':align == 'bottom' ? 'top' : 'bottom',
  453. 'halign':'center',
  454. 'tag': 'scale'
  455. });
  456. }
  457. /**
  458. * If the Y axis is in the center - this draws the left half of the labels
  459. */
  460. if (yaxispos == 'center') {
  461. for (var i=0; i<numlabels; ++i) {
  462. var original = (((max - min) / numlabels) * (numlabels - i)) + min;
  463. var hmargin = prop['chart.hmargin'];
  464. var text = String(typeof(formatter) == 'function' ? formatter(this, original) : RG.number_format(this, original.toFixed(decimals), units_pre, units_post));
  465. if (invert) {
  466. var x = ((width - hmargin - ((width - hmargin - hmargin) / numlabels) * i)) + gutterLeft;
  467. } else {
  468. var x = (((width - hmargin - hmargin) / numlabels) * i) + gutterLeft + hmargin;
  469. }
  470. RG.Text2(this, {'font':font,
  471. 'size':size,
  472. 'x':x,
  473. 'y':align == 'bottom' ? y + size + 2 : y - size - 2,'text':'-' + text,
  474. 'valign':'center',
  475. 'halign':'center',
  476. 'tag': 'scale'
  477. });
  478. }
  479. }
  480. }
  481. /**
  482. * Draw the title for the axes
  483. */
  484. if (title) {
  485. var dimensions = RG.MeasureText(title, false, font, size + 2);
  486. co.fillStyle = title_color
  487. RG.Text2(this,{'font': font,
  488. 'size': size + 2,
  489. 'x': (ca.width - this.gutterLeft - this.gutterRight) / 2 + this.gutterLeft,
  490. 'y': align == 'bottom' ? y + dimensions[1] + 10 : y - dimensions[1] - 10,
  491. 'text': title,
  492. 'valign': 'center',
  493. 'halign':'center',
  494. 'tag': 'title'
  495. });
  496. }
  497. }
  498. /**
  499. * Objects are now always registered so that the chart is redrawn if need be.
  500. */
  501. RG.Register(this);
  502. }