jquery.canvaswrapper.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /** ## jquery.flot.canvaswrapper
  2. This plugin contains the function for creating and manipulating both the canvas
  3. layers and svg layers.
  4. The Canvas object is a wrapper around an HTML5 canvas tag.
  5. The constructor Canvas(cls, container) takes as parameters cls,
  6. the list of classes to apply to the canvas adnd the containter,
  7. element onto which to append the canvas. The canvas operations
  8. don't work unless the canvas is attached to the DOM.
  9. ### jquery.canvaswrapper.js API functions
  10. */
  11. (function($) {
  12. var Canvas = function(cls, container) {
  13. var element = container.getElementsByClassName(cls)[0];
  14. if (!element) {
  15. element = document.createElement('canvas');
  16. element.className = cls;
  17. element.style.direction = 'ltr';
  18. element.style.position = 'absolute';
  19. element.style.left = '0px';
  20. element.style.top = '0px';
  21. container.appendChild(element);
  22. // If HTML5 Canvas isn't available, throw
  23. if (!element.getContext) {
  24. throw new Error('Canvas is not available.');
  25. }
  26. }
  27. this.element = element;
  28. var context = this.context = element.getContext('2d');
  29. this.pixelRatio = $.plot.browser.getPixelRatio(context);
  30. // Size the canvas to match the internal dimensions of its container
  31. var box = container.getBoundingClientRect();
  32. this.resize(box.width, box.height);
  33. // Collection of HTML div layers for text overlaid onto the canvas
  34. this.SVGContainer = null;
  35. this.SVG = {};
  36. // Cache of text fragments and metrics, so we can avoid expensively
  37. // re-calculating them when the plot is re-rendered in a loop.
  38. this._textCache = {};
  39. }
  40. /**
  41. - resize(width, height)
  42. Resizes the canvas to the given dimensions.
  43. The width represents the new width of the canvas, meanwhile the height
  44. is the new height of the canvas, both of them in pixels.
  45. */
  46. Canvas.prototype.resize = function(width, height) {
  47. var minSize = 10;
  48. width = width < minSize ? minSize : width;
  49. height = height < minSize ? minSize : height;
  50. var element = this.element,
  51. context = this.context,
  52. pixelRatio = this.pixelRatio;
  53. // Resize the canvas, increasing its density based on the display's
  54. // pixel ratio; basically giving it more pixels without increasing the
  55. // size of its element, to take advantage of the fact that retina
  56. // displays have that many more pixels in the same advertised space.
  57. // Resizing should reset the state (excanvas seems to be buggy though)
  58. if (this.width !== width) {
  59. element.width = width * pixelRatio;
  60. element.style.width = width + 'px';
  61. this.width = width;
  62. }
  63. if (this.height !== height) {
  64. element.height = height * pixelRatio;
  65. element.style.height = height + 'px';
  66. this.height = height;
  67. }
  68. // Save the context, so we can reset in case we get replotted. The
  69. // restore ensure that we're really back at the initial state, and
  70. // should be safe even if we haven't saved the initial state yet.
  71. context.restore();
  72. context.save();
  73. // Scale the coordinate space to match the display density; so even though we
  74. // may have twice as many pixels, we still want lines and other drawing to
  75. // appear at the same size; the extra pixels will just make them crisper.
  76. context.scale(pixelRatio, pixelRatio);
  77. };
  78. /**
  79. - clear()
  80. Clears the entire canvas area, not including any overlaid HTML text
  81. */
  82. Canvas.prototype.clear = function() {
  83. this.context.clearRect(0, 0, this.width, this.height);
  84. };
  85. /**
  86. - render()
  87. Finishes rendering the canvas, including managing the text overlay.
  88. */
  89. Canvas.prototype.render = function() {
  90. var cache = this._textCache;
  91. // For each text layer, add elements marked as active that haven't
  92. // already been rendered, and remove those that are no longer active.
  93. for (var layerKey in cache) {
  94. if (hasOwnProperty.call(cache, layerKey)) {
  95. var layer = this.getSVGLayer(layerKey),
  96. layerCache = cache[layerKey];
  97. var display = layer.style.display;
  98. layer.style.display = 'none';
  99. for (var styleKey in layerCache) {
  100. if (hasOwnProperty.call(layerCache, styleKey)) {
  101. var styleCache = layerCache[styleKey];
  102. for (var key in styleCache) {
  103. if (hasOwnProperty.call(styleCache, key)) {
  104. var val = styleCache[key],
  105. positions = val.positions;
  106. for (var i = 0, position; positions[i]; i++) {
  107. position = positions[i];
  108. if (position.active) {
  109. if (!position.rendered) {
  110. layer.appendChild(position.element);
  111. position.rendered = true;
  112. }
  113. } else {
  114. positions.splice(i--, 1);
  115. if (position.rendered) {
  116. while (position.element.firstChild) {
  117. position.element.removeChild(position.element.firstChild);
  118. }
  119. position.element.parentNode.removeChild(position.element);
  120. }
  121. }
  122. }
  123. if (positions.length === 0) {
  124. if (val.measured) {
  125. val.measured = false;
  126. } else {
  127. delete styleCache[key];
  128. }
  129. }
  130. }
  131. }
  132. }
  133. }
  134. layer.style.display = display;
  135. }
  136. }
  137. };
  138. /**
  139. - getSVGLayer(classes)
  140. Creates (if necessary) and returns the SVG overlay container.
  141. The classes string represents the string of space-separated CSS classes
  142. used to uniquely identify the text layer. It return the svg-layer div.
  143. */
  144. Canvas.prototype.getSVGLayer = function(classes) {
  145. var layer = this.SVG[classes];
  146. // Create the SVG layer if it doesn't exist
  147. if (!layer) {
  148. // Create the svg layer container, if it doesn't exist
  149. var svgElement;
  150. if (!this.SVGContainer) {
  151. this.SVGContainer = document.createElement('div');
  152. this.SVGContainer.className = 'flot-svg';
  153. this.SVGContainer.style.position = 'absolute';
  154. this.SVGContainer.style.top = '0px';
  155. this.SVGContainer.style.left = '0px';
  156. this.SVGContainer.style.height = '100%';
  157. this.SVGContainer.style.width = '100%';
  158. this.SVGContainer.style.pointerEvents = 'none';
  159. this.element.parentNode.appendChild(this.SVGContainer);
  160. svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  161. svgElement.style.width = '100%';
  162. svgElement.style.height = '100%';
  163. this.SVGContainer.appendChild(svgElement);
  164. } else {
  165. svgElement = this.SVGContainer.firstChild;
  166. }
  167. layer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  168. layer.setAttribute('class', classes);
  169. layer.style.position = 'absolute';
  170. layer.style.top = '0px';
  171. layer.style.left = '0px';
  172. layer.style.bottom = '0px';
  173. layer.style.right = '0px';
  174. svgElement.appendChild(layer);
  175. this.SVG[classes] = layer;
  176. }
  177. return layer;
  178. };
  179. /**
  180. - getTextInfo(layer, text, font, angle, width)
  181. Creates (if necessary) and returns a text info object.
  182. The object looks like this:
  183. ```js
  184. {
  185. width //Width of the text's wrapper div.
  186. height //Height of the text's wrapper div.
  187. element //The HTML div containing the text.
  188. positions //Array of positions at which this text is drawn.
  189. }
  190. ```
  191. The positions array contains objects that look like this:
  192. ```js
  193. {
  194. active //Flag indicating whether the text should be visible.
  195. rendered //Flag indicating whether the text is currently visible.
  196. element //The HTML div containing the text.
  197. text //The actual text and is identical with element[0].textContent.
  198. x //X coordinate at which to draw the text.
  199. y //Y coordinate at which to draw the text.
  200. }
  201. ```
  202. Each position after the first receives a clone of the original element.
  203. The idea is that that the width, height, and general 'identity' of the
  204. text is constant no matter where it is placed; the placements are a
  205. secondary property.
  206. Canvas maintains a cache of recently-used text info objects; getTextInfo
  207. either returns the cached element or creates a new entry.
  208. The layer parameter is string of space-separated CSS classes uniquely
  209. identifying the layer containing this text.
  210. Text is the text string to retrieve info for.
  211. Font is either a string of space-separated CSS classes or a font-spec object,
  212. defining the text's font and style.
  213. Angle is the angle at which to rotate the text, in degrees. Angle is currently unused,
  214. it will be implemented in the future.
  215. The last parameter is the Maximum width of the text before it wraps.
  216. The method returns a text info object.
  217. */
  218. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
  219. var textStyle, layerCache, styleCache, info;
  220. // Cast the value to a string, in case we were given a number or such
  221. text = '' + text;
  222. // If the font is a font-spec object, generate a CSS font definition
  223. if (typeof font === 'object') {
  224. textStyle = font.style + ' ' + font.variant + ' ' + font.weight + ' ' + font.size + 'px/' + font.lineHeight + 'px ' + font.family;
  225. } else {
  226. textStyle = font;
  227. }
  228. // Retrieve (or create) the cache for the text's layer and styles
  229. layerCache = this._textCache[layer];
  230. if (layerCache == null) {
  231. layerCache = this._textCache[layer] = {};
  232. }
  233. styleCache = layerCache[textStyle];
  234. if (styleCache == null) {
  235. styleCache = layerCache[textStyle] = {};
  236. }
  237. var key = generateKey(text);
  238. info = styleCache[key];
  239. // If we can't find a matching element in our cache, create a new one
  240. if (!info) {
  241. var element = document.createElementNS('http://www.w3.org/2000/svg', 'text');
  242. if (text.indexOf('<br>') !== -1) {
  243. addTspanElements(text, element, -9999);
  244. } else {
  245. var textNode = document.createTextNode(text);
  246. element.appendChild(textNode);
  247. }
  248. element.style.position = 'absolute';
  249. element.style.maxWidth = width;
  250. element.setAttributeNS(null, 'x', -9999);
  251. element.setAttributeNS(null, 'y', -9999);
  252. if (typeof font === 'object') {
  253. element.style.font = textStyle;
  254. element.style.fill = font.fill;
  255. } else if (typeof font === 'string') {
  256. element.setAttribute('class', font);
  257. }
  258. this.getSVGLayer(layer).appendChild(element);
  259. var elementRect = element.getBBox();
  260. info = styleCache[key] = {
  261. width: elementRect.width,
  262. height: elementRect.height,
  263. measured: true,
  264. element: element,
  265. positions: []
  266. };
  267. //remove elements from dom
  268. while (element.firstChild) {
  269. element.removeChild(element.firstChild);
  270. }
  271. element.parentNode.removeChild(element);
  272. }
  273. info.measured = true;
  274. return info;
  275. };
  276. /**
  277. - addText (layer, x, y, text, font, angle, width, halign, valign, transforms)
  278. Adds a text string to the canvas text overlay.
  279. The text isn't drawn immediately; it is marked as rendering, which will
  280. result in its addition to the canvas on the next render pass.
  281. The layer is string of space-separated CSS classes uniquely
  282. identifying the layer containing this text.
  283. X and Y represents the X and Y coordinate at which to draw the text.
  284. and text is the string to draw
  285. */
  286. Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign, transforms) {
  287. var info = this.getTextInfo(layer, text, font, angle, width),
  288. positions = info.positions;
  289. // Tweak the div's position to match the text's alignment
  290. if (halign === 'center') {
  291. x -= info.width / 2;
  292. } else if (halign === 'right') {
  293. x -= info.width;
  294. }
  295. if (valign === 'middle') {
  296. y -= info.height / 2;
  297. } else if (valign === 'bottom') {
  298. y -= info.height;
  299. }
  300. y += 0.75 * info.height;
  301. // Determine whether this text already exists at this position.
  302. // If so, mark it for inclusion in the next render pass.
  303. for (var i = 0, position; positions[i]; i++) {
  304. position = positions[i];
  305. if (position.x === x && position.y === y && position.text === text) {
  306. position.active = true;
  307. return;
  308. } else if (position.active === false) {
  309. position.active = true;
  310. position.text = text;
  311. if (text.indexOf('<br>') !== -1) {
  312. y -= 0.25 * info.height;
  313. addTspanElements(text, position.element, x);
  314. } else {
  315. position.element.textContent = text;
  316. }
  317. position.element.setAttributeNS(null, 'x', x);
  318. position.element.setAttributeNS(null, 'y', y);
  319. position.x = x;
  320. position.y = y;
  321. return;
  322. }
  323. }
  324. // If the text doesn't exist at this position, create a new entry
  325. // For the very first position we'll re-use the original element,
  326. // while for subsequent ones we'll clone it.
  327. position = {
  328. active: true,
  329. rendered: false,
  330. element: positions.length ? info.element.cloneNode() : info.element,
  331. text: text,
  332. x: x,
  333. y: y
  334. };
  335. positions.push(position);
  336. if (text.indexOf('<br>') !== -1) {
  337. y -= 0.25 * info.height;
  338. addTspanElements(text, position.element, x);
  339. } else {
  340. position.element.textContent = text;
  341. }
  342. // Move the element to its final position within the container
  343. position.element.setAttributeNS(null, 'x', x);
  344. position.element.setAttributeNS(null, 'y', y);
  345. position.element.style.textAlign = halign;
  346. if (transforms) {
  347. transforms.forEach(function(t) {
  348. info.element.transform.baseVal.appendItem(t);
  349. });
  350. }
  351. };
  352. var addTspanElements = function(text, element, x) {
  353. var lines = text.split('<br>'),
  354. tspan, i, offset;
  355. for (i = 0; i < lines.length; i++) {
  356. if (!element.childNodes[i]) {
  357. tspan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
  358. element.appendChild(tspan);
  359. } else {
  360. tspan = element.childNodes[i];
  361. }
  362. tspan.textContent = lines[i];
  363. offset = i * 1 + 'em';
  364. tspan.setAttributeNS(null, 'dy', offset);
  365. tspan.setAttributeNS(null, 'x', x);
  366. }
  367. }
  368. /**
  369. - removeText (layer, x, y, text, font, angle)
  370. The function removes one or more text strings from the canvas text overlay.
  371. If no parameters are given, all text within the layer is removed.
  372. Note that the text is not immediately removed; it is simply marked as
  373. inactive, which will result in its removal on the next render pass.
  374. This avoids the performance penalty for 'clear and redraw' behavior,
  375. where we potentially get rid of all text on a layer, but will likely
  376. add back most or all of it later, as when redrawing axes, for example.
  377. The layer is a string of space-separated CSS classes uniquely
  378. identifying the layer containing this text. The following parameter are
  379. X and Y coordinate of the text.
  380. Text is the string to remove, while the font is either a string of space-separated CSS
  381. classes or a font-spec object, defining the text's font and style.
  382. */
  383. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
  384. var info, htmlYCoord;
  385. if (text == null) {
  386. var layerCache = this._textCache[layer];
  387. if (layerCache != null) {
  388. for (var styleKey in layerCache) {
  389. if (hasOwnProperty.call(layerCache, styleKey)) {
  390. var styleCache = layerCache[styleKey];
  391. for (var key in styleCache) {
  392. if (hasOwnProperty.call(styleCache, key)) {
  393. var positions = styleCache[key].positions;
  394. positions.forEach(function(position) {
  395. position.active = false;
  396. });
  397. }
  398. }
  399. }
  400. }
  401. }
  402. } else {
  403. info = this.getTextInfo(layer, text, font, angle);
  404. positions = info.positions;
  405. positions.forEach(function(position) {
  406. htmlYCoord = y + 0.75 * info.height;
  407. if (position.x === x && position.y === htmlYCoord && position.text === text) {
  408. position.active = false;
  409. }
  410. });
  411. }
  412. };
  413. /**
  414. - clearCache()
  415. Clears the cache used to speed up the text size measurements.
  416. As an (unfortunate) side effect all text within the text Layer is removed.
  417. Use this function before plot.setupGrid() and plot.draw() if the plot just
  418. became visible or the styles changed.
  419. */
  420. Canvas.prototype.clearCache = function() {
  421. var cache = this._textCache;
  422. for (var layerKey in cache) {
  423. if (hasOwnProperty.call(cache, layerKey)) {
  424. var layer = this.getSVGLayer(layerKey);
  425. while (layer.firstChild) {
  426. layer.removeChild(layer.firstChild);
  427. }
  428. }
  429. };
  430. this._textCache = {};
  431. };
  432. function generateKey(text) {
  433. return text.replace(/0|1|2|3|4|5|6|7|8|9/g, '0');
  434. }
  435. if (!window.Flot) {
  436. window.Flot = {};
  437. }
  438. window.Flot.Canvas = Canvas;
  439. })(jQuery);