HTML:
<div style="display:block;margin:0 auto;width:638px;height:795px;">
<div id="render" >
        CONTENT
</div>
</div>

<div id="template" style="margin:10px 0 0 385px;">
 <input type="button" onclick="qc0926()" value="下载图片" />
 </div>
 
JS:
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript">
 var canvas,render,html,imgsrcgo;
    function renderHTMLAndSave() {
       var render= document.getElementById('render');
        html2canvas(render).then(function (canvas) {         
var imgsrc= canvas.toDataURL();
imgsrcgo=imgsrc;
        });
    }
window.onload=renderHTMLAndSave();
var imgsrc;
var imgData;
var type='png';
 
var _fixType = function(type) {
    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
    var r = type.match(/png|jpeg|bmp|gif/)[0];
    return 'image/' + r;
};
function saveFile(data, filename){
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;  
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
};
function qc0926()
{
imgData=imgsrcgo;
imgData = imgData.replace(_fixType(type),'image/octet-stream'); // 加工image data,替换mime type
var filename = 'zgsjdomaincertification' + '_name' + '.' + type; // 下载后的文件名
window.load=saveFile(imgData,filename); //下载域名证书
};
</script>

html2canvas.js-代码:

  1. /*
  2. html2canvas 0.5.0-alpha2 <http://html2canvas.hertzen.com>
  3. Copyright (c) 2015 Niklas von Hertzen
  4.  
  5. Released under MIT License
  6. */
  7.  
  8. !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(require,module,exports){
  9. (function (process,global){
  10. /*!
  11. * @overview es6-promise - a tiny implementation of Promises/A+.
  12. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13. * @license Licensed under MIT license
  14. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  15. * @version 2.0.1
  16. */
  17.  
  18. (function() {
  19. "use strict";
  20.  
  21. function $$utils$$objectOrFunction(x) {
  22. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  23. }
  24.  
  25. function $$utils$$isFunction(x) {
  26. return typeof x === 'function';
  27. }
  28.  
  29. function $$utils$$isMaybeThenable(x) {
  30. return typeof x === 'object' && x !== null;
  31. }
  32.  
  33. var $$utils$$_isArray;
  34.  
  35. if (!Array.isArray) {
  36. $$utils$$_isArray = function (x) {
  37. return Object.prototype.toString.call(x) === '[object Array]';
  38. };
  39. } else {
  40. $$utils$$_isArray = Array.isArray;
  41. }
  42.  
  43. var $$utils$$isArray = $$utils$$_isArray;
  44. var $$utils$$now = Date.now || function() { return new Date().getTime(); };
  45. function $$utils$$F() { }
  46.  
  47. var $$utils$$o_create = (Object.create || function (o) {
  48. if (arguments.length > 1) {
  49. throw new Error('Second argument not supported');
  50. }
  51. if (typeof o !== 'object') {
  52. throw new TypeError('Argument must be an object');
  53. }
  54. $$utils$$F.prototype = o;
  55. return new $$utils$$F();
  56. });
  57.  
  58. var $$asap$$len = 0;
  59.  
  60. var $$asap$$default = function asap(callback, arg) {
  61. $$asap$$queue[$$asap$$len] = callback;
  62. $$asap$$queue[$$asap$$len + 1] = arg;
  63. $$asap$$len += 2;
  64. if ($$asap$$len === 2) {
  65. // If len is 1, that means that we need to schedule an async flush.
  66. // If additional callbacks are queued before the queue is flushed, they
  67. // will be processed by this flush that we are scheduling.
  68. $$asap$$scheduleFlush();
  69. }
  70. };
  71.  
  72. var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {};
  73. var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver;
  74.  
  75. // test for web worker but not in IE10
  76. var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  77. typeof importScripts !== 'undefined' &&
  78. typeof MessageChannel !== 'undefined';
  79.  
  80. // node
  81. function $$asap$$useNextTick() {
  82. return function() {
  83. process.nextTick($$asap$$flush);
  84. };
  85. }
  86.  
  87. function $$asap$$useMutationObserver() {
  88. var iterations = 0;
  89. var observer = new $$asap$$BrowserMutationObserver($$asap$$flush);
  90. var node = document.createTextNode('');
  91. observer.observe(node, { characterData: true });
  92.  
  93. return function() {
  94. node.data = (iterations = ++iterations % 2);
  95. };
  96. }
  97.  
  98. // web worker
  99. function $$asap$$useMessageChannel() {
  100. var channel = new MessageChannel();
  101. channel.port1.onmessage = $$asap$$flush;
  102. return function () {
  103. channel.port2.postMessage(0);
  104. };
  105. }
  106.  
  107. function $$asap$$useSetTimeout() {
  108. return function() {
  109. setTimeout($$asap$$flush, 1);
  110. };
  111. }
  112.  
  113. var $$asap$$queue = new Array(1000);
  114.  
  115. function $$asap$$flush() {
  116. for (var i = 0; i < $$asap$$len; i+=2) {
  117. var callback = $$asap$$queue[i];
  118. var arg = $$asap$$queue[i+1];
  119.  
  120. callback(arg);
  121.  
  122. $$asap$$queue[i] = undefined;
  123. $$asap$$queue[i+1] = undefined;
  124. }
  125.  
  126. $$asap$$len = 0;
  127. }
  128.  
  129. var $$asap$$scheduleFlush;
  130.  
  131. // Decide what async method to use to triggering processing of queued callbacks:
  132. if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
  133. $$asap$$scheduleFlush = $$asap$$useNextTick();
  134. } else if ($$asap$$BrowserMutationObserver) {
  135. $$asap$$scheduleFlush = $$asap$$useMutationObserver();
  136. } else if ($$asap$$isWorker) {
  137. $$asap$$scheduleFlush = $$asap$$useMessageChannel();
  138. } else {
  139. $$asap$$scheduleFlush = $$asap$$useSetTimeout();
  140. }
  141.  
  142. function $$$internal$$noop() {}
  143. var $$$internal$$PENDING = void 0;
  144. var $$$internal$$FULFILLED = 1;
  145. var $$$internal$$REJECTED = 2;
  146. var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject();
  147.  
  148. function $$$internal$$selfFullfillment() {
  149. return new TypeError("You cannot resolve a promise with itself");
  150. }
  151.  
  152. function $$$internal$$cannotReturnOwn() {
  153. return new TypeError('A promises callback cannot return that same promise.')
  154. }
  155.  
  156. function $$$internal$$getThen(promise) {
  157. try {
  158. return promise.then;
  159. } catch(error) {
  160. $$$internal$$GET_THEN_ERROR.error = error;
  161. return $$$internal$$GET_THEN_ERROR;
  162. }
  163. }
  164.  
  165. function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  166. try {
  167. then.call(value, fulfillmentHandler, rejectionHandler);
  168. } catch(e) {
  169. return e;
  170. }
  171. }
  172.  
  173. function $$$internal$$handleForeignThenable(promise, thenable, then) {
  174. $$asap$$default(function(promise) {
  175. var sealed = false;
  176. var error = $$$internal$$tryThen(then, thenable, function(value) {
  177. if (sealed) { return; }
  178. sealed = true;
  179. if (thenable !== value) {
  180. $$$internal$$resolve(promise, value);
  181. } else {
  182. $$$internal$$fulfill(promise, value);
  183. }
  184. }, function(reason) {
  185. if (sealed) { return; }
  186. sealed = true;
  187.  
  188. $$$internal$$reject(promise, reason);
  189. }, 'Settle: ' + (promise._label || ' unknown promise'));
  190.  
  191. if (!sealed && error) {
  192. sealed = true;
  193. $$$internal$$reject(promise, error);
  194. }
  195. }, promise);
  196. }
  197.  
  198. function $$$internal$$handleOwnThenable(promise, thenable) {
  199. if (thenable._state === $$$internal$$FULFILLED) {
  200. $$$internal$$fulfill(promise, thenable._result);
  201. } else if (promise._state === $$$internal$$REJECTED) {
  202. $$$internal$$reject(promise, thenable._result);
  203. } else {
  204. $$$internal$$subscribe(thenable, undefined, function(value) {
  205. $$$internal$$resolve(promise, value);
  206. }, function(reason) {
  207. $$$internal$$reject(promise, reason);
  208. });
  209. }
  210. }
  211.  
  212. function $$$internal$$handleMaybeThenable(promise, maybeThenable) {
  213. if (maybeThenable.constructor === promise.constructor) {
  214. $$$internal$$handleOwnThenable(promise, maybeThenable);
  215. } else {
  216. var then = $$$internal$$getThen(maybeThenable);
  217.  
  218. if (then === $$$internal$$GET_THEN_ERROR) {
  219. $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error);
  220. } else if (then === undefined) {
  221. $$$internal$$fulfill(promise, maybeThenable);
  222. } else if ($$utils$$isFunction(then)) {
  223. $$$internal$$handleForeignThenable(promise, maybeThenable, then);
  224. } else {
  225. $$$internal$$fulfill(promise, maybeThenable);
  226. }
  227. }
  228. }
  229.  
  230. function $$$internal$$resolve(promise, value) {
  231. if (promise === value) {
  232. $$$internal$$reject(promise, $$$internal$$selfFullfillment());
  233. } else if ($$utils$$objectOrFunction(value)) {
  234. $$$internal$$handleMaybeThenable(promise, value);
  235. } else {
  236. $$$internal$$fulfill(promise, value);
  237. }
  238. }
  239.  
  240. function $$$internal$$publishRejection(promise) {
  241. if (promise._onerror) {
  242. promise._onerror(promise._result);
  243. }
  244.  
  245. $$$internal$$publish(promise);
  246. }
  247.  
  248. function $$$internal$$fulfill(promise, value) {
  249. if (promise._state !== $$$internal$$PENDING) { return; }
  250.  
  251. promise._result = value;
  252. promise._state = $$$internal$$FULFILLED;
  253.  
  254. if (promise._subscribers.length === 0) {
  255. } else {
  256. $$asap$$default($$$internal$$publish, promise);
  257. }
  258. }
  259.  
  260. function $$$internal$$reject(promise, reason) {
  261. if (promise._state !== $$$internal$$PENDING) { return; }
  262. promise._state = $$$internal$$REJECTED;
  263. promise._result = reason;
  264.  
  265. $$asap$$default($$$internal$$publishRejection, promise);
  266. }
  267.  
  268. function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  269. var subscribers = parent._subscribers;
  270. var length = subscribers.length;
  271.  
  272. parent._onerror = null;
  273.  
  274. subscribers[length] = child;
  275. subscribers[length + $$$internal$$FULFILLED] = onFulfillment;
  276. subscribers[length + $$$internal$$REJECTED] = onRejection;
  277.  
  278. if (length === 0 && parent._state) {
  279. $$asap$$default($$$internal$$publish, parent);
  280. }
  281. }
  282.  
  283. function $$$internal$$publish(promise) {
  284. var subscribers = promise._subscribers;
  285. var settled = promise._state;
  286.  
  287. if (subscribers.length === 0) { return; }
  288.  
  289. var child, callback, detail = promise._result;
  290.  
  291. for (var i = 0; i < subscribers.length; i += 3) {
  292. child = subscribers[i];
  293. callback = subscribers[i + settled];
  294.  
  295. if (child) {
  296. $$$internal$$invokeCallback(settled, child, callback, detail);
  297. } else {
  298. callback(detail);
  299. }
  300. }
  301.  
  302. promise._subscribers.length = 0;
  303. }
  304.  
  305. function $$$internal$$ErrorObject() {
  306. this.error = null;
  307. }
  308.  
  309. var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject();
  310.  
  311. function $$$internal$$tryCatch(callback, detail) {
  312. try {
  313. return callback(detail);
  314. } catch(e) {
  315. $$$internal$$TRY_CATCH_ERROR.error = e;
  316. return $$$internal$$TRY_CATCH_ERROR;
  317. }
  318. }
  319.  
  320. function $$$internal$$invokeCallback(settled, promise, callback, detail) {
  321. var hasCallback = $$utils$$isFunction(callback),
  322. value, error, succeeded, failed;
  323.  
  324. if (hasCallback) {
  325. value = $$$internal$$tryCatch(callback, detail);
  326.  
  327. if (value === $$$internal$$TRY_CATCH_ERROR) {
  328. failed = true;
  329. error = value.error;
  330. value = null;
  331. } else {
  332. succeeded = true;
  333. }
  334.  
  335. if (promise === value) {
  336. $$$internal$$reject(promise, $$$internal$$cannotReturnOwn());
  337. return;
  338. }
  339.  
  340. } else {
  341. value = detail;
  342. succeeded = true;
  343. }
  344.  
  345. if (promise._state !== $$$internal$$PENDING) {
  346. // noop
  347. } else if (hasCallback && succeeded) {
  348. $$$internal$$resolve(promise, value);
  349. } else if (failed) {
  350. $$$internal$$reject(promise, error);
  351. } else if (settled === $$$internal$$FULFILLED) {
  352. $$$internal$$fulfill(promise, value);
  353. } else if (settled === $$$internal$$REJECTED) {
  354. $$$internal$$reject(promise, value);
  355. }
  356. }
  357.  
  358. function $$$internal$$initializePromise(promise, resolver) {
  359. try {
  360. resolver(function resolvePromise(value){
  361. $$$internal$$resolve(promise, value);
  362. }, function rejectPromise(reason) {
  363. $$$internal$$reject(promise, reason);
  364. });
  365. } catch(e) {
  366. $$$internal$$reject(promise, e);
  367. }
  368. }
  369.  
  370. function $$$enumerator$$makeSettledResult(state, position, value) {
  371. if (state === $$$internal$$FULFILLED) {
  372. return {
  373. state: 'fulfilled',
  374. value: value
  375. };
  376. } else {
  377. return {
  378. state: 'rejected',
  379. reason: value
  380. };
  381. }
  382. }
  383.  
  384. function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) {
  385. this._instanceConstructor = Constructor;
  386. this.promise = new Constructor($$$internal$$noop, label);
  387. this._abortOnReject = abortOnReject;
  388.  
  389. if (this._validateInput(input)) {
  390. this._input = input;
  391. this.length = input.length;
  392. this._remaining = input.length;
  393.  
  394. this._init();
  395.  
  396. if (this.length === 0) {
  397. $$$internal$$fulfill(this.promise, this._result);
  398. } else {
  399. this.length = this.length || 0;
  400. this._enumerate();
  401. if (this._remaining === 0) {
  402. $$$internal$$fulfill(this.promise, this._result);
  403. }
  404. }
  405. } else {
  406. $$$internal$$reject(this.promise, this._validationError());
  407. }
  408. }
  409.  
  410. $$$enumerator$$Enumerator.prototype._validateInput = function(input) {
  411. return $$utils$$isArray(input);
  412. };
  413.  
  414. $$$enumerator$$Enumerator.prototype._validationError = function() {
  415. return new Error('Array Methods must be provided an Array');
  416. };
  417.  
  418. $$$enumerator$$Enumerator.prototype._init = function() {
  419. this._result = new Array(this.length);
  420. };
  421.  
  422. var $$$enumerator$$default = $$$enumerator$$Enumerator;
  423.  
  424. $$$enumerator$$Enumerator.prototype._enumerate = function() {
  425. var length = this.length;
  426. var promise = this.promise;
  427. var input = this._input;
  428.  
  429. for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
  430. this._eachEntry(input[i], i);
  431. }
  432. };
  433.  
  434. $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  435. var c = this._instanceConstructor;
  436. if ($$utils$$isMaybeThenable(entry)) {
  437. if (entry.constructor === c && entry._state !== $$$internal$$PENDING) {
  438. entry._onerror = null;
  439. this._settledAt(entry._state, i, entry._result);
  440. } else {
  441. this._willSettleAt(c.resolve(entry), i);
  442. }
  443. } else {
  444. this._remaining--;
  445. this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry);
  446. }
  447. };
  448.  
  449. $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  450. var promise = this.promise;
  451.  
  452. if (promise._state === $$$internal$$PENDING) {
  453. this._remaining--;
  454.  
  455. if (this._abortOnReject && state === $$$internal$$REJECTED) {
  456. $$$internal$$reject(promise, value);
  457. } else {
  458. this._result[i] = this._makeResult(state, i, value);
  459. }
  460. }
  461.  
  462. if (this._remaining === 0) {
  463. $$$internal$$fulfill(promise, this._result);
  464. }
  465. };
  466.  
  467. $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) {
  468. return value;
  469. };
  470.  
  471. $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  472. var enumerator = this;
  473.  
  474. $$$internal$$subscribe(promise, undefined, function(value) {
  475. enumerator._settledAt($$$internal$$FULFILLED, i, value);
  476. }, function(reason) {
  477. enumerator._settledAt($$$internal$$REJECTED, i, reason);
  478. });
  479. };
  480.  
  481. var $$promise$all$$default = function all(entries, label) {
  482. return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise;
  483. };
  484.  
  485. var $$promise$race$$default = function race(entries, label) {
  486. /*jshint validthis:true */
  487. var Constructor = this;
  488.  
  489. var promise = new Constructor($$$internal$$noop, label);
  490.  
  491. if (!$$utils$$isArray(entries)) {
  492. $$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  493. return promise;
  494. }
  495.  
  496. var length = entries.length;
  497.  
  498. function onFulfillment(value) {
  499. $$$internal$$resolve(promise, value);
  500. }
  501.  
  502. function onRejection(reason) {
  503. $$$internal$$reject(promise, reason);
  504. }
  505.  
  506. for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
  507. $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  508. }
  509.  
  510. return promise;
  511. };
  512.  
  513. var $$promise$resolve$$default = function resolve(object, label) {
  514. /*jshint validthis:true */
  515. var Constructor = this;
  516.  
  517. if (object && typeof object === 'object' && object.constructor === Constructor) {
  518. return object;
  519. }
  520.  
  521. var promise = new Constructor($$$internal$$noop, label);
  522. $$$internal$$resolve(promise, object);
  523. return promise;
  524. };
  525.  
  526. var $$promise$reject$$default = function reject(reason, label) {
  527. /*jshint validthis:true */
  528. var Constructor = this;
  529. var promise = new Constructor($$$internal$$noop, label);
  530. $$$internal$$reject(promise, reason);
  531. return promise;
  532. };
  533.  
  534. var $$es6$promise$promise$$counter = 0;
  535.  
  536. function $$es6$promise$promise$$needsResolver() {
  537. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  538. }
  539.  
  540. function $$es6$promise$promise$$needsNew() {
  541. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  542. }
  543.  
  544. var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise;
  545.  
  546. /**
  547. Promise objects represent the eventual result of an asynchronous operation. The
  548. primary way of interacting with a promise is through its `then` method, which
  549. registers callbacks to receive either a promiseos eventual value or the reason
  550. why the promise cannot be fulfilled.
  551.  
  552. Terminology
  553. -----------
  554.  
  555. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  556. - `thenable` is an object or function that defines a `then` method.
  557. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  558. - `exception` is a value that is thrown using the throw statement.
  559. - `reason` is a value that indicates why a promise was rejected.
  560. - `settled` the final resting state of a promise, fulfilled or rejected.
  561.  
  562. A promise can be in one of three states: pending, fulfilled, or rejected.
  563.  
  564. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  565. state. Promises that are rejected have a rejection reason and are in the
  566. rejected state. A fulfillment value is never a thenable.
  567.  
  568. Promises can also be said to *resolve* a value. If this value is also a
  569. promise, then the original promise's settled state will match the value's
  570. settled state. So a promise that *resolves* a promise that rejects will
  571. itself reject, and a promise that *resolves* a promise that fulfills will
  572. itself fulfill.
  573.  
  574. Basic Usage:
  575. ------------
  576.  
  577. ```js
  578. var promise = new Promise(function(resolve, reject) {
  579. // on success
  580. resolve(value);
  581.  
  582. // on failure
  583. reject(reason);
  584. });
  585.  
  586. promise.then(function(value) {
  587. // on fulfillment
  588. }, function(reason) {
  589. // on rejection
  590. });
  591. ```
  592.  
  593. Advanced Usage:
  594. ---------------
  595.  
  596. Promises shine when abstracting away asynchronous interactions such as
  597. `XMLHttpRequest`s.
  598.  
  599. ```js
  600. function getJSON(url) {
  601. return new Promise(function(resolve, reject){
  602. var xhr = new XMLHttpRequest();
  603.  
  604. xhr.open('GET', url);
  605. xhr.onreadystatechange = handler;
  606. xhr.responseType = 'json';
  607. xhr.setRequestHeader('Accept', 'application/json');
  608. xhr.send();
  609.  
  610. function handler() {
  611. if (this.readyState === this.DONE) {
  612. if (this.status === 200) {
  613. resolve(this.response);
  614. } else {
  615. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  616. }
  617. }
  618. };
  619. });
  620. }
  621.  
  622. getJSON('/posts.json').then(function(json) {
  623. // on fulfillment
  624. }, function(reason) {
  625. // on rejection
  626. });
  627. ```
  628.  
  629. Unlike callbacks, promises are great composable primitives.
  630.  
  631. ```js
  632. Promise.all([
  633. getJSON('/posts'),
  634. getJSON('/comments')
  635. ]).then(function(values){
  636. values[0] // => postsJSON
  637. values[1] // => commentsJSON
  638.  
  639. return values;
  640. });
  641. ```
  642.  
  643. @class Promise
  644. @param {function} resolver
  645. Useful for tooling.
  646. @constructor
  647. */
  648. function $$es6$promise$promise$$Promise(resolver) {
  649. this._id = $$es6$promise$promise$$counter++;
  650. this._state = undefined;
  651. this._result = undefined;
  652. this._subscribers = [];
  653.  
  654. if ($$$internal$$noop !== resolver) {
  655. if (!$$utils$$isFunction(resolver)) {
  656. $$es6$promise$promise$$needsResolver();
  657. }
  658.  
  659. if (!(this instanceof $$es6$promise$promise$$Promise)) {
  660. $$es6$promise$promise$$needsNew();
  661. }
  662.  
  663. $$$internal$$initializePromise(this, resolver);
  664. }
  665. }
  666.  
  667. $$es6$promise$promise$$Promise.all = $$promise$all$$default;
  668. $$es6$promise$promise$$Promise.race = $$promise$race$$default;
  669. $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default;
  670. $$es6$promise$promise$$Promise.reject = $$promise$reject$$default;
  671.  
  672. $$es6$promise$promise$$Promise.prototype = {
  673. constructor: $$es6$promise$promise$$Promise,
  674.  
  675. /**
  676. The primary way of interacting with a promise is through its `then` method,
  677. which registers callbacks to receive either a promise's eventual value or the
  678. reason why the promise cannot be fulfilled.
  679.  
  680. ```js
  681. findUser().then(function(user){
  682. // user is available
  683. }, function(reason){
  684. // user is unavailable, and you are given the reason why
  685. });
  686. ```
  687.  
  688. Chaining
  689. --------
  690.  
  691. The return value of `then` is itself a promise. This second, 'downstream'
  692. promise is resolved with the return value of the first promise's fulfillment
  693. or rejection handler, or rejected if the handler throws an exception.
  694.  
  695. ```js
  696. findUser().then(function (user) {
  697. return user.name;
  698. }, function (reason) {
  699. return 'default name';
  700. }).then(function (userName) {
  701. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  702. // will be `'default name'`
  703. });
  704.  
  705. findUser().then(function (user) {
  706. throw new Error('Found user, but still unhappy');
  707. }, function (reason) {
  708. throw new Error('`findUser` rejected and we're unhappy');
  709. }).then(function (value) {
  710. // never reached
  711. }, function (reason) {
  712. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  713. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  714. });
  715. ```
  716. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  717.  
  718. ```js
  719. findUser().then(function (user) {
  720. throw new PedagogicalException('Upstream error');
  721. }).then(function (value) {
  722. // never reached
  723. }).then(function (value) {
  724. // never reached
  725. }, function (reason) {
  726. // The `PedgagocialException` is propagated all the way down to here
  727. });
  728. ```
  729.  
  730. Assimilation
  731. ------------
  732.  
  733. Sometimes the value you want to propagate to a downstream promise can only be
  734. retrieved asynchronously. This can be achieved by returning a promise in the
  735. fulfillment or rejection handler. The downstream promise will then be pending
  736. until the returned promise is settled. This is called *assimilation*.
  737.  
  738. ```js
  739. findUser().then(function (user) {
  740. return findCommentsByAuthor(user);
  741. }).then(function (comments) {
  742. // The user's comments are now available
  743. });
  744. ```
  745.  
  746. If the assimliated promise rejects, then the downstream promise will also reject.
  747.  
  748. ```js
  749. findUser().then(function (user) {
  750. return findCommentsByAuthor(user);
  751. }).then(function (comments) {
  752. // If `findCommentsByAuthor` fulfills, we'll have the value here
  753. }, function (reason) {
  754. // If `findCommentsByAuthor` rejects, we'll have the reason here
  755. });
  756. ```
  757.  
  758. Simple Example
  759. --------------
  760.  
  761. Synchronous Example
  762.  
  763. ```javascript
  764. var result;
  765.  
  766. try {
  767. result = findResult();
  768. // success
  769. } catch(reason) {
  770. // failure
  771. }
  772. ```
  773.  
  774. Errback Example
  775.  
  776. ```js
  777. findResult(function(result, err){
  778. if (err) {
  779. // failure
  780. } else {
  781. // success
  782. }
  783. });
  784. ```
  785.  
  786. Promise Example;
  787.  
  788. ```javascript
  789. findResult().then(function(result){
  790. // success
  791. }, function(reason){
  792. // failure
  793. });
  794. ```
  795.  
  796. Advanced Example
  797. --------------
  798.  
  799. Synchronous Example
  800.  
  801. ```javascript
  802. var author, books;
  803.  
  804. try {
  805. author = findAuthor();
  806. books = findBooksByAuthor(author);
  807. // success
  808. } catch(reason) {
  809. // failure
  810. }
  811. ```
  812.  
  813. Errback Example
  814.  
  815. ```js
  816.  
  817. function foundBooks(books) {
  818.  
  819. }
  820.  
  821. function failure(reason) {
  822.  
  823. }
  824.  
  825. findAuthor(function(author, err){
  826. if (err) {
  827. failure(err);
  828. // failure
  829. } else {
  830. try {
  831. findBoooksByAuthor(author, function(books, err) {
  832. if (err) {
  833. failure(err);
  834. } else {
  835. try {
  836. foundBooks(books);
  837. } catch(reason) {
  838. failure(reason);
  839. }
  840. }
  841. });
  842. } catch(error) {
  843. failure(err);
  844. }
  845. // success
  846. }
  847. });
  848. ```
  849.  
  850. Promise Example;
  851.  
  852. ```javascript
  853. findAuthor().
  854. then(findBooksByAuthor).
  855. then(function(books){
  856. // found books
  857. }).catch(function(reason){
  858. // something went wrong
  859. });
  860. ```
  861.  
  862. @method then
  863. @param {Function} onFulfilled
  864. @param {Function} onRejected
  865. Useful for tooling.
  866. @return {Promise}
  867. */
  868. then: function(onFulfillment, onRejection) {
  869. var parent = this;
  870. var state = parent._state;
  871.  
  872. if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) {
  873. return this;
  874. }
  875.  
  876. var child = new this.constructor($$$internal$$noop);
  877. var result = parent._result;
  878.  
  879. if (state) {
  880. var callback = arguments[state - 1];
  881. $$asap$$default(function(){
  882. $$$internal$$invokeCallback(state, child, callback, result);
  883. });
  884. } else {
  885. $$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  886. }
  887.  
  888. return child;
  889. },
  890.  
  891. /**
  892. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  893. as the catch block of a try/catch statement.
  894.  
  895. ```js
  896. function findAuthor(){
  897. throw new Error('couldn't find that author');
  898. }
  899.  
  900. // synchronous
  901. try {
  902. findAuthor();
  903. } catch(reason) {
  904. // something went wrong
  905. }
  906.  
  907. // async with promises
  908. findAuthor().catch(function(reason){
  909. // something went wrong
  910. });
  911. ```
  912.  
  913. @method catch
  914. @param {Function} onRejection
  915. Useful for tooling.
  916. @return {Promise}
  917. */
  918. 'catch': function(onRejection) {
  919. return this.then(null, onRejection);
  920. }
  921. };
  922.  
  923. var $$es6$promise$polyfill$$default = function polyfill() {
  924. var local;
  925.  
  926. if (typeof global !== 'undefined') {
  927. local = global;
  928. } else if (typeof window !== 'undefined' && window.document) {
  929. local = window;
  930. } else {
  931. local = self;
  932. }
  933.  
  934. var es6PromiseSupport =
  935. "Promise" in local &&
  936. // Some of these methods are missing from
  937. // Firefox/Chrome experimental implementations
  938. "resolve" in local.Promise &&
  939. "reject" in local.Promise &&
  940. "all" in local.Promise &&
  941. "race" in local.Promise &&
  942. // Older version of the spec had a resolver object
  943. // as the arg rather than a function
  944. (function() {
  945. var resolve;
  946. new local.Promise(function(r) { resolve = r; });
  947. return $$utils$$isFunction(resolve);
  948. }());
  949.  
  950. if (!es6PromiseSupport) {
  951. local.Promise = $$es6$promise$promise$$default;
  952. }
  953. };
  954.  
  955. var es6$promise$umd$$ES6Promise = {
  956. 'Promise': $$es6$promise$promise$$default,
  957. 'polyfill': $$es6$promise$polyfill$$default
  958. };
  959.  
  960. /* global define:true module:true window: true */
  961. if (typeof define === 'function' && define['amd']) {
  962. define(function() { return es6$promise$umd$$ES6Promise; });
  963. } else if (typeof module !== 'undefined' && module['exports']) {
  964. module['exports'] = es6$promise$umd$$ES6Promise;
  965. } else if (typeof this !== 'undefined') {
  966. this['ES6Promise'] = es6$promise$umd$$ES6Promise;
  967. }
  968. }).call(this);
  969. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  970. },{"_process":2}],2:[function(require,module,exports){
  971. // shim for using process in browser
  972.  
  973. var process = module.exports = {};
  974. var queue = [];
  975. var draining = false;
  976.  
  977. function drainQueue() {
  978. if (draining) {
  979. return;
  980. }
  981. draining = true;
  982. var currentQueue;
  983. var len = queue.length;
  984. while(len) {
  985. currentQueue = queue;
  986. queue = [];
  987. var i = -1;
  988. while (++i < len) {
  989. currentQueue[i]();
  990. }
  991. len = queue.length;
  992. }
  993. draining = false;
  994. }
  995. process.nextTick = function (fun) {
  996. queue.push(fun);
  997. if (!draining) {
  998. setTimeout(drainQueue, 0);
  999. }
  1000. };
  1001.  
  1002. process.title = 'browser';
  1003. process.browser = true;
  1004. process.env = {};
  1005. process.argv = [];
  1006. process.version = ''; // empty string to avoid regexp issues
  1007.  
  1008. function noop() {}
  1009.  
  1010. process.on = noop;
  1011. process.addListener = noop;
  1012. process.once = noop;
  1013. process.off = noop;
  1014. process.removeListener = noop;
  1015. process.removeAllListeners = noop;
  1016. process.emit = noop;
  1017.  
  1018. process.binding = function (name) {
  1019. throw new Error('process.binding is not supported');
  1020. };
  1021.  
  1022. // TODO(shtylman)
  1023. process.cwd = function () { return '/' };
  1024. process.chdir = function (dir) {
  1025. throw new Error('process.chdir is not supported');
  1026. };
  1027. process.umask = function() { return 0; };
  1028.  
  1029. },{}],3:[function(require,module,exports){
  1030. (function (global){
  1031. /*! http://mths.be/punycode v1.2.4 by @mathias */
  1032. ;(function(root) {
  1033.  
  1034. /** Detect free variables */
  1035. var freeExports = typeof exports == 'object' && exports;
  1036. var freeModule = typeof module == 'object' && module &&
  1037. module.exports == freeExports && module;
  1038. var freeGlobal = typeof global == 'object' && global;
  1039. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  1040. root = freeGlobal;
  1041. }
  1042.  
  1043. /**
  1044. * The `punycode` object.
  1045. * @name punycode
  1046. * @type Object
  1047. */
  1048. var punycode,
  1049.  
  1050. /** Highest positive signed 32-bit float value */
  1051. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  1052.  
  1053. /** Bootstring parameters */
  1054. base = 36,
  1055. tMin = 1,
  1056. tMax = 26,
  1057. skew = 38,
  1058. damp = 700,
  1059. initialBias = 72,
  1060. initialN = 128, // 0x80
  1061. delimiter = '-', // '\x2D'
  1062.  
  1063. /** Regular expressions */
  1064. regexPunycode = /^xn--/,
  1065. regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
  1066. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
  1067.  
  1068. /** Error messages */
  1069. errors = {
  1070. 'overflow': 'Overflow: input needs wider integers to process',
  1071. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  1072. 'invalid-input': 'Invalid input'
  1073. },
  1074.  
  1075. /** Convenience shortcuts */
  1076. baseMinusTMin = base - tMin,
  1077. floor = Math.floor,
  1078. stringFromCharCode = String.fromCharCode,
  1079.  
  1080. /** Temporary variable */
  1081. key;
  1082.  
  1083. /*--------------------------------------------------------------------------*/
  1084.  
  1085. /**
  1086. * A generic error utility function.
  1087. * @private
  1088. * @param {String} type The error type.
  1089. * @returns {Error} Throws a `RangeError` with the applicable error message.
  1090. */
  1091. function error(type) {
  1092. throw RangeError(errors[type]);
  1093. }
  1094.  
  1095. /**
  1096. * A generic `Array#map` utility function.
  1097. * @private
  1098. * @param {Array} array The array to iterate over.
  1099. * @param {Function} callback The function that gets called for every array
  1100. * item.
  1101. * @returns {Array} A new array of values returned by the callback function.
  1102. */
  1103. function map(array, fn) {
  1104. var length = array.length;
  1105. while (length--) {
  1106. array[length] = fn(array[length]);
  1107. }
  1108. return array;
  1109. }
  1110.  
  1111. /**
  1112. * A simple `Array#map`-like wrapper to work with domain name strings.
  1113. * @private
  1114. * @param {String} domain The domain name.
  1115. * @param {Function} callback The function that gets called for every
  1116. * character.
  1117. * @returns {Array} A new string of characters returned by the callback
  1118. * function.
  1119. */
  1120. function mapDomain(string, fn) {
  1121. return map(string.split(regexSeparators), fn).join('.');
  1122. }
  1123.  
  1124. /**
  1125. * Creates an array containing the numeric code points of each Unicode
  1126. * character in the string. While JavaScript uses UCS-2 internally,
  1127. * this function will convert a pair of surrogate halves (each of which
  1128. * UCS-2 exposes as separate characters) into a single code point,
  1129. * matching UTF-16.
  1130. * @see `punycode.ucs2.encode`
  1131. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  1132. * @memberOf punycode.ucs2
  1133. * @name decode
  1134. * @param {String} string The Unicode input string (UCS-2).
  1135. * @returns {Array} The new array of code points.
  1136. */
  1137. function ucs2decode(string) {
  1138. var output = [],
  1139. counter = 0,
  1140. length = string.length,
  1141. value,
  1142. extra;
  1143. while (counter < length) {
  1144. value = string.charCodeAt(counter++);
  1145. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  1146. // high surrogate, and there is a next character
  1147. extra = string.charCodeAt(counter++);
  1148. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  1149. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  1150. } else {
  1151. // unmatched surrogate; only append this code unit, in case the next
  1152. // code unit is the high surrogate of a surrogate pair
  1153. output.push(value);
  1154. counter--;
  1155. }
  1156. } else {
  1157. output.push(value);
  1158. }
  1159. }
  1160. return output;
  1161. }
  1162.  
  1163. /**
  1164. * Creates a string based on an array of numeric code points.
  1165. * @see `punycode.ucs2.decode`
  1166. * @memberOf punycode.ucs2
  1167. * @name encode
  1168. * @param {Array} codePoints The array of numeric code points.
  1169. * @returns {String} The new Unicode string (UCS-2).
  1170. */
  1171. function ucs2encode(array) {
  1172. return map(array, function(value) {
  1173. var output = '';
  1174. if (value > 0xFFFF) {
  1175. value -= 0x10000;
  1176. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  1177. value = 0xDC00 | value & 0x3FF;
  1178. }
  1179. output += stringFromCharCode(value);
  1180. return output;
  1181. }).join('');
  1182. }
  1183.  
  1184. /**
  1185. * Converts a basic code point into a digit/integer.
  1186. * @see `digitToBasic()`
  1187. * @private
  1188. * @param {Number} codePoint The basic numeric code point value.
  1189. * @returns {Number} The numeric value of a basic code point (for use in
  1190. * representing integers) in the range `0` to `base - 1`, or `base` if
  1191. * the code point does not represent a value.
  1192. */
  1193. function basicToDigit(codePoint) {
  1194. if (codePoint - 48 < 10) {
  1195. return codePoint - 22;
  1196. }
  1197. if (codePoint - 65 < 26) {
  1198. return codePoint - 65;
  1199. }
  1200. if (codePoint - 97 < 26) {
  1201. return codePoint - 97;
  1202. }
  1203. return base;
  1204. }
  1205.  
  1206. /**
  1207. * Converts a digit/integer into a basic code point.
  1208. * @see `basicToDigit()`
  1209. * @private
  1210. * @param {Number} digit The numeric value of a basic code point.
  1211. * @returns {Number} The basic code point whose value (when used for
  1212. * representing integers) is `digit`, which needs to be in the range
  1213. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  1214. * used; else, the lowercase form is used. The behavior is undefined
  1215. * if `flag` is non-zero and `digit` has no uppercase form.
  1216. */
  1217. function digitToBasic(digit, flag) {
  1218. // 0..25 map to ASCII a..z or A..Z
  1219. // 26..35 map to ASCII 0..9
  1220. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  1221. }
  1222.  
  1223. /**
  1224. * Bias adaptation function as per section 3.4 of RFC 3492.
  1225. * http://tools.ietf.org/html/rfc3492#section-3.4
  1226. * @private
  1227. */
  1228. function adapt(delta, numPoints, firstTime) {
  1229. var k = 0;
  1230. delta = firstTime ? floor(delta / damp) : delta >> 1;
  1231. delta += floor(delta / numPoints);
  1232. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  1233. delta = floor(delta / baseMinusTMin);
  1234. }
  1235. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  1236. }
  1237.  
  1238. /**
  1239. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  1240. * symbols.
  1241. * @memberOf punycode
  1242. * @param {String} input The Punycode string of ASCII-only symbols.
  1243. * @returns {String} The resulting string of Unicode symbols.
  1244. */
  1245. function decode(input) {
  1246. // Don't use UCS-2
  1247. var output = [],
  1248. inputLength = input.length,
  1249. out,
  1250. i = 0,
  1251. n = initialN,
  1252. bias = initialBias,
  1253. basic,
  1254. j,
  1255. index,
  1256. oldi,
  1257. w,
  1258. k,
  1259. digit,
  1260. t,
  1261. /** Cached calculation results */
  1262. baseMinusT;
  1263.  
  1264. // Handle the basic code points: let `basic` be the number of input code
  1265. // points before the last delimiter, or `0` if there is none, then copy
  1266. // the first basic code points to the output.
  1267.  
  1268. basic = input.lastIndexOf(delimiter);
  1269. if (basic < 0) {
  1270. basic = 0;
  1271. }
  1272.  
  1273. for (j = 0; j < basic; ++j) {
  1274. // if it's not a basic code point
  1275. if (input.charCodeAt(j) >= 0x80) {
  1276. error('not-basic');
  1277. }
  1278. output.push(input.charCodeAt(j));
  1279. }
  1280.  
  1281. // Main decoding loop: start just after the last delimiter if any basic code
  1282. // points were copied; start at the beginning otherwise.
  1283.  
  1284. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  1285.  
  1286. // `index` is the index of the next character to be consumed.
  1287. // Decode a generalized variable-length integer into `delta`,
  1288. // which gets added to `i`. The overflow checking is easier
  1289. // if we increase `i` as we go, then subtract off its starting
  1290. // value at the end to obtain `delta`.
  1291. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  1292.  
  1293. if (index >= inputLength) {
  1294. error('invalid-input');
  1295. }
  1296.  
  1297. digit = basicToDigit(input.charCodeAt(index++));
  1298.  
  1299. if (digit >= base || digit > floor((maxInt - i) / w)) {
  1300. error('overflow');
  1301. }
  1302.  
  1303. i += digit * w;
  1304. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  1305.  
  1306. if (digit < t) {
  1307. break;
  1308. }
  1309.  
  1310. baseMinusT = base - t;
  1311. if (w > floor(maxInt / baseMinusT)) {
  1312. error('overflow');
  1313. }
  1314.  
  1315. w *= baseMinusT;
  1316.  
  1317. }
  1318.  
  1319. out = output.length + 1;
  1320. bias = adapt(i - oldi, out, oldi == 0);
  1321.  
  1322. // `i` was supposed to wrap around from `out` to `0`,
  1323. // incrementing `n` each time, so we'll fix that now:
  1324. if (floor(i / out) > maxInt - n) {
  1325. error('overflow');
  1326. }
  1327.  
  1328. n += floor(i / out);
  1329. i %= out;
  1330.  
  1331. // Insert `n` at position `i` of the output
  1332. output.splice(i++, 0, n);
  1333.  
  1334. }
  1335.  
  1336. return ucs2encode(output);
  1337. }
  1338.  
  1339. /**
  1340. * Converts a string of Unicode symbols to a Punycode string of ASCII-only
  1341. * symbols.
  1342. * @memberOf punycode
  1343. * @param {String} input The string of Unicode symbols.
  1344. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  1345. */
  1346. function encode(input) {
  1347. var n,
  1348. delta,
  1349. handledCPCount,
  1350. basicLength,
  1351. bias,
  1352. j,
  1353. m,
  1354. q,
  1355. k,
  1356. t,
  1357. currentValue,
  1358. output = [],
  1359. /** `inputLength` will hold the number of code points in `input`. */
  1360. inputLength,
  1361. /** Cached calculation results */
  1362. handledCPCountPlusOne,
  1363. baseMinusT,
  1364. qMinusT;
  1365.  
  1366. // Convert the input in UCS-2 to Unicode
  1367. input = ucs2decode(input);
  1368.  
  1369. // Cache the length
  1370. inputLength = input.length;
  1371.  
  1372. // Initialize the state
  1373. n = initialN;
  1374. delta = 0;
  1375. bias = initialBias;
  1376.  
  1377. // Handle the basic code points
  1378. for (j = 0; j < inputLength; ++j) {
  1379. currentValue = input[j];
  1380. if (currentValue < 0x80) {
  1381. output.push(stringFromCharCode(currentValue));
  1382. }
  1383. }
  1384.  
  1385. handledCPCount = basicLength = output.length;
  1386.  
  1387. // `handledCPCount` is the number of code points that have been handled;
  1388. // `basicLength` is the number of basic code points.
  1389.  
  1390. // Finish the basic string - if it is not empty - with a delimiter
  1391. if (basicLength) {
  1392. output.push(delimiter);
  1393. }
  1394.  
  1395. // Main encoding loop:
  1396. while (handledCPCount < inputLength) {
  1397.  
  1398. // All non-basic code points < n have been handled already. Find the next
  1399. // larger one:
  1400. for (m = maxInt, j = 0; j < inputLength; ++j) {
  1401. currentValue = input[j];
  1402. if (currentValue >= n && currentValue < m) {
  1403. m = currentValue;
  1404. }
  1405. }
  1406.  
  1407. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  1408. // but guard against overflow
  1409. handledCPCountPlusOne = handledCPCount + 1;
  1410. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  1411. error('overflow');
  1412. }
  1413.  
  1414. delta += (m - n) * handledCPCountPlusOne;
  1415. n = m;
  1416.  
  1417. for (j = 0; j < inputLength; ++j) {
  1418. currentValue = input[j];
  1419.  
  1420. if (currentValue < n && ++delta > maxInt) {
  1421. error('overflow');
  1422. }
  1423.  
  1424. if (currentValue == n) {
  1425. // Represent delta as a generalized variable-length integer
  1426. for (q = delta, k = base; /* no condition */; k += base) {
  1427. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  1428. if (q < t) {
  1429. break;
  1430. }
  1431. qMinusT = q - t;
  1432. baseMinusT = base - t;
  1433. output.push(
  1434. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  1435. );
  1436. q = floor(qMinusT / baseMinusT);
  1437. }
  1438.  
  1439. output.push(stringFromCharCode(digitToBasic(q, 0)));
  1440. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  1441. delta = 0;
  1442. ++handledCPCount;
  1443. }
  1444. }
  1445.  
  1446. ++delta;
  1447. ++n;
  1448.  
  1449. }
  1450. return output.join('');
  1451. }
  1452.  
  1453. /**
  1454. * Converts a Punycode string representing a domain name to Unicode. Only the
  1455. * Punycoded parts of the domain name will be converted, i.e. it doesn't
  1456. * matter if you call it on a string that has already been converted to
  1457. * Unicode.
  1458. * @memberOf punycode
  1459. * @param {String} domain The Punycode domain name to convert to Unicode.
  1460. * @returns {String} The Unicode representation of the given Punycode
  1461. * string.
  1462. */
  1463. function toUnicode(domain) {
  1464. return mapDomain(domain, function(string) {
  1465. return regexPunycode.test(string)
  1466. ? decode(string.slice(4).toLowerCase())
  1467. : string;
  1468. });
  1469. }
  1470.  
  1471. /**
  1472. * Converts a Unicode string representing a domain name to Punycode. Only the
  1473. * non-ASCII parts of the domain name will be converted, i.e. it doesn't
  1474. * matter if you call it with a domain that's already in ASCII.
  1475. * @memberOf punycode
  1476. * @param {String} domain The domain name to convert, as a Unicode string.
  1477. * @returns {String} The Punycode representation of the given domain name.
  1478. */
  1479. function toASCII(domain) {
  1480. return mapDomain(domain, function(string) {
  1481. return regexNonASCII.test(string)
  1482. ? 'xn--' + encode(string)
  1483. : string;
  1484. });
  1485. }
  1486.  
  1487. /*--------------------------------------------------------------------------*/
  1488.  
  1489. /** Define the public API */
  1490. punycode = {
  1491. /**
  1492. * A string representing the current Punycode.js version number.
  1493. * @memberOf punycode
  1494. * @type String
  1495. */
  1496. 'version': '1.2.4',
  1497. /**
  1498. * An object of methods to convert from JavaScript's internal character
  1499. * representation (UCS-2) to Unicode code points, and back.
  1500. * @see <http://mathiasbynens.be/notes/javascript-encoding>
  1501. * @memberOf punycode
  1502. * @type Object
  1503. */
  1504. 'ucs2': {
  1505. 'decode': ucs2decode,
  1506. 'encode': ucs2encode
  1507. },
  1508. 'decode': decode,
  1509. 'encode': encode,
  1510. 'toASCII': toASCII,
  1511. 'toUnicode': toUnicode
  1512. };
  1513.  
  1514. /** Expose `punycode` */
  1515. // Some AMD build optimizers, like r.js, check for specific condition patterns
  1516. // like the following:
  1517. if (
  1518. typeof define == 'function' &&
  1519. typeof define.amd == 'object' &&
  1520. define.amd
  1521. ) {
  1522. define('punycode', function() {
  1523. return punycode;
  1524. });
  1525. } else if (freeExports && !freeExports.nodeType) {
  1526. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  1527. freeModule.exports = punycode;
  1528. } else { // in Narwhal or RingoJS v0.7.0-
  1529. for (key in punycode) {
  1530. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  1531. }
  1532. }
  1533. } else { // in Rhino or a web browser
  1534. root.punycode = punycode;
  1535. }
  1536.  
  1537. }(this));
  1538.  
  1539. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1540. },{}],4:[function(require,module,exports){
  1541. var log = require('./log');
  1542. var Promise = require('./promise');
  1543.  
  1544. function restoreOwnerScroll(ownerDocument, x, y) {
  1545. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  1546. ownerDocument.defaultView.scrollTo(x, y);
  1547. }
  1548. }
  1549.  
  1550. function cloneCanvasContents(canvas, clonedCanvas) {
  1551. try {
  1552. if (clonedCanvas) {
  1553. clonedCanvas.width = canvas.width;
  1554. clonedCanvas.height = canvas.height;
  1555. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
  1556. }
  1557. } catch(e) {
  1558. log("Unable to copy canvas content from", canvas, e);
  1559. }
  1560. }
  1561.  
  1562. function cloneNode(node, javascriptEnabled) {
  1563. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  1564.  
  1565. var child = node.firstChild;
  1566. while(child) {
  1567. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  1568. clone.appendChild(cloneNode(child, javascriptEnabled));
  1569. }
  1570. child = child.nextSibling;
  1571. }
  1572.  
  1573. if (node.nodeType === 1) {
  1574. clone._scrollTop = node.scrollTop;
  1575. clone._scrollLeft = node.scrollLeft;
  1576. if (node.nodeName === "CANVAS") {
  1577. cloneCanvasContents(node, clone);
  1578. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  1579. clone.value = node.value;
  1580. }
  1581. }
  1582.  
  1583. return clone;
  1584. }
  1585.  
  1586. function initNode(node) {
  1587. if (node.nodeType === 1) {
  1588. node.scrollTop = node._scrollTop;
  1589. node.scrollLeft = node._scrollLeft;
  1590.  
  1591. var child = node.firstChild;
  1592. while(child) {
  1593. initNode(child);
  1594. child = child.nextSibling;
  1595. }
  1596. }
  1597. }
  1598.  
  1599. module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
  1600. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  1601. var container = containerDocument.createElement("iframe");
  1602.  
  1603. container.className = "html2canvas-container";
  1604. container.style.visibility = "hidden";
  1605. container.style.position = "fixed";
  1606. container.style.left = "-10000px";
  1607. container.style.top = "0px";
  1608. container.style.border = "0";
  1609. container.width = width;
  1610. container.height = height;
  1611. container.scrolling = "no"; // ios won't scroll without it
  1612. containerDocument.body.appendChild(container);
  1613.  
  1614. return new Promise(function(resolve) {
  1615. var documentClone = container.contentWindow.document;
  1616.  
  1617. /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
  1618. if window url is about:blank, we can assign the url to current by writing onto the document
  1619. */
  1620. container.contentWindow.onload = container.onload = function() {
  1621. var interval = setInterval(function() {
  1622. if (documentClone.body.childNodes.length > 0) {
  1623. initNode(documentClone.documentElement);
  1624. clearInterval(interval);
  1625. if (options.type === "view") {
  1626. container.contentWindow.scrollTo(x, y);
  1627. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  1628. documentClone.documentElement.style.top = (-y) + "px";
  1629. documentClone.documentElement.style.left = (-x) + "px";
  1630. documentClone.documentElement.style.position = 'absolute';
  1631. }
  1632. }
  1633. resolve(container);
  1634. }
  1635. }, 50);
  1636. };
  1637.  
  1638. documentClone.open();
  1639. documentClone.write("<!DOCTYPE html><html></html>");
  1640. // Chrome scrolls the parent document for some reason after the write to the cloned window???
  1641. restoreOwnerScroll(ownerDocument, x, y);
  1642. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  1643. documentClone.close();
  1644. });
  1645. };
  1646.  
  1647. },{"./log":15,"./promise":18}],5:[function(require,module,exports){
  1648. // http://dev.w3.org/csswg/css-color/
  1649.  
  1650. function Color(value) {
  1651. this.r = 0;
  1652. this.g = 0;
  1653. this.b = 0;
  1654. this.a = null;
  1655. var result = this.fromArray(value) ||
  1656. this.namedColor(value) ||
  1657. this.rgb(value) ||
  1658. this.rgba(value) ||
  1659. this.hex6(value) ||
  1660. this.hex3(value);
  1661. }
  1662.  
  1663. Color.prototype.darken = function(amount) {
  1664. var a = 1 - amount;
  1665. return new Color([
  1666. Math.round(this.r * a),
  1667. Math.round(this.g * a),
  1668. Math.round(this.b * a),
  1669. this.a
  1670. ]);
  1671. };
  1672.  
  1673. Color.prototype.isTransparent = function() {
  1674. return this.a === 0;
  1675. };
  1676.  
  1677. Color.prototype.isBlack = function() {
  1678. return this.r === 0 && this.g === 0 && this.b === 0;
  1679. };
  1680.  
  1681. Color.prototype.fromArray = function(array) {
  1682. if (Array.isArray(array)) {
  1683. this.r = Math.min(array[0], 255);
  1684. this.g = Math.min(array[1], 255);
  1685. this.b = Math.min(array[2], 255);
  1686. if (array.length > 3) {
  1687. this.a = array[3];
  1688. }
  1689. }
  1690.  
  1691. return (Array.isArray(array));
  1692. };
  1693.  
  1694. var _hex3 = /^#([a-f0-9]{3})$/i;
  1695.  
  1696. Color.prototype.hex3 = function(value) {
  1697. var match = null;
  1698. if ((match = value.match(_hex3)) !== null) {
  1699. this.r = parseInt(match[1][0] + match[1][0], 16);
  1700. this.g = parseInt(match[1][1] + match[1][1], 16);
  1701. this.b = parseInt(match[1][2] + match[1][2], 16);
  1702. }
  1703. return match !== null;
  1704. };
  1705.  
  1706. var _hex6 = /^#([a-f0-9]{6})$/i;
  1707.  
  1708. Color.prototype.hex6 = function(value) {
  1709. var match = null;
  1710. if ((match = value.match(_hex6)) !== null) {
  1711. this.r = parseInt(match[1].substring(0, 2), 16);
  1712. this.g = parseInt(match[1].substring(2, 4), 16);
  1713. this.b = parseInt(match[1].substring(4, 6), 16);
  1714. }
  1715. return match !== null;
  1716. };
  1717.  
  1718. var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/;
  1719.  
  1720. Color.prototype.rgb = function(value) {
  1721. var match = null;
  1722. if ((match = value.match(_rgb)) !== null) {
  1723. this.r = Number(match[1]);
  1724. this.g = Number(match[2]);
  1725. this.b = Number(match[3]);
  1726. }
  1727. return match !== null;
  1728. };
  1729.  
  1730. var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/;
  1731.  
  1732. Color.prototype.rgba = function(value) {
  1733. var match = null;
  1734. if ((match = value.match(_rgba)) !== null) {
  1735. this.r = Number(match[1]);
  1736. this.g = Number(match[2]);
  1737. this.b = Number(match[3]);
  1738. this.a = Number(match[4]);
  1739. }
  1740. return match !== null;
  1741. };
  1742.  
  1743. Color.prototype.toString = function() {
  1744. return this.a !== null && this.a !== 1 ?
  1745. "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
  1746. "rgb(" + [this.r, this.g, this.b].join(",") + ")";
  1747. };
  1748.  
  1749. Color.prototype.namedColor = function(value) {
  1750. var color = colors[value.toLowerCase()];
  1751. if (color) {
  1752. this.r = color[0];
  1753. this.g = color[1];
  1754. this.b = color[2];
  1755. } else if (value.toLowerCase() === "transparent") {
  1756. this.r = this.g = this.b = this.a = 0;
  1757. return true;
  1758. }
  1759.  
  1760. return !!color;
  1761. };
  1762.  
  1763. Color.prototype.isColor = true;
  1764.  
  1765. // 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}, {}))
  1766. var colors = {
  1767. "aliceblue": [240, 248, 255],
  1768. "antiquewhite": [250, 235, 215],
  1769. "aqua": [0, 255, 255],
  1770. "aquamarine": [127, 255, 212],
  1771. "azure": [240, 255, 255],
  1772. "beige": [245, 245, 220],
  1773. "bisque": [255, 228, 196],
  1774. "black": [0, 0, 0],
  1775. "blanchedalmond": [255, 235, 205],
  1776. "blue": [0, 0, 255],
  1777. "blueviolet": [138, 43, 226],
  1778. "brown": [165, 42, 42],
  1779. "burlywood": [222, 184, 135],
  1780. "cadetblue": [95, 158, 160],
  1781. "chartreuse": [127, 255, 0],
  1782. "chocolate": [210, 105, 30],
  1783. "coral": [255, 127, 80],
  1784. "cornflowerblue": [100, 149, 237],
  1785. "cornsilk": [255, 248, 220],
  1786. "crimson": [220, 20, 60],
  1787. "cyan": [0, 255, 255],
  1788. "darkblue": [0, 0, 139],
  1789. "darkcyan": [0, 139, 139],
  1790. "darkgoldenrod": [184, 134, 11],
  1791. "darkgray": [169, 169, 169],
  1792. "darkgreen": [0, 100, 0],
  1793. "darkgrey": [169, 169, 169],
  1794. "darkkhaki": [189, 183, 107],
  1795. "darkmagenta": [139, 0, 139],
  1796. "darkolivegreen": [85, 107, 47],
  1797. "darkorange": [255, 140, 0],
  1798. "darkorchid": [153, 50, 204],
  1799. "darkred": [139, 0, 0],
  1800. "darksalmon": [233, 150, 122],
  1801. "darkseagreen": [143, 188, 143],
  1802. "darkslateblue": [72, 61, 139],
  1803. "darkslategray": [47, 79, 79],
  1804. "darkslategrey": [47, 79, 79],
  1805. "darkturquoise": [0, 206, 209],
  1806. "darkviolet": [148, 0, 211],
  1807. "deeppink": [255, 20, 147],
  1808. "deepskyblue": [0, 191, 255],
  1809. "dimgray": [105, 105, 105],
  1810. "dimgrey": [105, 105, 105],
  1811. "dodgerblue": [30, 144, 255],
  1812. "firebrick": [178, 34, 34],
  1813. "floralwhite": [255, 250, 240],
  1814. "forestgreen": [34, 139, 34],
  1815. "fuchsia": [255, 0, 255],
  1816. "gainsboro": [220, 220, 220],
  1817. "ghostwhite": [248, 248, 255],
  1818. "gold": [255, 215, 0],
  1819. "goldenrod": [218, 165, 32],
  1820. "gray": [128, 128, 128],
  1821. "green": [0, 128, 0],
  1822. "greenyellow": [173, 255, 47],
  1823. "grey": [128, 128, 128],
  1824. "honeydew": [240, 255, 240],
  1825. "hotpink": [255, 105, 180],
  1826. "indianred": [205, 92, 92],
  1827. "indigo": [75, 0, 130],
  1828. "ivory": [255, 255, 240],
  1829. "khaki": [240, 230, 140],
  1830. "lavender": [230, 230, 250],
  1831. "lavenderblush": [255, 240, 245],
  1832. "lawngreen": [124, 252, 0],
  1833. "lemonchiffon": [255, 250, 205],
  1834. "lightblue": [173, 216, 230],
  1835. "lightcoral": [240, 128, 128],
  1836. "lightcyan": [224, 255, 255],
  1837. "lightgoldenrodyellow": [250, 250, 210],
  1838. "lightgray": [211, 211, 211],
  1839. "lightgreen": [144, 238, 144],
  1840. "lightgrey": [211, 211, 211],
  1841. "lightpink": [255, 182, 193],
  1842. "lightsalmon": [255, 160, 122],
  1843. "lightseagreen": [32, 178, 170],
  1844. "lightskyblue": [135, 206, 250],
  1845. "lightslategray": [119, 136, 153],
  1846. "lightslategrey": [119, 136, 153],
  1847. "lightsteelblue": [176, 196, 222],
  1848. "lightyellow": [255, 255, 224],
  1849. "lime": [0, 255, 0],
  1850. "limegreen": [50, 205, 50],
  1851. "linen": [250, 240, 230],
  1852. "magenta": [255, 0, 255],
  1853. "maroon": [128, 0, 0],
  1854. "mediumaquamarine": [102, 205, 170],
  1855. "mediumblue": [0, 0, 205],
  1856. "mediumorchid": [186, 85, 211],
  1857. "mediumpurple": [147, 112, 219],
  1858. "mediumseagreen": [60, 179, 113],
  1859. "mediumslateblue": [123, 104, 238],
  1860. "mediumspringgreen": [0, 250, 154],
  1861. "mediumturquoise": [72, 209, 204],
  1862. "mediumvioletred": [199, 21, 133],
  1863. "midnightblue": [25, 25, 112],
  1864. "mintcream": [245, 255, 250],
  1865. "mistyrose": [255, 228, 225],
  1866. "moccasin": [255, 228, 181],
  1867. "navajowhite": [255, 222, 173],
  1868. "navy": [0, 0, 128],
  1869. "oldlace": [253, 245, 230],
  1870. "olive": [128, 128, 0],
  1871. "olivedrab": [107, 142, 35],
  1872. "orange": [255, 165, 0],
  1873. "orangered": [255, 69, 0],
  1874. "orchid": [218, 112, 214],
  1875. "palegoldenrod": [238, 232, 170],
  1876. "palegreen": [152, 251, 152],
  1877. "paleturquoise": [175, 238, 238],
  1878. "palevioletred": [219, 112, 147],
  1879. "papayawhip": [255, 239, 213],
  1880. "peachpuff": [255, 218, 185],
  1881. "peru": [205, 133, 63],
  1882. "pink": [255, 192, 203],
  1883. "plum": [221, 160, 221],
  1884. "powderblue": [176, 224, 230],
  1885. "purple": [128, 0, 128],
  1886. "rebeccapurple": [102, 51, 153],
  1887. "red": [255, 0, 0],
  1888. "rosybrown": [188, 143, 143],
  1889. "royalblue": [65, 105, 225],
  1890. "saddlebrown": [139, 69, 19],
  1891. "salmon": [250, 128, 114],
  1892. "sandybrown": [244, 164, 96],
  1893. "seagreen": [46, 139, 87],
  1894. "seashell": [255, 245, 238],
  1895. "sienna": [160, 82, 45],
  1896. "silver": [192, 192, 192],
  1897. "skyblue": [135, 206, 235],
  1898. "slateblue": [106, 90, 205],
  1899. "slategray": [112, 128, 144],
  1900. "slategrey": [112, 128, 144],
  1901. "snow": [255, 250, 250],
  1902. "springgreen": [0, 255, 127],
  1903. "steelblue": [70, 130, 180],
  1904. "tan": [210, 180, 140],
  1905. "teal": [0, 128, 128],
  1906. "thistle": [216, 191, 216],
  1907. "tomato": [255, 99, 71],
  1908. "turquoise": [64, 224, 208],
  1909. "violet": [238, 130, 238],
  1910. "wheat": [245, 222, 179],
  1911. "white": [255, 255, 255],
  1912. "whitesmoke": [245, 245, 245],
  1913. "yellow": [255, 255, 0],
  1914. "yellowgreen": [154, 205, 50]
  1915. };
  1916.  
  1917. module.exports = Color;
  1918.  
  1919. },{}],6:[function(require,module,exports){
  1920. var Promise = require('./promise');
  1921. var Support = require('./support');
  1922. var CanvasRenderer = require('./renderers/canvas');
  1923. var ImageLoader = require('./imageloader');
  1924. var NodeParser = require('./nodeparser');
  1925. var NodeContainer = require('./nodecontainer');
  1926. var log = require('./log');
  1927. var utils = require('./utils');
  1928. var createWindowClone = require('./clone');
  1929. var loadUrlDocument = require('./proxy').loadUrlDocument;
  1930. var getBounds = utils.getBounds;
  1931.  
  1932. var html2canvasNodeAttribute = "data-html2canvas-node";
  1933. var html2canvasCloneIndex = 0;
  1934.  
  1935. function html2canvas(nodeList, options) {
  1936. var index = html2canvasCloneIndex++;
  1937. options = options || {};
  1938. if (options.logging) {
  1939. window.html2canvas.logging = true;
  1940. window.html2canvas.start = Date.now();
  1941. }
  1942.  
  1943. options.async = typeof(options.async) === "undefined" ? true : options.async;
  1944. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  1945. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  1946. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  1947. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  1948. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  1949. options.strict = !!options.strict;
  1950.  
  1951. if (typeof(nodeList) === "string") {
  1952. if (typeof(options.proxy) !== "string") {
  1953. return Promise.reject("Proxy must be used when rendering url");
  1954. }
  1955. var width = options.width != null ? options.width : window.innerWidth;
  1956. var height = options.height != null ? options.height : window.innerHeight;
  1957. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  1958. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
  1959. });
  1960. }
  1961.  
  1962. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  1963. node.setAttribute(html2canvasNodeAttribute + index, index);
  1964. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  1965. if (typeof(options.onrendered) === "function") {
  1966. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  1967. options.onrendered(canvas);
  1968. }
  1969. return canvas;
  1970. });
  1971. }
  1972.  
  1973. html2canvas.Promise = Promise;
  1974. html2canvas.CanvasRenderer = CanvasRenderer;
  1975. html2canvas.NodeContainer = NodeContainer;
  1976. html2canvas.log = log;
  1977. html2canvas.utils = utils;
  1978.  
  1979. module.exports = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
  1980. return Promise.reject("No canvas support");
  1981. } : html2canvas;
  1982.  
  1983. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  1984. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  1985. log("Document cloned");
  1986. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  1987. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  1988. document.querySelector(selector).removeAttribute(attributeName);
  1989. var clonedWindow = container.contentWindow;
  1990. var node = clonedWindow.document.querySelector(selector);
  1991. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  1992. return oncloneHandler.then(function() {
  1993. return renderWindow(node, container, options, windowWidth, windowHeight);
  1994. });
  1995. });
  1996. }
  1997.  
  1998. function renderWindow(node, container, options, windowWidth, windowHeight) {
  1999. var clonedWindow = container.contentWindow;
  2000. var support = new Support(clonedWindow.document);
  2001. var imageLoader = new ImageLoader(options, support);
  2002. var bounds = getBounds(node);
  2003. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  2004. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  2005. var renderer = new options.renderer(width, height, imageLoader, options, document);
  2006. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  2007. return parser.ready.then(function() {
  2008. log("Finished rendering");
  2009. var canvas;
  2010.  
  2011. if (options.type === "view") {
  2012. canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
  2013. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  2014. canvas = renderer.canvas;
  2015. } else {
  2016. 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: clonedWindow.pageXOffset, y: clonedWindow.pageYOffset});
  2017. }
  2018.  
  2019. cleanupContainer(container, options);
  2020. return canvas;
  2021. });
  2022. }
  2023.  
  2024. function cleanupContainer(container, options) {
  2025. if (options.removeContainer) {
  2026. container.parentNode.removeChild(container);
  2027. log("Cleaned up container");
  2028. }
  2029. }
  2030.  
  2031. function crop(canvas, bounds) {
  2032. var croppedCanvas = document.createElement("canvas");
  2033. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  2034. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  2035. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  2036. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  2037. croppedCanvas.width = bounds.width;
  2038. croppedCanvas.height = bounds.height;
  2039. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", (x2-x1), "height:", (y2-y1));
  2040. log("Resulting crop with width", bounds.width, "and height", bounds.height, " with x", x1, "and y", y1);
  2041. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, x2-x1, y2-y1, bounds.x, bounds.y, x2-x1, y2-y1);
  2042. return croppedCanvas;
  2043. }
  2044.  
  2045. function documentWidth (doc) {
  2046. return Math.max(
  2047. Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
  2048. Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
  2049. Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
  2050. );
  2051. }
  2052.  
  2053. function documentHeight (doc) {
  2054. return Math.max(
  2055. Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
  2056. Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
  2057. Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
  2058. );
  2059. }
  2060.  
  2061. function absoluteUrl(url) {
  2062. var link = document.createElement("a");
  2063. link.href = url;
  2064. link.href = link.href;
  2065. return link;
  2066. }
  2067.  
  2068. },{"./clone":4,"./imageloader":13,"./log":15,"./nodecontainer":16,"./nodeparser":17,"./promise":18,"./proxy":19,"./renderers/canvas":23,"./support":25,"./utils":29}],7:[function(require,module,exports){
  2069. var Promise = require('./promise');
  2070. var log = require('./log');
  2071. var smallImage = require('./utils').smallImage;
  2072.  
  2073. function DummyImageContainer(src) {
  2074. this.src = src;
  2075. log("DummyImageContainer for", src);
  2076. if (!this.promise || !this.image) {
  2077. log("Initiating DummyImageContainer");
  2078. DummyImageContainer.prototype.image = new Image();
  2079. var image = this.image;
  2080. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  2081. image.onload = resolve;
  2082. image.onerror = reject;
  2083. image.src = smallImage();
  2084. if (image.complete === true) {
  2085. resolve(image);
  2086. }
  2087. });
  2088. }
  2089. }
  2090.  
  2091. module.exports = DummyImageContainer;
  2092.  
  2093. },{"./log":15,"./promise":18,"./utils":29}],8:[function(require,module,exports){
  2094. var smallImage = require('./utils').smallImage;
  2095.  
  2096. function Font(family, size) {
  2097. var container = document.createElement('div'),
  2098. img = document.createElement('img'),
  2099. span = document.createElement('span'),
  2100. sampleText = 'Hidden Text',
  2101. baseline,
  2102. middle;
  2103.  
  2104. container.style.visibility = "hidden";
  2105. container.style.fontFamily = family;
  2106. container.style.fontSize = size;
  2107. container.style.margin = 0;
  2108. container.style.padding = 0;
  2109.  
  2110. document.body.appendChild(container);
  2111.  
  2112. img.src = smallImage();
  2113. img.width = 1;
  2114. img.height = 1;
  2115.  
  2116. img.style.margin = 0;
  2117. img.style.padding = 0;
  2118. img.style.verticalAlign = "baseline";
  2119.  
  2120. span.style.fontFamily = family;
  2121. span.style.fontSize = size;
  2122. span.style.margin = 0;
  2123. span.style.padding = 0;
  2124.  
  2125. span.appendChild(document.createTextNode(sampleText));
  2126. container.appendChild(span);
  2127. container.appendChild(img);
  2128. baseline = (img.offsetTop - span.offsetTop) + 1;
  2129.  
  2130. container.removeChild(span);
  2131. container.appendChild(document.createTextNode(sampleText));
  2132.  
  2133. container.style.lineHeight = "normal";
  2134. img.style.verticalAlign = "super";
  2135.  
  2136. middle = (img.offsetTop-container.offsetTop) + 1;
  2137.  
  2138. document.body.removeChild(container);
  2139.  
  2140. this.baseline = baseline;
  2141. this.lineWidth = 1;
  2142. this.middle = middle;
  2143. }
  2144.  
  2145. module.exports = Font;
  2146.  
  2147. },{"./utils":29}],9:[function(require,module,exports){
  2148. var Font = require('./font');
  2149.  
  2150. function FontMetrics() {
  2151. this.data = {};
  2152. }
  2153.  
  2154. FontMetrics.prototype.getMetrics = function(family, size) {
  2155. if (this.data[family + "-" + size] === undefined) {
  2156. this.data[family + "-" + size] = new Font(family, size);
  2157. }
  2158. return this.data[family + "-" + size];
  2159. };
  2160.  
  2161. module.exports = FontMetrics;
  2162.  
  2163. },{"./font":8}],10:[function(require,module,exports){
  2164. var utils = require('./utils');
  2165. var Promise = require('./promise');
  2166. var getBounds = utils.getBounds;
  2167. var loadUrlDocument = require('./proxy').loadUrlDocument;
  2168.  
  2169. function FrameContainer(container, sameOrigin, options) {
  2170. this.image = null;
  2171. this.src = container;
  2172. var self = this;
  2173. var bounds = getBounds(container);
  2174. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  2175. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  2176. container.contentWindow.onload = container.onload = function() {
  2177. resolve(container);
  2178. };
  2179. } else {
  2180. resolve(container);
  2181. }
  2182. })).then(function(container) {
  2183. var html2canvas = require('./core');
  2184. 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});
  2185. }).then(function(canvas) {
  2186. return self.image = canvas;
  2187. });
  2188. }
  2189.  
  2190. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  2191. var container = this.src;
  2192. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
  2193. };
  2194.  
  2195. module.exports = FrameContainer;
  2196.  
  2197. },{"./core":6,"./promise":18,"./proxy":19,"./utils":29}],11:[function(require,module,exports){
  2198. var Promise = require('./promise');
  2199.  
  2200. function GradientContainer(imageData) {
  2201. this.src = imageData.value;
  2202. this.colorStops = [];
  2203. this.type = null;
  2204. this.x0 = 0.5;
  2205. this.y0 = 0.5;
  2206. this.x1 = 0.5;
  2207. this.y1 = 0.5;
  2208. this.promise = Promise.resolve(true);
  2209. }
  2210.  
  2211. GradientContainer.prototype.TYPES = {
  2212. LINEAR: 1,
  2213. RADIAL: 2
  2214. };
  2215.  
  2216. module.exports = GradientContainer;
  2217.  
  2218. },{"./promise":18}],12:[function(require,module,exports){
  2219. var Promise = require('./promise');
  2220.  
  2221. function ImageContainer(src, cors) {
  2222. this.src = src;
  2223. this.image = new Image();
  2224. var self = this;
  2225. this.tainted = null;
  2226. this.promise = new Promise(function(resolve, reject) {
  2227. self.image.onload = resolve;
  2228. self.image.onerror = reject;
  2229. if (cors) {
  2230. self.image.crossOrigin = "anonymous";
  2231. }
  2232. self.image.src = src;
  2233. if (self.image.complete === true) {
  2234. resolve(self.image);
  2235. }
  2236. });
  2237. }
  2238.  
  2239. module.exports = ImageContainer;
  2240.  
  2241. },{"./promise":18}],13:[function(require,module,exports){
  2242. var Promise = require('./promise');
  2243. var log = require('./log');
  2244. var ImageContainer = require('./imagecontainer');
  2245. var DummyImageContainer = require('./dummyimagecontainer');
  2246. var ProxyImageContainer = require('./proxyimagecontainer');
  2247. var FrameContainer = require('./framecontainer');
  2248. var SVGContainer = require('./svgcontainer');
  2249. var SVGNodeContainer = require('./svgnodecontainer');
  2250. var LinearGradientContainer = require('./lineargradientcontainer');
  2251. var WebkitGradientContainer = require('./webkitgradientcontainer');
  2252. var bind = require('./utils').bind;
  2253.  
  2254. function ImageLoader(options, support) {
  2255. this.link = null;
  2256. this.options = options;
  2257. this.support = support;
  2258. this.origin = this.getOrigin(window.location.href);
  2259. }
  2260.  
  2261. ImageLoader.prototype.findImages = function(nodes) {
  2262. var images = [];
  2263. nodes.reduce(function(imageNodes, container) {
  2264. switch(container.node.nodeName) {
  2265. case "IMG":
  2266. return imageNodes.concat([{
  2267. args: [container.node.src],
  2268. method: "url"
  2269. }]);
  2270. case "svg":
  2271. case "IFRAME":
  2272. return imageNodes.concat([{
  2273. args: [container.node],
  2274. method: container.node.nodeName
  2275. }]);
  2276. }
  2277. return imageNodes;
  2278. }, []).forEach(this.addImage(images, this.loadImage), this);
  2279. return images;
  2280. };
  2281.  
  2282. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  2283. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  2284. return images;
  2285. };
  2286.  
  2287. ImageLoader.prototype.addImage = function(images, callback) {
  2288. return function(newImage) {
  2289. newImage.args.forEach(function(image) {
  2290. if (!this.imageExists(images, image)) {
  2291. images.splice(0, 0, callback.call(this, newImage));
  2292. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
  2293. }
  2294. }, this);
  2295. };
  2296. };
  2297.  
  2298. ImageLoader.prototype.hasImageBackground = function(imageData) {
  2299. return imageData.method !== "none";
  2300. };
  2301.  
  2302. ImageLoader.prototype.loadImage = function(imageData) {
  2303. if (imageData.method === "url") {
  2304. var src = imageData.args[0];
  2305. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  2306. return new SVGContainer(src);
  2307. } else if (src.match(/data:image\/.*;base64,/i)) {
  2308. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
  2309. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  2310. return new ImageContainer(src, false);
  2311. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  2312. return new ImageContainer(src, true);
  2313. } else if (this.options.proxy) {
  2314. return new ProxyImageContainer(src, this.options.proxy);
  2315. } else {
  2316. return new DummyImageContainer(src);
  2317. }
  2318. } else if (imageData.method === "linear-gradient") {
  2319. return new LinearGradientContainer(imageData);
  2320. } else if (imageData.method === "gradient") {
  2321. return new WebkitGradientContainer(imageData);
  2322. } else if (imageData.method === "svg") {
  2323. return new SVGNodeContainer(imageData.args[0], this.support.svg);
  2324. } else if (imageData.method === "IFRAME") {
  2325. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
  2326. } else {
  2327. return new DummyImageContainer(imageData);
  2328. }
  2329. };
  2330.  
  2331. ImageLoader.prototype.isSVG = function(src) {
  2332. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
  2333. };
  2334.  
  2335. ImageLoader.prototype.imageExists = function(images, src) {
  2336. return images.some(function(image) {
  2337. return image.src === src;
  2338. });
  2339. };
  2340.  
  2341. ImageLoader.prototype.isSameOrigin = function(url) {
  2342. return (this.getOrigin(url) === this.origin);
  2343. };
  2344.  
  2345. ImageLoader.prototype.getOrigin = function(url) {
  2346. var link = this.link || (this.link = document.createElement("a"));
  2347. link.href = url;
  2348. link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
  2349. return link.protocol + link.hostname + link.port;
  2350. };
  2351.  
  2352. ImageLoader.prototype.getPromise = function(container) {
  2353. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  2354. var dummy = new DummyImageContainer(container.src);
  2355. return dummy.promise.then(function(image) {
  2356. container.image = image;
  2357. });
  2358. });
  2359. };
  2360.  
  2361. ImageLoader.prototype.get = function(src) {
  2362. var found = null;
  2363. return this.images.some(function(img) {
  2364. return (found = img).src === src;
  2365. }) ? found : null;
  2366. };
  2367.  
  2368. ImageLoader.prototype.fetch = function(nodes) {
  2369. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  2370. this.images.forEach(function(image, index) {
  2371. image.promise.then(function() {
  2372. log("Succesfully loaded image #"+ (index+1), image);
  2373. }, function(e) {
  2374. log("Failed loading image #"+ (index+1), image, e);
  2375. });
  2376. });
  2377. this.ready = Promise.all(this.images.map(this.getPromise, this));
  2378. log("Finished searching images");
  2379. return this;
  2380. };
  2381.  
  2382. ImageLoader.prototype.timeout = function(container, timeout) {
  2383. var timer;
  2384. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  2385. timer = setTimeout(function() {
  2386. log("Timed out loading image", container);
  2387. reject(container);
  2388. }, timeout);
  2389. })]).then(function(container) {
  2390. clearTimeout(timer);
  2391. return container;
  2392. });
  2393. promise['catch'](function() {
  2394. clearTimeout(timer);
  2395. });
  2396. return promise;
  2397. };
  2398.  
  2399. module.exports = ImageLoader;
  2400.  
  2401. },{"./dummyimagecontainer":7,"./framecontainer":10,"./imagecontainer":12,"./lineargradientcontainer":14,"./log":15,"./promise":18,"./proxyimagecontainer":20,"./svgcontainer":26,"./svgnodecontainer":27,"./utils":29,"./webkitgradientcontainer":30}],14:[function(require,module,exports){
  2402. var GradientContainer = require('./gradientcontainer');
  2403. var Color = require('./color');
  2404.  
  2405. function LinearGradientContainer(imageData) {
  2406. GradientContainer.apply(this, arguments);
  2407. this.type = this.TYPES.LINEAR;
  2408.  
  2409. var hasDirection = imageData.args[0].match(this.stepRegExp) === null;
  2410.  
  2411. if (hasDirection) {
  2412. imageData.args[0].split(" ").reverse().forEach(function(position) {
  2413. switch(position) {
  2414. case "left":
  2415. this.x0 = 0;
  2416. this.x1 = 1;
  2417. break;
  2418. case "top":
  2419. this.y0 = 0;
  2420. this.y1 = 1;
  2421. break;
  2422. case "right":
  2423. this.x0 = 1;
  2424. this.x1 = 0;
  2425. break;
  2426. case "bottom":
  2427. this.y0 = 1;
  2428. this.y1 = 0;
  2429. break;
  2430. case "to":
  2431. var y0 = this.y0;
  2432. var x0 = this.x0;
  2433. this.y0 = this.y1;
  2434. this.x0 = this.x1;
  2435. this.x1 = x0;
  2436. this.y1 = y0;
  2437. break;
  2438. }
  2439. }, this);
  2440. } else {
  2441. this.y0 = 0;
  2442. this.y1 = 1;
  2443. }
  2444.  
  2445. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  2446. var colorStopMatch = colorStop.match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)|\w+)\s*(\d{1,3})?(%|px)?/);
  2447. return {
  2448. color: new Color(colorStopMatch[1]),
  2449. stop: colorStopMatch[3] === "%" ? colorStopMatch[2] / 100 : null
  2450. };
  2451. }, this);
  2452.  
  2453. if (this.colorStops[0].stop === null) {
  2454. this.colorStops[0].stop = 0;
  2455. }
  2456.  
  2457. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  2458. this.colorStops[this.colorStops.length - 1].stop = 1;
  2459. }
  2460.  
  2461. this.colorStops.forEach(function(colorStop, index) {
  2462. if (colorStop.stop === null) {
  2463. this.colorStops.slice(index).some(function(find, count) {
  2464. if (find.stop !== null) {
  2465. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  2466. return true;
  2467. } else {
  2468. return false;
  2469. }
  2470. }, this);
  2471. }
  2472. }, this);
  2473. }
  2474.  
  2475. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  2476.  
  2477. LinearGradientContainer.prototype.stepRegExp = /((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/;
  2478.  
  2479. module.exports = LinearGradientContainer;
  2480.  
  2481. },{"./color":5,"./gradientcontainer":11}],15:[function(require,module,exports){
  2482. module.exports = function() {
  2483. if (window.html2canvas.logging && window.console && window.console.log) {
  2484. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - window.html2canvas.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
  2485. }
  2486. };
  2487.  
  2488. },{}],16:[function(require,module,exports){
  2489. var Color = require('./color');
  2490. var utils = require('./utils');
  2491. var getBounds = utils.getBounds;
  2492. var parseBackgrounds = utils.parseBackgrounds;
  2493. var offsetBounds = utils.offsetBounds;
  2494.  
  2495. function NodeContainer(node, parent) {
  2496. this.node = node;
  2497. this.parent = parent;
  2498. this.stack = null;
  2499. this.bounds = null;
  2500. this.borders = null;
  2501. this.clip = [];
  2502. this.backgroundClip = [];
  2503. this.offsetBounds = null;
  2504. this.visible = null;
  2505. this.computedStyles = null;
  2506. this.colors = {};
  2507. this.styles = {};
  2508. this.backgroundImages = null;
  2509. this.transformData = null;
  2510. this.transformMatrix = null;
  2511. this.isPseudoElement = false;
  2512. this.opacity = null;
  2513. }
  2514.  
  2515. NodeContainer.prototype.cloneTo = function(stack) {
  2516. stack.visible = this.visible;
  2517. stack.borders = this.borders;
  2518. stack.bounds = this.bounds;
  2519. stack.clip = this.clip;
  2520. stack.backgroundClip = this.backgroundClip;
  2521. stack.computedStyles = this.computedStyles;
  2522. stack.styles = this.styles;
  2523. stack.backgroundImages = this.backgroundImages;
  2524. stack.opacity = this.opacity;
  2525. };
  2526.  
  2527. NodeContainer.prototype.getOpacity = function() {
  2528. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
  2529. };
  2530.  
  2531. NodeContainer.prototype.assignStack = function(stack) {
  2532. this.stack = stack;
  2533. stack.children.push(this);
  2534. };
  2535.  
  2536. NodeContainer.prototype.isElementVisible = function() {
  2537. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
  2538. this.css('display') !== "none" &&
  2539. this.css('visibility') !== "hidden" &&
  2540. !this.node.hasAttribute("data-html2canvas-ignore") &&
  2541. (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
  2542. );
  2543. };
  2544.  
  2545. NodeContainer.prototype.css = function(attribute) {
  2546. if (!this.computedStyles) {
  2547. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
  2548. }
  2549.  
  2550. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
  2551. };
  2552.  
  2553. NodeContainer.prototype.prefixedCss = function(attribute) {
  2554. var prefixes = ["webkit", "moz", "ms", "o"];
  2555. var value = this.css(attribute);
  2556. if (value === undefined) {
  2557. prefixes.some(function(prefix) {
  2558. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  2559. return value !== undefined;
  2560. }, this);
  2561. }
  2562. return value === undefined ? null : value;
  2563. };
  2564.  
  2565. NodeContainer.prototype.computedStyle = function(type) {
  2566. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
  2567. };
  2568.  
  2569. NodeContainer.prototype.cssInt = function(attribute) {
  2570. var value = parseInt(this.css(attribute), 10);
  2571. return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
  2572. };
  2573.  
  2574. NodeContainer.prototype.color = function(attribute) {
  2575. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
  2576. };
  2577.  
  2578. NodeContainer.prototype.cssFloat = function(attribute) {
  2579. var value = parseFloat(this.css(attribute));
  2580. return (isNaN(value)) ? 0 : value;
  2581. };
  2582.  
  2583. NodeContainer.prototype.fontWeight = function() {
  2584. var weight = this.css("fontWeight");
  2585. switch(parseInt(weight, 10)){
  2586. case 401:
  2587. weight = "bold";
  2588. break;
  2589. case 400:
  2590. weight = "normal";
  2591. break;
  2592. }
  2593. return weight;
  2594. };
  2595.  
  2596. NodeContainer.prototype.parseClip = function() {
  2597. var matches = this.css('clip').match(this.CLIP);
  2598. if (matches) {
  2599. return {
  2600. top: parseInt(matches[1], 10),
  2601. right: parseInt(matches[2], 10),
  2602. bottom: parseInt(matches[3], 10),
  2603. left: parseInt(matches[4], 10)
  2604. };
  2605. }
  2606. return null;
  2607. };
  2608.  
  2609. NodeContainer.prototype.parseBackgroundImages = function() {
  2610. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
  2611. };
  2612.  
  2613. NodeContainer.prototype.cssList = function(property, index) {
  2614. var value = (this.css(property) || '').split(',');
  2615. value = value[index || 0] || value[0] || 'auto';
  2616. value = value.trim().split(' ');
  2617. if (value.length === 1) {
  2618. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
  2619. }
  2620. return value;
  2621. };
  2622.  
  2623. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  2624. var size = this.cssList("backgroundSize", index);
  2625. var width, height;
  2626.  
  2627. if (isPercentage(size[0])) {
  2628. width = bounds.width * parseFloat(size[0]) / 100;
  2629. } else if (/contain|cover/.test(size[0])) {
  2630. var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
  2631. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
  2632. } else {
  2633. width = parseInt(size[0], 10);
  2634. }
  2635.  
  2636. if (size[0] === 'auto' && size[1] === 'auto') {
  2637. height = image.height;
  2638. } else if (size[1] === 'auto') {
  2639. height = width / image.width * image.height;
  2640. } else if (isPercentage(size[1])) {
  2641. height = bounds.height * parseFloat(size[1]) / 100;
  2642. } else {
  2643. height = parseInt(size[1], 10);
  2644. }
  2645.  
  2646. if (size[0] === 'auto') {
  2647. width = height / image.height * image.width;
  2648. }
  2649.  
  2650. return {width: width, height: height};
  2651. };
  2652.  
  2653. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  2654. var position = this.cssList('backgroundPosition', index);
  2655. var left, top;
  2656.  
  2657. if (isPercentage(position[0])){
  2658. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
  2659. } else {
  2660. left = parseInt(position[0], 10);
  2661. }
  2662.  
  2663. if (position[1] === 'auto') {
  2664. top = left / image.width * image.height;
  2665. } else if (isPercentage(position[1])){
  2666. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
  2667. } else {
  2668. top = parseInt(position[1], 10);
  2669. }
  2670.  
  2671. if (position[0] === 'auto') {
  2672. left = top / image.height * image.width;
  2673. }
  2674.  
  2675. return {left: left, top: top};
  2676. };
  2677.  
  2678. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  2679. return this.cssList("backgroundRepeat", index)[0];
  2680. };
  2681.  
  2682. NodeContainer.prototype.parseTextShadows = function() {
  2683. var textShadow = this.css("textShadow");
  2684. var results = [];
  2685.  
  2686. if (textShadow && textShadow !== 'none') {
  2687. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  2688. for (var i = 0; shadows && (i < shadows.length); i++) {
  2689. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  2690. results.push({
  2691. color: new Color(s[0]),
  2692. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  2693. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  2694. blur: s[3] ? s[3].replace('px', '') : 0
  2695. });
  2696. }
  2697. }
  2698. return results;
  2699. };
  2700.  
  2701. NodeContainer.prototype.parseTransform = function() {
  2702. if (!this.transformData) {
  2703. if (this.hasTransform()) {
  2704. var offset = this.parseBounds();
  2705. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  2706. origin[0] += offset.left;
  2707. origin[1] += offset.top;
  2708. this.transformData = {
  2709. origin: origin,
  2710. matrix: this.parseTransformMatrix()
  2711. };
  2712. } else {
  2713. this.transformData = {
  2714. origin: [0, 0],
  2715. matrix: [1, 0, 0, 1, 0, 0]
  2716. };
  2717. }
  2718. }
  2719. return this.transformData;
  2720. };
  2721.  
  2722. NodeContainer.prototype.parseTransformMatrix = function() {
  2723. if (!this.transformMatrix) {
  2724. var transform = this.prefixedCss("transform");
  2725. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  2726. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
  2727. }
  2728. return this.transformMatrix;
  2729. };
  2730.  
  2731. NodeContainer.prototype.parseBounds = function() {
  2732. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
  2733. };
  2734.  
  2735. NodeContainer.prototype.hasTransform = function() {
  2736. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
  2737. };
  2738.  
  2739. NodeContainer.prototype.getValue = function() {
  2740. var value = this.node.value || "";
  2741. if (this.node.tagName === "SELECT") {
  2742. value = selectionValue(this.node);
  2743. } else if (this.node.type === "password") {
  2744. value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
  2745. }
  2746. return value.length === 0 ? (this.node.placeholder || "") : value;
  2747. };
  2748.  
  2749. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  2750. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  2751. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  2752. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  2753.  
  2754. function selectionValue(node) {
  2755. var option = node.options[node.selectedIndex || 0];
  2756. return option ? (option.text || "") : "";
  2757. }
  2758.  
  2759. function parseMatrix(match) {
  2760. if (match && match[1] === "matrix") {
  2761. return match[2].split(",").map(function(s) {
  2762. return parseFloat(s.trim());
  2763. });
  2764. } else if (match && match[1] === "matrix3d") {
  2765. var matrix3d = match[2].split(",").map(function(s) {
  2766. return parseFloat(s.trim());
  2767. });
  2768. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
  2769. }
  2770. }
  2771.  
  2772. function isPercentage(value) {
  2773. return value.toString().indexOf("%") !== -1;
  2774. }
  2775.  
  2776. function removePx(str) {
  2777. return str.replace("px", "");
  2778. }
  2779.  
  2780. function asFloat(str) {
  2781. return parseFloat(str);
  2782. }
  2783.  
  2784. module.exports = NodeContainer;
  2785.  
  2786. },{"./color":5,"./utils":29}],17:[function(require,module,exports){
  2787. var log = require('./log');
  2788. var punycode = require('punycode');
  2789. var NodeContainer = require('./nodecontainer');
  2790. var TextContainer = require('./textcontainer');
  2791. var PseudoElementContainer = require('./pseudoelementcontainer');
  2792. var FontMetrics = require('./fontmetrics');
  2793. var Color = require('./color');
  2794. var Promise = require('./promise');
  2795. var StackingContext = require('./stackingcontext');
  2796. var utils = require('./utils');
  2797. var bind = utils.bind;
  2798. var getBounds = utils.getBounds;
  2799. var parseBackgrounds = utils.parseBackgrounds;
  2800. var offsetBounds = utils.offsetBounds;
  2801.  
  2802. function NodeParser(element, renderer, support, imageLoader, options) {
  2803. log("Starting NodeParser");
  2804. this.renderer = renderer;
  2805. this.options = options;
  2806. this.range = null;
  2807. this.support = support;
  2808. this.renderQueue = [];
  2809. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  2810. var parent = new NodeContainer(element, null);
  2811. if (options.background) {
  2812. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
  2813. }
  2814. if (element === element.ownerDocument.documentElement) {
  2815. // http://www.w3.org/TR/css3-background/#special-backgrounds
  2816. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  2817. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
  2818. }
  2819. parent.visibile = parent.isElementVisible();
  2820. this.createPseudoHideStyles(element.ownerDocument);
  2821. this.disableAnimations(element.ownerDocument);
  2822. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  2823. return container.visible = container.isElementVisible();
  2824. }).map(this.getPseudoElements, this));
  2825. this.fontMetrics = new FontMetrics();
  2826. log("Fetched nodes, total:", this.nodes.length);
  2827. log("Calculate overflow clips");
  2828. this.calculateOverflowClips();
  2829. log("Start fetching images");
  2830. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  2831. this.ready = this.images.ready.then(bind(function() {
  2832. log("Images loaded, starting parsing");
  2833. log("Creating stacking contexts");
  2834. this.createStackingContexts();
  2835. log("Sorting stacking contexts");
  2836. this.sortStackingContexts(this.stack);
  2837. this.parse(this.stack);
  2838. log("Render queue created with " + this.renderQueue.length + " items");
  2839. return new Promise(bind(function(resolve) {
  2840. if (!options.async) {
  2841. this.renderQueue.forEach(this.paint, this);
  2842. resolve();
  2843. } else if (typeof(options.async) === "function") {
  2844. options.async.call(this, this.renderQueue, resolve);
  2845. } else if (this.renderQueue.length > 0){
  2846. this.renderIndex = 0;
  2847. this.asyncRenderer(this.renderQueue, resolve);
  2848. } else {
  2849. resolve();
  2850. }
  2851. }, this));
  2852. }, this));
  2853. }
  2854.  
  2855. NodeParser.prototype.calculateOverflowClips = function() {
  2856. this.nodes.forEach(function(container) {
  2857. if (isElement(container)) {
  2858. if (isPseudoElement(container)) {
  2859. container.appendToDOM();
  2860. }
  2861. container.borders = this.parseBorders(container);
  2862. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  2863. var cssClip = container.parseClip();
  2864. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  2865. clip.push([["rect",
  2866. container.bounds.left + cssClip.left,
  2867. container.bounds.top + cssClip.top,
  2868. cssClip.right - cssClip.left,
  2869. cssClip.bottom - cssClip.top
  2870. ]]);
  2871. }
  2872. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  2873. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  2874. if (isPseudoElement(container)) {
  2875. container.cleanDOM();
  2876. }
  2877. } else if (isTextNode(container)) {
  2878. container.clip = hasParentClip(container) ? container.parent.clip : [];
  2879. }
  2880. if (!isPseudoElement(container)) {
  2881. container.bounds = null;
  2882. }
  2883. }, this);
  2884. };
  2885.  
  2886. function hasParentClip(container) {
  2887. return container.parent && container.parent.clip.length;
  2888. }
  2889.  
  2890. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  2891. asyncTimer = asyncTimer || Date.now();
  2892. this.paint(queue[this.renderIndex++]);
  2893. if (queue.length === this.renderIndex) {
  2894. resolve();
  2895. } else if (asyncTimer + 20 > Date.now()) {
  2896. this.asyncRenderer(queue, resolve, asyncTimer);
  2897. } else {
  2898. setTimeout(bind(function() {
  2899. this.asyncRenderer(queue, resolve);
  2900. }, this), 0);
  2901. }
  2902. };
  2903.  
  2904. NodeParser.prototype.createPseudoHideStyles = function(document) {
  2905. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
  2906. '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
  2907. };
  2908.  
  2909. NodeParser.prototype.disableAnimations = function(document) {
  2910. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
  2911. '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
  2912. };
  2913.  
  2914. NodeParser.prototype.createStyles = function(document, styles) {
  2915. var hidePseudoElements = document.createElement('style');
  2916. hidePseudoElements.innerHTML = styles;
  2917. document.body.appendChild(hidePseudoElements);
  2918. };
  2919.  
  2920. NodeParser.prototype.getPseudoElements = function(container) {
  2921. var nodes = [[container]];
  2922. if (container.node.nodeType === Node.ELEMENT_NODE) {
  2923. var before = this.getPseudoElement(container, ":before");
  2924. var after = this.getPseudoElement(container, ":after");
  2925.  
  2926. if (before) {
  2927. nodes.push(before);
  2928. }
  2929.  
  2930. if (after) {
  2931. nodes.push(after);
  2932. }
  2933. }
  2934. return flatten(nodes);
  2935. };
  2936.  
  2937. function toCamelCase(str) {
  2938. return str.replace(/(\-[a-z])/g, function(match){
  2939. return match.toUpperCase().replace('-','');
  2940. });
  2941. }
  2942.  
  2943. NodeParser.prototype.getPseudoElement = function(container, type) {
  2944. var style = container.computedStyle(type);
  2945. if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  2946. return null;
  2947. }
  2948.  
  2949. var content = stripQuotes(style.content);
  2950. var isImage = content.substr(0, 3) === 'url';
  2951. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  2952. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  2953.  
  2954. for (var i = style.length-1; i >= 0; i--) {
  2955. var property = toCamelCase(style.item(i));
  2956. pseudoNode.style[property] = style[property];
  2957. }
  2958.  
  2959. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  2960.  
  2961. if (isImage) {
  2962. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  2963. return [pseudoContainer];
  2964. } else {
  2965. var text = document.createTextNode(content);
  2966. pseudoNode.appendChild(text);
  2967. return [pseudoContainer, new TextContainer(text, pseudoContainer)];
  2968. }
  2969. };
  2970.  
  2971. NodeParser.prototype.getChildren = function(parentContainer) {
  2972. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  2973. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  2974. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
  2975. }, this));
  2976. };
  2977.  
  2978. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  2979. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  2980. container.cloneTo(stack);
  2981. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  2982. parentStack.contexts.push(stack);
  2983. container.stack = stack;
  2984. };
  2985.  
  2986. NodeParser.prototype.createStackingContexts = function() {
  2987. this.nodes.forEach(function(container) {
  2988. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  2989. this.newStackingContext(container, true);
  2990. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  2991. this.newStackingContext(container, false);
  2992. } else {
  2993. container.assignStack(container.parent.stack);
  2994. }
  2995. }, this);
  2996. };
  2997.  
  2998. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  2999. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
  3000. };
  3001.  
  3002. NodeParser.prototype.isRootElement = function(container) {
  3003. return container.parent === null;
  3004. };
  3005.  
  3006. NodeParser.prototype.sortStackingContexts = function(stack) {
  3007. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  3008. stack.contexts.forEach(this.sortStackingContexts, this);
  3009. };
  3010.  
  3011. NodeParser.prototype.parseTextBounds = function(container) {
  3012. return function(text, index, textList) {
  3013. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  3014. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  3015. var offset = textList.slice(0, index).join("").length;
  3016. return this.getRangeBounds(container.node, offset, text.length);
  3017. } else if (container.node && typeof(container.node.data) === "string") {
  3018. var replacementNode = container.node.splitText(text.length);
  3019. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  3020. container.node = replacementNode;
  3021. return bounds;
  3022. }
  3023. } else if(!this.support.rangeBounds || container.parent.hasTransform()){
  3024. container.node = container.node.splitText(text.length);
  3025. }
  3026. return {};
  3027. };
  3028. };
  3029.  
  3030. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  3031. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  3032. var parent = node.parentNode,
  3033. backupText = node.cloneNode(true);
  3034.  
  3035. wrapper.appendChild(node.cloneNode(true));
  3036. parent.replaceChild(wrapper, node);
  3037. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  3038. parent.replaceChild(backupText, wrapper);
  3039. return bounds;
  3040. };
  3041.  
  3042. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  3043. var range = this.range || (this.range = node.ownerDocument.createRange());
  3044. range.setStart(node, offset);
  3045. range.setEnd(node, offset + length);
  3046. return range.getBoundingClientRect();
  3047. };
  3048.  
  3049. function ClearTransform() {}
  3050.  
  3051. NodeParser.prototype.parse = function(stack) {
  3052. // http://www.w3.org/TR/CSS21/visuren.html#z-index
  3053. var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
  3054. var descendantElements = stack.children.filter(isElement);
  3055. var descendantNonFloats = descendantElements.filter(not(isFloating));
  3056. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
  3057. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
  3058. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
  3059. 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.
  3060. var text = stack.children.filter(isTextNode).filter(hasText);
  3061. var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
  3062. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
  3063. .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  3064. this.renderQueue.push(container);
  3065. if (isStackingContext(container)) {
  3066. this.parse(container);
  3067. this.renderQueue.push(new ClearTransform());
  3068. }
  3069. }, this);
  3070. };
  3071.  
  3072. NodeParser.prototype.paint = function(container) {
  3073. try {
  3074. if (container instanceof ClearTransform) {
  3075. this.renderer.ctx.restore();
  3076. } else if (isTextNode(container)) {
  3077. if (isPseudoElement(container.parent)) {
  3078. container.parent.appendToDOM();
  3079. }
  3080. this.paintText(container);
  3081. if (isPseudoElement(container.parent)) {
  3082. container.parent.cleanDOM();
  3083. }
  3084. } else {
  3085. this.paintNode(container);
  3086. }
  3087. } catch(e) {
  3088. log(e);
  3089. if (this.options.strict) {
  3090. throw e;
  3091. }
  3092. }
  3093. };
  3094.  
  3095. NodeParser.prototype.paintNode = function(container) {
  3096. if (isStackingContext(container)) {
  3097. this.renderer.setOpacity(container.opacity);
  3098. this.renderer.ctx.save();
  3099. if (container.hasTransform()) {
  3100. this.renderer.setTransform(container.parseTransform());
  3101. }
  3102. }
  3103.  
  3104. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  3105. this.paintCheckbox(container);
  3106. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  3107. this.paintRadio(container);
  3108. } else {
  3109. this.paintElement(container);
  3110. }
  3111. };
  3112.  
  3113. NodeParser.prototype.paintElement = function(container) {
  3114. var bounds = container.parseBounds();
  3115. this.renderer.clip(container.backgroundClip, function() {
  3116. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
  3117. }, this);
  3118.  
  3119. this.renderer.clip(container.clip, function() {
  3120. this.renderer.renderBorders(container.borders.borders);
  3121. }, this);
  3122.  
  3123. this.renderer.clip(container.backgroundClip, function() {
  3124. switch (container.node.nodeName) {
  3125. case "svg":
  3126. case "IFRAME":
  3127. var imgContainer = this.images.get(container.node);
  3128. if (imgContainer) {
  3129. this.renderer.renderImage(container, bounds, container.borders, imgContainer);
  3130. } else {
  3131. log("Error loading <" + container.node.nodeName + ">", container.node);
  3132. }
  3133. break;
  3134. case "IMG":
  3135. var imageContainer = this.images.get(container.node.src);
  3136. if (imageContainer) {
  3137. this.renderer.renderImage(container, bounds, container.borders, imageContainer);
  3138. } else {
  3139. log("Error loading <img>", container.node.src);
  3140. }
  3141. break;
  3142. case "CANVAS":
  3143. this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
  3144. break;
  3145. case "SELECT":
  3146. case "INPUT":
  3147. case "TEXTAREA":
  3148. this.paintFormValue(container);
  3149. break;
  3150. }
  3151. }, this);
  3152. };
  3153.  
  3154. NodeParser.prototype.paintCheckbox = function(container) {
  3155. var b = container.parseBounds();
  3156.  
  3157. var size = Math.min(b.width, b.height);
  3158. var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
  3159. var r = [3, 3];
  3160. var radius = [r, r, r, r];
  3161. var borders = [1,1,1,1].map(function(w) {
  3162. return {color: new Color('#A5A5A5'), width: w};
  3163. });
  3164.  
  3165. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  3166.  
  3167. this.renderer.clip(container.backgroundClip, function() {
  3168. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  3169. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  3170. if (container.node.checked) {
  3171. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  3172. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
  3173. }
  3174. }, this);
  3175. };
  3176.  
  3177. NodeParser.prototype.paintRadio = function(container) {
  3178. var bounds = container.parseBounds();
  3179.  
  3180. var size = Math.min(bounds.width, bounds.height) - 2;
  3181.  
  3182. this.renderer.clip(container.backgroundClip, function() {
  3183. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  3184. if (container.node.checked) {
  3185. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
  3186. }
  3187. }, this);
  3188. };
  3189.  
  3190. NodeParser.prototype.paintFormValue = function(container) {
  3191. var value = container.getValue();
  3192. if (value.length > 0) {
  3193. var document = container.node.ownerDocument;
  3194. var wrapper = document.createElement('html2canvaswrapper');
  3195. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
  3196. 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
  3197. 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
  3198. 'boxSizing', 'whiteSpace', 'wordWrap'];
  3199.  
  3200. properties.forEach(function(property) {
  3201. try {
  3202. wrapper.style[property] = container.css(property);
  3203. } catch(e) {
  3204. // Older IE has issues with "border"
  3205. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
  3206. }
  3207. });
  3208. var bounds = container.parseBounds();
  3209. wrapper.style.position = "fixed";
  3210. wrapper.style.left = bounds.left + "px";
  3211. wrapper.style.top = bounds.top + "px";
  3212. wrapper.textContent = value;
  3213. document.body.appendChild(wrapper);
  3214. this.paintText(new TextContainer(wrapper.firstChild, container));
  3215. document.body.removeChild(wrapper);
  3216. }
  3217. };
  3218.  
  3219. NodeParser.prototype.paintText = function(container) {
  3220. container.applyTextTransform();
  3221. var characters = punycode.ucs2.decode(container.node.data);
  3222. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  3223. return punycode.ucs2.encode([character]);
  3224. });
  3225.  
  3226. var weight = container.parent.fontWeight();
  3227. var size = container.parent.css('fontSize');
  3228. var family = container.parent.css('fontFamily');
  3229. var shadows = container.parent.parseTextShadows();
  3230.  
  3231. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  3232. if (shadows.length) {
  3233. // TODO: support multiple text shadows
  3234. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
  3235. } else {
  3236. this.renderer.clearShadow();
  3237. }
  3238.  
  3239. this.renderer.clip(container.parent.clip, function() {
  3240. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  3241. if (bounds) {
  3242. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  3243. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
  3244. }
  3245. }, this);
  3246. }, this);
  3247. };
  3248.  
  3249. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  3250. switch(container.css("textDecoration").split(" ")[0]) {
  3251. case "underline":
  3252. // Draws a line at the baseline of the font
  3253. // 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
  3254. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  3255. break;
  3256. case "overline":
  3257. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  3258. break;
  3259. case "line-through":
  3260. // TODO try and find exact position for line-through
  3261. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  3262. break;
  3263. }
  3264. };
  3265.  
  3266. var borderColorTransforms = {
  3267. inset: [
  3268. ["darken", 0.60],
  3269. ["darken", 0.10],
  3270. ["darken", 0.10],
  3271. ["darken", 0.60]
  3272. ]
  3273. };
  3274.  
  3275. NodeParser.prototype.parseBorders = function(container) {
  3276. var nodeBounds = container.parseBounds();
  3277. var radius = getBorderRadiusData(container);
  3278. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  3279. var style = container.css('border' + side + 'Style');
  3280. var color = container.color('border' + side + 'Color');
  3281. if (style === "inset" && color.isBlack()) {
  3282. color = new Color([255, 255, 255, color.a]); // this is wrong, but
  3283. }
  3284. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  3285. return {
  3286. width: container.cssInt('border' + side + 'Width'),
  3287. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  3288. args: null
  3289. };
  3290. });
  3291. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  3292.  
  3293. return {
  3294. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  3295. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  3296. };
  3297. };
  3298.  
  3299. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  3300. return borders.map(function(border, borderSide) {
  3301. if (border.width > 0) {
  3302. var bx = nodeBounds.left;
  3303. var by = nodeBounds.top;
  3304. var bw = nodeBounds.width;
  3305. var bh = nodeBounds.height - (borders[2].width);
  3306.  
  3307. switch(borderSide) {
  3308. case 0:
  3309. // top border
  3310. bh = borders[0].width;
  3311. border.args = drawSide({
  3312. c1: [bx, by],
  3313. c2: [bx + bw, by],
  3314. c3: [bx + bw - borders[1].width, by + bh],
  3315. c4: [bx + borders[3].width, by + bh]
  3316. }, radius[0], radius[1],
  3317. borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  3318. break;
  3319. case 1:
  3320. // right border
  3321. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  3322. bw = borders[1].width;
  3323.  
  3324. border.args = drawSide({
  3325. c1: [bx + bw, by],
  3326. c2: [bx + bw, by + bh + borders[2].width],
  3327. c3: [bx, by + bh],
  3328. c4: [bx, by + borders[0].width]
  3329. }, radius[1], radius[2],
  3330. borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  3331. break;
  3332. case 2:
  3333. // bottom border
  3334. by = (by + nodeBounds.height) - (borders[2].width);
  3335. bh = borders[2].width;
  3336. border.args = drawSide({
  3337. c1: [bx + bw, by + bh],
  3338. c2: [bx, by + bh],
  3339. c3: [bx + borders[3].width, by],
  3340. c4: [bx + bw - borders[3].width, by]
  3341. }, radius[2], radius[3],
  3342. borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  3343. break;
  3344. case 3:
  3345. // left border
  3346. bw = borders[3].width;
  3347. border.args = drawSide({
  3348. c1: [bx, by + bh + borders[2].width],
  3349. c2: [bx, by],
  3350. c3: [bx + bw, by + borders[0].width],
  3351. c4: [bx + bw, by + bh]
  3352. }, radius[3], radius[0],
  3353. borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  3354. break;
  3355. }
  3356. }
  3357. return border;
  3358. });
  3359. }
  3360.  
  3361. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  3362. var backgroundClip = container.css('backgroundClip'),
  3363. borderArgs = [];
  3364.  
  3365. switch(backgroundClip) {
  3366. case "content-box":
  3367. case "padding-box":
  3368. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  3369. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  3370. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  3371. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  3372. break;
  3373.  
  3374. default:
  3375. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  3376. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  3377. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  3378. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  3379. break;
  3380. }
  3381.  
  3382. return borderArgs;
  3383. };
  3384.  
  3385. function getCurvePoints(x, y, r1, r2) {
  3386. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  3387. var ox = (r1) * kappa, // control point offset horizontal
  3388. oy = (r2) * kappa, // control point offset vertical
  3389. xm = x + r1, // x-middle
  3390. ym = y + r2; // y-middle
  3391. return {
  3392. topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
  3393. topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
  3394. bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
  3395. bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
  3396. };
  3397. }
  3398.  
  3399. function calculateCurvePoints(bounds, borderRadius, borders) {
  3400. var x = bounds.left,
  3401. y = bounds.top,
  3402. width = bounds.width,
  3403. height = bounds.height,
  3404.  
  3405. tlh = borderRadius[0][0],
  3406. tlv = borderRadius[0][1],
  3407. trh = borderRadius[1][0],
  3408. trv = borderRadius[1][1],
  3409. brh = borderRadius[2][0],
  3410. brv = borderRadius[2][1],
  3411. blh = borderRadius[3][0],
  3412. blv = borderRadius[3][1];
  3413.  
  3414. var topWidth = width - trh,
  3415. rightHeight = height - brv,
  3416. bottomWidth = width - brh,
  3417. leftHeight = height - blv;
  3418.  
  3419. return {
  3420. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  3421. 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),
  3422. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  3423. 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),
  3424. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  3425. 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),
  3426. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  3427. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  3428. };
  3429. }
  3430.  
  3431. function bezierCurve(start, startControl, endControl, end) {
  3432. var lerp = function (a, b, t) {
  3433. return {
  3434. x: a.x + (b.x - a.x) * t,
  3435. y: a.y + (b.y - a.y) * t
  3436. };
  3437. };
  3438.  
  3439. return {
  3440. start: start,
  3441. startControl: startControl,
  3442. endControl: endControl,
  3443. end: end,
  3444. subdivide: function(t) {
  3445. var ab = lerp(start, startControl, t),
  3446. bc = lerp(startControl, endControl, t),
  3447. cd = lerp(endControl, end, t),
  3448. abbc = lerp(ab, bc, t),
  3449. bccd = lerp(bc, cd, t),
  3450. dest = lerp(abbc, bccd, t);
  3451. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
  3452. },
  3453. curveTo: function(borderArgs) {
  3454. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
  3455. },
  3456. curveToReversed: function(borderArgs) {
  3457. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
  3458. }
  3459. };
  3460. }
  3461.  
  3462. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  3463. var borderArgs = [];
  3464.  
  3465. if (radius1[0] > 0 || radius1[1] > 0) {
  3466. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  3467. outer1[1].curveTo(borderArgs);
  3468. } else {
  3469. borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
  3470. }
  3471.  
  3472. if (radius2[0] > 0 || radius2[1] > 0) {
  3473. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  3474. outer2[0].curveTo(borderArgs);
  3475. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  3476. inner2[0].curveToReversed(borderArgs);
  3477. } else {
  3478. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  3479. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
  3480. }
  3481.  
  3482. if (radius1[0] > 0 || radius1[1] > 0) {
  3483. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  3484. inner1[1].curveToReversed(borderArgs);
  3485. } else {
  3486. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
  3487. }
  3488.  
  3489. return borderArgs;
  3490. }
  3491.  
  3492. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  3493. if (radius1[0] > 0 || radius1[1] > 0) {
  3494. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  3495. corner1[0].curveTo(borderArgs);
  3496. corner1[1].curveTo(borderArgs);
  3497. } else {
  3498. borderArgs.push(["line", x, y]);
  3499. }
  3500.  
  3501. if (radius2[0] > 0 || radius2[1] > 0) {
  3502. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
  3503. }
  3504. }
  3505.  
  3506. function negativeZIndex(container) {
  3507. return container.cssInt("zIndex") < 0;
  3508. }
  3509.  
  3510. function positiveZIndex(container) {
  3511. return container.cssInt("zIndex") > 0;
  3512. }
  3513.  
  3514. function zIndex0(container) {
  3515. return container.cssInt("zIndex") === 0;
  3516. }
  3517.  
  3518. function inlineLevel(container) {
  3519. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  3520. }
  3521.  
  3522. function isStackingContext(container) {
  3523. return (container instanceof StackingContext);
  3524. }
  3525.  
  3526. function hasText(container) {
  3527. return container.node.data.trim().length > 0;
  3528. }
  3529.  
  3530. function noLetterSpacing(container) {
  3531. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
  3532. }
  3533.  
  3534. function getBorderRadiusData(container) {
  3535. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  3536. var value = container.css('border' + side + 'Radius');
  3537. var arr = value.split(" ");
  3538. if (arr.length <= 1) {
  3539. arr[1] = arr[0];
  3540. }
  3541. return arr.map(asInt);
  3542. });
  3543. }
  3544.  
  3545. function renderableNode(node) {
  3546. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
  3547. }
  3548.  
  3549. function isPositionedForStacking(container) {
  3550. var position = container.css("position");
  3551. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  3552. return zIndex !== "auto";
  3553. }
  3554.  
  3555. function isPositioned(container) {
  3556. return container.css("position") !== "static";
  3557. }
  3558.  
  3559. function isFloating(container) {
  3560. return container.css("float") !== "none";
  3561. }
  3562.  
  3563. function isInlineBlock(container) {
  3564. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
  3565. }
  3566.  
  3567. function not(callback) {
  3568. var context = this;
  3569. return function() {
  3570. return !callback.apply(context, arguments);
  3571. };
  3572. }
  3573.  
  3574. function isElement(container) {
  3575. return container.node.nodeType === Node.ELEMENT_NODE;
  3576. }
  3577.  
  3578. function isPseudoElement(container) {
  3579. return container.isPseudoElement === true;
  3580. }
  3581.  
  3582. function isTextNode(container) {
  3583. return container.node.nodeType === Node.TEXT_NODE;
  3584. }
  3585.  
  3586. function zIndexSort(contexts) {
  3587. return function(a, b) {
  3588. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
  3589. };
  3590. }
  3591.  
  3592. function hasOpacity(container) {
  3593. return container.getOpacity() < 1;
  3594. }
  3595.  
  3596. function asInt(value) {
  3597. return parseInt(value, 10);
  3598. }
  3599.  
  3600. function getWidth(border) {
  3601. return border.width;
  3602. }
  3603.  
  3604. function nonIgnoredElement(nodeContainer) {
  3605. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
  3606. }
  3607.  
  3608. function flatten(arrays) {
  3609. return [].concat.apply([], arrays);
  3610. }
  3611.  
  3612. function stripQuotes(content) {
  3613. var first = content.substr(0, 1);
  3614. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
  3615. }
  3616.  
  3617. function getWords(characters) {
  3618. var words = [], i = 0, onWordBoundary = false, word;
  3619. while(characters.length) {
  3620. if (isWordBoundary(characters[i]) === onWordBoundary) {
  3621. word = characters.splice(0, i);
  3622. if (word.length) {
  3623. words.push(punycode.ucs2.encode(word));
  3624. }
  3625. onWordBoundary =! onWordBoundary;
  3626. i = 0;
  3627. } else {
  3628. i++;
  3629. }
  3630.  
  3631. if (i >= characters.length) {
  3632. word = characters.splice(0, i);
  3633. if (word.length) {
  3634. words.push(punycode.ucs2.encode(word));
  3635. }
  3636. }
  3637. }
  3638. return words;
  3639. }
  3640.  
  3641. function isWordBoundary(characterCode) {
  3642. return [
  3643. 32, // <space>
  3644. 13, // \r
  3645. 10, // \n
  3646. 9, // \t
  3647. 45 // -
  3648. ].indexOf(characterCode) !== -1;
  3649. }
  3650.  
  3651. function hasUnicode(string) {
  3652. return (/[^\u0000-\u00ff]/).test(string);
  3653. }
  3654.  
  3655. module.exports = NodeParser;
  3656.  
  3657. },{"./color":5,"./fontmetrics":9,"./log":15,"./nodecontainer":16,"./promise":18,"./pseudoelementcontainer":21,"./stackingcontext":24,"./textcontainer":28,"./utils":29,"punycode":3}],18:[function(require,module,exports){
  3658. module.exports = require('es6-promise').Promise;
  3659.  
  3660. },{"es6-promise":1}],19:[function(require,module,exports){
  3661. var Promise = require('./promise');
  3662. var XHR = require('./xhr');
  3663. var utils = require('./utils');
  3664. var log = require('./log');
  3665. var createWindowClone = require('./clone');
  3666. var decode64 = utils.decode64;
  3667.  
  3668. function Proxy(src, proxyUrl, document) {
  3669. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  3670. if (!proxyUrl) {
  3671. return Promise.reject("No proxy configured");
  3672. }
  3673. var callback = createCallback(supportsCORS);
  3674. var url = createProxyUrl(proxyUrl, src, callback);
  3675.  
  3676. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  3677. return decode64(response.content);
  3678. }));
  3679. }
  3680. var proxyCount = 0;
  3681.  
  3682. function ProxyURL(src, proxyUrl, document) {
  3683. var supportsCORSImage = ('crossOrigin' in new Image());
  3684. var callback = createCallback(supportsCORSImage);
  3685. var url = createProxyUrl(proxyUrl, src, callback);
  3686. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  3687. return "data:" + response.type + ";base64," + response.content;
  3688. }));
  3689. }
  3690.  
  3691. function jsonp(document, url, callback) {
  3692. return new Promise(function(resolve, reject) {
  3693. var s = document.createElement("script");
  3694. var cleanup = function() {
  3695. delete window.html2canvas.proxy[callback];
  3696. document.body.removeChild(s);
  3697. };
  3698. window.html2canvas.proxy[callback] = function(response) {
  3699. cleanup();
  3700. resolve(response);
  3701. };
  3702. s.src = url;
  3703. s.onerror = function(e) {
  3704. cleanup();
  3705. reject(e);
  3706. };
  3707. document.body.appendChild(s);
  3708. });
  3709. }
  3710.  
  3711. function createCallback(useCORS) {
  3712. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
  3713. }
  3714.  
  3715. function createProxyUrl(proxyUrl, src, callback) {
  3716. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
  3717. }
  3718.  
  3719. function documentFromHTML(src) {
  3720. return function(html) {
  3721. var parser = new DOMParser(), doc;
  3722. try {
  3723. doc = parser.parseFromString(html, "text/html");
  3724. } catch(e) {
  3725. log("DOMParser not supported, falling back to createHTMLDocument");
  3726. doc = document.implementation.createHTMLDocument("");
  3727. try {
  3728. doc.open();
  3729. doc.write(html);
  3730. doc.close();
  3731. } catch(ee) {
  3732. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  3733. doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
  3734. }
  3735. }
  3736.  
  3737. var b = doc.querySelector("base");
  3738. if (!b || !b.href.host) {
  3739. var base = doc.createElement("base");
  3740. base.href = src;
  3741. doc.head.insertBefore(base, doc.head.firstChild);
  3742. }
  3743.  
  3744. return doc;
  3745. };
  3746. }
  3747.  
  3748. function loadUrlDocument(src, proxy, document, width, height, options) {
  3749. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  3750. return createWindowClone(doc, document, width, height, options, 0, 0);
  3751. });
  3752. }
  3753.  
  3754. exports.Proxy = Proxy;
  3755. exports.ProxyURL = ProxyURL;
  3756. exports.loadUrlDocument = loadUrlDocument;
  3757.  
  3758. },{"./clone":4,"./log":15,"./promise":18,"./utils":29,"./xhr":31}],20:[function(require,module,exports){
  3759. var ProxyURL = require('./proxy').ProxyURL;
  3760. var Promise = require('./promise');
  3761.  
  3762. function ProxyImageContainer(src, proxy) {
  3763. var link = document.createElement("a");
  3764. link.href = src;
  3765. src = link.href;
  3766. this.src = src;
  3767. this.image = new Image();
  3768. var self = this;
  3769. this.promise = new Promise(function(resolve, reject) {
  3770. self.image.crossOrigin = "Anonymous";
  3771. self.image.onload = resolve;
  3772. self.image.onerror = reject;
  3773.  
  3774. new ProxyURL(src, proxy, document).then(function(url) {
  3775. self.image.src = url;
  3776. })['catch'](reject);
  3777. });
  3778. }
  3779.  
  3780. module.exports = ProxyImageContainer;
  3781.  
  3782. },{"./promise":18,"./proxy":19}],21:[function(require,module,exports){
  3783. var NodeContainer = require('./nodecontainer');
  3784.  
  3785. function PseudoElementContainer(node, parent, type) {
  3786. NodeContainer.call(this, node, parent);
  3787. this.isPseudoElement = true;
  3788. this.before = type === ":before";
  3789. }
  3790.  
  3791. PseudoElementContainer.prototype.cloneTo = function(stack) {
  3792. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  3793. stack.isPseudoElement = true;
  3794. stack.before = this.before;
  3795. };
  3796.  
  3797. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  3798.  
  3799. PseudoElementContainer.prototype.appendToDOM = function() {
  3800. if (this.before) {
  3801. this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
  3802. } else {
  3803. this.parent.node.appendChild(this.node);
  3804. }
  3805. this.parent.node.className += " " + this.getHideClass();
  3806. };
  3807.  
  3808. PseudoElementContainer.prototype.cleanDOM = function() {
  3809. this.node.parentNode.removeChild(this.node);
  3810. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
  3811. };
  3812.  
  3813. PseudoElementContainer.prototype.getHideClass = function() {
  3814. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
  3815. };
  3816.  
  3817. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  3818. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  3819.  
  3820. module.exports = PseudoElementContainer;
  3821.  
  3822. },{"./nodecontainer":16}],22:[function(require,module,exports){
  3823. var log = require('./log');
  3824.  
  3825. function Renderer(width, height, images, options, document) {
  3826. this.width = width;
  3827. this.height = height;
  3828. this.images = images;
  3829. this.options = options;
  3830. this.document = document;
  3831. }
  3832.  
  3833. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  3834. var paddingLeft = container.cssInt('paddingLeft'),
  3835. paddingTop = container.cssInt('paddingTop'),
  3836. paddingRight = container.cssInt('paddingRight'),
  3837. paddingBottom = container.cssInt('paddingBottom'),
  3838. borders = borderData.borders;
  3839.  
  3840. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  3841. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  3842. this.drawImage(
  3843. imageContainer,
  3844. 0,
  3845. 0,
  3846. imageContainer.image.width || width,
  3847. imageContainer.image.height || height,
  3848. bounds.left + paddingLeft + borders[3].width,
  3849. bounds.top + paddingTop + borders[0].width,
  3850. width,
  3851. height
  3852. );
  3853. };
  3854.  
  3855. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  3856. if (bounds.height > 0 && bounds.width > 0) {
  3857. this.renderBackgroundColor(container, bounds);
  3858. this.renderBackgroundImage(container, bounds, borderData);
  3859. }
  3860. };
  3861.  
  3862. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  3863. var color = container.color("backgroundColor");
  3864. if (!color.isTransparent()) {
  3865. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
  3866. }
  3867. };
  3868.  
  3869. Renderer.prototype.renderBorders = function(borders) {
  3870. borders.forEach(this.renderBorder, this);
  3871. };
  3872.  
  3873. Renderer.prototype.renderBorder = function(data) {
  3874. if (!data.color.isTransparent() && data.args !== null) {
  3875. this.drawShape(data.args, data.color);
  3876. }
  3877. };
  3878.  
  3879. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  3880. var backgroundImages = container.parseBackgroundImages();
  3881. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  3882. switch(backgroundImage.method) {
  3883. case "url":
  3884. var image = this.images.get(backgroundImage.args[0]);
  3885. if (image) {
  3886. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
  3887. } else {
  3888. log("Error loading background-image", backgroundImage.args[0]);
  3889. }
  3890. break;
  3891. case "linear-gradient":
  3892. case "gradient":
  3893. var gradientImage = this.images.get(backgroundImage.value);
  3894. if (gradientImage) {
  3895. this.renderBackgroundGradient(gradientImage, bounds, borderData);
  3896. } else {
  3897. log("Error loading background-image", backgroundImage.args[0]);
  3898. }
  3899. break;
  3900. case "none":
  3901. break;
  3902. default:
  3903. log("Unknown background-image type", backgroundImage.args[0]);
  3904. }
  3905. }, this);
  3906. };
  3907.  
  3908. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  3909. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  3910. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  3911. var repeat = container.parseBackgroundRepeat(index);
  3912. switch (repeat) {
  3913. case "repeat-x":
  3914. case "repeat no-repeat":
  3915. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  3916. break;
  3917. case "repeat-y":
  3918. case "no-repeat repeat":
  3919. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  3920. break;
  3921. case "no-repeat":
  3922. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  3923. break;
  3924. default:
  3925. this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
  3926. break;
  3927. }
  3928. };
  3929.  
  3930. module.exports = Renderer;
  3931.  
  3932. },{"./log":15}],23:[function(require,module,exports){
  3933. var Renderer = require('../renderer');
  3934. var LinearGradientContainer = require('../lineargradientcontainer');
  3935. var log = require('../log');
  3936.  
  3937. function CanvasRenderer(width, height) {
  3938. Renderer.apply(this, arguments);
  3939. this.canvas = this.options.canvas || this.document.createElement("canvas");
  3940. if (!this.options.canvas) {
  3941. this.canvas.width = width;
  3942. this.canvas.height = height;
  3943. }
  3944. this.ctx = this.canvas.getContext("2d");
  3945. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  3946. this.ctx.textBaseline = "bottom";
  3947. this.variables = {};
  3948. log("Initialized CanvasRenderer with size", width, "x", height);
  3949. }
  3950.  
  3951. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  3952.  
  3953. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  3954. this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
  3955. return this.ctx;
  3956. };
  3957.  
  3958. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  3959. this.setFillStyle(color).fillRect(left, top, width, height);
  3960. };
  3961.  
  3962. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  3963. this.setFillStyle(color);
  3964. this.ctx.beginPath();
  3965. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
  3966. this.ctx.closePath();
  3967. this.ctx.fill();
  3968. };
  3969.  
  3970. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  3971. this.circle(left, top, size, color);
  3972. this.ctx.strokeStyle = strokeColor.toString();
  3973. this.ctx.stroke();
  3974. };
  3975.  
  3976. CanvasRenderer.prototype.drawShape = function(shape, color) {
  3977. this.shape(shape);
  3978. this.setFillStyle(color).fill();
  3979. };
  3980.  
  3981. CanvasRenderer.prototype.taints = function(imageContainer) {
  3982. if (imageContainer.tainted === null) {
  3983. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  3984. try {
  3985. this.taintCtx.getImageData(0, 0, 1, 1);
  3986. imageContainer.tainted = false;
  3987. } catch(e) {
  3988. this.taintCtx = document.createElement("canvas").getContext("2d");
  3989. imageContainer.tainted = true;
  3990. }
  3991. }
  3992.  
  3993. return imageContainer.tainted;
  3994. };
  3995.  
  3996. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  3997. if (!this.taints(imageContainer) || this.options.allowTaint) {
  3998. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
  3999. }
  4000. };
  4001.  
  4002. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  4003. this.ctx.save();
  4004. shapes.filter(hasEntries).forEach(function(shape) {
  4005. this.shape(shape).clip();
  4006. }, this);
  4007. callback.call(context);
  4008. this.ctx.restore();
  4009. };
  4010.  
  4011. CanvasRenderer.prototype.shape = function(shape) {
  4012. this.ctx.beginPath();
  4013. shape.forEach(function(point, index) {
  4014. if (point[0] === "rect") {
  4015. this.ctx.rect.apply(this.ctx, point.slice(1));
  4016. } else {
  4017. this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
  4018. }
  4019. }, this);
  4020. this.ctx.closePath();
  4021. return this.ctx;
  4022. };
  4023.  
  4024. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  4025. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
  4026. };
  4027.  
  4028. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  4029. this.setVariable("shadowColor", color.toString())
  4030. .setVariable("shadowOffsetY", offsetX)
  4031. .setVariable("shadowOffsetX", offsetY)
  4032. .setVariable("shadowBlur", blur);
  4033. };
  4034.  
  4035. CanvasRenderer.prototype.clearShadow = function() {
  4036. this.setVariable("shadowColor", "rgba(0,0,0,0)");
  4037. };
  4038.  
  4039. CanvasRenderer.prototype.setOpacity = function(opacity) {
  4040. this.ctx.globalAlpha = opacity;
  4041. };
  4042.  
  4043. CanvasRenderer.prototype.setTransform = function(transform) {
  4044. this.ctx.translate(transform.origin[0], transform.origin[1]);
  4045. this.ctx.transform.apply(this.ctx, transform.matrix);
  4046. this.ctx.translate(-transform.origin[0], -transform.origin[1]);
  4047. };
  4048.  
  4049. CanvasRenderer.prototype.setVariable = function(property, value) {
  4050. if (this.variables[property] !== value) {
  4051. this.variables[property] = this.ctx[property] = value;
  4052. }
  4053.  
  4054. return this;
  4055. };
  4056.  
  4057. CanvasRenderer.prototype.text = function(text, left, bottom) {
  4058. this.ctx.fillText(text, left, bottom);
  4059. };
  4060.  
  4061. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  4062. var shape = [
  4063. ["line", Math.round(left), Math.round(top)],
  4064. ["line", Math.round(left + width), Math.round(top)],
  4065. ["line", Math.round(left + width), Math.round(height + top)],
  4066. ["line", Math.round(left), Math.round(height + top)]
  4067. ];
  4068. this.clip([shape], function() {
  4069. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
  4070. }, this);
  4071. };
  4072.  
  4073. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  4074. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  4075. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  4076. this.ctx.translate(offsetX, offsetY);
  4077. this.ctx.fill();
  4078. this.ctx.translate(-offsetX, -offsetY);
  4079. };
  4080.  
  4081. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  4082. if (gradientImage instanceof LinearGradientContainer) {
  4083. var gradient = this.ctx.createLinearGradient(
  4084. bounds.left + bounds.width * gradientImage.x0,
  4085. bounds.top + bounds.height * gradientImage.y0,
  4086. bounds.left + bounds.width * gradientImage.x1,
  4087. bounds.top + bounds.height * gradientImage.y1);
  4088. gradientImage.colorStops.forEach(function(colorStop) {
  4089. gradient.addColorStop(colorStop.stop, colorStop.color.toString());
  4090. });
  4091. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
  4092. }
  4093. };
  4094.  
  4095. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  4096. var image = imageContainer.image;
  4097. if(image.width === size.width && image.height === size.height) {
  4098. return image;
  4099. }
  4100.  
  4101. var ctx, canvas = document.createElement('canvas');
  4102. canvas.width = size.width;
  4103. canvas.height = size.height;
  4104. ctx = canvas.getContext("2d");
  4105. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
  4106. return canvas;
  4107. };
  4108.  
  4109. function hasEntries(array) {
  4110. return array.length > 0;
  4111. }
  4112.  
  4113. module.exports = CanvasRenderer;
  4114.  
  4115. },{"../lineargradientcontainer":14,"../log":15,"../renderer":22}],24:[function(require,module,exports){
  4116. var NodeContainer = require('./nodecontainer');
  4117.  
  4118. function StackingContext(hasOwnStacking, opacity, element, parent) {
  4119. NodeContainer.call(this, element, parent);
  4120. this.ownStacking = hasOwnStacking;
  4121. this.contexts = [];
  4122. this.children = [];
  4123. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
  4124. }
  4125.  
  4126. StackingContext.prototype = Object.create(NodeContainer.prototype);
  4127.  
  4128. StackingContext.prototype.getParentStack = function(context) {
  4129. var parentStack = (this.parent) ? this.parent.stack : null;
  4130. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
  4131. };
  4132.  
  4133. module.exports = StackingContext;
  4134.  
  4135. },{"./nodecontainer":16}],25:[function(require,module,exports){
  4136. function Support(document) {
  4137. this.rangeBounds = this.testRangeBounds(document);
  4138. this.cors = this.testCORS();
  4139. this.svg = this.testSVG();
  4140. }
  4141.  
  4142. Support.prototype.testRangeBounds = function(document) {
  4143. var range, testElement, rangeBounds, rangeHeight, support = false;
  4144.  
  4145. if (document.createRange) {
  4146. range = document.createRange();
  4147. if (range.getBoundingClientRect) {
  4148. testElement = document.createElement('boundtest');
  4149. testElement.style.height = "123px";
  4150. testElement.style.display = "block";
  4151. document.body.appendChild(testElement);
  4152.  
  4153. range.selectNode(testElement);
  4154. rangeBounds = range.getBoundingClientRect();
  4155. rangeHeight = rangeBounds.height;
  4156.  
  4157. if (rangeHeight === 123) {
  4158. support = true;
  4159. }
  4160. document.body.removeChild(testElement);
  4161. }
  4162. }
  4163.  
  4164. return support;
  4165. };
  4166.  
  4167. Support.prototype.testCORS = function() {
  4168. return typeof((new Image()).crossOrigin) !== "undefined";
  4169. };
  4170.  
  4171. Support.prototype.testSVG = function() {
  4172. var img = new Image();
  4173. var canvas = document.createElement("canvas");
  4174. var ctx = canvas.getContext("2d");
  4175. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  4176.  
  4177. try {
  4178. ctx.drawImage(img, 0, 0);
  4179. canvas.toDataURL();
  4180. } catch(e) {
  4181. return false;
  4182. }
  4183. return true;
  4184. };
  4185.  
  4186. module.exports = Support;
  4187.  
  4188. },{}],26:[function(require,module,exports){
  4189. var Promise = require('./promise');
  4190. var XHR = require('./xhr');
  4191. var decode64 = require('./utils').decode64;
  4192.  
  4193. function SVGContainer(src) {
  4194. this.src = src;
  4195. this.image = null;
  4196. var self = this;
  4197.  
  4198. this.promise = this.hasFabric().then(function() {
  4199. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
  4200. }).then(function(svg) {
  4201. return new Promise(function(resolve) {
  4202. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
  4203. });
  4204. });
  4205. }
  4206.  
  4207. SVGContainer.prototype.hasFabric = function() {
  4208. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
  4209. };
  4210.  
  4211. SVGContainer.prototype.inlineFormatting = function(src) {
  4212. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
  4213. };
  4214.  
  4215. SVGContainer.prototype.removeContentType = function(src) {
  4216. return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
  4217. };
  4218.  
  4219. SVGContainer.prototype.isInline = function(src) {
  4220. return (/^data:image\/svg\+xml/i.test(src));
  4221. };
  4222.  
  4223. SVGContainer.prototype.createCanvas = function(resolve) {
  4224. var self = this;
  4225. return function (objects, options) {
  4226. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  4227. self.image = canvas.lowerCanvasEl;
  4228. canvas
  4229. .setWidth(options.width)
  4230. .setHeight(options.height)
  4231. .add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
  4232. .renderAll();
  4233. resolve(canvas.lowerCanvasEl);
  4234. };
  4235. };
  4236.  
  4237. SVGContainer.prototype.decode64 = function(str) {
  4238. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
  4239. };
  4240.  
  4241. module.exports = SVGContainer;
  4242.  
  4243. },{"./promise":18,"./utils":29,"./xhr":31}],27:[function(require,module,exports){
  4244. var SVGContainer = require('./svgcontainer');
  4245. var Promise = require('./promise');
  4246.  
  4247. function SVGNodeContainer(node, _native) {
  4248. this.src = node;
  4249. this.image = null;
  4250. var self = this;
  4251.  
  4252. this.promise = _native ? new Promise(function(resolve, reject) {
  4253. self.image = new Image();
  4254. self.image.onload = resolve;
  4255. self.image.onerror = reject;
  4256. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  4257. if (self.image.complete === true) {
  4258. resolve(self.image);
  4259. }
  4260. }) : this.hasFabric().then(function() {
  4261. return new Promise(function(resolve) {
  4262. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
  4263. });
  4264. });
  4265. }
  4266.  
  4267. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  4268.  
  4269. module.exports = SVGNodeContainer;
  4270.  
  4271. },{"./promise":18,"./svgcontainer":26}],28:[function(require,module,exports){
  4272. var NodeContainer = require('./nodecontainer');
  4273.  
  4274. function TextContainer(node, parent) {
  4275. NodeContainer.call(this, node, parent);
  4276. }
  4277.  
  4278. TextContainer.prototype = Object.create(NodeContainer.prototype);
  4279.  
  4280. TextContainer.prototype.applyTextTransform = function() {
  4281. this.node.data = this.transform(this.parent.css("textTransform"));
  4282. };
  4283.  
  4284. TextContainer.prototype.transform = function(transform) {
  4285. var text = this.node.data;
  4286. switch(transform){
  4287. case "lowercase":
  4288. return text.toLowerCase();
  4289. case "capitalize":
  4290. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  4291. case "uppercase":
  4292. return text.toUpperCase();
  4293. default:
  4294. return text;
  4295. }
  4296. };
  4297.  
  4298. function capitalize(m, p1, p2) {
  4299. if (m.length > 0) {
  4300. return p1 + p2.toUpperCase();
  4301. }
  4302. }
  4303.  
  4304. module.exports = TextContainer;
  4305.  
  4306. },{"./nodecontainer":16}],29:[function(require,module,exports){
  4307. exports.smallImage = function smallImage() {
  4308. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
  4309. };
  4310.  
  4311. exports.bind = function(callback, context) {
  4312. return function() {
  4313. return callback.apply(context, arguments);
  4314. };
  4315. };
  4316.  
  4317. /*
  4318. * base64-arraybuffer
  4319. * https://github.com/niklasvh/base64-arraybuffer
  4320. *
  4321. * Copyright (c) 2012 Niklas von Hertzen
  4322. * Licensed under the MIT license.
  4323. */
  4324.  
  4325. exports.decode64 = function(base64) {
  4326. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4327. var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  4328.  
  4329. var output = "";
  4330.  
  4331. for (i = 0; i < len; i+=4) {
  4332. encoded1 = chars.indexOf(base64[i]);
  4333. encoded2 = chars.indexOf(base64[i+1]);
  4334. encoded3 = chars.indexOf(base64[i+2]);
  4335. encoded4 = chars.indexOf(base64[i+3]);
  4336.  
  4337. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  4338. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  4339. byte3 = ((encoded3 & 3) << 6) | encoded4;
  4340. if (encoded3 === 64) {
  4341. output += String.fromCharCode(byte1);
  4342. } else if (encoded4 === 64 || encoded4 === -1) {
  4343. output += String.fromCharCode(byte1, byte2);
  4344. } else{
  4345. output += String.fromCharCode(byte1, byte2, byte3);
  4346. }
  4347. }
  4348.  
  4349. return output;
  4350. };
  4351.  
  4352. exports.getBounds = function(node) {
  4353. if (node.getBoundingClientRect) {
  4354. var clientRect = node.getBoundingClientRect();
  4355. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  4356. return {
  4357. top: clientRect.top,
  4358. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  4359. right: clientRect.left + width,
  4360. left: clientRect.left,
  4361. width: width,
  4362. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  4363. };
  4364. }
  4365. return {};
  4366. };
  4367.  
  4368. exports.offsetBounds = function(node) {
  4369. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
  4370.  
  4371. return {
  4372. top: node.offsetTop + parent.top,
  4373. bottom: node.offsetTop + node.offsetHeight + parent.top,
  4374. right: node.offsetLeft + parent.left + node.offsetWidth,
  4375. left: node.offsetLeft + parent.left,
  4376. width: node.offsetWidth,
  4377. height: node.offsetHeight
  4378. };
  4379. };
  4380.  
  4381. exports.parseBackgrounds = function(backgroundImage) {
  4382. var whitespace = ' \r\n\t',
  4383. method, definition, prefix, prefix_i, block, results = [],
  4384. mode = 0, numParen = 0, quote, args;
  4385. var appendResult = function() {
  4386. if(method) {
  4387. if (definition.substr(0, 1) === '"') {
  4388. definition = definition.substr(1, definition.length - 2);
  4389. }
  4390. if (definition) {
  4391. args.push(definition);
  4392. }
  4393. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
  4394. prefix = method.substr(0, prefix_i);
  4395. method = method.substr(prefix_i);
  4396. }
  4397. results.push({
  4398. prefix: prefix,
  4399. method: method.toLowerCase(),
  4400. value: block,
  4401. args: args,
  4402. image: null
  4403. });
  4404. }
  4405. args = [];
  4406. method = prefix = definition = block = '';
  4407. };
  4408. args = [];
  4409. method = prefix = definition = block = '';
  4410. backgroundImage.split("").forEach(function(c) {
  4411. if (mode === 0 && whitespace.indexOf(c) > -1) {
  4412. return;
  4413. }
  4414. switch(c) {
  4415. case '"':
  4416. if(!quote) {
  4417. quote = c;
  4418. } else if(quote === c) {
  4419. quote = null;
  4420. }
  4421. break;
  4422. case '(':
  4423. if(quote) {
  4424. break;
  4425. } else if(mode === 0) {
  4426. mode = 1;
  4427. block += c;
  4428. return;
  4429. } else {
  4430. numParen++;
  4431. }
  4432. break;
  4433. case ')':
  4434. if (quote) {
  4435. break;
  4436. } else if(mode === 1) {
  4437. if(numParen === 0) {
  4438. mode = 0;
  4439. block += c;
  4440. appendResult();
  4441. return;
  4442. } else {
  4443. numParen--;
  4444. }
  4445. }
  4446. break;
  4447.  
  4448. case ',':
  4449. if (quote) {
  4450. break;
  4451. } else if(mode === 0) {
  4452. appendResult();
  4453. return;
  4454. } else if (mode === 1) {
  4455. if (numParen === 0 && !method.match(/^url$/i)) {
  4456. args.push(definition);
  4457. definition = '';
  4458. block += c;
  4459. return;
  4460. }
  4461. }
  4462. break;
  4463. }
  4464.  
  4465. block += c;
  4466. if (mode === 0) {
  4467. method += c;
  4468. } else {
  4469. definition += c;
  4470. }
  4471. });
  4472.  
  4473. appendResult();
  4474. return results;
  4475. };
  4476.  
  4477. },{}],30:[function(require,module,exports){
  4478. var GradientContainer = require('./gradientcontainer');
  4479.  
  4480. function WebkitGradientContainer(imageData) {
  4481. GradientContainer.apply(this, arguments);
  4482. this.type = (imageData.args[0] === "linear") ? this.TYPES.LINEAR : this.TYPES.RADIAL;
  4483. }
  4484.  
  4485. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  4486.  
  4487. module.exports = WebkitGradientContainer;
  4488.  
  4489. },{"./gradientcontainer":11}],31:[function(require,module,exports){
  4490. var Promise = require('./promise');
  4491.  
  4492. function XHR(url) {
  4493. return new Promise(function(resolve, reject) {
  4494. var xhr = new XMLHttpRequest();
  4495. xhr.open('GET', url);
  4496.  
  4497. xhr.onload = function() {
  4498. if (xhr.status === 200) {
  4499. resolve(xhr.responseText);
  4500. } else {
  4501. reject(new Error(xhr.statusText));
  4502. }
  4503. };
  4504.  
  4505. xhr.onerror = function() {
  4506. reject(new Error("Network Error"));
  4507. };
  4508.  
  4509. xhr.send();
  4510. });
  4511. }
  4512.  
  4513. module.exports = XHR;
  4514.  
  4515. },{"./promise":18}]},{},[6])(6)
  4516. });

