jqplot.toImage.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * jqPlot
  3. * Pure JavaScript plotting plugin using jQuery
  4. *
  5. * Version: @VERSION
  6. * Revision: @REVISION
  7. *
  8. * Copyright (c) 2009-2013 Chris Leonello
  9. * jqPlot is currently available for use in all personal or commercial projects
  10. * under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
  11. * version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
  12. * choose the license that best suits your project and use it accordingly.
  13. *
  14. * Although not required, the author would appreciate an email letting him
  15. * know of any substantial use of jqPlot. You can reach the author at:
  16. * chris at jqplot dot com or see http://www.jqplot.com/info.php .
  17. *
  18. * If you are feeling kind and generous, consider supporting the project by
  19. * making a donation at: http://www.jqplot.com/donate.php .
  20. *
  21. * sprintf functions contained in jqplot.sprintf.js by Ash Searle:
  22. *
  23. * version 2007.04.27
  24. * author Ash Searle
  25. * http://hexmen.com/blog/2007/03/printf-sprintf/
  26. * http://hexmen.com/js/sprintf.js
  27. * The author (Ash Searle) has placed this code in the public domain:
  28. * "This code is unrestricted: you are free to use it however you like."
  29. *
  30. * jsDate library by Chris Leonello:
  31. *
  32. * Copyright (c) 2010-2013 Chris Leonello
  33. *
  34. * jsDate is currently available for use in all personal or commercial projects
  35. * under both the MIT and GPL version 2.0 licenses. This means that you can
  36. * choose the license that best suits your project and use it accordingly.
  37. *
  38. * jsDate borrows many concepts and ideas from the Date Instance
  39. * Methods by Ken Snyder along with some parts of Ken's actual code.
  40. * Ken has generously given permission to adapt his code and release
  41. * under the MIT and GPL V2 licenses.
  42. *
  43. * Ken's original Date Instance Methods and copyright notice:
  44. *
  45. * Ken Snyder (ken d snyder at gmail dot com)
  46. * 2008-09-10
  47. * version 2.0.2 (http://kendsnyder.com/sandbox/date/)
  48. * Creative Commons Attribution License 3.0 (http://creativecommons.org/licenses/by/3.0/)
  49. *
  50. * jqplotToImage function based on Larry Siden's export-jqplot-to-png.js.
  51. * Larry has generously given permission to adapt his code for inclusion
  52. * into jqPlot.
  53. *
  54. * Larry's original code can be found here:
  55. *
  56. * https://github.com/lsiden/export-jqplot-to-png
  57. *
  58. *
  59. */
  60. (function($) {
  61. $.fn.jqplotChildText = function() {
  62. return $(this).contents().filter(function() {
  63. return this.nodeType == 3; // Node.TEXT_NODE not defined in I7
  64. }).text();
  65. };
  66. // Returns font style as abbreviation for "font" property.
  67. $.fn.jqplotGetComputedFontStyle = function() {
  68. var css = window.getComputedStyle ? window.getComputedStyle(this[0], "") : this[0].currentStyle;
  69. var attrs = css['font-style'] ? ['font-style', 'font-weight', 'font-size', 'font-family'] : ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  70. var style = [];
  71. for (var i=0 ; i < attrs.length; ++i) {
  72. var attr = String(css[attrs[i]]);
  73. if (attr && attr != 'normal') {
  74. style.push(attr);
  75. }
  76. }
  77. return style.join(' ');
  78. };
  79. /**
  80. * Namespace: $.fn
  81. * jQuery namespace to attach functions to jQuery elements.
  82. *
  83. */
  84. $.fn.jqplotToImageCanvas = function(options) {
  85. options = options || {};
  86. var x_offset = (options.x_offset == null) ? 0 : options.x_offset;
  87. var y_offset = (options.y_offset == null) ? 0 : options.y_offset;
  88. var backgroundColor = (options.backgroundColor == null) ? 'rgb(255,255,255)' : options.backgroundColor;
  89. if ($(this).width() == 0 || $(this).height() == 0) {
  90. return null;
  91. }
  92. // excanvas and hence IE < 9 do not support toDataURL and cannot export images.
  93. if ($.jqplot.use_excanvas) {
  94. return null;
  95. }
  96. var newCanvas = document.createElement("canvas");
  97. var h = $(this).outerHeight(true);
  98. var w = $(this).outerWidth(true);
  99. var offs = $(this).offset();
  100. var plotleft = offs.left;
  101. var plottop = offs.top;
  102. var transx = 0, transy = 0;
  103. // have to check if any elements are hanging outside of plot area before rendering,
  104. // since changing width of canvas will erase canvas.
  105. var clses = ['jqplot-table-legend', 'jqplot-xaxis-tick', 'jqplot-x2axis-tick', 'jqplot-yaxis-tick', 'jqplot-y2axis-tick', 'jqplot-y3axis-tick',
  106. 'jqplot-y4axis-tick', 'jqplot-y5axis-tick', 'jqplot-y6axis-tick', 'jqplot-y7axis-tick', 'jqplot-y8axis-tick', 'jqplot-y9axis-tick',
  107. 'jqplot-xaxis-label', 'jqplot-x2axis-label', 'jqplot-yaxis-label', 'jqplot-y2axis-label', 'jqplot-y3axis-label', 'jqplot-y4axis-label',
  108. 'jqplot-y5axis-label', 'jqplot-y6axis-label', 'jqplot-y7axis-label', 'jqplot-y8axis-label', 'jqplot-y9axis-label' ];
  109. var temptop, templeft, tempbottom, tempright;
  110. for (var i = 0; i < clses.length; i++) {
  111. $(this).find('.'+clses[i]).each(function() {
  112. temptop = $(this).offset().top - plottop;
  113. templeft = $(this).offset().left - plotleft;
  114. tempright = templeft + $(this).outerWidth(true) + transx;
  115. tempbottom = temptop + $(this).outerHeight(true) + transy;
  116. if (templeft < -transx) {
  117. w = w - transx - templeft;
  118. transx = -templeft;
  119. }
  120. if (temptop < -transy) {
  121. h = h - transy - temptop;
  122. transy = - temptop;
  123. }
  124. if (tempright > w) {
  125. w = tempright;
  126. }
  127. if (tempbottom > h) {
  128. h = tempbottom;
  129. }
  130. });
  131. }
  132. newCanvas.width = w + Number(x_offset);
  133. newCanvas.height = h + Number(y_offset);
  134. var newContext = newCanvas.getContext("2d");
  135. newContext.save();
  136. newContext.fillStyle = backgroundColor;
  137. newContext.fillRect(0,0, newCanvas.width, newCanvas.height);
  138. newContext.restore();
  139. newContext.translate(transx, transy);
  140. newContext.textAlign = 'left';
  141. newContext.textBaseline = 'top';
  142. function getLineheight(el) {
  143. var lineheight = parseInt($(el).css('line-height'), 10);
  144. if (isNaN(lineheight)) {
  145. lineheight = parseInt($(el).css('font-size'), 10) * 1.2;
  146. }
  147. return lineheight;
  148. }
  149. function writeWrappedText (el, context, text, left, top, canvasWidth) {
  150. var lineheight = getLineheight(el);
  151. var tagwidth = $(el).innerWidth();
  152. var tagheight = $(el).innerHeight();
  153. var words = text.split(/\s+/);
  154. var wl = words.length;
  155. var w = '';
  156. var breaks = [];
  157. var temptop = top;
  158. var templeft = left;
  159. for (var i=0; i<wl; i++) {
  160. w += words[i];
  161. if (context.measureText(w).width > tagwidth) {
  162. breaks.push(i);
  163. w = '';
  164. i--;
  165. }
  166. }
  167. if (breaks.length === 0) {
  168. // center text if necessary
  169. if ($(el).css('textAlign') === 'center') {
  170. templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
  171. }
  172. context.fillText(text, templeft, top);
  173. }
  174. else {
  175. w = words.slice(0, breaks[0]).join(' ');
  176. // center text if necessary
  177. if ($(el).css('textAlign') === 'center') {
  178. templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
  179. }
  180. context.fillText(w, templeft, temptop);
  181. temptop += lineheight;
  182. for (var i=1, l=breaks.length; i<l; i++) {
  183. w = words.slice(breaks[i-1], breaks[i]).join(' ');
  184. // center text if necessary
  185. if ($(el).css('textAlign') === 'center') {
  186. templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
  187. }
  188. context.fillText(w, templeft, temptop);
  189. temptop += lineheight;
  190. }
  191. w = words.slice(breaks[i-1], words.length).join(' ');
  192. // center text if necessary
  193. if ($(el).css('textAlign') === 'center') {
  194. templeft = left + (canvasWidth - context.measureText(w).width)/2 - transx;
  195. }
  196. context.fillText(w, templeft, temptop);
  197. }
  198. }
  199. function _jqpToImage(el, x_offset, y_offset) {
  200. var tagname = el.tagName.toLowerCase();
  201. var p = $(el).position();
  202. var css = window.getComputedStyle ? window.getComputedStyle(el, "") : el.currentStyle; // for IE < 9
  203. var left = x_offset + p.left + parseInt(css.marginLeft, 10) + parseInt(css.borderLeftWidth, 10) + parseInt(css.paddingLeft, 10);
  204. var top = y_offset + p.top + parseInt(css.marginTop, 10) + parseInt(css.borderTopWidth, 10)+ parseInt(css.paddingTop, 10);
  205. var w = newCanvas.width;
  206. // var left = x_offset + p.left + $(el).css('marginLeft') + $(el).css('borderLeftWidth')
  207. // somehow in here, for divs within divs, the width of the inner div should be used instead of the canvas.
  208. if ((tagname == 'div' || tagname == 'span') && !$(el).hasClass('jqplot-highlighter-tooltip')) {
  209. $(el).children().each(function() {
  210. _jqpToImage(this, left, top);
  211. });
  212. var text = $(el).jqplotChildText();
  213. if (text) {
  214. newContext.font = $(el).jqplotGetComputedFontStyle();
  215. newContext.fillStyle = $(el).css('color');
  216. writeWrappedText(el, newContext, text, left, top, w);
  217. }
  218. }
  219. // handle the standard table legend
  220. else if (tagname === 'table' && $(el).hasClass('jqplot-table-legend')) {
  221. newContext.strokeStyle = $(el).css('border-top-color');
  222. newContext.fillStyle = $(el).css('background-color');
  223. newContext.fillRect(left, top, $(el).innerWidth(), $(el).innerHeight());
  224. if (parseInt($(el).css('border-top-width'), 10) > 0) {
  225. newContext.strokeRect(left, top, $(el).innerWidth(), $(el).innerHeight());
  226. }
  227. // find all the swatches
  228. $(el).find('div.jqplot-table-legend-swatch-outline').each(function() {
  229. // get the first div and stroke it
  230. var elem = $(this);
  231. newContext.strokeStyle = elem.css('border-top-color');
  232. var l = left + elem.position().left;
  233. var t = top + elem.position().top;
  234. newContext.strokeRect(l, t, elem.innerWidth(), elem.innerHeight());
  235. // now fill the swatch
  236. l += parseInt(elem.css('padding-left'), 10);
  237. t += parseInt(elem.css('padding-top'), 10);
  238. var h = elem.innerHeight() - 2 * parseInt(elem.css('padding-top'), 10);
  239. var w = elem.innerWidth() - 2 * parseInt(elem.css('padding-left'), 10);
  240. var swatch = elem.children('div.jqplot-table-legend-swatch');
  241. newContext.fillStyle = swatch.css('background-color');
  242. newContext.fillRect(l, t, w, h);
  243. });
  244. // now add text
  245. $(el).find('td.jqplot-table-legend-label').each(function(){
  246. var elem = $(this);
  247. var l = left + elem.position().left;
  248. var t = top + elem.position().top + parseInt(elem.css('padding-top'), 10);
  249. newContext.font = elem.jqplotGetComputedFontStyle();
  250. newContext.fillStyle = elem.css('color');
  251. writeWrappedText(elem, newContext, elem.text(), l, t, w);
  252. });
  253. var elem = null;
  254. }
  255. else if (tagname == 'canvas') {
  256. newContext.drawImage(el, left, top);
  257. }
  258. }
  259. $(this).children().each(function() {
  260. _jqpToImage(this, x_offset, y_offset);
  261. });
  262. return newCanvas;
  263. };
  264. // return the raw image data string.
  265. // Should work on canvas supporting browsers.
  266. $.fn.jqplotToImageStr = function(options) {
  267. var imgCanvas = $(this).jqplotToImageCanvas(options);
  268. if (imgCanvas) {
  269. return imgCanvas.toDataURL("image/png");
  270. }
  271. else {
  272. return null;
  273. }
  274. };
  275. // return a DOM <img> element and return it.
  276. // Should work on canvas supporting browsers.
  277. $.fn.jqplotToImageElem = function(options) {
  278. var elem = document.createElement("img");
  279. var str = $(this).jqplotToImageStr(options);
  280. elem.src = str;
  281. return elem;
  282. };
  283. // return a string for an <img> element and return it.
  284. // Should work on canvas supporting browsers.
  285. $.fn.jqplotToImageElemStr = function(options) {
  286. var str = '<img src='+$(this).jqplotToImageStr(options)+' />';
  287. return str;
  288. };
  289. // Not guaranteed to work, even on canvas supporting browsers due to
  290. // limitations with location.href and browser support.
  291. $.fn.jqplotSaveImage = function() {
  292. var imgData = $(this).jqplotToImageStr({});
  293. if (imgData) {
  294. window.location.href = imgData.replace("image/png", "image/octet-stream");
  295. }
  296. };
  297. // Not guaranteed to work, even on canvas supporting browsers due to
  298. // limitations with window.open and arbitrary data.
  299. $.fn.jqplotViewImage = function() {
  300. var imgStr = $(this).jqplotToImageElemStr({});
  301. var imgData = $(this).jqplotToImageStr({});
  302. if (imgStr) {
  303. var w = window.open('');
  304. w.document.open("image/png");
  305. w.document.write(imgStr);
  306. w.document.close();
  307. w = null;
  308. }
  309. };
  310. })(jQuery);