RGraph.drawing.marker2.js 16 KB

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