RGraph.drawing.rect.js 15 KB

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