RGraph.drawing.marker2.js 18 KB

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