RGraph.drawing.image.js 18 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.Image = function (id, x, y)
  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.src = (typeof(arguments[3]) == 'string') ? arguments[3] : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACcAAAAjCAYAAAAXMhMjAAAD5klEQVRYR+2Yf0xbVRTHP++1tHQMqBXKoIBAtmyIsokmIyxujgRdRMniT5yRzGjizIIxCm5m/lhiTESasDhEh0vcjDrnP0bBuYhuJoIsSrIpG3Nbha5IEQgrsxNKKe95Xxs16hikbdKaeJKXl/T+eJ9+zz3nnnslVRjCslIl7RUX5r4YRELS4DSwAaclLsA0iPy8C2iAUmYKajyB/aGQBvg/XDjrJSrK9Z7biDHRR1dnF/6Aj4KCPEpLy0nW7QmH6c8xUYE7+VMV9sYDHO2Yxu+HnFy4b9MK6raOxh5u3welvNZ0iOFBwSIygCkJim8081T9atbe9F3YgFFRbtebZTS83I46AzNCOVkPZevMPLOjhDWrTsQW7hV7Ca82fIFO5HBZhlmhXtlaM9ueL2RN8ZnYwu0/WCzc+hVDwq3qrEyiSaJUwB3cH8ry4VrEbvXqC+nuUtn57DecOQlKAJKT4f6aLBpf8oXLFRwXMZw2ydHvLey2Ozj2pXDpNFxthU2b03lu22zs4U6ct9LS5KT9Q18wKLJyoPbJfDbXXIw9nHMik70to7zdPIYi4IquT6J++zJuu9UVG7gplmPir0hsfS8F+04n3gm4ZX0G23esYOXK3tjA/fOrbUcsAs6Bywl33JnF7tcjC4aoBYQ2UWePleZGB6f7Atx1byYvviAiI0KLSrRqDMdP2WjdNcAPvZeofiib2q2TEaJFKZVoFM6ha9m3x013dz8PP2aj+p6p+IH7bXo1B94Z4/OOHrbULqH8ZrHJRmhRc+uY9xrOnTbybc9xKjakUVQQJ8oFJJuo47JxnRenJVmHNVNH0uJxDLN9EWkXFeV+di/j8KduDrUNMj4OGTYj1Q/ms6EynUX6U2EDRgXurVYz9oZ+vJ5grQminisugcefSGPj7Urs4H48m0pT4yCftQdIELXcpEhvinhb0uDuBzJ4us7GVSaRmcOweZWTE3LFfjn3Hnm238obzSO8/65HFJsS+gRJACokm6HmkVzq6nPFQWfutedXlmOQL1+QXhFO0q9CDVy5zB75tYCOw5O0NPfhcAh5RDVsWgTX3aDn0S05lK9PJ1XSGua2GbmcBOXIvzrMq9x83vBJFXg8Vjq/dvHxR8cYHLpAwdJsKqtKWFeeTcriCYzTbfNNc9n2iOHC+uoCB/034QJyEYrfg0HvDv1PxSbWUwJa4a1IKqokY1AHFqjBAroZqsD/yd86xrVyFZVLQ/dz5mSJEVf83M/lFeoY/mU0BKfpGc7NplGkjSntpC+OhHqxMyQm6jAYZC55Z7SsgioysqroQ4+qE7+JR+RDGbGdzGGJliX0DwwHW38HIHO9QizDMu0AAAAASUVORK5CYII=';
  42. this.img = new Image();
  43. this.img.src = this.src;
  44. /**
  45. * This defines the type of this shape
  46. */
  47. this.type = 'drawing.image';
  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.src': null,
  72. 'chart.width': null,
  73. 'chart.height': null,
  74. 'chart.halign': 'left',
  75. 'chart.valign': 'top',
  76. 'chart.events.mousemove': null,
  77. 'chart.events.click': null,
  78. 'chart.shadow': false,
  79. 'chart.shadow.color': 'gray',
  80. 'chart.shadow.offsetx': 3,
  81. 'chart.shadow.offsety': 3,
  82. 'chart.shadow.blur': 5,
  83. 'chart.tooltips': null,
  84. 'chart.tooltips.highlight': true,
  85. 'chart.tooltips.css.class': 'RGraph_tooltip',
  86. 'chart.tooltips.event': 'onclick',
  87. 'chart.highlight.stroke': 'rgba(0,0,0,0)',
  88. 'chart.highlight.fill': 'rgba(255,255,255,0.7)',
  89. 'chart.alpha': 1
  90. }
  91. /**
  92. * A simple check that the browser has canvas support
  93. */
  94. if (!this.canvas) {
  95. alert('[DRAWING.IMAGE] No canvas support');
  96. return;
  97. }
  98. /**
  99. * This can be used to store the coordinates of shapes on the graph
  100. */
  101. this.coords = [];
  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 PROPERTIES /////////////////////////////////
  115. var RG = RGraph;
  116. var ca = this.canvas;
  117. var co = ca.getContext('2d');
  118. var prop = this.properties;
  119. //////////////////////////////////// METHODS ///////////////////////////////////////
  120. /**
  121. * A setter method for setting graph properties. It can be used like this: obj.Set('chart.strokestyle', '#666');
  122. *
  123. * @param name string The name of the property to set
  124. * @param value mixed The value of the property
  125. */
  126. this.Set = function (name, value)
  127. {
  128. name = name.toLowerCase();
  129. /**
  130. * This should be done first - prepend the propertyy name with "chart." if necessary
  131. */
  132. if (name.substr(0,6) != 'chart.') {
  133. name = 'chart.' + name;
  134. }
  135. prop[name] = value;
  136. return this;
  137. }
  138. /**
  139. * A getter method for retrieving graph properties. It can be used like this: obj.Get('chart.strokestyle');
  140. *
  141. * @param name string The name of the property to get
  142. */
  143. this.Get = function (name)
  144. {
  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. return prop[name.toLowerCase()];
  152. }
  153. /**
  154. * Draws the circle
  155. */
  156. this.Draw = function ()
  157. {
  158. /**
  159. * Fire the onbeforedraw event
  160. */
  161. RG.FireCustomEvent(this, 'onbeforedraw');
  162. /**
  163. * Parse the colors. This allows for simple gradient syntax
  164. */
  165. var __object__ = this;
  166. this.img.onload = function ()
  167. {
  168. if (!__object__.colorsParsed) {
  169. __object__.parseColors();
  170. // Don't want to do this again
  171. __object__.colorsParsed = true;
  172. }
  173. __object__.width = this.width;
  174. __object__.height = this.height;
  175. if (typeof(alignmentProcessed) == 'undefined') {
  176. var customWidthHeight = (typeof(__object__.properties['chart.width']) == 'number' && typeof(__object__.properties['chart.width']) == 'number');
  177. // Horizontal alignment
  178. if (__object__.properties['chart.halign'] == 'center') {
  179. __object__.x -= customWidthHeight ? (__object__.properties['chart.width'] / 2) : (this.width / 2);
  180. } else if (__object__.properties['chart.halign'] == 'right') {
  181. __object__.x -= customWidthHeight ? __object__.properties['chart.width'] : this.width;
  182. }
  183. // Vertical alignment
  184. if (__object__.properties['chart.valign'] == 'center') {
  185. __object__.y -= customWidthHeight ? (__object__.properties['chart.height'] / 2) : (this.height / 2);
  186. } else if (__object__.properties['chart.valign'] == 'bottom') {
  187. __object__.y -= customWidthHeight ? __object__.properties['chart.height'] : this.height;
  188. }
  189. // Don't do this again
  190. alignmentProcessed = true;
  191. }
  192. }
  193. // The onload event doesn't always fire - so call it manually as well
  194. if (this.img.complete || this.img.readyState === 4) {
  195. this.img.onload();
  196. }
  197. /**
  198. * Draw the image here
  199. */
  200. if (prop['chart.shadow']) {
  201. RG.SetShadow(this, prop['chart.shadow.color'], prop['chart.shadow.offsetx'], prop['chart.shadow.offsety'], prop['chart.shadow.blur']);
  202. }
  203. var oldAlpha = co.globalAlpha;
  204. co.globalAlpha = prop['chart.alpha'];
  205. if (typeof(prop['chart.width']) == 'number' && typeof(prop['chart.width']) == 'number') {
  206. co.drawImage(
  207. this.img,
  208. Math.round(this.x),
  209. Math.round(this.y),
  210. prop['chart.width'],
  211. prop['chart.height']
  212. );
  213. } else {
  214. co.drawImage(
  215. this.img,
  216. Math.round(this.x),
  217. Math.round(this.y)
  218. );
  219. }
  220. co.globalAlpha = oldAlpha;
  221. var obj = this;
  222. this.img.onload = function ()
  223. {
  224. RGraph.RedrawCanvas(ca);
  225. obj.coords[0] = [Math.round(obj.x), Math.round(obj.y), typeof(prop['chart.width']) == 'number' ? prop['chart.width'] : this.width, typeof(prop['chart.height']) == 'number' ? prop['chart.height'] : this.height];
  226. }
  227. RG.NoShadow(this);
  228. /**
  229. * This installs the event listeners
  230. */
  231. RG.InstallEventListeners(this);
  232. /**
  233. * Fire the ondraw event
  234. */
  235. RG.FireCustomEvent(this, 'ondraw');
  236. return this;
  237. }
  238. /**
  239. * The getObjectByXY() worker method
  240. */
  241. this.getObjectByXY = function (e)
  242. {
  243. var mouseXY = RG.getMouseXY(e);
  244. if (this.getShape(e)) {
  245. return this;
  246. }
  247. }
  248. /**
  249. * Not used by the class during creating the shape, but is used by event handlers
  250. * to get the coordinates (if any) of the selected bar
  251. *
  252. * @param object e The event object
  253. * @param object OPTIONAL You can pass in the bar object instead of the
  254. * function using "this"
  255. */
  256. this.getShape = function (e)
  257. {
  258. var mouseXY = RG.getMouseXY(e);
  259. var mouseX = mouseXY[0];
  260. var mouseY = mouseXY[1];
  261. if ( this.coords
  262. && this.coords[0]
  263. && mouseXY[0] >= this.coords[0][0]
  264. && mouseXY[0] <= (this.coords[0][0] + this.coords[0][2])
  265. && mouseXY[1] >= this.coords[0][1]
  266. && mouseXY[1] <= (this.coords[0][1] + this.coords[0][3])) {
  267. return {
  268. 0: this, 1: this.coords[0][0], 2: this.coords[0][1], 3: this.coords[0][2], 4: this.coords[0][3], 5: 0,
  269. '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
  270. };
  271. }
  272. return null;
  273. }
  274. /**
  275. * This function positions a tooltip when it is displayed
  276. *
  277. * @param obj object The chart object
  278. * @param int x The X coordinate specified for the tooltip
  279. * @param int y The Y coordinate specified for the tooltip
  280. * @param object tooltip The tooltips DIV element
  281. * @param number idx The index of the tooltip
  282. */
  283. this.positionTooltip = function (obj, x, y, tooltip, idx)
  284. {
  285. var canvasXY = RG.getCanvasXY(obj.canvas);
  286. var width = tooltip.offsetWidth;
  287. var height = tooltip.offsetHeight;
  288. // Set the top position
  289. tooltip.style.left = 0;
  290. tooltip.style.top = canvasXY[1] + this.coords[0][1] - height - 7 + 'px';
  291. // By default any overflow is hidden
  292. tooltip.style.overflow = '';
  293. // The arrow
  294. var img = new Image();
  295. img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAFCAYAAACjKgd3AAAARUlEQVQYV2NkQAN79+797+RkhC4M5+/bd47B2dmZEVkBCgcmgcsgbAaA9GA1BCSBbhAuA/AagmwQPgMIGgIzCD0M0AMMAEFVIAa6UQgcAAAAAElFTkSuQmCC';
  296. img.style.position = 'absolute';
  297. img.id = '__rgraph_tooltip_pointer__';
  298. img.style.top = (tooltip.offsetHeight - 2) + 'px';
  299. tooltip.appendChild(img);
  300. // Reposition the tooltip if at the edges:
  301. // LEFT edge
  302. if ((canvasXY[0] + obj.coords[0][0] + (obj.coords[0][2] / 2) - (width / 2)) < 10) {
  303. tooltip.style.left = (canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) - (width * 0.1)) + 'px';
  304. img.style.left = ((width * 0.1) - 8.5) + 'px';
  305. // RIGHT edge
  306. } else if ((canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) + (width / 2)) > document.body.offsetWidth) {
  307. tooltip.style.left = (canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) - (width * 0.9)) + 'px';
  308. img.style.left = ((width * 0.9) - 8.5) + 'px';
  309. // Default positioning - CENTERED
  310. } else {
  311. tooltip.style.left = (canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) - (width * 0.5)) + 'px';
  312. img.style.left = ((width * 0.5) - 8.5) + 'px';
  313. }
  314. }
  315. /**
  316. * Each object type has its own Highlight() function which highlights the appropriate shape
  317. *
  318. * @param object shape The shape to highlight
  319. */
  320. this.Highlight = function (shape)
  321. {
  322. if (prop['chart.tooltips.highlight']) {
  323. co.beginPath();
  324. co.strokeStyle = prop['chart.highlight.stroke'];
  325. co.fillStyle = prop['chart.highlight.fill'];
  326. co.rect(this.coords[0][0],this.coords[0][1],this.coords[0][2],this.coords[0][3]);
  327. co.fill();
  328. co.stroke();
  329. }
  330. }
  331. /**
  332. * This allows for easy specification of gradients
  333. */
  334. this.parseColors = function ()
  335. {
  336. /**
  337. * Parse various properties for colors
  338. */
  339. prop['chart.highlight.stroke'] = this.parseSingleColorForGradient(prop['chart.highlight.stroke']);
  340. prop['chart.highlight.fill'] = this.parseSingleColorForGradient(prop['chart.highlight.fill']);
  341. }
  342. /**
  343. * This parses a single color value
  344. */
  345. this.parseSingleColorForGradient = function (color)
  346. {
  347. if (!color || typeof(color) != 'string') {
  348. return color;
  349. }
  350. if (color.match(/^gradient\((.*)\)$/i)) {
  351. var parts = RegExp.$1.split(':');
  352. // Create the gradient
  353. var grad = co.createLinearGradient(this.x, this.y, this.x + this.img.width, this.y);
  354. var diff = 1 / (parts.length - 1);
  355. grad.addColorStop(0, RG.trim(parts[0]));
  356. for (var j=1; j<parts.length; ++j) {
  357. grad.addColorStop(j * diff, RG.trim(parts[j]));
  358. }
  359. }
  360. return grad ? grad : color;
  361. }
  362. /**
  363. * Objects are now always registered so that the chart is redrawn if need be.
  364. */
  365. RG.Register(this);
  366. }