🏠 Home 

Capture current page

Screen capture for current full page with Ctrl+F10, also be used to change text into image which inside the INPUT/TEXTAREA element.


Installer dette script?
  1. // ==UserScript==
  2. // @name Capture current page
  3. // @name:zh-CN 网页整页截图
  4. // @name:zh-TW 網頁整頁截圖
  5. // @namespace hoothin
  6. // @version 0.4
  7. // @description Screen capture for current full page with Ctrl+F10, also be used to change text into image which inside the INPUT/TEXTAREA element.
  8. // @description:zh-CN Ctrl+F10 网页整页截图,焦点位于输入框时将输入框内文字转换为图片
  9. // @description:zh-TW Ctrl+F10 網頁整頁截圖,焦點位於輸入框時將輸入框内文字轉換為圖片
  10. // @author hoothin
  11. // @include http*://*
  12. // @grant GM_openInTab
  13. // @grant GM_registerMenuCommand
  14. // @license MIT License
  15. // @compatible chrome
  16. // @compatible firefox
  17. // @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=rixixi@sina.com&item_name=Greasy+Fork+donation
  18. // @contributionAmount 1
  19. // ==/UserScript==
  20. /*
  21. html2canvas 0.5.0-beta3 <http://html2canvas.hertzen.com>
  22. Copyright (c) 2016 Niklas von Hertzen
  23. Released under License
  24. */
  25. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  26. (function (global){
  27. /*! http://mths.be/punycode v1.2.4 by @mathias */
  28. ;(function(root) {
  29. /** Detect free variables */
  30. var freeExports = typeof exports == 'object' && exports;
  31. var freeModule = typeof module == 'object' && module &&
  32. module.exports == freeExports && module;
  33. var freeGlobal = typeof global == 'object' && global;
  34. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  35. root = freeGlobal;
  36. }
  37. /**
  38. * The `punycode` object.
  39. * @name punycode
  40. * @type Object
  41. */
  42. var punycode,
  43. /** Highest positive signed 32-bit float value */
  44. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  45. /** Bootstring parameters */
  46. base = 36,
  47. tMin = 1,
  48. tMax = 26,
  49. skew = 38,
  50. damp = 700,
  51. initialBias = 72,
  52. initialN = 128, // 0x80
  53. delimiter = '-', // '\x2D'
  54. /** Regular expressions */
  55. regexPunycode = /^xn--/,
  56. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  57. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  58. /** Error messages */
  59. errors = {
  60. 'overflow': 'Overflow: input needs wider integers to process',
  61. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  62. 'invalid-input': 'Invalid input'
  63. },
  64. /** Convenience shortcuts */
  65. baseMinusTMin = base - tMin,
  66. floor = Math.floor,
  67. stringFromCharCode = String.fromCharCode,
  68. /** Temporary variable */
  69. key;
  70. /*--------------------------------------------------------------------------*/
  71. /**
  72. * A generic error utility function.
  73. * @private
  74. * @param {String} type The error type.
  75. * @returns {Error} Throws a `RangeError` with the applicable error message.
  76. */
  77. function error(type) {
  78. throw RangeError(errors[type]);
  79. }
  80. /**
  81. * A generic `Array#map` utility function.
  82. * @private
  83. * @param {Array} array The array to iterate over.
  84. * @param {Function} callback The function that gets called for every array
  85. * item.
  86. * @returns {Array} A new array of values returned by the callback function.
  87. */
  88. function map(array, fn) {
  89. var length = array.length;
  90. while (length--) {
  91. array[length] = fn(array[length]);
  92. }
  93. return array;
  94. }
  95. /**
  96. * A simple `Array#map`-like wrapper to work with domain name strings.
  97. * @private
  98. * @param {String} domain The domain name.
  99. * @param {Function} callback The function that gets called for every
  100. * character.
  101. * @returns {Array} A new string of characters returned by the callback
  102. * function.
  103. */
  104. function mapDomain(string, fn) {
  105. return map(string.split(regexSeparators), fn).join('.');
  106. }
  107. /**
  108. * Creates an array containing the numeric code points of each Unicode
  109. * character in the string. While JavaScript uses UCS-2 internally,
  110. * this function will convert a pair of surrogate halves (each of which
  111. * UCS-2 exposes as separate characters) into a single code point,
  112. * matching UTF-16.
  113. * @see `punycode.ucs2.encode`
  114. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  115. * @memberOf punycode.ucs2
  116. * @name decode
  117. * @param {String} string The Unicode input string (UCS-2).
  118. * @returns {Array} The new array of code points.
  119. */
  120. function ucs2decode(string) {
  121. var output = [],
  122. counter = 0,
  123. length = string.length,
  124. value,
  125. extra;
  126. while (counter < length) {
  127. value = string.charCodeAt(counter++);
  128. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  129. // high surrogate, and there is a next character
  130. extra = string.charCodeAt(counter++);
  131. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  132. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  133. } else {
  134. // unmatched surrogate; only append this code unit, in case the next
  135. // code unit is the high surrogate of a surrogate pair
  136. output.push(value);
  137. counter--;
  138. }
  139. } else {
  140. output.push(value);
  141. }
  142. }
  143. return output;
  144. }
  145. /**
  146. * Creates a string based on an array of numeric code points.
  147. * @see `punycode.ucs2.decode`
  148. * @memberOf punycode.ucs2
  149. * @name encode
  150. * @param {Array} codePoints The array of numeric code points.
  151. * @returns {String} The new Unicode string (UCS-2).
  152. */
  153. function ucs2encode(array) {
  154. return map(array, function(value) {
  155. var output = '';
  156. if (value > 0xFFFF) {
  157. value -= 0x10000;
  158. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  159. value = 0xDC00 | value & 0x3FF;
  160. }
  161. output += stringFromCharCode(value);
  162. return output;
  163. }).join('');
  164. }
  165. /**
  166. * Converts a basic code point into a digit/integer.
  167. * @see `digitToBasic()`
  168. * @private
  169. * @param {Number} codePoint The basic numeric code point value.
  170. * @returns {Number} The numeric value of a basic code point (for use in
  171. * representing integers) in the range `0` to `base - 1`, or `base` if
  172. * the code point does not represent a value.
  173. */
  174. function basicToDigit(codePoint) {
  175. if (codePoint - 48 < 10) {
  176. return codePoint - 22;
  177. }
  178. if (codePoint - 65 < 26) {
  179. return codePoint - 65;
  180. }
  181. if (codePoint - 97 < 26) {
  182. return codePoint - 97;
  183. }
  184. return base;
  185. }
  186. /**
  187. * Converts a digit/integer into a basic code point.
  188. * @see `basicToDigit()`
  189. * @private
  190. * @param {Number} digit The numeric value of a basic code point.
  191. * @returns {Number} The basic code point whose value (when used for
  192. * representing integers) is `digit`, which needs to be in the range
  193. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  194. * used; else, the lowercase form is used. The behavior is undefined
  195. * if `flag` is non-zero and `digit` has no uppercase form.
  196. */
  197. function digitToBasic(digit, flag) {
  198. // 0..25 map to ASCII a..z or A..Z
  199. // 26..35 map to ASCII 0..9
  200. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  201. }
  202. /**
  203. * Bias adaptation function as per section 3.4 of RFC 3492.
  204. * http://tools.ietf.org/html/rfc3492#section-3.4
  205. * @private
  206. */
  207. function adapt(delta, numPoints, firstTime) {
  208. var k = 0;
  209. delta = firstTime ? floor(delta / damp) : delta >> 1;
  210. delta += floor(delta / numPoints);
  211. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  212. delta = floor(delta / baseMinusTMin);
  213. }
  214. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  215. }
  216. /**
  217. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  218. * symbols.
  219. * @memberOf punycode
  220. * @param {String} input The Punycode string of ASCII-only symbols.
  221. * @returns {String} The r###lting string of Unicode symbols.
  222. */
  223. function decode(input) {
  224. // Don't use UCS-2
  225. var output = [],
  226. inputLength = input.length,
  227. out,
  228. i = 0,
  229. n = initialN,
  230. bias = initialBias,
  231. basic,
  232. j,
  233. index,
  234. oldi,
  235. w,
  236. k,
  237. digit,
  238. t,
  239. /** Cached calculation r###lts */
  240. baseMinusT;
  241. // Handle the basic code points: let `basic` be the number of input code
  242. // points before the last delimiter, or `0` if there is none, then copy
  243. // the first basic code points to the output.
  244. basic = input.lastIndexOf(delimiter);
  245. if (basic < 0) {
  246. basic = 0;
  247. }
  248. for (j = 0; j < basic; ++j) {
  249. // if it's not a basic code point
  250. if (input.charCodeAt(j) >= 0x80) {
  251. error('not-basic');
  252. }
  253. output.push(input.charCodeAt(j));
  254. }
  255. // Main decoding loop: start just after the last delimiter if any basic code
  256. // points were copied; start at the beginning otherwise.
  257. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  258. // `index` is the index of the next character to be consumed.
  259. // Decode a generalized variable-length integer into `delta`,
  260. // which gets added to `i`. The overflow checking is easier
  261. // if we increase `i` as we go, then subtract off its starting
  262. // value at the end to obtain `delta`.
  263. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  264. if (index >= inputLength) {
  265. error('invalid-input');
  266. }
  267. digit = basicToDigit(input.charCodeAt(index++));
  268. if (digit >= base || digit > floor((maxInt - i) / w)) {
  269. error('overflow');
  270. }
  271. i += digit * w;
  272. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  273. if (digit < t) {
  274. break;
  275. }
  276. baseMinusT = base - t;
  277. if (w > floor(maxInt / baseMinusT)) {
  278. error('overflow');
  279. }
  280. w *= baseMinusT;
  281. }
  282. out = output.length + 1;
  283. bias = adapt(i - oldi, out, oldi == 0);
  284. // `i` was supposed to wrap around from `out` to `0`,
  285. // incrementing `n` each time, so we'll fix that now:
  286. if (floor(i / out) > maxInt - n) {
  287. error('overflow');
  288. }
  289. n += floor(i / out);
  290. i %= out;
  291. // Insert `n` at position `i` of the output
  292. output.splice(i++, 0, n);
  293. }
  294. return ucs2encode(output);
  295. }
  296. /**
  297. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  298. * symbols.
  299. * @memberOf punycode
  300. * @param {String} input The string of Unicode symbols.
  301. * @returns {String} The r###lting Punycode string of ASCII-only symbols.
  302. */
  303. function encode(input) {
  304. var n,
  305. delta,
  306. handled###ount,
  307. basicLength,
  308. bias,
  309. j,
  310. m,
  311. q,
  312. k,
  313. t,
  314. currentValue,
  315. output = [],
  316. /** `inputLength` will hold the number of code points in `input`. */
  317. inputLength,
  318. /** Cached calculation r###lts */
  319. handled###ountPlusOne,
  320. baseMinusT,
  321. qMinusT;
  322. // Convert the input in UCS-2 to Unicode
  323. input = ucs2decode(input);
  324. // Cache the length
  325. inputLength = input.length;
  326. // Initialize the state
  327. n = initialN;
  328. delta = 0;
  329. bias = initialBias;
  330. // Handle the basic code points
  331. for (j = 0; j < inputLength; ++j) {
  332. currentValue = input[j];
  333. if (currentValue < 0x80) {
  334. output.push(stringFromCharCode(currentValue));
  335. }
  336. }
  337. handled###ount = basicLength = output.length;
  338. // `handled###ount` is the number of code points that have been handled;
  339. // `basicLength` is the number of basic code points.
  340. // Finish the basic string - if it is not empty - with a delimiter
  341. if (basicLength) {
  342. output.push(delimiter);
  343. }
  344. // Main encoding loop:
  345. while (handled###ount < inputLength) {
  346. // All non-basic code points < n have been handled already. Find the next
  347. // larger one:
  348. for (m = maxInt, j = 0; j < inputLength; ++j) {
  349. currentValue = input[j];
  350. if (currentValue >= n && currentValue < m) {
  351. m = currentValue;
  352. }
  353. }
  354. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  355. // but guard against overflow
  356. handled###ountPlusOne = handled###ount + 1;
  357. if (m - n > floor((maxInt - delta) / handled###ountPlusOne)) {
  358. error('overflow');
  359. }
  360. delta += (m - n) * handled###ountPlusOne;
  361. n = m;
  362. for (j = 0; j < inputLength; ++j) {
  363. currentValue = input[j];
  364. if (currentValue < n && ++delta > maxInt) {
  365. error('overflow');
  366. }
  367. if (currentValue == n) {
  368. // Represent delta as a generalized variable-length integer
  369. for (q = delta, k = base; /* no condition */; k += base) {
  370. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  371. if (q < t) {
  372. break;
  373. }
  374. qMinusT = q - t;
  375. baseMinusT = base - t;
  376. output.push(
  377. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  378. );
  379. q = floor(qMinusT / baseMinusT);
  380. }
  381. output.push(stringFromCharCode(digitToBasic(q, 0)));
  382. bias = adapt(delta, handled###ountPlusOne, handled###ount == basicLength);
  383. delta = 0;
  384. ++handled###ount;
  385. }
  386. }
  387. ++delta;
  388. ++n;
  389. }
  390. return output.join('');
  391. }
  392. /**
  393. * Converts a Punycode string representing a domain name to Unicode. Only the
  394. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  395. * matter if you call it on a string that has already been converted to
  396. * Unicode.
  397. * @memberOf punycode
  398. * @param {String} domain The Punycode domain name to convert to Unicode.
  399. * @returns {String} The Unicode representation of the given Punycode
  400. * string.
  401. */
  402. function toUnicode(domain) {
  403. return mapDomain(domain, function(string) {
  404. return regexPunycode.test(string)
  405. ? decode(string.slice(4).toLowerCase())
  406. : string;
  407. });
  408. }
  409. /**
  410. * Converts a Unicode string representing a domain name to Punycode. Only the
  411. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  412. * matter if you call it with a domain that's already in ASCII.
  413. * @memberOf punycode
  414. * @param {String} domain The domain name to convert, as a Unicode string.
  415. * @returns {String} The Punycode representation of the given domain name.
  416. */
  417. function toASCII(domain) {
  418. return mapDomain(domain, function(string) {
  419. return regexNonASCII.test(string)
  420. ? 'xn--' + encode(string)
  421. : string;
  422. });
  423. }
  424. /*--------------------------------------------------------------------------*/
  425. /** Define the public API */
  426. punycode = {
  427. /**
  428. * A string representing the current Punycode.js version number.
  429. * @memberOf punycode
  430. * @type String
  431. */
  432. 'version': '1.2.4',
  433. /**
  434. * An object of methods to convert from JavaScript's internal character
  435. * representation (UCS-2) to Unicode code points, and back.
  436. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  437. * @memberOf punycode
  438. * @type Object
  439. */
  440. 'ucs2': {
  441. 'decode': ucs2decode,
  442. 'encode': ucs2encode
  443. },
  444. 'decode': decode,
  445. 'encode': encode,
  446. 'toASCII': toASCII,
  447. 'toUnicode': toUnicode
  448. };
  449. /** Expose `punycode` */
  450. // Some AMD build optimizers, like r.js, check for specific condition patterns
  451. // like the following:
  452. if (
  453. typeof define == 'function' &&
  454. typeof define.amd == 'object' &&
  455. define.amd
  456. ) {
  457. define('punycode', function() {
  458. return punycode;
  459. });
  460. } else if (freeExports && !freeExports.nodeType) {
  461. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  462. freeModule.exports = punycode;
  463. } else { // in Narwhal or RingoJS v0.7.0-
  464. for (key in punycode) {
  465. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  466. }
  467. }
  468. } else { // in Rhino or a web browser
  469. root.punycode = punycode;
  470. }
  471. }(this));
  472. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  473. },{}],2:[function(_dereq_,module,exports){
  474. var log = _dereq_('./log');
  475. function restoreOwnerScroll(ownerDocument, x, y) {
  476. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  477. ownerDocument.defaultView.scrollTo(x, y);
  478. }
  479. }
  480. function cloneCanvasContents(canvas, clonedCanvas) {
  481. try {
  482. if (clonedCanvas) {
  483. clonedCanvas.width = canvas.width;
  484. clonedCanvas.height = canvas.height;
  485. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  486. }
  487. } catch(e) {
  488. log("Unable to copy canvas content from", canvas, e);
  489. }
  490. }
  491. function cloneNode(node, javascriptEnabled) {
  492. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  493. var child = node.firstChild;
  494. while(child) {
  495. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  496. clone.appendChild(cloneNode(child, javascriptEnabled));
  497. }
  498. child = child.nextSibling;
  499. }
  500. if (node.nodeType === 1) {
  501. clone._scrollTop = node.scrollTop;
  502. clone._scrollLeft = node.scrollLeft;
  503. if (node.nodeName === "CANVAS") {
  504. cloneCanvasContents(node, clone);
  505. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  506. clone.value = node.value;
  507. }
  508. }
  509. return clone;
  510. }
  511. function initNode(node) {
  512. if (node.nodeType === 1) {
  513. node.scrollTop = node._scrollTop;
  514. node.scrollLeft = node._scrollLeft;
  515. var child = node.firstChild;
  516. while(child) {
  517. initNode(child);
  518. child = child.nextSibling;
  519. }
  520. }
  521. }
  522. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  523. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  524. var container = containerDocument.createElement("iframe");
  525. container.className = "html2canvas-container";
  526. container.style.visibility = "hidden";
  527. container.style.position = "fixed";
  528. container.style.left = "-10000px";
  529. container.style.top = "0px";
  530. container.style.border = "0";
  531. container.width = width;
  532. container.height = height;
  533. container.scrolling = "no"; // ios won't scroll without it
  534. containerDocument.body.appendChild(container);
  535. return new Promise(function(resolve) {
  536. var documentClone = container.contentWindow.document;
  537. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  538. if window url is about:blank, we can assign the url to current by writing onto the document
  539. */
  540. container.contentWindow.onload = container.onload = function() {
  541. var interval = setInterval(function() {
  542. if (documentClone.body.childNodes.length > 0) {
  543. initNode(documentClone.documentElement);
  544. clearInterval(interval);
  545. if (options.type === "view") {
  546. container.contentWindow.scrollTo(x, y);
  547. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  548. documentClone.documentElement.style.top = (-y) + "px";
  549. documentClone.documentElement.style.left = (-x) + "px";
  550. documentClone.documentElement.style.position = 'absolute';
  551. }
  552. }
  553. resolve(container);
  554. }
  555. }, 50);
  556. };
  557. documentClone.open();
  558. documentClone.write("<!DOCTYPE html><html></html>");
  559. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  560. restoreOwnerScroll(ownerDocument, x, y);
  561. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  562. documentClone.close();
  563. });
  564. };
  565. },{"./log":13}],3:[function(_dereq_,module,exports){
  566. // http://dev.w3.org/csswg/css-color/
  567. function Color(value) {
  568. this.r = 0;
  569. this.g = 0;
  570. this.b = 0;
  571. this.a = null;
  572. var r###lt = this.fromArray(value) ||
  573. this.namedColor(value) ||
  574. this.rgb(value) ||
  575. this.rgba(value) ||
  576. this.hex6(value) ||
  577. this.hex3(value);
  578. }
  579. Color.prototype.darken = function(amount) {
  580. var a = 1 - amount;
  581. return new Color([
  582. Math.round(this.r * a),
  583. Math.round(this.g * a),
  584. Math.round(this.b * a),
  585. this.a
  586. ]);
  587. };
  588. Color.prototype.isTransparent = function() {
  589. return this.a === 0;
  590. };
  591. Color.prototype.isBlack = function() {
  592. return this.r === 0 && this.g === 0 && this.b === 0;
  593. };
  594. Color.prototype.fromArray = function(array) {
  595. if (Array.isArray(array)) {
  596. this.r = Math.min(array[0], 255);
  597. this.g = Math.min(array[1], 255);
  598. this.b = Math.min(array[2], 255);
  599. if (array.length > 3) {
  600. this.a = array[3];
  601. }
  602. }
  603. return (Array.isArray(array));
  604. };
  605. var _hex3 = /^#([a-f0-9]{3})$/i;
  606. Color.prototype.hex3 = function(value) {
  607. var match = null;
  608. if ((match = value.match(_hex3)) !== null) {
  609. this.r = parseInt(match[1][0] + match[1][0], 16);
  610. this.g = parseInt(match[1][1] + match[1][1], 16);
  611. this.b = parseInt(match[1][2] + match[1][2], 16);
  612. }
  613. return match !== null;
  614. };
  615. var _hex6 = /^#([a-f0-9]{6})$/i;
  616. Color.prototype.hex6 = function(value) {
  617. var match = null;
  618. if ((match = value.match(_hex6)) !== null) {
  619. this.r = parseInt(match[1].substring(0, 2), 16);
  620. this.g = parseInt(match[1].substring(2, 4), 16);
  621. this.b = parseInt(match[1].substring(4, 6), 16);
  622. }
  623. return match !== null;
  624. };
  625. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  626. Color.prototype.rgb = function(value) {
  627. var match = null;
  628. if ((match = value.match(_rgb)) !== null) {
  629. this.r = Number(match[1]);
  630. this.g = Number(match[2]);
  631. this.b = Number(match[3]);
  632. }
  633. return match !== null;
  634. };
  635. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  636. Color.prototype.rgba = function(value) {
  637. var match = null;
  638. if ((match = value.match(_rgba)) !== null) {
  639. this.r = Number(match[1]);
  640. this.g = Number(match[2]);
  641. this.b = Number(match[3]);
  642. this.a = Number(match[4]);
  643. }
  644. return match !== null;
  645. };
  646. Color.prototype.toString = function() {
  647. return this.a !== null && this.a !== 1 ?
  648. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  649. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  650. };
  651. Color.prototype.namedColor = function(value) {
  652. value = value.toLowerCase();
  653. var color = colors[value];
  654. if (color) {
  655. this.r = color[0];
  656. this.g = color[1];
  657. this.b = color[2];
  658. } else if (value === "transparent") {
  659. this.r = this.g = this.b = this.a = 0;
  660. return true;
  661. }
  662. return !!color;
  663. };
  664. Color.prototype.isColor = true;
  665. // JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
  666. var colors = {
  667. "aliceblue": [240, 248, 255],
  668. "antiquewhite": [250, 235, 215],
  669. "aqua": [0, 255, 255],
  670. "aquamarine": [127, 255, 212],
  671. "azure": [240, 255, 255],
  672. "beige": [245, 245, 220],
  673. "bisque": [255, 228, 196],
  674. "black": [0, 0, 0],
  675. "blanchedalmond": [255, 235, 205],
  676. "blue": [0, 0, 255],
  677. "blueviolet": [138, 43, 226],
  678. "brown": [165, 42, 42],
  679. "burlywood": [222, 184, 135],
  680. "cadetblue": [95, 158, 160],
  681. "chartreuse": [127, 255, 0],
  682. "chocolate": [210, 105, 30],
  683. "coral": [255, 127, 80],
  684. "cornflowerblue": [100, 149, 237],
  685. "cornsilk": [255, 248, 220],
  686. "crimson": [220, 20, 60],
  687. "cyan": [0, 255, 255],
  688. "darkblue": [0, 0, 139],
  689. "darkcyan": [0, 139, 139],
  690. "darkgoldenrod": [184, 134, 11],
  691. "darkgray": [169, 169, 169],
  692. "darkgreen": [0, 100, 0],
  693. "darkgrey": [169, 169, 169],
  694. "darkkhaki": [189, 183, 107],
  695. "darkmagenta": [139, 0, 139],
  696. "darkolivegreen": [85, 107, 47],
  697. "darkorange": [255, 140, 0],
  698. "darkorchid": [153, 50, 204],
  699. "darkred": [139, 0, 0],
  700. "darksalmon": [233, 150, 122],
  701. "darkseagreen": [143, 188, 143],
  702. "darkslateblue": [72, 61, 139],
  703. "darkslategray": [47, 79, 79],
  704. "darkslategrey": [47, 79, 79],
  705. "darkturquoise": [0, 206, 209],
  706. "darkviolet": [148, 0, 211],
  707. "deeppink": [255, 20, 147],
  708. "deepskyblue": [0, 191, 255],
  709. "dimgray": [105, 105, 105],
  710. "dimgrey": [105, 105, 105],
  711. "dodgerblue": [30, 144, 255],
  712. "firebrick": [178, 34, 34],
  713. "floralwhite": [255, 250, 240],
  714. "forestgreen": [34, 139, 34],
  715. "fuchsia": [255, 0, 255],
  716. "gainsboro": [220, 220, 220],
  717. "ghostwhite": [248, 248, 255],
  718. "gold": [255, 215, 0],
  719. "goldenrod": [218, 165, 32],
  720. "gray": [128, 128, 128],
  721. "green": [0, 128, 0],
  722. "greenyellow": [173, 255, 47],
  723. "grey": [128, 128, 128],
  724. "honeydew": [240, 255, 240],
  725. "hotpink": [255, 105, 180],
  726. "indianred": [205, 92, 92],
  727. "indigo": [75, 0, 130],
  728. "ivory": [255, 255, 240],
  729. "khaki": [240, 230, 140],
  730. "lavender": [230, 230, 250],
  731. "lavenderblush": [255, 240, 245],
  732. "lawngreen": [124, 252, 0],
  733. "lemonchiffon": [255, 250, 205],
  734. "lightblue": [173, 216, 230],
  735. "lightcoral": [240, 128, 128],
  736. "lightcyan": [224, 255, 255],
  737. "lightgoldenrodyellow": [250, 250, 210],
  738. "lightgray": [211, 211, 211],
  739. "lightgreen": [144, 238, 144],
  740. "lightgrey": [211, 211, 211],
  741. "lightpink": [255, 182, 193],
  742. "lightsalmon": [255, 160, 122],
  743. "lightseagreen": [32, 178, 170],
  744. "lightskyblue": [135, 206, 250],
  745. "lightslategray": [119, 136, 153],
  746. "lightslategrey": [119, 136, 153],
  747. "lightsteelblue": [176, 196, 222],
  748. "lightyellow": [255, 255, 224],
  749. "lime": [0, 255, 0],
  750. "limegreen": [50, 205, 50],
  751. "linen": [250, 240, 230],
  752. "magenta": [255, 0, 255],
  753. "maroon": [128, 0, 0],
  754. "mediumaquamarine": [102, 205, 170],
  755. "mediumblue": [0, 0, 205],
  756. "mediumorchid": [186, 85, 211],
  757. "mediumpurple": [147, 112, 219],
  758. "mediumseagreen": [60, 179, 113],
  759. "mediumslateblue": [123, 104, 238],
  760. "mediumspringgreen": [0, 250, 154],
  761. "mediumturquoise": [72, 209, 204],
  762. "mediumvioletred": [199, 21, 133],
  763. "midnightblue": [25, 25, 112],
  764. "mintcream": [245, 255, 250],
  765. "mistyrose": [255, 228, 225],
  766. "moccasin": [255, 228, 181],
  767. "navajowhite": [255, 222, 173],
  768. "navy": [0, 0, 128],
  769. "oldlace": [253, 245, 230],
  770. "olive": [128, 128, 0],
  771. "olivedrab": [107, 142, 35],
  772. "orange": [255, 165, 0],
  773. "orangered": [255, 69, 0],
  774. "orchid": [218, 112, 214],
  775. "palegoldenrod": [238, 232, 170],
  776. "palegreen": [152, 251, 152],
  777. "paleturquoise": [175, 238, 238],
  778. "palevioletred": [219, 112, 147],
  779. "papayawhip": [255, 239, 213],
  780. "peachpuff": [255, 218, 185],
  781. "peru": [205, 133, 63],
  782. "pink": [255, 192, 203],
  783. "plum": [221, 160, 221],
  784. "powderblue": [176, 224, 230],
  785. "purple": [128, 0, 128],
  786. "rebeccapurple": [102, 51, 153],
  787. "red": [255, 0, 0],
  788. "rosybrown": [188, 143, 143],
  789. "royalblue": [65, 105, 225],
  790. "saddlebrown": [139, 69, 19],
  791. "salmon": [250, 128, 114],
  792. "sandybrown": [244, 164, 96],
  793. "seagreen": [46, 139, 87],
  794. "seashell": [255, 245, 238],
  795. "sienna": [160, 82, 45],
  796. "silver": [192, 192, 192],
  797. "skyblue": [135, 206, 235],
  798. "slateblue": [106, 90, 205],
  799. "slategray": [112, 128, 144],
  800. "slategrey": [112, 128, 144],
  801. "snow": [255, 250, 250],
  802. "springgreen": [0, 255, 127],
  803. "steelblue": [70, 130, 180],
  804. "tan": [210, 180, 140],
  805. "teal": [0, 128, 128],
  806. "thistle": [216, 191, 216],
  807. "tomato": [255, 99, 71],
  808. "turquoise": [64, 224, 208],
  809. "violet": [238, 130, 238],
  810. "wheat": [245, 222, 179],
  811. "white": [255, 255, 255],
  812. "whitesmoke": [245, 245, 245],
  813. "yellow": [255, 255, 0],
  814. "yellowgreen": [154, 205, 50]
  815. };
  816. module.exports = Color;
  817. },{}],4:[function(_dereq_,module,exports){
  818. var Support = _dereq_('./support');
  819. var CanvasRenderer = _dereq_('./renderers/canvas');
  820. var ImageLoader = _dereq_('./imageloader');
  821. var NodeParser = _dereq_('./nodeparser');
  822. var NodeContainer = _dereq_('./nodecontainer');
  823. var log = _dereq_('./log');
  824. var utils = _dereq_('./utils');
  825. var createWindowClone = _dereq_('./clone');
  826. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  827. var getBounds = utils.getBounds;
  828. var html2canvasNodeAttribute = "data-html2canvas-node";
  829. var html2canvasCloneIndex = 0;
  830. function html2canvas(nodeList, options) {
  831. var index = html2canvasCloneIndex++;
  832. options = options || {};
  833. if (options.logging) {
  834. log.options.logging = true;
  835. log.options.start = Date.now();
  836. }
  837. options.async = typeof(options.async) === "undefined" ? true : options.async;
  838. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  839. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  840. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  841. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  842. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  843. options.strict = !!options.strict;
  844. if (typeof(nodeList) === "string") {
  845. if (typeof(options.proxy) !== "string") {
  846. return Promise.reject("Proxy must be used when rendering url");
  847. }
  848. var width = options.width != null ? options.width : window.innerWidth;
  849. var height = options.height != null ? options.height : window.innerHeight;
  850. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  851. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  852. });
  853. }
  854. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  855. node.setAttribute(html2canvasNodeAttribute + index, index);
  856. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  857. if (typeof(options.onrendered) === "function") {
  858. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  859. options.onrendered(canvas);
  860. }
  861. return canvas;
  862. });
  863. }
  864. html2canvas.CanvasRenderer = CanvasRenderer;
  865. html2canvas.NodeContainer = NodeContainer;
  866. html2canvas.log = log;
  867. html2canvas.utils = utils;
  868. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  869. return Promise.reject("No canvas support");
  870. } : html2canvas;
  871. module.exports = html2canvasExport;
  872. if (typeof(define) === 'function' && define.amd) {
  873. define('html2canvas', [], function() {
  874. return html2canvasExport;
  875. });
  876. }
  877. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  878. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  879. log("Document cloned");
  880. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  881. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  882. document.querySelector(selector).removeAttribute(attributeName);
  883. var clonedWindow = container.contentWindow;
  884. var node = clonedWindow.document.querySelector(selector);
  885. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  886. return oncloneHandler.then(function() {
  887. return renderWindow(node, container, options, windowWidth, windowHeight);
  888. });
  889. });
  890. }
  891. function renderWindow(node, container, options, windowWidth, windowHeight) {
  892. var clonedWindow = container.contentWindow;
  893. var support = new Support(clonedWindow.document);
  894. var imageLoader = new ImageLoader(options, support);
  895. var bounds = getBounds(node);
  896. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  897. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  898. var renderer = new options.renderer(width, height, imageLoader, options, document);
  899. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  900. return parser.ready.then(function() {
  901. log("Finished rendering");
  902. var canvas;
  903. if (options.type === "view") {
  904. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  905. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  906. canvas = renderer.canvas;
  907. } else {
  908. canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: 0, y: 0});
  909. }
  910. cleanupContainer(container, options);
  911. return canvas;
  912. });
  913. }
  914. function cleanupContainer(container, options) {
  915. if (options.removeContainer) {
  916. container.parentNode.removeChild(container);
  917. log("Cleaned up container");
  918. }
  919. }
  920. function crop(canvas, bounds) {
  921. var croppedCanvas = document.createElement("canvas");
  922. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  923. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  924. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  925. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  926. croppedCanvas.width = bounds.width;
  927. croppedCanvas.height = bounds.height;
  928. var width = x2-x1;
  929. var height = y2-y1;
  930. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  931. log("R###lting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  932. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  933. return croppedCanvas;
  934. }
  935. function documentWidth (doc) {
  936. return Math.max(
  937. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  938. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  939. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  940. );
  941. }
  942. function documentHeight (doc) {
  943. return Math.max(
  944. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  945. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  946. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  947. );
  948. }
  949. function absoluteUrl(url) {
  950. var link = document.createElement("a");
  951. link.href = url;
  952. link.href = link.href;
  953. return link;
  954. }
  955. },{"./clone":2,"./imageloader":11,"./log":13,"./nodecontainer":14,"./nodeparser":15,"./proxy":16,"./renderers/canvas":20,"./support":22,"./utils":26}],5:[function(_dereq_,module,exports){
  956. var log = _dereq_('./log');
  957. var smallImage = _dereq_('./utils').smallImage;
  958. function DummyImageContainer(src) {
  959. this.src = src;
  960. log("DummyImageContainer for", src);
  961. if (!this.promise || !this.image) {
  962. log("Initiating DummyImageContainer");
  963. DummyImageContainer.prototype.image = new Image();
  964. var image = this.image;
  965. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  966. image.onload = resolve;
  967. image.onerror = reject;
  968. image.src = smallImage();
  969. if (image.complete === true) {
  970. resolve(image);
  971. }
  972. });
  973. }
  974. }
  975. module.exports = DummyImageContainer;
  976. },{"./log":13,"./utils":26}],6:[function(_dereq_,module,exports){
  977. var smallImage = _dereq_('./utils').smallImage;
  978. function Font(family, size) {
  979. var container = document.createElement('div'),
  980. img = document.createElement('img'),
  981. span = document.createElement('span'),
  982. sampleText = 'Hidden Text',
  983. baseline,
  984. middle;
  985. container.style.visibility = "hidden";
  986. container.style.fontFamily = family;
  987. container.style.fontSize = size;
  988. container.style.margin = 0;
  989. container.style.padding = 0;
  990. document.body.appendChild(container);
  991. img.src = smallImage();
  992. img.width = 1;
  993. img.height = 1;
  994. img.style.margin = 0;
  995. img.style.padding = 0;
  996. img.style.verticalAlign = "baseline";
  997. span.style.fontFamily = family;
  998. span.style.fontSize = size;
  999. span.style.margin = 0;
  1000. span.style.padding = 0;
  1001. span.appendChild(document.createTextNode(sampleText));
  1002. container.appendChild(span);
  1003. container.appendChild(img);
  1004. baseline = (img.offsetTop - span.offsetTop) + 1;
  1005. container.removeChild(span);
  1006. container.appendChild(document.createTextNode(sampleText));
  1007. container.style.lineHeight = "normal";
  1008. img.style.verticalAlign = "super";
  1009. middle = (img.offsetTop-container.offsetTop) + 1;
  1010. document.body.removeChild(container);
  1011. this.baseline = baseline;
  1012. this.lineWidth = 1;
  1013. this.middle = middle;
  1014. }
  1015. module.exports = Font;
  1016. },{"./utils":26}],7:[function(_dereq_,module,exports){
  1017. var Font = _dereq_('./font');
  1018. function FontMetrics() {
  1019. this.data = {};
  1020. }
  1021. FontMetrics.prototype.getMetrics = function(family, size) {
  1022. if (this.data[family + "-" + size] === undefined) {
  1023. this.data[family + "-" + size] = new Font(family, size);
  1024. }
  1025. return this.data[family + "-" + size];
  1026. };
  1027. module.exports = FontMetrics;
  1028. },{"./font":6}],8:[function(_dereq_,module,exports){
  1029. var utils = _dereq_('./utils');
  1030. var getBounds = utils.getBounds;
  1031. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  1032. function FrameContainer(container, sameOrigin, options) {
  1033. this.image = null;
  1034. this.src = container;
  1035. var self = this;
  1036. var bounds = getBounds(container);
  1037. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  1038. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  1039. container.contentWindow.onload = container.onload = function() {
  1040. resolve(container);
  1041. };
  1042. } else {
  1043. resolve(container);
  1044. }
  1045. })).then(function(container) {
  1046. var html2canvas = _dereq_('./core');
  1047. return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
  1048. }).then(function(canvas) {
  1049. return self.image = canvas;
  1050. });
  1051. }
  1052. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  1053. var container = this.src;
  1054. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  1055. };
  1056. module.exports = FrameContainer;
  1057. },{"./core":4,"./proxy":16,"./utils":26}],9:[function(_dereq_,module,exports){
  1058. function GradientContainer(imageData) {
  1059. this.src = imageData.value;
  1060. this.colorStops = [];
  1061. this.type = null;
  1062. this.x0 = 0.5;
  1063. this.y0 = 0.5;
  1064. this.x1 = 0.5;
  1065. this.y1 = 0.5;
  1066. this.promise = Promise.resolve(true);
  1067. }
  1068. GradientContainer.TYPES = {
  1069. LINEAR: 1,
  1070. RADIAL: 2
  1071. };
  1072. // TODO: support hsl[a], negative %/length values
  1073. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  1074. GradientContainer.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i;
  1075. module.exports = GradientContainer;
  1076. },{}],10:[function(_dereq_,module,exports){
  1077. function ImageContainer(src, cors) {
  1078. this.src = src;
  1079. this.image = new Image();
  1080. var self = this;
  1081. this.tainted = null;
  1082. this.promise = new Promise(function(resolve, reject) {
  1083. self.image.onload = resolve;
  1084. self.image.onerror = reject;
  1085. if (cors) {
  1086. self.image.crossOrigin = "anonymous";
  1087. }
  1088. self.image.src = src;
  1089. if (self.image.complete === true) {
  1090. resolve(self.image);
  1091. }
  1092. });
  1093. }
  1094. module.exports = ImageContainer;
  1095. },{}],11:[function(_dereq_,module,exports){
  1096. var log = _dereq_('./log');
  1097. var ImageContainer = _dereq_('./imagecontainer');
  1098. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  1099. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  1100. var FrameContainer = _dereq_('./framecontainer');
  1101. var SVGContainer = _dereq_('./svgcontainer');
  1102. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  1103. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  1104. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  1105. var bind = _dereq_('./utils').bind;
  1106. function ImageLoader(options, support) {
  1107. this.link = null;
  1108. this.options = options;
  1109. this.support = support;
  1110. this.origin = this.getOrigin(window.location.href);
  1111. }
  1112. ImageLoader.prototype.findImages = function(nodes) {
  1113. var images = [];
  1114. nodes.reduce(function(imageNodes, container) {
  1115. switch(container.node.nodeName) {
  1116. case "IMG":
  1117. return imageNodes.concat([{
  1118. args: [container.node.src],
  1119. method: "url"
  1120. }]);
  1121. case "svg":
  1122. case "IFRAME":
  1123. return imageNodes.concat([{
  1124. args: [container.node],
  1125. method: container.node.nodeName
  1126. }]);
  1127. }
  1128. return imageNodes;
  1129. }, []).forEach(this.addImage(images, this.loadImage), this);
  1130. return images;
  1131. };
  1132. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  1133. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  1134. return images;
  1135. };
  1136. ImageLoader.prototype.addImage = function(images, callback) {
  1137. return function(newImage) {
  1138. newImage.args.forEach(function(image) {
  1139. if (!this.imageExists(images, image)) {
  1140. images.splice(0, 0, callback.call(this, newImage));
  1141. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  1142. }
  1143. }, this);
  1144. };
  1145. };
  1146. ImageLoader.prototype.hasImageBackground = function(imageData) {
  1147. return imageData.method !== "none";
  1148. };
  1149. ImageLoader.prototype.loadImage = function(imageData) {
  1150. if (imageData.method === "url") {
  1151. var src = imageData.args[0];
  1152. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  1153. return new SVGContainer(src);
  1154. } else if (src.match(/data:image\/.*;base64,/i)) {
  1155. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  1156. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  1157. return new ImageContainer(src, false);
  1158. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  1159. return new ImageContainer(src, true);
  1160. } else if (this.options.proxy) {
  1161. return new ProxyImageContainer(src, this.options.proxy);
  1162. } else {
  1163. return new DummyImageContainer(src);
  1164. }
  1165. } else if (imageData.method === "linear-gradient") {
  1166. return new LinearGradientContainer(imageData);
  1167. } else if (imageData.method === "gradient") {
  1168. return new WebkitGradientContainer(imageData);
  1169. } else if (imageData.method === "svg") {
  1170. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  1171. } else if (imageData.method === "IFRAME") {
  1172. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  1173. } else {
  1174. return new DummyImageContainer(imageData);
  1175. }
  1176. };
  1177. ImageLoader.prototype.isSVG = function(src) {
  1178. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  1179. };
  1180. ImageLoader.prototype.imageExists = function(images, src) {
  1181. return images.some(function(image) {
  1182. return image.src === src;
  1183. });
  1184. };
  1185. ImageLoader.prototype.isSameOrigin = function(url) {
  1186. return (this.getOrigin(url) === this.origin);
  1187. };
  1188. ImageLoader.prototype.getOrigin = function(url) {
  1189. var link = this.link || (this.link = document.createElement("a"));
  1190. link.href = url;
  1191. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  1192. return link.protocol + link.hostname + link.port;
  1193. };
  1194. ImageLoader.prototype.getPromise = function(container) {
  1195. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  1196. var dummy = new DummyImageContainer(container.src);
  1197. return dummy.promise.then(function(image) {
  1198. container.image = image;
  1199. });
  1200. });
  1201. };
  1202. ImageLoader.prototype.get = function(src) {
  1203. var found = null;
  1204. return this.images.some(function(img) {
  1205. return (found = img).src === src;
  1206. }) ? found : null;
  1207. };
  1208. ImageLoader.prototype.fetch = function(nodes) {
  1209. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  1210. this.images.forEach(function(image, index) {
  1211. image.promise.then(function() {
  1212. log("Succesfully loaded image #"+ (index+1), image);
  1213. }, function(e) {
  1214. log("Failed loading image #"+ (index+1), image, e);
  1215. });
  1216. });
  1217. this.ready = Promise.all(this.images.map(this.getPromise, this));
  1218. log("Finished searching images");
  1219. return this;
  1220. };
  1221. ImageLoader.prototype.timeout = function(container, timeout) {
  1222. var timer;
  1223. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  1224. timer = setTimeout(function() {
  1225. log("Timed out loading image", container);
  1226. reject(container);
  1227. }, timeout);
  1228. })]).then(function(container) {
  1229. clearTimeout(timer);
  1230. return container;
  1231. });
  1232. promise['catch'](function() {
  1233. clearTimeout(timer);
  1234. });
  1235. return promise;
  1236. };
  1237. module.exports = ImageLoader;
  1238. },{"./dummyimagecontainer":5,"./framecontainer":8,"./imagecontainer":10,"./lineargradientcontainer":12,"./log":13,"./proxyimagecontainer":17,"./svgcontainer":23,"./svgnodecontainer":24,"./utils":26,"./webkitgradientcontainer":27}],12:[function(_dereq_,module,exports){
  1239. var GradientContainer = _dereq_('./gradientcontainer');
  1240. var Color = _dereq_('./color');
  1241. function LinearGradientContainer(imageData) {
  1242. GradientContainer.apply(this, arguments);
  1243. this.type = GradientContainer.TYPES.LINEAR;
  1244. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test( imageData.args[0] ) ||
  1245. !GradientContainer.REGEXP_COLORSTOP.test( imageData.args[0] );
  1246. if (hasDirection) {
  1247. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  1248. switch(position) {
  1249. case "left":
  1250. this.x0 = 0;
  1251. this.x1 = 1;
  1252. break;
  1253. case "top":
  1254. this.y0 = 0;
  1255. this.y1 = 1;
  1256. break;
  1257. case "right":
  1258. this.x0 = 1;
  1259. this.x1 = 0;
  1260. break;
  1261. case "bottom":
  1262. this.y0 = 1;
  1263. this.y1 = 0;
  1264. break;
  1265. case "to":
  1266. var y0 = this.y0;
  1267. var x0 = this.x0;
  1268. this.y0 = this.y1;
  1269. this.x0 = this.x1;
  1270. this.x1 = x0;
  1271. this.y1 = y0;
  1272. break;
  1273. case "center":
  1274. break; // centered by default
  1275. // Firefox internally converts position keywords to percentages:
  1276. // http://www.w3.org/TR/2010/WD-CSS2-20101207/colors.html#propdef-background-position
  1277. default: // percentage or absolute length
  1278. // TODO: support absolute start point positions (e.g., use bounds to convert px to a ratio)
  1279. var ratio = parseFloat(position, 10) * 1e-2;
  1280. if (isNaN(ratio)) { // invalid or unhandled value
  1281. break;
  1282. }
  1283. if (index === 0) {
  1284. this.y0 = ratio;
  1285. this.y1 = 1 - this.y0;
  1286. } else {
  1287. this.x0 = ratio;
  1288. this.x1 = 1 - this.x0;
  1289. }
  1290. break;
  1291. }
  1292. }, this);
  1293. } else {
  1294. this.y0 = 0;
  1295. this.y1 = 1;
  1296. }
  1297. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  1298. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  1299. var value = +colorStopMatch[2];
  1300. var unit = value === 0 ? "%" : colorStopMatch[3]; // treat "0" as "0%"
  1301. return {
  1302. color: new Color(colorStopMatch[1]),
  1303. // TODO: support absolute stop positions (e.g., compute gradient line length & convert px to ratio)
  1304. stop: unit === "%" ? value / 100 : null
  1305. };
  1306. });
  1307. if (this.colorStops[0].stop === null) {
  1308. this.colorStops[0].stop = 0;
  1309. }
  1310. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  1311. this.colorStops[this.colorStops.length - 1].stop = 1;
  1312. }
  1313. // calculates and fills-in explicit stop positions when omitted from rule
  1314. this.colorStops.forEach(function(colorStop, index) {
  1315. if (colorStop.stop === null) {
  1316. this.colorStops.slice(index).some(function(find, count) {
  1317. if (find.stop !== null) {
  1318. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  1319. return true;
  1320. } else {
  1321. return false;
  1322. }
  1323. }, this);
  1324. }
  1325. }, this);
  1326. }
  1327. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  1328. // TODO: support <angle> (e.g. -?\d{1,3}(?:\.\d+)deg, etc. : https://developer.mozilla.org/docs/Web/CSS/angle )
  1329. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  1330. module.exports = LinearGradientContainer;
  1331. },{"./color":3,"./gradientcontainer":9}],13:[function(_dereq_,module,exports){
  1332. var logger = function() {
  1333. if (logger.options.logging && window.console && window.console.log) {
  1334. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  1335. }
  1336. };
  1337. logger.options = {logging: false};
  1338. module.exports = logger;
  1339. },{}],14:[function(_dereq_,module,exports){
  1340. var Color = _dereq_('./color');
  1341. var utils = _dereq_('./utils');
  1342. var getBounds = utils.getBounds;
  1343. var parseBackgrounds = utils.parseBackgrounds;
  1344. var offsetBounds = utils.offsetBounds;
  1345. function NodeContainer(node, parent) {
  1346. this.node = node;
  1347. this.parent = parent;
  1348. this.stack = null;
  1349. this.bounds = null;
  1350. this.borders = null;
  1351. this.clip = [];
  1352. this.backgroundClip = [];
  1353. this.offsetBounds = null;
  1354. this.visible = null;
  1355. this.computedStyles = null;
  1356. this.colors = {};
  1357. this.styles = {};
  1358. this.backgroundImages = null;
  1359. this.transformData = null;
  1360. this.transformMatrix = null;
  1361. this.isPseudoElement = false;
  1362. this.opacity = null;
  1363. }
  1364. NodeContainer.prototype.cloneTo = function(stack) {
  1365. stack.visible = this.visible;
  1366. stack.borders = this.borders;
  1367. stack.bounds = this.bounds;
  1368. stack.clip = this.clip;
  1369. stack.backgroundClip = this.backgroundClip;
  1370. stack.computedStyles = this.computedStyles;
  1371. stack.styles = this.styles;
  1372. stack.backgroundImages = this.backgroundImages;
  1373. stack.opacity = this.opacity;
  1374. };
  1375. NodeContainer.prototype.getOpacity = function() {
  1376. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  1377. };
  1378. NodeContainer.prototype.assignStack = function(stack) {
  1379. this.stack = stack;
  1380. stack.children.push(this);
  1381. };
  1382. NodeContainer.prototype.isElementVisible = function() {
  1383. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  1384. this.css('display') !== "none" &&
  1385. this.css('visibility') !== "hidden" &&
  1386. !this.node.hasAttribute("data-html2canvas-ignore") &&
  1387. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  1388. );
  1389. };
  1390. NodeContainer.prototype.css = function(attribute) {
  1391. if (!this.computedStyles) {
  1392. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  1393. }
  1394. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  1395. };
  1396. NodeContainer.prototype.prefixedCss = function(attribute) {
  1397. var prefixes = ["webkit", "moz", "ms", "o"];
  1398. var value = this.css(attribute);
  1399. if (value === undefined) {
  1400. prefixes.some(function(prefix) {
  1401. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  1402. return value !== undefined;
  1403. }, this);
  1404. }
  1405. return value === undefined ? null : value;
  1406. };
  1407. NodeContainer.prototype.computedStyle = function(type) {
  1408. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  1409. };
  1410. NodeContainer.prototype.cssInt = function(attribute) {
  1411. var value = parseInt(this.css(attribute), 10);
  1412. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  1413. };
  1414. NodeContainer.prototype.color = function(attribute) {
  1415. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  1416. };
  1417. NodeContainer.prototype.cssFloat = function(attribute) {
  1418. var value = parseFloat(this.css(attribute));
  1419. return (isNaN(value)) ? 0 : value;
  1420. };
  1421. NodeContainer.prototype.fontWeight = function() {
  1422. var weight = this.css("fontWeight");
  1423. switch(parseInt(weight, 10)){
  1424. case 401:
  1425. weight = "bold";
  1426. break;
  1427. case 400:
  1428. weight = "normal";
  1429. break;
  1430. }
  1431. return weight;
  1432. };
  1433. NodeContainer.prototype.parseClip = function() {
  1434. var matches = this.css('clip').match(this.CLIP);
  1435. if (matches) {
  1436. return {
  1437. top: parseInt(matches[1], 10),
  1438. right: parseInt(matches[2], 10),
  1439. bottom: parseInt(matches[3], 10),
  1440. left: parseInt(matches[4], 10)
  1441. };
  1442. }
  1443. return null;
  1444. };
  1445. NodeContainer.prototype.parseBackgroundImages = function() {
  1446. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  1447. };
  1448. NodeContainer.prototype.cssList = function(property, index) {
  1449. var value = (this.css(property) || '').split(',');
  1450. value = value[index || 0] || value[0] || 'auto';
  1451. value = value.trim().split(' ');
  1452. if (value.length === 1) {
  1453. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  1454. }
  1455. return value;
  1456. };
  1457. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  1458. var size = this.cssList("backgroundSize", index);
  1459. var width, height;
  1460. if (isPercentage(size[0])) {
  1461. width = bounds.width * parseFloat(size[0]) / 100;
  1462. } else if (/contain|cover/.test(size[0])) {
  1463. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  1464. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  1465. } else {
  1466. width = parseInt(size[0], 10);
  1467. }
  1468. if (size[0] === 'auto' && size[1] === 'auto') {
  1469. height = image.height;
  1470. } else if (size[1] === 'auto') {
  1471. height = width / image.width * image.height;
  1472. } else if (isPercentage(size[1])) {
  1473. height = bounds.height * parseFloat(size[1]) / 100;
  1474. } else {
  1475. height = parseInt(size[1], 10);
  1476. }
  1477. if (size[0] === 'auto') {
  1478. width = height / image.height * image.width;
  1479. }
  1480. return {width: width, height: height};
  1481. };
  1482. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  1483. var position = this.cssList('backgroundPosition', index);
  1484. var left, top;
  1485. if (isPercentage(position[0])){
  1486. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  1487. } else {
  1488. left = parseInt(position[0], 10);
  1489. }
  1490. if (position[1] === 'auto') {
  1491. top = left / image.width * image.height;
  1492. } else if (isPercentage(position[1])){
  1493. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  1494. } else {
  1495. top = parseInt(position[1], 10);
  1496. }
  1497. if (position[0] === 'auto') {
  1498. left = top / image.height * image.width;
  1499. }
  1500. return {left: left, top: top};
  1501. };
  1502. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  1503. return this.cssList("backgroundRepeat", index)[0];
  1504. };
  1505. NodeContainer.prototype.parseTextShadows = function() {
  1506. var textShadow = this.css("textShadow");
  1507. var r###lts = [];
  1508. if (textShadow && textShadow !== 'none') {
  1509. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  1510. for (var i = 0; shadows && (i < shadows.length); i++) {
  1511. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  1512. r###lts.push({
  1513. color: new Color(s[0]),
  1514. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  1515. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  1516. blur: s[3] ? s[3].replace('px', '') : 0
  1517. });
  1518. }
  1519. }
  1520. return r###lts;
  1521. };
  1522. NodeContainer.prototype.parseTransform = function() {
  1523. if (!this.transformData) {
  1524. if (this.hasTransform()) {
  1525. var offset = this.parseBounds();
  1526. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  1527. origin[0] += offset.left;
  1528. origin[1] += offset.top;
  1529. this.transformData = {
  1530. origin: origin,
  1531. matrix: this.parseTransformMatrix()
  1532. };
  1533. } else {
  1534. this.transformData = {
  1535. origin: [0, 0],
  1536. matrix: [1, 0, 0, 1, 0, 0]
  1537. };
  1538. }
  1539. }
  1540. return this.transformData;
  1541. };
  1542. NodeContainer.prototype.parseTransformMatrix = function() {
  1543. if (!this.transformMatrix) {
  1544. var transform = this.prefixedCss("transform");
  1545. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  1546. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  1547. }
  1548. return this.transformMatrix;
  1549. };
  1550. NodeContainer.prototype.parseBounds = function() {
  1551. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  1552. };
  1553. NodeContainer.prototype.hasTransform = function() {
  1554. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  1555. };
  1556. NodeContainer.prototype.getValue = function() {
  1557. var value = this.node.value || "";
  1558. if (this.node.tagName === "SELECT") {
  1559. value = selectionValue(this.node);
  1560. } else if (this.node.type === "password") {
  1561. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  1562. }
  1563. return value.length === 0 ? (this.node.placeholder || "") : value;
  1564. };
  1565. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  1566. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  1567. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  1568. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  1569. function selectionValue(node) {
  1570. var option = node.options[node.selectedIndex || 0];
  1571. return option ? (option.text || "") : "";
  1572. }
  1573. function parseMatrix(match) {
  1574. if (match && match[1] === "matrix") {
  1575. return match[2].split(",").map(function(s) {
  1576. return parseFloat(s.trim());
  1577. });
  1578. } else if (match && match[1] === "matrix3d") {
  1579. var matrix3d = match[2].split(",").map(function(s) {
  1580. return parseFloat(s.trim());
  1581. });
  1582. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  1583. }
  1584. }
  1585. function isPercentage(value) {
  1586. return value.toString().indexOf("%") !== -1;
  1587. }
  1588. function removePx(str) {
  1589. return str.replace("px", "");
  1590. }
  1591. function asFloat(str) {
  1592. return parseFloat(str);
  1593. }
  1594. module.exports = NodeContainer;
  1595. },{"./color":3,"./utils":26}],15:[function(_dereq_,module,exports){
  1596. var log = _dereq_('./log');
  1597. var punycode = _dereq_('punycode');
  1598. var NodeContainer = _dereq_('./nodecontainer');
  1599. var TextContainer = _dereq_('./textcontainer');
  1600. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  1601. var FontMetrics = _dereq_('./fontmetrics');
  1602. var Color = _dereq_('./color');
  1603. var StackingContext = _dereq_('./stackingcontext');
  1604. var utils = _dereq_('./utils');
  1605. var bind = utils.bind;
  1606. var getBounds = utils.getBounds;
  1607. var parseBackgrounds = utils.parseBackgrounds;
  1608. var offsetBounds = utils.offsetBounds;
  1609. function NodeParser(element, renderer, support, imageLoader, options) {
  1610. log("Starting NodeParser");
  1611. this.renderer = renderer;
  1612. this.options = options;
  1613. this.range = null;
  1614. this.support = support;
  1615. this.renderQueue = [];
  1616. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  1617. var parent = new NodeContainer(element, null);
  1618. if (options.background) {
  1619. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  1620. }
  1621. if (element === element.ownerDocument.documentElement) {
  1622. // http://www.w3.org/TR/css3-background/#special-backgrounds
  1623. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  1624. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  1625. }
  1626. parent.visibile = parent.isElementVisible();
  1627. this.createPseudoHideStyles(element.ownerDocument);
  1628. this.disableAnimations(element.ownerDocument);
  1629. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  1630. return container.visible = container.isElementVisible();
  1631. }).map(this.getPseudoElements, this));
  1632. this.fontMetrics = new FontMetrics();
  1633. log("Fetched nodes, total:", this.nodes.length);
  1634. log("Calculate overflow clips");
  1635. this.calculateOverflowClips();
  1636. log("Start fetching images");
  1637. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  1638. this.ready = this.images.ready.then(bind(function() {
  1639. log("Images loaded, starting parsing");
  1640. log("Creating stacking contexts");
  1641. this.createStackingContexts();
  1642. log("Sorting stacking contexts");
  1643. this.sortStackingContexts(this.stack);
  1644. this.parse(this.stack);
  1645. log("Render queue created with " + this.renderQueue.length + " items");
  1646. return new Promise(bind(function(resolve) {
  1647. if (!options.async) {
  1648. this.renderQueue.forEach(this.paint, this);
  1649. resolve();
  1650. } else if (typeof(options.async) === "function") {
  1651. options.async.call(this, this.renderQueue, resolve);
  1652. } else if (this.renderQueue.length > 0){
  1653. this.renderIndex = 0;
  1654. this.asyncRenderer(this.renderQueue, resolve);
  1655. } else {
  1656. resolve();
  1657. }
  1658. }, this));
  1659. }, this));
  1660. }
  1661. NodeParser.prototype.calculateOverflowClips = function() {
  1662. this.nodes.forEach(function(container) {
  1663. if (isElement(container)) {
  1664. if (isPseudoElement(container)) {
  1665. container.appendToDOM();
  1666. }
  1667. container.borders = this.parseBorders(container);
  1668. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  1669. var cssClip = container.parseClip();
  1670. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  1671. clip.push([["rect",
  1672. container.bounds.left + cssClip.left,
  1673. container.bounds.top + cssClip.top,
  1674. cssClip.right - cssClip.left,
  1675. cssClip.bottom - cssClip.top
  1676. ]]);
  1677. }
  1678. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  1679. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  1680. if (isPseudoElement(container)) {
  1681. container.cleanDOM();
  1682. }
  1683. } else if (isTextNode(container)) {
  1684. container.clip = hasParentClip(container) ? container.parent.clip : [];
  1685. }
  1686. if (!isPseudoElement(container)) {
  1687. container.bounds = null;
  1688. }
  1689. }, this);
  1690. };
  1691. function hasParentClip(container) {
  1692. return container.parent && container.parent.clip.length;
  1693. }
  1694. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  1695. asyncTimer = asyncTimer || Date.now();
  1696. this.paint(queue[this.renderIndex++]);
  1697. if (queue.length === this.renderIndex) {
  1698. resolve();
  1699. } else if (asyncTimer + 20 > Date.now()) {
  1700. this.asyncRenderer(queue, resolve, asyncTimer);
  1701. } else {
  1702. setTimeout(bind(function() {
  1703. this.asyncRenderer(queue, resolve);
  1704. }, this), 0);
  1705. }
  1706. };
  1707. NodeParser.prototype.createPseudoHideStyles = function(document) {
  1708. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  1709. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  1710. };
  1711. NodeParser.prototype.disableAnimations = function(document) {
  1712. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  1713. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  1714. };
  1715. NodeParser.prototype.createStyles = function(document, styles) {
  1716. var hidePseudoElements = document.createElement('style');
  1717. hidePseudoElements.innerHTML = styles;
  1718. document.body.appendChild(hidePseudoElements);
  1719. };
  1720. NodeParser.prototype.getPseudoElements = function(container) {
  1721. var nodes = [[container]];
  1722. if (container.node.nodeType === Node.ELEMENT_NODE) {
  1723. var before = this.getPseudoElement(container, ":before");
  1724. var after = this.getPseudoElement(container, ":after");
  1725. if (before) {
  1726. nodes.push(before);
  1727. }
  1728. if (after) {
  1729. nodes.push(after);
  1730. }
  1731. }
  1732. return flatten(nodes);
  1733. };
  1734. function toCamelCase(str) {
  1735. return str.replace(/(\-[a-z])/g, function(match){
  1736. return match.toUpperCase().replace('-','');
  1737. });
  1738. }
  1739. NodeParser.prototype.getPseudoElement = function(container, type) {
  1740. var style = container.computedStyle(type);
  1741. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  1742. return null;
  1743. }
  1744. var content = stripQuotes(style.content);
  1745. var isImage = content.substr(0, 3) === 'url';
  1746. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  1747. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  1748. for (var i = style.length-1; i >= 0; i--) {
  1749. var property = toCamelCase(style.item(i));
  1750. pseudoNode.style[property] = style[property];
  1751. }
  1752. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  1753. if (isImage) {
  1754. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  1755. return [pseudoContainer];
  1756. } else {
  1757. var text = document.createTextNode(content);
  1758. pseudoNode.appendChild(text);
  1759. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  1760. }
  1761. };
  1762. NodeParser.prototype.getChildren = function(parentContainer) {
  1763. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  1764. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  1765. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  1766. }, this));
  1767. };
  1768. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  1769. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  1770. container.cloneTo(stack);
  1771. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  1772. parentStack.contexts.push(stack);
  1773. container.stack = stack;
  1774. };
  1775. NodeParser.prototype.createStackingContexts = function() {
  1776. this.nodes.forEach(function(container) {
  1777. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  1778. this.newStackingContext(container, true);
  1779. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  1780. this.newStackingContext(container, false);
  1781. } else {
  1782. container.assignStack(container.parent.stack);
  1783. }
  1784. }, this);
  1785. };
  1786. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  1787. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  1788. };
  1789. NodeParser.prototype.isRootElement = function(container) {
  1790. return container.parent === null;
  1791. };
  1792. NodeParser.prototype.sortStackingContexts = function(stack) {
  1793. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  1794. stack.contexts.forEach(this.sortStackingContexts, this);
  1795. };
  1796. NodeParser.prototype.parseTextBounds = function(container) {
  1797. return function(text, index, textList) {
  1798. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  1799. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  1800. var offset = textList.slice(0, index).join("").length;
  1801. return this.getRangeBounds(container.node, offset, text.length);
  1802. } else if (container.node && typeof(container.node.data) === "string") {
  1803. var replacementNode = container.node.splitText(text.length);
  1804. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  1805. container.node = replacementNode;
  1806. return bounds;
  1807. }
  1808. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  1809. container.node = container.node.splitText(text.length);
  1810. }
  1811. return {};
  1812. };
  1813. };
  1814. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  1815. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  1816. var parent = node.parentNode,
  1817. backupText = node.cloneNode(true);
  1818. wrapper.appendChild(node.cloneNode(true));
  1819. parent.replaceChild(wrapper, node);
  1820. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  1821. parent.replaceChild(backupText, wrapper);
  1822. return bounds;
  1823. };
  1824. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  1825. var range = this.range || (this.range = node.ownerDocument.createRange());
  1826. range.setStart(node, offset);
  1827. range.setEnd(node, offset + length);
  1828. return range.getBoundingClientRect();
  1829. };
  1830. function ClearTransform() {}
  1831. NodeParser.prototype.parse = function(stack) {
  1832. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  1833. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  1834. var descendantElements = stack.children.filter(isElement);
  1835. var descendantNonFloats = descendantElements.filter(not(isFloating));
  1836. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  1837. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  1838. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  1839. var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
  1840. var text = stack.children.filter(isTextNode).filter(hasText);
  1841. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  1842. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  1843. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  1844. this.renderQueue.push(container);
  1845. if (isStackingContext(container)) {
  1846. this.parse(container);
  1847. this.renderQueue.push(new ClearTransform());
  1848. }
  1849. }, this);
  1850. };
  1851. NodeParser.prototype.paint = function(container) {
  1852. try {
  1853. if (container instanceof ClearTransform) {
  1854. this.renderer.ctx.restore();
  1855. } else if (isTextNode(container)) {
  1856. if (isPseudoElement(container.parent)) {
  1857. container.parent.appendToDOM();
  1858. }
  1859. this.paintText(container);
  1860. if (isPseudoElement(container.parent)) {
  1861. container.parent.cleanDOM();
  1862. }
  1863. } else {
  1864. this.paintNode(container);
  1865. }
  1866. } catch(e) {
  1867. log(e);
  1868. if (this.options.strict) {
  1869. throw e;
  1870. }
  1871. }
  1872. };
  1873. NodeParser.prototype.paintNode = function(container) {
  1874. if (isStackingContext(container)) {
  1875. this.renderer.setOpacity(container.opacity);
  1876. this.renderer.ctx.save();
  1877. if (container.hasTransform()) {
  1878. this.renderer.setTransform(container.parseTransform());
  1879. }
  1880. }
  1881. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  1882. this.paintCheckbox(container);
  1883. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  1884. this.paintRadio(container);
  1885. } else {
  1886. this.paintElement(container);
  1887. }
  1888. };
  1889. NodeParser.prototype.paintElement = function(container) {
  1890. var bounds = container.parseBounds();
  1891. this.renderer.clip(container.backgroundClip, function() {
  1892. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  1893. }, this);
  1894. this.renderer.clip(container.clip, function() {
  1895. this.renderer.renderBorders(container.borders.borders);
  1896. }, this);
  1897. this.renderer.clip(container.backgroundClip, function() {
  1898. switch (container.node.nodeName) {
  1899. case "svg":
  1900. case "IFRAME":
  1901. var imgContainer = this.images.get(container.node);
  1902. if (imgContainer) {
  1903. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  1904. } else {
  1905. log("Error loading <" + container.node.nodeName + ">", container.node);
  1906. }
  1907. break;
  1908. case "IMG":
  1909. var imageContainer = this.images.get(container.node.src);
  1910. if (imageContainer) {
  1911. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  1912. } else {
  1913. log("Error loading <img>", container.node.src);
  1914. }
  1915. break;
  1916. case "CANVAS":
  1917. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  1918. break;
  1919. case "SELECT":
  1920. case "INPUT":
  1921. case "TEXTAREA":
  1922. this.paintFormValue(container);
  1923. break;
  1924. }
  1925. }, this);
  1926. };
  1927. NodeParser.prototype.paintCheckbox = function(container) {
  1928. var b = container.parseBounds();
  1929. var size = Math.min(b.width, b.height);
  1930. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  1931. var r = [3, 3];
  1932. var radius = [r, r, r, r];
  1933. var borders = [1,1,1,1].map(function(w) {
  1934. return {color: new Color('#A5A5A5'), width: w};
  1935. });
  1936. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  1937. this.renderer.clip(container.backgroundClip, function() {
  1938. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  1939. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  1940. if (container.node.checked) {
  1941. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  1942. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  1943. }
  1944. }, this);
  1945. };
  1946. NodeParser.prototype.paintRadio = function(container) {
  1947. var bounds = container.parseBounds();
  1948. var size = Math.min(bounds.width, bounds.height) - 2;
  1949. this.renderer.clip(container.backgroundClip, function() {
  1950. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  1951. if (container.node.checked) {
  1952. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  1953. }
  1954. }, this);
  1955. };
  1956. NodeParser.prototype.paintFormValue = function(container) {
  1957. var value = container.getValue();
  1958. if (value.length > 0) {
  1959. var document = container.node.ownerDocument;
  1960. var wrapper = document.createElement('html2canvaswrapper');
  1961. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  1962. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  1963. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  1964. 'boxSizing', 'whiteSpace', 'wordWrap'];
  1965. properties.forEach(function(property) {
  1966. try {
  1967. wrapper.style[property] = container.css(property);
  1968. } catch(e) {
  1969. // Older IE has issues with "border"
  1970. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  1971. }
  1972. });
  1973. var bounds = container.parseBounds();
  1974. wrapper.style.position = "fixed";
  1975. wrapper.style.left = bounds.left + "px";
  1976. wrapper.style.top = bounds.top + "px";
  1977. wrapper.textContent = value;
  1978. document.body.appendChild(wrapper);
  1979. this.paintText(new TextContainer(wrapper.firstChild, container));
  1980. document.body.removeChild(wrapper);
  1981. }
  1982. };
  1983. NodeParser.prototype.paintText = function(container) {
  1984. container.applyTextTransform();
  1985. var characters = punycode.ucs2.decode(container.node.data);
  1986. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  1987. return punycode.ucs2.encode([character]);
  1988. });
  1989. var weight = container.parent.fontWeight();
  1990. var size = container.parent.css('fontSize');
  1991. var family = container.parent.css('fontFamily');
  1992. var shadows = container.parent.parseTextShadows();
  1993. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  1994. if (shadows.length) {
  1995. // TODO: support multiple text shadows
  1996. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  1997. } else {
  1998. this.renderer.clearShadow();
  1999. }
  2000. this.renderer.clip(container.parent.clip, function() {
  2001. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  2002. if (bounds) {
  2003. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  2004. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  2005. }
  2006. }, this);
  2007. }, this);
  2008. };
  2009. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  2010. switch(container.css("textDecoration").split(" ")[0]) {
  2011. case "underline":
  2012. // Draws a line at the baseline of the font
  2013. // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
  2014. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  2015. break;
  2016. case "overline":
  2017. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  2018. break;
  2019. case "line-through":
  2020. // TODO try and find exact position for line-through
  2021. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  2022. break;
  2023. }
  2024. };
  2025. var borderColorTransforms = {
  2026. inset: [
  2027. ["darken", 0.60],
  2028. ["darken", 0.10],
  2029. ["darken", 0.10],
  2030. ["darken", 0.60]
  2031. ]
  2032. };
  2033. NodeParser.prototype.parseBorders = function(container) {
  2034. var nodeBounds = container.parseBounds();
  2035. var radius = getBorderRadiusData(container);
  2036. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  2037. var style = container.css('border' + side + 'Style');
  2038. var color = container.color('border' + side + 'Color');
  2039. if (style === "inset" && color.isBlack()) {
  2040. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  2041. }
  2042. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  2043. return {
  2044. width: container.cssInt('border' + side + 'Width'),
  2045. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  2046. args: null
  2047. };
  2048. });
  2049. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  2050. return {
  2051. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  2052. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  2053. };
  2054. };
  2055. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  2056. return borders.map(function(border, borderSide) {
  2057. if (border.width > 0) {
  2058. var bx = nodeBounds.left;
  2059. var by = nodeBounds.top;
  2060. var bw = nodeBounds.width;
  2061. var bh = nodeBounds.height - (borders[2].width);
  2062. switch(borderSide) {
  2063. case 0:
  2064. // top border
  2065. bh = borders[0].width;
  2066. border.args = drawSide({
  2067. c1: [bx, by],
  2068. c2: [bx + bw, by],
  2069. c3: [bx + bw - borders[1].width, by + bh],
  2070. c4: [bx + borders[3].width, by + bh]
  2071. }, radius[0], radius[1],
  2072. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  2073. break;
  2074. case 1:
  2075. // right border
  2076. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  2077. bw = borders[1].width;
  2078. border.args = drawSide({
  2079. c1: [bx + bw, by],
  2080. c2: [bx + bw, by + bh + borders[2].width],
  2081. c3: [bx, by + bh],
  2082. c4: [bx, by + borders[0].width]
  2083. }, radius[1], radius[2],
  2084. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  2085. break;
  2086. case 2:
  2087. // bottom border
  2088. by = (by + nodeBounds.height) - (borders[2].width);
  2089. bh = borders[2].width;
  2090. border.args = drawSide({
  2091. c1: [bx + bw, by + bh],
  2092. c2: [bx, by + bh],
  2093. c3: [bx + borders[3].width, by],
  2094. c4: [bx + bw - borders[3].width, by]
  2095. }, radius[2], radius[3],
  2096. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  2097. break;
  2098. case 3:
  2099. // left border
  2100. bw = borders[3].width;
  2101. border.args = drawSide({
  2102. c1: [bx, by + bh + borders[2].width],
  2103. c2: [bx, by],
  2104. c3: [bx + bw, by + borders[0].width],
  2105. c4: [bx + bw, by + bh]
  2106. }, radius[3], radius[0],
  2107. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  2108. break;
  2109. }
  2110. }
  2111. return border;
  2112. });
  2113. }
  2114. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  2115. var backgroundClip = container.css('backgroundClip'),
  2116. borderArgs = [];
  2117. switch(backgroundClip) {
  2118. case "content-box":
  2119. case "padding-box":
  2120. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  2121. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  2122. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  2123. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  2124. break;
  2125. default:
  2126. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  2127. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  2128. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  2129. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  2130. break;
  2131. }
  2132. return borderArgs;
  2133. };
  2134. function getCurvePoints(x, y, r1, r2) {
  2135. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  2136. var ox = (r1) * kappa, // control point offset horizontal
  2137. oy = (r2) * kappa, // control point offset vertical
  2138. xm = x + r1, // x-middle
  2139. ym = y + r2; // y-middle
  2140. return {
  2141. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  2142. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  2143. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  2144. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  2145. };
  2146. }
  2147. function calculateCurvePoints(bounds, borderRadius, borders) {
  2148. var x = bounds.left,
  2149. y = bounds.top,
  2150. width = bounds.width,
  2151. height = bounds.height,
  2152. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  2153. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  2154. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  2155. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  2156. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  2157. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  2158. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  2159. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  2160. var topWidth = width - trh,
  2161. rightHeight = height - brv,
  2162. bottomWidth = width - brh,
  2163. leftHeight = height - blv;
  2164. return {
  2165. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  2166. topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
  2167. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  2168. topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
  2169. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  2170. bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
  2171. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  2172. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  2173. };
  2174. }
  2175. function bezierCurve(start, startControl, endControl, end) {
  2176. var lerp = function (a, b, t) {
  2177. return {
  2178. x: a.x + (b.x - a.x) * t,
  2179. y: a.y + (b.y - a.y) * t
  2180. };
  2181. };
  2182. return {
  2183. start: start,
  2184. startControl: startControl,
  2185. endControl: endControl,
  2186. end: end,
  2187. subdivide: function(t) {
  2188. var ab = lerp(start, startControl, t),
  2189. bc = lerp(startControl, endControl, t),
  2190. cd = lerp(endControl, end, t),
  2191. abbc = lerp(ab, bc, t),
  2192. bccd = lerp(bc, cd, t),
  2193. dest = lerp(abbc, bccd, t);
  2194. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  2195. },
  2196. curveTo: function(borderArgs) {
  2197. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  2198. },
  2199. curveToReversed: function(borderArgs) {
  2200. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  2201. }
  2202. };
  2203. }
  2204. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  2205. var borderArgs = [];
  2206. if (radius1[0] > 0 || radius1[1] > 0) {
  2207. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  2208. outer1[1].curveTo(borderArgs);
  2209. } else {
  2210. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  2211. }
  2212. if (radius2[0] > 0 || radius2[1] > 0) {
  2213. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  2214. outer2[0].curveTo(borderArgs);
  2215. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  2216. inner2[0].curveToReversed(borderArgs);
  2217. } else {
  2218. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  2219. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  2220. }
  2221. if (radius1[0] > 0 || radius1[1] > 0) {
  2222. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  2223. inner1[1].curveToReversed(borderArgs);
  2224. } else {
  2225. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  2226. }
  2227. return borderArgs;
  2228. }
  2229. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  2230. if (radius1[0] > 0 || radius1[1] > 0) {
  2231. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  2232. corner1[0].curveTo(borderArgs);
  2233. corner1[1].curveTo(borderArgs);
  2234. } else {
  2235. borderArgs.push(["line", x, y]);
  2236. }
  2237. if (radius2[0] > 0 || radius2[1] > 0) {
  2238. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  2239. }
  2240. }
  2241. function negativeZIndex(container) {
  2242. return container.cssInt("zIndex") < 0;
  2243. }
  2244. function positiveZIndex(container) {
  2245. return container.cssInt("zIndex") > 0;
  2246. }
  2247. function zIndex0(container) {
  2248. return container.cssInt("zIndex") === 0;
  2249. }
  2250. function inlineLevel(container) {
  2251. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  2252. }
  2253. function isStackingContext(container) {
  2254. return (container instanceof StackingContext);
  2255. }
  2256. function hasText(container) {
  2257. return container.node.data.trim().length > 0;
  2258. }
  2259. function noLetterSpacing(container) {
  2260. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  2261. }
  2262. function getBorderRadiusData(container) {
  2263. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  2264. var value = container.css('border' + side + 'Radius');
  2265. var arr = value.split(" ");
  2266. if (arr.length <= 1) {
  2267. arr[1] = arr[0];
  2268. }
  2269. return arr.map(asInt);
  2270. });
  2271. }
  2272. function renderableNode(node) {
  2273. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  2274. }
  2275. function isPositionedForStacking(container) {
  2276. var position = container.css("position");
  2277. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  2278. return zIndex !== "auto";
  2279. }
  2280. function isPositioned(container) {
  2281. return container.css("position") !== "static";
  2282. }
  2283. function isFloating(container) {
  2284. return container.css("float") !== "none";
  2285. }
  2286. function isInlineBlock(container) {
  2287. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  2288. }
  2289. function not(callback) {
  2290. var context = this;
  2291. return function() {
  2292. return !callback.apply(context, arguments);
  2293. };
  2294. }
  2295. function isElement(container) {
  2296. return container.node.nodeType === Node.ELEMENT_NODE;
  2297. }
  2298. function isPseudoElement(container) {
  2299. return container.isPseudoElement === true;
  2300. }
  2301. function isTextNode(container) {
  2302. return container.node.nodeType === Node.TEXT_NODE;
  2303. }
  2304. function zIndexSort(contexts) {
  2305. return function(a, b) {
  2306. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  2307. };
  2308. }
  2309. function hasOpacity(container) {
  2310. return container.getOpacity() < 1;
  2311. }
  2312. function asInt(value) {
  2313. return parseInt(value, 10);
  2314. }
  2315. function getWidth(border) {
  2316. return border.width;
  2317. }
  2318. function nonIgnoredElement(nodeContainer) {
  2319. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  2320. }
  2321. function flatten(arrays) {
  2322. return [].concat.apply([], arrays);
  2323. }
  2324. function stripQuotes(content) {
  2325. var first = content.substr(0, 1);
  2326. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  2327. }
  2328. function getWords(characters) {
  2329. var words = [], i = 0, onWordBoundary = false, word;
  2330. while(characters.length) {
  2331. if (isWordBoundary(characters[i]) === onWordBoundary) {
  2332. word = characters.splice(0, i);
  2333. if (word.length) {
  2334. words.push(punycode.ucs2.encode(word));
  2335. }
  2336. onWordBoundary =! onWordBoundary;
  2337. i = 0;
  2338. } else {
  2339. i++;
  2340. }
  2341. if (i >= characters.length) {
  2342. word = characters.splice(0, i);
  2343. if (word.length) {
  2344. words.push(punycode.ucs2.encode(word));
  2345. }
  2346. }
  2347. }
  2348. return words;
  2349. }
  2350. function isWordBoundary(characterCode) {
  2351. return [
  2352. 32, // <space>
  2353. 13, // \r
  2354. 10, // \n
  2355. 9, // \t
  2356. 45 // -
  2357. ].indexOf(characterCode) !== -1;
  2358. }
  2359. function hasUnicode(string) {
  2360. return (/[^\u0000-\u00ff]/).test(string);
  2361. }
  2362. module.exports = NodeParser;
  2363. },{"./color":3,"./fontmetrics":7,"./log":13,"./nodecontainer":14,"./pseudoelementcontainer":18,"./stackingcontext":21,"./textcontainer":25,"./utils":26,"punycode":1}],16:[function(_dereq_,module,exports){
  2364. var XHR = _dereq_('./xhr');
  2365. var utils = _dereq_('./utils');
  2366. var log = _dereq_('./log');
  2367. var createWindowClone = _dereq_('./clone');
  2368. var decode64 = utils.decode64;
  2369. function Proxy(src, proxyUrl, document) {
  2370. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  2371. if (!proxyUrl) {
  2372. return Promise.reject("No proxy configured");
  2373. }
  2374. var callback = createCallback(supportsCORS);
  2375. var url = createProxyUrl(proxyUrl, src, callback);
  2376. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  2377. return decode64(response.content);
  2378. }));
  2379. }
  2380. var proxyCount = 0;
  2381. function ProxyURL(src, proxyUrl, document) {
  2382. var supportsCORSImage = ('crossOrigin' in new Image());
  2383. var callback = createCallback(supportsCORSImage);
  2384. var url = createProxyUrl(proxyUrl, src, callback);
  2385. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  2386. return "data:" + response.type + ";base64," + response.content;
  2387. }));
  2388. }
  2389. function jsonp(document, url, callback) {
  2390. return new Promise(function(resolve, reject) {
  2391. var s = document.createElement("script");
  2392. var cleanup = function() {
  2393. delete window.html2canvas.proxy[callback];
  2394. document.body.removeChild(s);
  2395. };
  2396. window.html2canvas.proxy[callback] = function(response) {
  2397. cleanup();
  2398. resolve(response);
  2399. };
  2400. s.src = url;
  2401. s.onerror = function(e) {
  2402. cleanup();
  2403. reject(e);
  2404. };
  2405. document.body.appendChild(s);
  2406. });
  2407. }
  2408. function createCallback(useCORS) {
  2409. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  2410. }
  2411. function createProxyUrl(proxyUrl, src, callback) {
  2412. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  2413. }
  2414. function documentFromHTML(src) {
  2415. return function(html) {
  2416. var parser = new DOMParser(), doc;
  2417. try {
  2418. doc = parser.parseFromString(html, "text/html");
  2419. } catch(e) {
  2420. log("DOMParser not supported, falling back to createHTMLDocument");
  2421. doc = document.implementation.createHTMLDocument("");
  2422. try {
  2423. doc.open();
  2424. doc.write(html);
  2425. doc.close();
  2426. } catch(ee) {
  2427. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  2428. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  2429. }
  2430. }
  2431. var b = doc.querySelector("base");
  2432. if (!b || !b.href.host) {
  2433. var base = doc.createElement("base");
  2434. base.href = src;
  2435. doc.head.insertBefore(base, doc.head.firstChild);
  2436. }
  2437. return doc;
  2438. };
  2439. }
  2440. function loadUrlDocument(src, proxy, document, width, height, options) {
  2441. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  2442. return createWindowClone(doc, document, width, height, options, 0, 0);
  2443. });
  2444. }
  2445. exports.Proxy = Proxy;
  2446. exports.ProxyURL = ProxyURL;
  2447. exports.loadUrlDocument = loadUrlDocument;
  2448. },{"./clone":2,"./log":13,"./utils":26,"./xhr":28}],17:[function(_dereq_,module,exports){
  2449. var ProxyURL = _dereq_('./proxy').ProxyURL;
  2450. function ProxyImageContainer(src, proxy) {
  2451. var link = document.createElement("a");
  2452. link.href = src;
  2453. src = link.href;
  2454. this.src = src;
  2455. this.image = new Image();
  2456. var self = this;
  2457. this.promise = new Promise(function(resolve, reject) {
  2458. self.image.crossOrigin = "Anonymous";
  2459. self.image.onload = resolve;
  2460. self.image.onerror = reject;
  2461. new ProxyURL(src, proxy, document).then(function(url) {
  2462. self.image.src = url;
  2463. })['catch'](reject);
  2464. });
  2465. }
  2466. module.exports = ProxyImageContainer;
  2467. },{"./proxy":16}],18:[function(_dereq_,module,exports){
  2468. var NodeContainer = _dereq_('./nodecontainer');
  2469. function PseudoElementContainer(node, parent, type) {
  2470. NodeContainer.call(this, node, parent);
  2471. this.isPseudoElement = true;
  2472. this.before = type === ":before";
  2473. }
  2474. PseudoElementContainer.prototype.cloneTo = function(stack) {
  2475. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  2476. stack.isPseudoElement = true;
  2477. stack.before = this.before;
  2478. };
  2479. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  2480. PseudoElementContainer.prototype.appendToDOM = function() {
  2481. if (this.before) {
  2482. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  2483. } else {
  2484. this.parent.node.appendChild(this.node);
  2485. }
  2486. this.parent.node.className += " " + this.getHideClass();
  2487. };
  2488. PseudoElementContainer.prototype.cleanDOM = function() {
  2489. this.node.parentNode.removeChild(this.node);
  2490. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  2491. };
  2492. PseudoElementContainer.prototype.getHideClass = function() {
  2493. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  2494. };
  2495. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  2496. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  2497. module.exports = PseudoElementContainer;
  2498. },{"./nodecontainer":14}],19:[function(_dereq_,module,exports){
  2499. var log = _dereq_('./log');
  2500. function Renderer(width, height, images, options, document) {
  2501. this.width = width;
  2502. this.height = height;
  2503. this.images = images;
  2504. this.options = options;
  2505. this.document = document;
  2506. }
  2507. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  2508. var paddingLeft = container.cssInt('paddingLeft'),
  2509. paddingTop = container.cssInt('paddingTop'),
  2510. paddingRight = container.cssInt('paddingRight'),
  2511. paddingBottom = container.cssInt('paddingBottom'),
  2512. borders = borderData.borders;
  2513. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  2514. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  2515. this.drawImage(
  2516. imageContainer,
  2517. 0,
  2518. 0,
  2519. imageContainer.image.width || width,
  2520. imageContainer.image.height || height,
  2521. bounds.left + paddingLeft + borders[3].width,
  2522. bounds.top + paddingTop + borders[0].width,
  2523. width,
  2524. height
  2525. );
  2526. };
  2527. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  2528. if (bounds.height > 0 && bounds.width > 0) {
  2529. this.renderBackgroundColor(container, bounds);
  2530. this.renderBackgroundImage(container, bounds, borderData);
  2531. }
  2532. };
  2533. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  2534. var color = container.color("backgroundColor");
  2535. if (!color.isTransparent()) {
  2536. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  2537. }
  2538. };
  2539. Renderer.prototype.renderBorders = function(borders) {
  2540. borders.forEach(this.renderBorder, this);
  2541. };
  2542. Renderer.prototype.renderBorder = function(data) {
  2543. if (!data.color.isTransparent() && data.args !== null) {
  2544. this.drawShape(data.args, data.color);
  2545. }
  2546. };
  2547. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  2548. var backgroundImages = container.parseBackgroundImages();
  2549. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  2550. switch(backgroundImage.method) {
  2551. case "url":
  2552. var image = this.images.get(backgroundImage.args[0]);
  2553. if (image) {
  2554. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  2555. } else {
  2556. log("Error loading background-image", backgroundImage.args[0]);
  2557. }
  2558. break;
  2559. case "linear-gradient":
  2560. case "gradient":
  2561. var gradientImage = this.images.get(backgroundImage.value);
  2562. if (gradientImage) {
  2563. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  2564. } else {
  2565. log("Error loading background-image", backgroundImage.args[0]);
  2566. }
  2567. break;
  2568. case "none":
  2569. break;
  2570. default:
  2571. log("Unknown background-image type", backgroundImage.args[0]);
  2572. }
  2573. }, this);
  2574. };
  2575. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  2576. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  2577. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  2578. var repeat = container.parseBackgroundRepeat(index);
  2579. switch (repeat) {
  2580. case "repeat-x":
  2581. case "repeat no-repeat":
  2582. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  2583. break;
  2584. case "repeat-y":
  2585. case "no-repeat repeat":
  2586. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  2587. break;
  2588. case "no-repeat":
  2589. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  2590. break;
  2591. default:
  2592. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  2593. break;
  2594. }
  2595. };
  2596. module.exports = Renderer;
  2597. },{"./log":13}],20:[function(_dereq_,module,exports){
  2598. var Renderer = _dereq_('../renderer');
  2599. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  2600. var log = _dereq_('../log');
  2601. function CanvasRenderer(width, height) {
  2602. Renderer.apply(this, arguments);
  2603. this.canvas = this.options.canvas || this.document.createElement("canvas");
  2604. if (!this.options.canvas) {
  2605. this.canvas.width = width;
  2606. this.canvas.height = height;
  2607. }
  2608. this.ctx = this.canvas.getContext("2d");
  2609. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  2610. this.ctx.textBaseline = "bottom";
  2611. this.variables = {};
  2612. log("Initialized CanvasRenderer with size", width, "x", height);
  2613. }
  2614. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  2615. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  2616. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  2617. return this.ctx;
  2618. };
  2619. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  2620. this.setFillStyle(color).fillRect(left, top, width, height);
  2621. };
  2622. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  2623. this.setFillStyle(color);
  2624. this.ctx.beginPath();
  2625. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  2626. this.ctx.closePath();
  2627. this.ctx.fill();
  2628. };
  2629. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  2630. this.circle(left, top, size, color);
  2631. this.ctx.strokeStyle = strokeColor.toString();
  2632. this.ctx.stroke();
  2633. };
  2634. CanvasRenderer.prototype.drawShape = function(shape, color) {
  2635. this.shape(shape);
  2636. this.setFillStyle(color).fill();
  2637. };
  2638. CanvasRenderer.prototype.taints = function(imageContainer) {
  2639. if (imageContainer.tainted === null) {
  2640. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  2641. try {
  2642. this.taintCtx.getImageData(0, 0, 1, 1);
  2643. imageContainer.tainted = false;
  2644. } catch(e) {
  2645. this.taintCtx = document.createElement("canvas").getContext("2d");
  2646. imageContainer.tainted = true;
  2647. }
  2648. }
  2649. return imageContainer.tainted;
  2650. };
  2651. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  2652. if (!this.taints(imageContainer) || this.options.allowTaint) {
  2653. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  2654. }
  2655. };
  2656. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  2657. this.ctx.save();
  2658. shapes.filter(hasEntries).forEach(function(shape) {
  2659. this.shape(shape).clip();
  2660. }, this);
  2661. callback.call(context);
  2662. this.ctx.restore();
  2663. };
  2664. CanvasRenderer.prototype.shape = function(shape) {
  2665. this.ctx.beginPath();
  2666. shape.forEach(function(point, index) {
  2667. if (point[0] === "rect") {
  2668. this.ctx.rect.apply(this.ctx, point.slice(1));
  2669. } else {
  2670. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  2671. }
  2672. }, this);
  2673. this.ctx.closePath();
  2674. return this.ctx;
  2675. };
  2676. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  2677. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  2678. };
  2679. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  2680. this.setVariable("shadowColor", color.toString())
  2681. .setVariable("shadowOffsetY", offsetX)
  2682. .setVariable("shadowOffsetX", offsetY)
  2683. .setVariable("shadowBlur", blur);
  2684. };
  2685. CanvasRenderer.prototype.clearShadow = function() {
  2686. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  2687. };
  2688. CanvasRenderer.prototype.setOpacity = function(opacity) {
  2689. this.ctx.globalAlpha = opacity;
  2690. };
  2691. CanvasRenderer.prototype.setTransform = function(transform) {
  2692. this.ctx.translate(transform.origin[0], transform.origin[1]);
  2693. this.ctx.transform.apply(this.ctx, transform.matrix);
  2694. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  2695. };
  2696. CanvasRenderer.prototype.setVariable = function(property, value) {
  2697. if (this.variables[property] !== value) {
  2698. this.variables[property] = this.ctx[property] = value;
  2699. }
  2700. return this;
  2701. };
  2702. CanvasRenderer.prototype.text = function(text, left, bottom) {
  2703. this.ctx.fillText(text, left, bottom);
  2704. };
  2705. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  2706. var shape = [
  2707. ["line", Math.round(left), Math.round(top)],
  2708. ["line", Math.round(left + width), Math.round(top)],
  2709. ["line", Math.round(left + width), Math.round(height + top)],
  2710. ["line", Math.round(left), Math.round(height + top)]
  2711. ];
  2712. this.clip([shape], function() {
  2713. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  2714. }, this);
  2715. };
  2716. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  2717. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  2718. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  2719. this.ctx.translate(offsetX, offsetY);
  2720. this.ctx.fill();
  2721. this.ctx.translate(-offsetX, -offsetY);
  2722. };
  2723. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  2724. if (gradientImage instanceof LinearGradientContainer) {
  2725. var gradient = this.ctx.createLinearGradient(
  2726. bounds.left + bounds.width * gradientImage.x0,
  2727. bounds.top + bounds.height * gradientImage.y0,
  2728. bounds.left + bounds.width * gradientImage.x1,
  2729. bounds.top + bounds.height * gradientImage.y1);
  2730. gradientImage.colorStops.forEach(function(colorStop) {
  2731. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  2732. });
  2733. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  2734. }
  2735. };
  2736. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  2737. var image = imageContainer.image;
  2738. if(image.width === size.width && image.height === size.height) {
  2739. return image;
  2740. }
  2741. var ctx, canvas = document.createElement('canvas');
  2742. canvas.width = size.width;
  2743. canvas.height = size.height;
  2744. ctx = canvas.getContext("2d");
  2745. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  2746. return canvas;
  2747. };
  2748. function hasEntries(array) {
  2749. return array.length > 0;
  2750. }
  2751. module.exports = CanvasRenderer;
  2752. },{"../lineargradientcontainer":12,"../log":13,"../renderer":19}],21:[function(_dereq_,module,exports){
  2753. var NodeContainer = _dereq_('./nodecontainer');
  2754. function StackingContext(hasOwnStacking, opacity, element, parent) {
  2755. NodeContainer.call(this, element, parent);
  2756. this.ownStacking = hasOwnStacking;
  2757. this.contexts = [];
  2758. this.children = [];
  2759. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  2760. }
  2761. StackingContext.prototype = Object.create(NodeContainer.prototype);
  2762. StackingContext.prototype.getParentStack = function(context) {
  2763. var parentStack = (this.parent) ? this.parent.stack : null;
  2764. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  2765. };
  2766. module.exports = StackingContext;
  2767. },{"./nodecontainer":14}],22:[function(_dereq_,module,exports){
  2768. function Support(document) {
  2769. this.rangeBounds = this.testRangeBounds(document);
  2770. this.cors = this.testCORS();
  2771. this.svg = this.testSVG();
  2772. }
  2773. Support.prototype.testRangeBounds = function(document) {
  2774. var range, testElement, rangeBounds, rangeHeight, support = false;
  2775. if (document.createRange) {
  2776. range = document.createRange();
  2777. if (range.getBoundingClientRect) {
  2778. testElement = document.createElement('boundtest');
  2779. testElement.style.height = "123px";
  2780. testElement.style.display = "block";
  2781. document.body.appendChild(testElement);
  2782. range.selectNode(testElement);
  2783. rangeBounds = range.getBoundingClientRect();
  2784. rangeHeight = rangeBounds.height;
  2785. if (rangeHeight === 123) {
  2786. support = true;
  2787. }
  2788. document.body.removeChild(testElement);
  2789. }
  2790. }
  2791. return support;
  2792. };
  2793. Support.prototype.testCORS = function() {
  2794. return typeof((new Image()).crossOrigin) !== "undefined";
  2795. };
  2796. Support.prototype.testSVG = function() {
  2797. var img = new Image();
  2798. var canvas = document.createElement("canvas");
  2799. var ctx = canvas.getContext("2d");
  2800. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  2801. try {
  2802. ctx.drawImage(img, 0, 0);
  2803. canvas.toDataURL();
  2804. } catch(e) {
  2805. return false;
  2806. }
  2807. return true;
  2808. };
  2809. module.exports = Support;
  2810. },{}],23:[function(_dereq_,module,exports){
  2811. var XHR = _dereq_('./xhr');
  2812. var decode64 = _dereq_('./utils').decode64;
  2813. function SVGContainer(src) {
  2814. this.src = src;
  2815. this.image = null;
  2816. var self = this;
  2817. this.promise = this.hasFabric().then(function() {
  2818. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  2819. }).then(function(svg) {
  2820. return new Promise(function(resolve) {
  2821. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  2822. });
  2823. });
  2824. }
  2825. SVGContainer.prototype.hasFabric = function() {
  2826. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  2827. };
  2828. SVGContainer.prototype.inlineFormatting = function(src) {
  2829. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  2830. };
  2831. SVGContainer.prototype.removeContentType = function(src) {
  2832. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  2833. };
  2834. SVGContainer.prototype.isInline = function(src) {
  2835. return (/^data:image\/svg\+xml/i.test(src));
  2836. };
  2837. SVGContainer.prototype.createCanvas = function(resolve) {
  2838. var self = this;
  2839. return function (objects, options) {
  2840. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  2841. self.image = canvas.lowerCanvasEl;
  2842. canvas
  2843. .setWidth(options.width)
  2844. .setHeight(options.height)
  2845. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  2846. .renderAll();
  2847. resolve(canvas.lowerCanvasEl);
  2848. };
  2849. };
  2850. SVGContainer.prototype.decode64 = function(str) {
  2851. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  2852. };
  2853. module.exports = SVGContainer;
  2854. },{"./utils":26,"./xhr":28}],24:[function(_dereq_,module,exports){
  2855. var SVGContainer = _dereq_('./svgcontainer');
  2856. function SVGNodeContainer(node, _native) {
  2857. this.src = node;
  2858. this.image = null;
  2859. var self = this;
  2860. this.promise = _native ? new Promise(function(resolve, reject) {
  2861. self.image = new Image();
  2862. self.image.onload = resolve;
  2863. self.image.onerror = reject;
  2864. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  2865. if (self.image.complete === true) {
  2866. resolve(self.image);
  2867. }
  2868. }) : this.hasFabric().then(function() {
  2869. return new Promise(function(resolve) {
  2870. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  2871. });
  2872. });
  2873. }
  2874. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  2875. module.exports = SVGNodeContainer;
  2876. },{"./svgcontainer":23}],25:[function(_dereq_,module,exports){
  2877. var NodeContainer = _dereq_('./nodecontainer');
  2878. function TextContainer(node, parent) {
  2879. NodeContainer.call(this, node, parent);
  2880. }
  2881. TextContainer.prototype = Object.create(NodeContainer.prototype);
  2882. TextContainer.prototype.applyTextTransform = function() {
  2883. this.node.data = this.transform(this.parent.css("textTransform"));
  2884. };
  2885. TextContainer.prototype.transform = function(transform) {
  2886. var text = this.node.data;
  2887. switch(transform){
  2888. case "lowercase":
  2889. return text.toLowerCase();
  2890. case "capitalize":
  2891. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  2892. case "uppercase":
  2893. return text.toUpperCase();
  2894. default:
  2895. return text;
  2896. }
  2897. };
  2898. function capitalize(m, p1, p2) {
  2899. if (m.length > 0) {
  2900. return p1 + p2.toUpperCase();
  2901. }
  2902. }
  2903. module.exports = TextContainer;
  2904. },{"./nodecontainer":14}],26:[function(_dereq_,module,exports){
  2905. exports.smallImage = function smallImage() {
  2906. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  2907. };
  2908. exports.bind = function(callback, context) {
  2909. return function() {
  2910. return callback.apply(context, arguments);
  2911. };
  2912. };
  2913. /*
  2914. * base64-arraybuffer
  2915. * https://github.com/niklasvh/base64-arraybuffer
  2916. *
  2917. * Copyright (c) 2012 Niklas von Hertzen
  2918. * Licensed under the MIT license.
  2919. */
  2920. exports.decode64 = function(base64) {
  2921. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2922. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  2923. var output = "";
  2924. for (i = 0; i < len; i+=4) {
  2925. encoded1 = chars.indexOf(base64[i]);
  2926. encoded2 = chars.indexOf(base64[i+1]);
  2927. encoded3 = chars.indexOf(base64[i+2]);
  2928. encoded4 = chars.indexOf(base64[i+3]);
  2929. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  2930. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  2931. byte3 = ((encoded3 & 3) << 6) | encoded4;
  2932. if (encoded3 === 64) {
  2933. output += String.fromCharCode(byte1);
  2934. } else if (encoded4 === 64 || encoded4 === -1) {
  2935. output += String.fromCharCode(byte1, byte2);
  2936. } else{
  2937. output += String.fromCharCode(byte1, byte2, byte3);
  2938. }
  2939. }
  2940. return output;
  2941. };
  2942. exports.getBounds = function(node) {
  2943. if (node.getBoundingClientRect) {
  2944. var clientRect = node.getBoundingClientRect();
  2945. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  2946. return {
  2947. top: clientRect.top,
  2948. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  2949. right: clientRect.left + width,
  2950. left: clientRect.left,
  2951. width: width,
  2952. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  2953. };
  2954. }
  2955. return {};
  2956. };
  2957. exports.offsetBounds = function(node) {
  2958. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  2959. return {
  2960. top: node.offsetTop + parent.top,
  2961. bottom: node.offsetTop + node.offsetHeight + parent.top,
  2962. right: node.offsetLeft + parent.left + node.offsetWidth,
  2963. left: node.offsetLeft + parent.left,
  2964. width: node.offsetWidth,
  2965. height: node.offsetHeight
  2966. };
  2967. };
  2968. exports.parseBackgrounds = function(backgroundImage) {
  2969. var whitespace = ' \r\n\t',
  2970. method, definition, prefix, prefix_i, block, r###lts = [],
  2971. mode = 0, numParen = 0, quote, args;
  2972. var appendR###lt = function() {
  2973. if(method) {
  2974. if (definition.substr(0, 1) === '"') {
  2975. definition = definition.substr(1, definition.length - 2);
  2976. }
  2977. if (definition) {
  2978. args.push(definition);
  2979. }
  2980. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  2981. prefix = method.substr(0, prefix_i);
  2982. method = method.substr(prefix_i);
  2983. }
  2984. r###lts.push({
  2985. prefix: prefix,
  2986. method: method.toLowerCase(),
  2987. value: block,
  2988. args: args,
  2989. image: null
  2990. });
  2991. }
  2992. args = [];
  2993. method = prefix = definition = block = '';
  2994. };
  2995. args = [];
  2996. method = prefix = definition = block = '';
  2997. backgroundImage.split("").forEach(function(c) {
  2998. if (mode === 0 && whitespace.indexOf(c) > -1) {
  2999. return;
  3000. }
  3001. switch(c) {
  3002. case '"':
  3003. if(!quote) {
  3004. quote = c;
  3005. } else if(quote === c) {
  3006. quote = null;
  3007. }
  3008. break;
  3009. case '(':
  3010. if(quote) {
  3011. break;
  3012. } else if(mode === 0) {
  3013. mode = 1;
  3014. block += c;
  3015. return;
  3016. } else {
  3017. numParen++;
  3018. }
  3019. break;
  3020. case ')':
  3021. if (quote) {
  3022. break;
  3023. } else if(mode === 1) {
  3024. if(numParen === 0) {
  3025. mode = 0;
  3026. block += c;
  3027. appendR###lt();
  3028. return;
  3029. } else {
  3030. numParen--;
  3031. }
  3032. }
  3033. break;
  3034. case ',':
  3035. if (quote) {
  3036. break;
  3037. } else if(mode === 0) {
  3038. appendR###lt();
  3039. return;
  3040. } else if (mode === 1) {
  3041. if (numParen === 0 && !method.match(/^url$/i)) {
  3042. args.push(definition);
  3043. definition = '';
  3044. block += c;
  3045. return;
  3046. }
  3047. }
  3048. break;
  3049. }
  3050. block += c;
  3051. if (mode === 0) {
  3052. method += c;
  3053. } else {
  3054. definition += c;
  3055. }
  3056. });
  3057. appendR###lt();
  3058. return r###lts;
  3059. };
  3060. },{}],27:[function(_dereq_,module,exports){
  3061. var GradientContainer = _dereq_('./gradientcontainer');
  3062. function WebkitGradientContainer(imageData) {
  3063. GradientContainer.apply(this, arguments);
  3064. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL;
  3065. }
  3066. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  3067. module.exports = WebkitGradientContainer;
  3068. },{"./gradientcontainer":9}],28:[function(_dereq_,module,exports){
  3069. function XHR(url) {
  3070. return new Promise(function(resolve, reject) {
  3071. var xhr = new XMLHttpRequest();
  3072. xhr.open('GET', url);
  3073. xhr.onload = function() {
  3074. if (xhr.status === 200) {
  3075. resolve(xhr.responseText);
  3076. } else {
  3077. reject(new Error(xhr.statusText));
  3078. }
  3079. };
  3080. xhr.onerror = function() {
  3081. reject(new Error("Network Error"));
  3082. };
  3083. xhr.send();
  3084. });
  3085. }
  3086. module.exports = XHR;
  3087. },{}]},{},[4])(4)
  3088. });
  3089. (function() {
  3090. 'use strict';
  3091. function capturePage(){
  3092. var focusedElement,att={};
  3093. if(document.getSelection().toString()==""){
  3094. focusedElement = document.activeElement;
  3095. att.background="#ffffff";
  3096. scrollTo(0,0);
  3097. }else{
  3098. focusedElement = document.getSelection().focusNode.parentElement;
  3099. }
  3100. html2canvas(focusedElement,att).then(function(canvas) {
  3101. var img = canvas.toDataURL();
  3102. GM_openInTab(img);
  3103. });
  3104. }
  3105. GM_registerMenuCommand("Capture current page", capturePage);
  3106. document.addEventListener("keydown", function(e) {
  3107. if(e.keyCode == 121 && e.ctrlKey) {
  3108. capturePage();
  3109. }
  3110. });
  3111. })();