通过JS将BSAE64生成图片并下载的更多相关文章

  1. js使用html2canvas 生成图片然后下载

    1:html2canvas官网 首先去官网把这个JS下载下来 <!DOCTYPE html> <html lang="en"> <head> & ...

  2. js、css引用文件的下载方式

    js.css引用文件的下载方式 一.测试(chrome):1.直接使用<script...>.<link...>标签来混合引入脚本文件和css文件, <script as ...

  3. js中使用showModelDialog中下载文件的时候,闪一下后无法下载

    在js中使用showModelDialog中下载文件的时候,会因为showModelDialog自动设置target为_self导致下载文件“只会闪一下”就消失掉 在吧target设置为_blank后 ...

  4. js接收文件流并下载

    js接收文件流并下载 标签(空格分隔): js 在此输入正文 <script type="text/javascript"> function download(fil ...

  5. 前端js保存页面为图片下载到本地

    前端js保存页面为图片下载到本地 手机端点击下载按钮将页面保存成图片到本地 前端js保存页面为图片下载到本地的坑 html2canvas 识别 svg 解决方案 方案 html2canvas.js:可 ...

  6. 移动端js模拟截屏生成图片并下载功能的实现方案

    一.根据PM需求如下: 移动端wap 实现将二维码生成图片下载至用户手机相册保存 二.根据现有思路: 1.使用第三方工具html2canvas,将页面中指定范围的dom转换为canvas 2.随后使用 ...

  7. C# html生成图片保存下载

    最近有个需求,需要把内容生成图片,我找到一些资料可以将html页面生成图片并保存下载 下面是简单的实现 1.html页面 @{ Layout = null; } <!DOCTYPE html&g ...

  8. 通过js实现随机生成图片

    这次给大家分享一个通过js向HTML添加便签,实现随机代码生成的案例,代码已经放在下方,这里我在下面准备了50张图片,但是没有放在博文中,如果读者想要练习,可以自己下载一些图片,建议下载的多一些. & ...

  9. KRPano资源分析工具使用说明(KRPano XML/JS解密 切片图批量下载 球面图还原 加密混淆JS还原美化)

    软件交流群:571171251(软件免费版本在群内提供) krpano技术交流群:551278936(软件免费版本在群内提供) 最新博客地址:blog.turenlong.com 限时下载地址:htt ...

随机推荐

  1. Selenium IE6 Failed to load the library from temp directory: C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\IED1C1.tmp

    项目中用到了使用Selenium打开IE浏览器.前期都是基于IE8+.Firefox.Chrome.项目后期开始现场测试时发现大部分客户还都是使用的Windows XP + IE6.结果可想而知,直接 ...

  2. myeclipse 2014破解

    开始安装的时候已经进行了破解,不知道为什么还是会出现问题,按照下面说的才可以了: http://blog.sina.com.cn/s/blog_7f5862570101oxyv.html

  3. bootstrap 表单控件 控件状态 控件大小 help-block

    bootstrap 表单控件 控件状态 控件大小 help-block <!DOCTYPE html> <html lang="en"> <head& ...

  4. aix下java程序运行问题

    CLASSPATH=/track.jar:/standalone.jar export CLASSPATH nohup /usr/java6_64/bin/java com.TrackMain > ...

  5. Spring生命周期各种接口使用

    1,BeanPostProcessor接口:不能在POJO上面使用,需要单独找一个类进行使用:如果在POJO上面实现了此接口,在实现了其他*Aware接口之后,这个接口方法将不会被调用:2, POJO ...

  6. Neutron Router 工作原理 - 每天5分钟玩转 OpenStack(142)

    上一节我们创建了 router 连通了 vlan100 和 vlan101, 今天分析router是如何工作的.首先查看控制节点的网络结构发生了什么变化: br-int 上多了两个 port: 1. ...

  7. Socket通信流程

    Socket通信流程 HTTP 底层就是通过socket建立连接通信管道,实现数据传输 HTTP是一个TCP的传输协议(方式),它是一个可靠,安全的协议

  8. DB2函数大全

    DB2函数大全 函数名 函数解释 函数举例 AVG() 返回一组数值的平均值. SELECTAVG(SALARY)FROMBSEMPMS; CORR(),CORRELATION() 返回一对数值的关系 ...

  9. JS闭包深入理解(理解篇)

    看书的时候很是不明白为啥变量老是五,经过认真思考的出一下理解: function box() {   var arr = [];   for (var i = 0; i < 5; i++) {  ...

  10. int装箱比较

    看过Effctive-java 这本书的人多少都会记得,int类型的值,-128到127之间的数,会进行缓存. 所以在心间装箱对象 new Integer()的时候,如果在此范围则不会新建对象而是使用 ...