test.js 132 KB

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