RGraph.drawing.text.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 th X position, the Y position and then the text to show
  21. *
  22. * @param string id The canvas tag ID
  23. * @param number x The X position of the text
  24. * @param number y The Y position of the text
  25. * @param number text The text to show
  26. */
  27. RGraph.Drawing.Text = function (id, x, y, text)
  28. {
  29. var tmp = RGraph.getCanvasTag(id);
  30. // Get the canvas and context objects
  31. this.id = tmp[0];
  32. this.canvas = tmp[1];
  33. this.context = this.canvas.getContext ? this.canvas.getContext("2d", {alpha: (typeof id === 'object' && id.alpha === false) ? false : true}) : null;
  34. this.colorsParsed = false;
  35. this.canvas.__object__ = this;
  36. this.x = x;
  37. this.y = y;
  38. this.text = text;
  39. this.coords = [];
  40. this.coordsText = [];
  41. this.original_colors = [];
  42. this.firstDraw = true; // After the first draw this will be false
  43. /**
  44. * This defines the type of this shape
  45. */
  46. this.type = 'drawing.text';
  47. /**
  48. * This facilitates easy object identification, and should always be true
  49. */
  50. this.isRGraph = true;
  51. /**
  52. * This adds a uid to the object that you can use for identification purposes
  53. */
  54. this.uid = RGraph.CreateUID();
  55. /**
  56. * This adds a UID to the canvas for identification purposes
  57. */
  58. this.canvas.uid = this.canvas.uid ? this.canvas.uid : RGraph.CreateUID();
  59. /**
  60. * This does a few things, for example adding the .fillText() method to the canvas 2D context when
  61. * it doesn't exist. This facilitates the graphs to be still shown in older browser (though without
  62. * text obviously). You'll find the function in RGraph.common.core.js
  63. */
  64. //RGraph.OldBrowserCompat(this.context);
  65. /**
  66. * Some example background properties
  67. */
  68. this.properties =
  69. {
  70. 'chart.size': 10,
  71. 'chart.font': 'Arial',
  72. 'chart.bold': false,
  73. 'chart.angle': 0,
  74. 'chart.colors': ['black'],
  75. 'chart.events.click': null,
  76. 'chart.events.mousemove': null,
  77. 'chart.highlight.stroke': '#ccc',
  78. 'chart.highlight.fill': 'rgba(255,255,255,0.7)',
  79. 'chart.tooltips': null,
  80. 'chart.tooltips.effect': 'fade',
  81. 'chart.tooltips.css.class': 'RGraph_tooltip',
  82. 'chart.tooltips.event': 'onclick',
  83. 'chart.tooltips.highlight': true,
  84. 'chart.tooltips.coords.page': false,
  85. 'chart.bounding': false,
  86. 'chart.bounding.fill': 'rgba(255,255,255,0.7)',
  87. 'chart.bounding.stroke': '#777',
  88. 'chart.bounding.shadow': false,
  89. 'chart.bounding.shadow.color': '#ccc',
  90. 'chart.bounding.shadow.blur': 3,
  91. 'chart.bounding.shadow.offsetx': 3,
  92. 'chart.bounding.shadow.offsety': 3,
  93. 'chart.marker': false,
  94. 'chart.halign': 'left',
  95. 'chart.valign': 'bottom',
  96. 'chart.link': null,
  97. 'chart.link.target': '_self',
  98. 'chart.link.options': ''
  99. }
  100. /**
  101. * A simple check that the browser has canvas support
  102. */
  103. if (!this.canvas) {
  104. alert('[DRAWING.TEXT] No canvas support');
  105. return;
  106. }
  107. /**
  108. * Create the dollar object so that functions can be added to them
  109. */
  110. this.$0 = {};
  111. /**
  112. * Translate half a pixel for antialiasing purposes - but only if it hasn't beeen
  113. * done already
  114. */
  115. if (!this.canvas.__rgraph_aa_translated__) {
  116. this.context.translate(0.5,0.5);
  117. this.canvas.__rgraph_aa_translated__ = true;
  118. }
  119. // Short variable names
  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 properties.
  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. prop[name] = value;
  152. return this;
  153. };
  154. /**
  155. * A getter method for retrieving graph properties. It can be used like this: obj.Get('chart.strokestyle');
  156. *
  157. * @param name string The name of the property to get
  158. */
  159. this.get =
  160. this.Get = function (name)
  161. {
  162. /**
  163. * This should be done first - prepend the property name with "chart." if necessary
  164. */
  165. if (name.substr(0,6) != 'chart.') {
  166. name = 'chart.' + name;
  167. }
  168. return prop[name.toLowerCase()];
  169. };
  170. /**
  171. * Draws the rectangle
  172. */
  173. this.draw =
  174. this.Draw = function ()
  175. {
  176. /**
  177. * Fire the onbeforedraw event
  178. */
  179. RG.FireCustomEvent(this, 'onbeforedraw');
  180. /**
  181. * Parse the colors. This allows for simple gradient syntax
  182. */
  183. if (!this.colorsParsed) {
  184. this.parseColors();
  185. // Don't want to do this again
  186. this.colorsParsed = true;
  187. }
  188. /**
  189. * Stop the coods array from growing
  190. */
  191. this.coords = [];
  192. /**
  193. * Stop this growing uncntrollably
  194. */
  195. this.coordsText = [];
  196. /**
  197. * The font, its size and whether its bold or not can be set by properties,
  198. * so now they have been (potentiall) set - measure the text
  199. */
  200. /**
  201. * Measure the text and add the width/height
  202. *
  203. * text, bold, font, size
  204. *
  205. */
  206. var dimensions = RG.MeasureText(this.text, prop['chart.text.bold'],prop['chart.text.font'], prop['chart.text.size']);
  207. // ------------- DRAW TEXT HERE -------------
  208. co.fillStyle = prop['chart.colors'][0];
  209. var ret = RG.Text2(this, {'font': prop['chart.font'],
  210. 'size': prop['chart.size'],
  211. 'x': this.x,
  212. 'y': this.y,
  213. 'text': this.text,
  214. 'bold': prop['chart.bold'],
  215. 'angle': prop['chart.angle'],
  216. 'bounding': prop['chart.bounding'],
  217. 'bounding.fill': prop['chart.bounding.fill'],
  218. 'bounding.stroke': prop['chart.bounding.stroke'],
  219. 'bounding.shadow': prop['chart.bounding.shadow'],
  220. 'bounding.shadow.color': prop['chart.bounding.shadow.color'],
  221. 'bounding.shadow.blur': prop['chart.bounding.shadow.blur'],
  222. 'bounding.shadow.offsetx': prop['chart.bounding.shadow.offsetx'],
  223. 'bounding.shadow.offsety': prop['chart.bounding.shadow.offsety'],
  224. 'marker': prop['chart.marker'],
  225. 'halign': prop['chart.halign'],
  226. 'valign': prop['chart.valign']
  227. });
  228. // store the dimensions
  229. this.coords.push({
  230. 0: ret.x, 'x': ret.x,
  231. 1: ret.y, 'y': ret.y,
  232. 2: ret.width, 'width': ret.width,
  233. 3: ret.height, 'height': ret.height
  234. });
  235. /**
  236. * This installs the event listeners
  237. */
  238. RG.InstallEventListeners(this);
  239. /**
  240. * Fire the onfirstdraw event
  241. */
  242. if (this.firstDraw) {
  243. RG.fireCustomEvent(this, 'onfirstdraw');
  244. this.firstDrawFunc();
  245. this.firstDraw = false;
  246. }
  247. /**
  248. * Fire the ondraw event
  249. */
  250. RG.FireCustomEvent(this, 'ondraw');
  251. return this;
  252. };
  253. /**
  254. * The getObjectByXY() worker method
  255. */
  256. this.getObjectByXY = function (e)
  257. {
  258. if (this.getShape(e)) {
  259. return this;
  260. }
  261. };
  262. /**
  263. * Not used by the class during creating the graph, but is used by event handlers
  264. * to get the coordinates (if any) of the selected bar
  265. *
  266. * @param object e The event object
  267. */
  268. this.getShape = function (e)
  269. {
  270. var prop = this.properties;
  271. var coords = this.coords;
  272. var mouseXY = RGraph.getMouseXY(e);
  273. var mouseX = mouseXY[0];
  274. var mouseY = mouseXY[1];
  275. for (var i=0,len=this.coords.length; i<len; i++) {
  276. var left = coords[i].x;
  277. var top = coords[i].y;
  278. var width = coords[i].width;
  279. var height = coords[i].height;
  280. if (mouseX >= left && mouseX <= (left + width) && mouseY >= top && mouseY <= (top + height)) {
  281. return {
  282. 0: this, 1: left, 2: top, 3: width, 4: height, 5: 0,
  283. 'object': this, 'x': left, 'y': top, 'width': width, 'height': height, 'index': 0, 'tooltip': prop['chart.tooltips'] ? prop['chart.tooltips'][0] : null
  284. };
  285. }
  286. }
  287. return null;
  288. };
  289. /**
  290. * This function positions a tooltip when it is displayed
  291. *
  292. * @param obj object The chart object
  293. * @param int x The X coordinate specified for the tooltip
  294. * @param int y The Y coordinate specified for the tooltip
  295. * @param objec tooltip The tooltips DIV element
  296. */
  297. this.positionTooltip = function (obj, x, y, tooltip, idx)
  298. {
  299. var coords = obj.coords[0];
  300. var coordX = coords.x;
  301. var coordY = coords.y;
  302. var coordW = coords.width;
  303. var coordH = coords.height;
  304. var canvasXY = RGraph.getCanvasXY(obj.canvas);
  305. var width = tooltip.offsetWidth;
  306. var height = tooltip.offsetHeight;
  307. // Set the top position
  308. tooltip.style.left = 0;
  309. tooltip.style.top = canvasXY[1] + coordY + (coordH / 2) - height + 'px';
  310. // By default any overflow is hidden
  311. tooltip.style.overflow = '';
  312. // The arrow
  313. var img = new Image();
  314. img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAFCAYAAACjKgd3AAAARUlEQVQYV2NkQAN79+797+RkhC4M5+/bd47B2dmZEVkBCgcmgcsgbAaA9GA1BCSBbhAuA/AagmwQPgMIGgIzCD0M0AMMAEFVIAa6UQgcAAAAAElFTkSuQmCC';
  315. img.style.position = 'absolute';
  316. img.id = '__rgraph_tooltip_pointer__';
  317. img.style.top = (tooltip.offsetHeight - 2) + 'px';
  318. tooltip.appendChild(img);
  319. // Reposition the tooltip if at the edges:
  320. // LEFT edge
  321. if ((canvasXY[0] + coordX + (coordW / 2) - (width / 2)) < 10) {
  322. tooltip.style.left = (canvasXY[0] + coordX - (width * 0.1)) + (coordW / 2) + 'px';
  323. img.style.left = ((width * 0.1) - 8.5) + 'px';
  324. // RIGHT edge
  325. } else if ((canvasXY[0] + coordX + (coordW / 2) + (width / 2)) > (doc.body.offsetWidth - 10)) {
  326. tooltip.style.left = canvasXY[0] + coordX - (width * 0.9) + (coordW / 2) + 'px';
  327. img.style.left = ((width * 0.9) - 8.5) + 'px';
  328. // Default positioning - CENTERED
  329. } else {
  330. tooltip.style.left = (canvasXY[0] + coordX + (coordW / 2) - (width * 0.5)) + 'px';
  331. img.style.left = ((width * 0.5) - 8.5) + 'px';
  332. }
  333. };
  334. /**
  335. * Each object type has its own Highlight() function which highlights the appropriate shape
  336. *
  337. * @param object shape The shape to highlight
  338. */
  339. this.highlight =
  340. this.Highlight = function (shape)
  341. {
  342. // Add the new highlight
  343. RG.Highlight.Rect(this, shape);
  344. };
  345. /**
  346. * This allows for easy specification of gradients
  347. */
  348. this.parseColors = function ()
  349. {
  350. // Save the original colors so that they can be restored when the canvas is reset
  351. if (this.original_colors.length === 0) {
  352. this.original_colors['chart.colors'] = RG.array_clone(prop['chart.colors'])[0];
  353. this.original_colors['chart.fillstyle'] = RG.array_clone(prop['chart.fillstyle']);
  354. this.original_colors['chart.strokestyle'] = RG.array_clone(prop['chart.strokestyle']);
  355. this.original_colors['chart.highlight.stroke'] = RG.array_clone(prop['chart.highlight.stroke']);
  356. this.original_colors['chart.highlight.fill'] = RG.array_clone(prop['chart.highlight.fill']);
  357. }
  358. /**
  359. * Parse various properties for colors
  360. */
  361. prop['chart.colors'][0] = this.parseSingleColorForGradient(prop['chart.colors'][0]);
  362. prop['chart.fillstyle'] = this.parseSingleColorForGradient(prop['chart.fillstyle']);
  363. prop['chart.strokestyle'] = this.parseSingleColorForGradient(prop['chart.strokestyle']);
  364. prop['chart.highlight.stroke'] = this.parseSingleColorForGradient(prop['chart.highlight.stroke']);
  365. prop['chart.highlight.fill'] = this.parseSingleColorForGradient(prop['chart.highlight.fill']);
  366. };
  367. /**
  368. * This parses a single color value
  369. */
  370. this.parseSingleColorForGradient = function (color)
  371. {
  372. if (!color) {
  373. return color;
  374. }
  375. if (typeof color === 'string' && color.match(/^gradient\((.*)\)$/i)) {
  376. var parts = RegExp.$1.split(':');
  377. // Create the gradient
  378. var grad = co.createLinearGradient(0,0,ca.width,0);
  379. var diff = 1 / (parts.length - 1);
  380. grad.addColorStop(0, RGraph.trim(parts[0]));
  381. for (var j=1,len=parts.length; j<len; ++j) {
  382. grad.addColorStop(j * diff, RG.trim(parts[j]));
  383. }
  384. }
  385. return grad ? grad : color;
  386. };
  387. /**
  388. * Using a function to add events makes it easier to facilitate method chaining
  389. *
  390. * @param string type The type of even to add
  391. * @param function func
  392. */
  393. this.on = function (type, func)
  394. {
  395. if (type.substr(0,2) !== 'on') {
  396. type = 'on' + type;
  397. }
  398. this[type] = func;
  399. return this;
  400. };
  401. /**
  402. * This function runs once only
  403. * (put at the end of the file (before any effects))
  404. */
  405. this.firstDrawFunc = function ()
  406. {
  407. };
  408. /**
  409. * Objects are now always registered so that the chart is redrawn if need be.
  410. */
  411. RG.Register(this);
  412. };