jquery.flot.composeImages.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /** ## jquery.flot.composeImages.js
  2. This plugin is used to expose a function used to overlap several canvases and
  3. SVGs, for the purpose of creating a snaphot out of them.
  4. ### When composeImages is used:
  5. When multiple canvases and SVGs have to be overlapped into a single image
  6. and their offset on the page, must be preserved.
  7. ### Where can be used:
  8. In creating a downloadable snapshot of the plots, axes, cursors etc of a graph.
  9. ### How it works:
  10. The entry point is composeImages function. It expects an array of objects,
  11. which should be either canvases or SVGs (or a mix). It does a prevalidation
  12. of them, by verifying if they will be usable or not, later in the flow.
  13. After selecting only usable sources, it passes them to getGenerateTempImg
  14. function, which generates temporary images out of them. This function
  15. expects that some of the passed sources (canvas or SVG) may still have
  16. problems being converted to an image and makes sure the promises system,
  17. used by composeImages function, moves forward. As an example, SVGs with
  18. missing information from header or with unsupported content, may lead to
  19. failure in generating the temporary image. Temporary images are required
  20. mostly on extracting content from SVGs, but this is also where the x/y
  21. offsets are extracted for each image which will be added. For SVGs in
  22. particular, their CSS rules have to be applied.
  23. After all temporary images are generated, they are overlapped using
  24. getExecuteImgComposition function. This is where the destination canvas
  25. is set to the proper dimensions. It is then output by composeImages.
  26. This function returns a promise, which can be used to wait for the whole
  27. composition process. It requires to be asynchronous, because this is how
  28. temporary images load their data.
  29. */
  30. (function($) {
  31. "use strict";
  32. const GENERALFAILURECALLBACKERROR = -100; //simply a negative number
  33. const SUCCESSFULIMAGEPREPARATION = 0;
  34. const EMPTYARRAYOFIMAGESOURCES = -1;
  35. const NEGATIVEIMAGESIZE = -2;
  36. var pixelRatio = 1;
  37. var browser = $.plot.browser;
  38. var getPixelRatio = browser.getPixelRatio;
  39. function composeImages(canvasOrSvgSources, destinationCanvas) {
  40. var validCanvasOrSvgSources = canvasOrSvgSources.filter(isValidSource);
  41. pixelRatio = getPixelRatio(destinationCanvas.getContext('2d'));
  42. var allImgCompositionPromises = validCanvasOrSvgSources.map(function(validCanvasOrSvgSource) {
  43. var tempImg = new Image();
  44. var currentPromise = new Promise(getGenerateTempImg(tempImg, validCanvasOrSvgSource));
  45. return currentPromise;
  46. });
  47. var lastPromise = Promise.all(allImgCompositionPromises).then(getExecuteImgComposition(destinationCanvas), failureCallback);
  48. return lastPromise;
  49. }
  50. function isValidSource(canvasOrSvgSource) {
  51. var isValidFromCanvas = true;
  52. var isValidFromContent = true;
  53. if ((canvasOrSvgSource === null) || (canvasOrSvgSource === undefined)) {
  54. isValidFromContent = false;
  55. } else {
  56. if (canvasOrSvgSource.tagName === 'CANVAS') {
  57. if ((canvasOrSvgSource.getBoundingClientRect().right === canvasOrSvgSource.getBoundingClientRect().left) ||
  58. (canvasOrSvgSource.getBoundingClientRect().bottom === canvasOrSvgSource.getBoundingClientRect().top)) {
  59. isValidFromCanvas = false;
  60. }
  61. }
  62. }
  63. return isValidFromContent && isValidFromCanvas && (window.getComputedStyle(canvasOrSvgSource).visibility === 'visible');
  64. }
  65. function getGenerateTempImg(tempImg, canvasOrSvgSource) {
  66. tempImg.sourceDescription = '<info className="' + canvasOrSvgSource.className + '" tagName="' + canvasOrSvgSource.tagName + '" id="' + canvasOrSvgSource.id + '">';
  67. tempImg.sourceComponent = canvasOrSvgSource;
  68. return function doGenerateTempImg(successCallbackFunc, failureCallbackFunc) {
  69. tempImg.onload = function(evt) {
  70. tempImg.successfullyLoaded = true;
  71. successCallbackFunc(tempImg);
  72. };
  73. tempImg.onabort = function(evt) {
  74. tempImg.successfullyLoaded = false;
  75. console.log('Can\'t generate temp image from ' + tempImg.sourceDescription + '. It is possible that it is missing some properties or its content is not supported by this browser. Source component:', tempImg.sourceComponent);
  76. successCallbackFunc(tempImg); //call successCallback, to allow snapshot of all working images
  77. };
  78. tempImg.onerror = function(evt) {
  79. tempImg.successfullyLoaded = false;
  80. console.log('Can\'t generate temp image from ' + tempImg.sourceDescription + '. It is possible that it is missing some properties or its content is not supported by this browser. Source component:', tempImg.sourceComponent);
  81. successCallbackFunc(tempImg); //call successCallback, to allow snapshot of all working images
  82. };
  83. generateTempImageFromCanvasOrSvg(canvasOrSvgSource, tempImg);
  84. };
  85. }
  86. function getExecuteImgComposition(destinationCanvas) {
  87. return function executeImgComposition(tempImgs) {
  88. var compositionResult = copyImgsToCanvas(tempImgs, destinationCanvas);
  89. return compositionResult;
  90. };
  91. }
  92. function copyCanvasToImg(canvas, img) {
  93. img.src = canvas.toDataURL('image/png');
  94. }
  95. function getCSSRules(document) {
  96. var styleSheets = document.styleSheets,
  97. rulesList = [];
  98. for (var i = 0; i < styleSheets.length; i++) {
  99. // in Chrome, the external CSS files are empty when the page is directly loaded from disk
  100. var rules = styleSheets[i].cssRules || [];
  101. for (var j = 0; j < rules.length; j++) {
  102. var rule = rules[j];
  103. rulesList.push(rule.cssText);
  104. }
  105. }
  106. return rulesList;
  107. }
  108. function embedCSSRulesInSVG(rules, svg) {
  109. var text = [
  110. '<svg class="snapshot ' + svg.classList + '" width="' + svg.width.baseVal.value * pixelRatio + '" height="' + svg.height.baseVal.value * pixelRatio + '" viewBox="0 0 ' + svg.width.baseVal.value + ' ' + svg.height.baseVal.value + '" xmlns="http://www.w3.org/2000/svg">',
  111. '<style>',
  112. '/* <![CDATA[ */',
  113. rules.join('\n'),
  114. '/* ]]> */',
  115. '</style>',
  116. svg.innerHTML,
  117. '</svg>'
  118. ].join('\n');
  119. return text;
  120. }
  121. function copySVGToImgMostBrowsers(svg, img) {
  122. var rules = getCSSRules(document),
  123. source = embedCSSRulesInSVG(rules, svg);
  124. source = patchSVGSource(source);
  125. var blob = new Blob([source], {type: "image/svg+xml;charset=utf-8"}),
  126. domURL = self.URL || self.webkitURL || self,
  127. url = domURL.createObjectURL(blob);
  128. img.src = url;
  129. }
  130. function copySVGToImgSafari(svg, img) {
  131. // Use this method to convert a string buffer array to a binary string.
  132. // Do so by breaking up large strings into smaller substrings; this is necessary to avoid the
  133. // "maximum call stack size exceeded" exception that can happen when calling 'String.fromCharCode.apply'
  134. // with a very long array.
  135. function buildBinaryString (arrayBuffer) {
  136. var binaryString = "";
  137. const utf8Array = new Uint8Array(arrayBuffer);
  138. const blockSize = 16384;
  139. for (var i = 0; i < utf8Array.length; i = i + blockSize) {
  140. const binarySubString = String.fromCharCode.apply(null, utf8Array.subarray(i, i + blockSize));
  141. binaryString = binaryString + binarySubString;
  142. }
  143. return binaryString;
  144. };
  145. var rules = getCSSRules(document),
  146. source = embedCSSRulesInSVG(rules, svg),
  147. data,
  148. utf8BinaryString;
  149. source = patchSVGSource(source);
  150. // Encode the string as UTF-8 and convert it to a binary string. The UTF-8 encoding is required to
  151. // capture unicode characters correctly.
  152. utf8BinaryString = buildBinaryString(new (TextEncoder || TextEncoderLite)('utf-8').encode(source));
  153. data = "data:image/svg+xml;base64," + btoa(utf8BinaryString);
  154. img.src = data;
  155. }
  156. function patchSVGSource(svgSource) {
  157. var source = '';
  158. //add name spaces.
  159. if (!svgSource.match(/^<svg[^>]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/)) {
  160. source = svgSource.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
  161. }
  162. if (!svgSource.match(/^<svg[^>]+"http:\/\/www\.w3\.org\/1999\/xlink"/)) {
  163. source = svgSource.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
  164. }
  165. //add xml declaration
  166. return '<?xml version="1.0" standalone="no"?>\r\n' + source;
  167. }
  168. function copySVGToImg(svg, img) {
  169. if (browser.isSafari() || browser.isMobileSafari()) {
  170. copySVGToImgSafari(svg, img);
  171. } else {
  172. copySVGToImgMostBrowsers(svg, img);
  173. }
  174. }
  175. function adaptDestSizeToZoom(destinationCanvas, sources) {
  176. function containsSVGs(source) {
  177. return source.srcImgTagName === 'svg';
  178. }
  179. if (sources.find(containsSVGs) !== undefined) {
  180. if (pixelRatio < 1) {
  181. destinationCanvas.width = destinationCanvas.width * pixelRatio;
  182. destinationCanvas.height = destinationCanvas.height * pixelRatio;
  183. }
  184. }
  185. }
  186. function prepareImagesToBeComposed(sources, destination) {
  187. var result = SUCCESSFULIMAGEPREPARATION;
  188. if (sources.length === 0) {
  189. result = EMPTYARRAYOFIMAGESOURCES; //nothing to do if called without sources
  190. } else {
  191. var minX = sources[0].genLeft;
  192. var minY = sources[0].genTop;
  193. var maxX = sources[0].genRight;
  194. var maxY = sources[0].genBottom;
  195. var i = 0;
  196. for (i = 1; i < sources.length; i++) {
  197. if (minX > sources[i].genLeft) {
  198. minX = sources[i].genLeft;
  199. }
  200. if (minY > sources[i].genTop) {
  201. minY = sources[i].genTop;
  202. }
  203. }
  204. for (i = 1; i < sources.length; i++) {
  205. if (maxX < sources[i].genRight) {
  206. maxX = sources[i].genRight;
  207. }
  208. if (maxY < sources[i].genBottom) {
  209. maxY = sources[i].genBottom;
  210. }
  211. }
  212. if ((maxX - minX <= 0) || (maxY - minY <= 0)) {
  213. result = NEGATIVEIMAGESIZE; //this might occur on hidden images
  214. } else {
  215. destination.width = Math.round(maxX - minX);
  216. destination.height = Math.round(maxY - minY);
  217. for (i = 0; i < sources.length; i++) {
  218. sources[i].xCompOffset = sources[i].genLeft - minX;
  219. sources[i].yCompOffset = sources[i].genTop - minY;
  220. }
  221. adaptDestSizeToZoom(destination, sources);
  222. }
  223. }
  224. return result;
  225. }
  226. function copyImgsToCanvas(sources, destination) {
  227. var prepareImagesResult = prepareImagesToBeComposed(sources, destination);
  228. if (prepareImagesResult === SUCCESSFULIMAGEPREPARATION) {
  229. var destinationCtx = destination.getContext('2d');
  230. for (var i = 0; i < sources.length; i++) {
  231. if (sources[i].successfullyLoaded === true) {
  232. destinationCtx.drawImage(sources[i], sources[i].xCompOffset * pixelRatio, sources[i].yCompOffset * pixelRatio);
  233. }
  234. }
  235. }
  236. return prepareImagesResult;
  237. }
  238. function adnotateDestImgWithBoundingClientRect(srcCanvasOrSvg, destImg) {
  239. destImg.genLeft = srcCanvasOrSvg.getBoundingClientRect().left;
  240. destImg.genTop = srcCanvasOrSvg.getBoundingClientRect().top;
  241. if (srcCanvasOrSvg.tagName === 'CANVAS') {
  242. destImg.genRight = destImg.genLeft + srcCanvasOrSvg.width;
  243. destImg.genBottom = destImg.genTop + srcCanvasOrSvg.height;
  244. }
  245. if (srcCanvasOrSvg.tagName === 'svg') {
  246. destImg.genRight = srcCanvasOrSvg.getBoundingClientRect().right;
  247. destImg.genBottom = srcCanvasOrSvg.getBoundingClientRect().bottom;
  248. }
  249. }
  250. function generateTempImageFromCanvasOrSvg(srcCanvasOrSvg, destImg) {
  251. if (srcCanvasOrSvg.tagName === 'CANVAS') {
  252. copyCanvasToImg(srcCanvasOrSvg, destImg);
  253. }
  254. if (srcCanvasOrSvg.tagName === 'svg') {
  255. copySVGToImg(srcCanvasOrSvg, destImg);
  256. }
  257. destImg.srcImgTagName = srcCanvasOrSvg.tagName;
  258. adnotateDestImgWithBoundingClientRect(srcCanvasOrSvg, destImg);
  259. }
  260. function failureCallback() {
  261. return GENERALFAILURECALLBACKERROR;
  262. }
  263. // used for testing
  264. $.plot.composeImages = composeImages;
  265. function init(plot) {
  266. // used to extend the public API of the plot
  267. plot.composeImages = composeImages;
  268. }
  269. $.plot.plugins.push({
  270. init: init,
  271. name: 'composeImages',
  272. version: '1.0'
  273. });
  274. })(jQuery);