Brak opisu

html2canvas.js 121KB

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