zrender.js 556 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.zrender = {})));
  5. }(this, (function (exports) { 'use strict';
  6. /**
  7. * zrender: 生成唯一id
  8. *
  9. * @author errorrik (errorrik@gmail.com)
  10. */
  11. var idStart = 0x0907;
  12. var guid = function () {
  13. return idStart++;
  14. };
  15. /**
  16. * echarts设备环境识别
  17. *
  18. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  19. * @author firede[firede@firede.us]
  20. * @desc thanks zepto.
  21. */
  22. /* global wx */
  23. var env = {};
  24. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  25. // In Weixin Application
  26. env = {
  27. browser: {},
  28. os: {},
  29. node: false,
  30. wxa: true, // Weixin Application
  31. canvasSupported: true,
  32. svgSupported: false,
  33. touchEventsSupported: true,
  34. domSupported: false
  35. };
  36. }
  37. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  38. // In worker
  39. env = {
  40. browser: {},
  41. os: {},
  42. node: false,
  43. worker: true,
  44. canvasSupported: true,
  45. domSupported: false
  46. };
  47. }
  48. else if (typeof navigator === 'undefined') {
  49. // In node
  50. env = {
  51. browser: {},
  52. os: {},
  53. node: true,
  54. worker: false,
  55. // Assume canvas is supported
  56. canvasSupported: true,
  57. svgSupported: true,
  58. domSupported: false
  59. };
  60. }
  61. else {
  62. env = detect(navigator.userAgent);
  63. }
  64. var env$1 = env;
  65. // Zepto.js
  66. // (c) 2010-2013 Thomas Fuchs
  67. // Zepto.js may be freely distributed under the MIT license.
  68. function detect(ua) {
  69. var os = {};
  70. var browser = {};
  71. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  72. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  73. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  74. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  75. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  76. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  77. // var touchpad = webos && ua.match(/TouchPad/);
  78. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  79. // var silk = ua.match(/Silk\/([\d._]+)/);
  80. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  81. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  82. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  83. // var playbook = ua.match(/PlayBook/);
  84. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  85. var firefox = ua.match(/Firefox\/([\d.]+)/);
  86. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  87. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  88. var ie = ua.match(/MSIE\s([\d.]+)/)
  89. // IE 11 Trident/7.0; rv:11.0
  90. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  91. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  92. var weChat = (/micromessenger/i).test(ua);
  93. // Todo: clean this up with a better OS/browser seperation:
  94. // - discern (more) between multiple browsers on android
  95. // - decide if kindle fire in silk mode is android or not
  96. // - Firefox on Android doesn't specify the Android version
  97. // - possibly devide in os, device and browser hashes
  98. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  99. // if (android) os.android = true, os.version = android[2];
  100. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  101. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  102. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  103. // if (webos) os.webos = true, os.version = webos[2];
  104. // if (touchpad) os.touchpad = true;
  105. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  106. // if (bb10) os.bb10 = true, os.version = bb10[2];
  107. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  108. // if (playbook) browser.playbook = true;
  109. // if (kindle) os.kindle = true, os.version = kindle[1];
  110. // if (silk) browser.silk = true, browser.version = silk[1];
  111. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  112. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  113. if (firefox) {
  114. browser.firefox = true;
  115. browser.version = firefox[1];
  116. }
  117. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  118. // if (webview) browser.webview = true;
  119. if (ie) {
  120. browser.ie = true;
  121. browser.version = ie[1];
  122. }
  123. if (edge) {
  124. browser.edge = true;
  125. browser.version = edge[1];
  126. }
  127. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  128. // not be set on win phone. So we do not consider Win Phone.
  129. if (weChat) {
  130. browser.weChat = true;
  131. }
  132. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  133. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  134. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  135. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  136. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  137. return {
  138. browser: browser,
  139. os: os,
  140. node: false,
  141. // 原生canvas支持,改极端点了
  142. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  143. canvasSupported: !!document.createElement('canvas').getContext,
  144. svgSupported: typeof SVGRect !== 'undefined',
  145. // works on most browsers
  146. // IE10/11 does not support touch event, and MS Edge supports them but not by
  147. // default, so we dont check navigator.maxTouchPoints for them here.
  148. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  149. // <http://caniuse.com/#search=pointer%20event>.
  150. pointerEventsSupported:
  151. // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  152. // events currently. So we dont use that on other browsers unless tested sufficiently.
  153. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  154. // scroll, the `pointermove` event can not be fired any more. That will break some
  155. // features like "pan horizontally to move something and pan vertically to page scroll".
  156. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  157. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  158. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  159. 'onpointerdown' in window
  160. && (browser.edge || (browser.ie && browser.version >= 11)),
  161. // passiveSupported: detectPassiveSupport()
  162. domSupported: typeof document !== 'undefined'
  163. };
  164. }
  165. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  166. // function detectPassiveSupport() {
  167. // // Test via a getter in the options object to see if the passive property is accessed
  168. // var supportsPassive = false;
  169. // try {
  170. // var opts = Object.defineProperty({}, 'passive', {
  171. // get: function() {
  172. // supportsPassive = true;
  173. // }
  174. // });
  175. // window.addEventListener('testPassive', function() {}, opts);
  176. // } catch (e) {
  177. // }
  178. // return supportsPassive;
  179. // }
  180. /**
  181. * @module zrender/core/util
  182. */
  183. // 用于处理merge时无法遍历Date等对象的问题
  184. var BUILTIN_OBJECT = {
  185. '[object Function]': 1,
  186. '[object RegExp]': 1,
  187. '[object Date]': 1,
  188. '[object Error]': 1,
  189. '[object CanvasGradient]': 1,
  190. '[object CanvasPattern]': 1,
  191. // For node-canvas
  192. '[object Image]': 1,
  193. '[object Canvas]': 1
  194. };
  195. var TYPED_ARRAY = {
  196. '[object Int8Array]': 1,
  197. '[object Uint8Array]': 1,
  198. '[object Uint8ClampedArray]': 1,
  199. '[object Int16Array]': 1,
  200. '[object Uint16Array]': 1,
  201. '[object Int32Array]': 1,
  202. '[object Uint32Array]': 1,
  203. '[object Float32Array]': 1,
  204. '[object Float64Array]': 1
  205. };
  206. var objToString = Object.prototype.toString;
  207. var arrayProto = Array.prototype;
  208. var nativeForEach = arrayProto.forEach;
  209. var nativeFilter = arrayProto.filter;
  210. var nativeSlice = arrayProto.slice;
  211. var nativeMap = arrayProto.map;
  212. var nativeReduce = arrayProto.reduce;
  213. // Avoid assign to an exported variable, for transforming to cjs.
  214. var methods = {};
  215. function $override(name, fn) {
  216. // Clear ctx instance for different environment
  217. if (name === 'createCanvas') {
  218. _ctx = null;
  219. }
  220. methods[name] = fn;
  221. }
  222. /**
  223. * Those data types can be cloned:
  224. * Plain object, Array, TypedArray, number, string, null, undefined.
  225. * Those data types will be assgined using the orginal data:
  226. * BUILTIN_OBJECT
  227. * Instance of user defined class will be cloned to a plain object, without
  228. * properties in prototype.
  229. * Other data types is not supported (not sure what will happen).
  230. *
  231. * Caution: do not support clone Date, for performance consideration.
  232. * (There might be a large number of date in `series.data`).
  233. * So date should not be modified in and out of echarts.
  234. *
  235. * @param {*} source
  236. * @return {*} new
  237. */
  238. function clone(source) {
  239. if (source == null || typeof source !== 'object') {
  240. return source;
  241. }
  242. var result = source;
  243. var typeStr = objToString.call(source);
  244. if (typeStr === '[object Array]') {
  245. if (!isPrimitive(source)) {
  246. result = [];
  247. for (var i = 0, len = source.length; i < len; i++) {
  248. result[i] = clone(source[i]);
  249. }
  250. }
  251. }
  252. else if (TYPED_ARRAY[typeStr]) {
  253. if (!isPrimitive(source)) {
  254. var Ctor = source.constructor;
  255. if (source.constructor.from) {
  256. result = Ctor.from(source);
  257. }
  258. else {
  259. result = new Ctor(source.length);
  260. for (var i = 0, len = source.length; i < len; i++) {
  261. result[i] = clone(source[i]);
  262. }
  263. }
  264. }
  265. }
  266. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  267. result = {};
  268. for (var key in source) {
  269. if (source.hasOwnProperty(key)) {
  270. result[key] = clone(source[key]);
  271. }
  272. }
  273. }
  274. return result;
  275. }
  276. /**
  277. * @memberOf module:zrender/core/util
  278. * @param {*} target
  279. * @param {*} source
  280. * @param {boolean} [overwrite=false]
  281. */
  282. function merge(target, source, overwrite) {
  283. // We should escapse that source is string
  284. // and enter for ... in ...
  285. if (!isObject(source) || !isObject(target)) {
  286. return overwrite ? clone(source) : target;
  287. }
  288. for (var key in source) {
  289. if (source.hasOwnProperty(key)) {
  290. var targetProp = target[key];
  291. var sourceProp = source[key];
  292. if (isObject(sourceProp)
  293. && isObject(targetProp)
  294. && !isArray(sourceProp)
  295. && !isArray(targetProp)
  296. && !isDom(sourceProp)
  297. && !isDom(targetProp)
  298. && !isBuiltInObject(sourceProp)
  299. && !isBuiltInObject(targetProp)
  300. && !isPrimitive(sourceProp)
  301. && !isPrimitive(targetProp)
  302. ) {
  303. // 如果需要递归覆盖,就递归调用merge
  304. merge(targetProp, sourceProp, overwrite);
  305. }
  306. else if (overwrite || !(key in target)) {
  307. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  308. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  309. target[key] = clone(source[key], true);
  310. }
  311. }
  312. }
  313. return target;
  314. }
  315. /**
  316. * @param {Array} targetAndSources The first item is target, and the rests are source.
  317. * @param {boolean} [overwrite=false]
  318. * @return {*} target
  319. */
  320. function mergeAll(targetAndSources, overwrite) {
  321. var result = targetAndSources[0];
  322. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  323. result = merge(result, targetAndSources[i], overwrite);
  324. }
  325. return result;
  326. }
  327. /**
  328. * @param {*} target
  329. * @param {*} source
  330. * @memberOf module:zrender/core/util
  331. */
  332. function extend(target, source) {
  333. for (var key in source) {
  334. if (source.hasOwnProperty(key)) {
  335. target[key] = source[key];
  336. }
  337. }
  338. return target;
  339. }
  340. /**
  341. * @param {*} target
  342. * @param {*} source
  343. * @param {boolean} [overlay=false]
  344. * @memberOf module:zrender/core/util
  345. */
  346. function defaults(target, source, overlay) {
  347. for (var key in source) {
  348. if (source.hasOwnProperty(key)
  349. && (overlay ? source[key] != null : target[key] == null)
  350. ) {
  351. target[key] = source[key];
  352. }
  353. }
  354. return target;
  355. }
  356. var createCanvas = function () {
  357. return methods.createCanvas();
  358. };
  359. methods.createCanvas = function () {
  360. return document.createElement('canvas');
  361. };
  362. // FIXME
  363. var _ctx;
  364. function getContext() {
  365. if (!_ctx) {
  366. // Use util.createCanvas instead of createCanvas
  367. // because createCanvas may be overwritten in different environment
  368. _ctx = createCanvas().getContext('2d');
  369. }
  370. return _ctx;
  371. }
  372. /**
  373. * 查询数组中元素的index
  374. * @memberOf module:zrender/core/util
  375. */
  376. function indexOf(array, value) {
  377. if (array) {
  378. if (array.indexOf) {
  379. return array.indexOf(value);
  380. }
  381. for (var i = 0, len = array.length; i < len; i++) {
  382. if (array[i] === value) {
  383. return i;
  384. }
  385. }
  386. }
  387. return -1;
  388. }
  389. /**
  390. * 构造类继承关系
  391. *
  392. * @memberOf module:zrender/core/util
  393. * @param {Function} clazz 源类
  394. * @param {Function} baseClazz 基类
  395. */
  396. function inherits(clazz, baseClazz) {
  397. var clazzPrototype = clazz.prototype;
  398. function F() {}
  399. F.prototype = baseClazz.prototype;
  400. clazz.prototype = new F();
  401. for (var prop in clazzPrototype) {
  402. if (clazzPrototype.hasOwnProperty(prop)) {
  403. clazz.prototype[prop] = clazzPrototype[prop];
  404. }
  405. }
  406. clazz.prototype.constructor = clazz;
  407. clazz.superClass = baseClazz;
  408. }
  409. /**
  410. * @memberOf module:zrender/core/util
  411. * @param {Object|Function} target
  412. * @param {Object|Function} sorce
  413. * @param {boolean} overlay
  414. */
  415. function mixin(target, source, overlay) {
  416. target = 'prototype' in target ? target.prototype : target;
  417. source = 'prototype' in source ? source.prototype : source;
  418. defaults(target, source, overlay);
  419. }
  420. /**
  421. * Consider typed array.
  422. * @param {Array|TypedArray} data
  423. */
  424. function isArrayLike(data) {
  425. if (!data) {
  426. return;
  427. }
  428. if (typeof data === 'string') {
  429. return false;
  430. }
  431. return typeof data.length === 'number';
  432. }
  433. /**
  434. * 数组或对象遍历
  435. * @memberOf module:zrender/core/util
  436. * @param {Object|Array} obj
  437. * @param {Function} cb
  438. * @param {*} [context]
  439. */
  440. function each(obj, cb, context) {
  441. if (!(obj && cb)) {
  442. return;
  443. }
  444. if (obj.forEach && obj.forEach === nativeForEach) {
  445. obj.forEach(cb, context);
  446. }
  447. else if (obj.length === +obj.length) {
  448. for (var i = 0, len = obj.length; i < len; i++) {
  449. cb.call(context, obj[i], i, obj);
  450. }
  451. }
  452. else {
  453. for (var key in obj) {
  454. if (obj.hasOwnProperty(key)) {
  455. cb.call(context, obj[key], key, obj);
  456. }
  457. }
  458. }
  459. }
  460. /**
  461. * 数组映射
  462. * @memberOf module:zrender/core/util
  463. * @param {Array} obj
  464. * @param {Function} cb
  465. * @param {*} [context]
  466. * @return {Array}
  467. */
  468. function map(obj, cb, context) {
  469. if (!(obj && cb)) {
  470. return;
  471. }
  472. if (obj.map && obj.map === nativeMap) {
  473. return obj.map(cb, context);
  474. }
  475. else {
  476. var result = [];
  477. for (var i = 0, len = obj.length; i < len; i++) {
  478. result.push(cb.call(context, obj[i], i, obj));
  479. }
  480. return result;
  481. }
  482. }
  483. /**
  484. * @memberOf module:zrender/core/util
  485. * @param {Array} obj
  486. * @param {Function} cb
  487. * @param {Object} [memo]
  488. * @param {*} [context]
  489. * @return {Array}
  490. */
  491. function reduce(obj, cb, memo, context) {
  492. if (!(obj && cb)) {
  493. return;
  494. }
  495. if (obj.reduce && obj.reduce === nativeReduce) {
  496. return obj.reduce(cb, memo, context);
  497. }
  498. else {
  499. for (var i = 0, len = obj.length; i < len; i++) {
  500. memo = cb.call(context, memo, obj[i], i, obj);
  501. }
  502. return memo;
  503. }
  504. }
  505. /**
  506. * 数组过滤
  507. * @memberOf module:zrender/core/util
  508. * @param {Array} obj
  509. * @param {Function} cb
  510. * @param {*} [context]
  511. * @return {Array}
  512. */
  513. function filter(obj, cb, context) {
  514. if (!(obj && cb)) {
  515. return;
  516. }
  517. if (obj.filter && obj.filter === nativeFilter) {
  518. return obj.filter(cb, context);
  519. }
  520. else {
  521. var result = [];
  522. for (var i = 0, len = obj.length; i < len; i++) {
  523. if (cb.call(context, obj[i], i, obj)) {
  524. result.push(obj[i]);
  525. }
  526. }
  527. return result;
  528. }
  529. }
  530. /**
  531. * 数组项查找
  532. * @memberOf module:zrender/core/util
  533. * @param {Array} obj
  534. * @param {Function} cb
  535. * @param {*} [context]
  536. * @return {*}
  537. */
  538. function find(obj, cb, context) {
  539. if (!(obj && cb)) {
  540. return;
  541. }
  542. for (var i = 0, len = obj.length; i < len; i++) {
  543. if (cb.call(context, obj[i], i, obj)) {
  544. return obj[i];
  545. }
  546. }
  547. }
  548. /**
  549. * @memberOf module:zrender/core/util
  550. * @param {Function} func
  551. * @param {*} context
  552. * @return {Function}
  553. */
  554. function bind(func, context) {
  555. var args = nativeSlice.call(arguments, 2);
  556. return function () {
  557. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  558. };
  559. }
  560. /**
  561. * @memberOf module:zrender/core/util
  562. * @param {Function} func
  563. * @return {Function}
  564. */
  565. function curry(func) {
  566. var args = nativeSlice.call(arguments, 1);
  567. return function () {
  568. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  569. };
  570. }
  571. /**
  572. * @memberOf module:zrender/core/util
  573. * @param {*} value
  574. * @return {boolean}
  575. */
  576. function isArray(value) {
  577. return objToString.call(value) === '[object Array]';
  578. }
  579. /**
  580. * @memberOf module:zrender/core/util
  581. * @param {*} value
  582. * @return {boolean}
  583. */
  584. function isFunction(value) {
  585. return typeof value === 'function';
  586. }
  587. /**
  588. * @memberOf module:zrender/core/util
  589. * @param {*} value
  590. * @return {boolean}
  591. */
  592. function isString(value) {
  593. return objToString.call(value) === '[object String]';
  594. }
  595. /**
  596. * @memberOf module:zrender/core/util
  597. * @param {*} value
  598. * @return {boolean}
  599. */
  600. function isObject(value) {
  601. // Avoid a V8 JIT bug in Chrome 19-20.
  602. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  603. var type = typeof value;
  604. return type === 'function' || (!!value && type === 'object');
  605. }
  606. /**
  607. * @memberOf module:zrender/core/util
  608. * @param {*} value
  609. * @return {boolean}
  610. */
  611. function isBuiltInObject(value) {
  612. return !!BUILTIN_OBJECT[objToString.call(value)];
  613. }
  614. /**
  615. * @memberOf module:zrender/core/util
  616. * @param {*} value
  617. * @return {boolean}
  618. */
  619. function isTypedArray(value) {
  620. return !!TYPED_ARRAY[objToString.call(value)];
  621. }
  622. /**
  623. * @memberOf module:zrender/core/util
  624. * @param {*} value
  625. * @return {boolean}
  626. */
  627. function isDom(value) {
  628. return typeof value === 'object'
  629. && typeof value.nodeType === 'number'
  630. && typeof value.ownerDocument === 'object';
  631. }
  632. /**
  633. * Whether is exactly NaN. Notice isNaN('a') returns true.
  634. * @param {*} value
  635. * @return {boolean}
  636. */
  637. function eqNaN(value) {
  638. /* eslint-disable-next-line no-self-compare */
  639. return value !== value;
  640. }
  641. /**
  642. * If value1 is not null, then return value1, otherwise judget rest of values.
  643. * Low performance.
  644. * @memberOf module:zrender/core/util
  645. * @return {*} Final value
  646. */
  647. function retrieve(values) {
  648. for (var i = 0, len = arguments.length; i < len; i++) {
  649. if (arguments[i] != null) {
  650. return arguments[i];
  651. }
  652. }
  653. }
  654. function retrieve2(value0, value1) {
  655. return value0 != null
  656. ? value0
  657. : value1;
  658. }
  659. function retrieve3(value0, value1, value2) {
  660. return value0 != null
  661. ? value0
  662. : value1 != null
  663. ? value1
  664. : value2;
  665. }
  666. /**
  667. * @memberOf module:zrender/core/util
  668. * @param {Array} arr
  669. * @param {number} startIndex
  670. * @param {number} endIndex
  671. * @return {Array}
  672. */
  673. function slice() {
  674. return Function.call.apply(nativeSlice, arguments);
  675. }
  676. /**
  677. * Normalize css liked array configuration
  678. * e.g.
  679. * 3 => [3, 3, 3, 3]
  680. * [4, 2] => [4, 2, 4, 2]
  681. * [4, 3, 2] => [4, 3, 2, 3]
  682. * @param {number|Array.<number>} val
  683. * @return {Array.<number>}
  684. */
  685. function normalizeCssArray(val) {
  686. if (typeof (val) === 'number') {
  687. return [val, val, val, val];
  688. }
  689. var len = val.length;
  690. if (len === 2) {
  691. // vertical | horizontal
  692. return [val[0], val[1], val[0], val[1]];
  693. }
  694. else if (len === 3) {
  695. // top | horizontal | bottom
  696. return [val[0], val[1], val[2], val[1]];
  697. }
  698. return val;
  699. }
  700. /**
  701. * @memberOf module:zrender/core/util
  702. * @param {boolean} condition
  703. * @param {string} message
  704. */
  705. function assert(condition, message) {
  706. if (!condition) {
  707. throw new Error(message);
  708. }
  709. }
  710. /**
  711. * @memberOf module:zrender/core/util
  712. * @param {string} str string to be trimed
  713. * @return {string} trimed string
  714. */
  715. function trim(str) {
  716. if (str == null) {
  717. return null;
  718. }
  719. else if (typeof str.trim === 'function') {
  720. return str.trim();
  721. }
  722. else {
  723. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  724. }
  725. }
  726. var primitiveKey = '__ec_primitive__';
  727. /**
  728. * Set an object as primitive to be ignored traversing children in clone or merge
  729. */
  730. function setAsPrimitive(obj) {
  731. obj[primitiveKey] = true;
  732. }
  733. function isPrimitive(obj) {
  734. return obj[primitiveKey];
  735. }
  736. /**
  737. * @constructor
  738. * @param {Object} obj Only apply `ownProperty`.
  739. */
  740. function HashMap(obj) {
  741. var isArr = isArray(obj);
  742. // Key should not be set on this, otherwise
  743. // methods get/set/... may be overrided.
  744. this.data = {};
  745. var thisMap = this;
  746. (obj instanceof HashMap)
  747. ? obj.each(visit)
  748. : (obj && each(obj, visit));
  749. function visit(value, key) {
  750. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  751. }
  752. }
  753. HashMap.prototype = {
  754. constructor: HashMap,
  755. // Do not provide `has` method to avoid defining what is `has`.
  756. // (We usually treat `null` and `undefined` as the same, different
  757. // from ES6 Map).
  758. get: function (key) {
  759. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  760. },
  761. set: function (key, value) {
  762. // Comparing with invocation chaining, `return value` is more commonly
  763. // used in this case: `var someVal = map.set('a', genVal());`
  764. return (this.data[key] = value);
  765. },
  766. // Although util.each can be performed on this hashMap directly, user
  767. // should not use the exposed keys, who are prefixed.
  768. each: function (cb, context) {
  769. context !== void 0 && (cb = bind(cb, context));
  770. /* eslint-disable guard-for-in */
  771. for (var key in this.data) {
  772. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  773. }
  774. /* eslint-enable guard-for-in */
  775. },
  776. // Do not use this method if performance sensitive.
  777. removeKey: function (key) {
  778. delete this.data[key];
  779. }
  780. };
  781. function createHashMap(obj) {
  782. return new HashMap(obj);
  783. }
  784. function concatArray(a, b) {
  785. var newArray = new a.constructor(a.length + b.length);
  786. for (var i = 0; i < a.length; i++) {
  787. newArray[i] = a[i];
  788. }
  789. var offset = a.length;
  790. for (i = 0; i < b.length; i++) {
  791. newArray[i + offset] = b[i];
  792. }
  793. return newArray;
  794. }
  795. function noop() {}
  796. var util = (Object.freeze || Object)({
  797. $override: $override,
  798. clone: clone,
  799. merge: merge,
  800. mergeAll: mergeAll,
  801. extend: extend,
  802. defaults: defaults,
  803. createCanvas: createCanvas,
  804. getContext: getContext,
  805. indexOf: indexOf,
  806. inherits: inherits,
  807. mixin: mixin,
  808. isArrayLike: isArrayLike,
  809. each: each,
  810. map: map,
  811. reduce: reduce,
  812. filter: filter,
  813. find: find,
  814. bind: bind,
  815. curry: curry,
  816. isArray: isArray,
  817. isFunction: isFunction,
  818. isString: isString,
  819. isObject: isObject,
  820. isBuiltInObject: isBuiltInObject,
  821. isTypedArray: isTypedArray,
  822. isDom: isDom,
  823. eqNaN: eqNaN,
  824. retrieve: retrieve,
  825. retrieve2: retrieve2,
  826. retrieve3: retrieve3,
  827. slice: slice,
  828. normalizeCssArray: normalizeCssArray,
  829. assert: assert,
  830. trim: trim,
  831. setAsPrimitive: setAsPrimitive,
  832. isPrimitive: isPrimitive,
  833. createHashMap: createHashMap,
  834. concatArray: concatArray,
  835. noop: noop
  836. });
  837. /* global Float32Array */
  838. var ArrayCtor = typeof Float32Array === 'undefined'
  839. ? Array
  840. : Float32Array;
  841. /**
  842. * 创建一个向量
  843. * @param {number} [x=0]
  844. * @param {number} [y=0]
  845. * @return {Vector2}
  846. */
  847. function create(x, y) {
  848. var out = new ArrayCtor(2);
  849. if (x == null) {
  850. x = 0;
  851. }
  852. if (y == null) {
  853. y = 0;
  854. }
  855. out[0] = x;
  856. out[1] = y;
  857. return out;
  858. }
  859. /**
  860. * 复制向量数据
  861. * @param {Vector2} out
  862. * @param {Vector2} v
  863. * @return {Vector2}
  864. */
  865. function copy(out, v) {
  866. out[0] = v[0];
  867. out[1] = v[1];
  868. return out;
  869. }
  870. /**
  871. * 克隆一个向量
  872. * @param {Vector2} v
  873. * @return {Vector2}
  874. */
  875. function clone$1(v) {
  876. var out = new ArrayCtor(2);
  877. out[0] = v[0];
  878. out[1] = v[1];
  879. return out;
  880. }
  881. /**
  882. * 设置向量的两个项
  883. * @param {Vector2} out
  884. * @param {number} a
  885. * @param {number} b
  886. * @return {Vector2} 结果
  887. */
  888. function set(out, a, b) {
  889. out[0] = a;
  890. out[1] = b;
  891. return out;
  892. }
  893. /**
  894. * 向量相加
  895. * @param {Vector2} out
  896. * @param {Vector2} v1
  897. * @param {Vector2} v2
  898. */
  899. function add(out, v1, v2) {
  900. out[0] = v1[0] + v2[0];
  901. out[1] = v1[1] + v2[1];
  902. return out;
  903. }
  904. /**
  905. * 向量缩放后相加
  906. * @param {Vector2} out
  907. * @param {Vector2} v1
  908. * @param {Vector2} v2
  909. * @param {number} a
  910. */
  911. function scaleAndAdd(out, v1, v2, a) {
  912. out[0] = v1[0] + v2[0] * a;
  913. out[1] = v1[1] + v2[1] * a;
  914. return out;
  915. }
  916. /**
  917. * 向量相减
  918. * @param {Vector2} out
  919. * @param {Vector2} v1
  920. * @param {Vector2} v2
  921. */
  922. function sub(out, v1, v2) {
  923. out[0] = v1[0] - v2[0];
  924. out[1] = v1[1] - v2[1];
  925. return out;
  926. }
  927. /**
  928. * 向量长度
  929. * @param {Vector2} v
  930. * @return {number}
  931. */
  932. function len(v) {
  933. return Math.sqrt(lenSquare(v));
  934. }
  935. var length = len; // jshint ignore:line
  936. /**
  937. * 向量长度平方
  938. * @param {Vector2} v
  939. * @return {number}
  940. */
  941. function lenSquare(v) {
  942. return v[0] * v[0] + v[1] * v[1];
  943. }
  944. var lengthSquare = lenSquare;
  945. /**
  946. * 向量乘法
  947. * @param {Vector2} out
  948. * @param {Vector2} v1
  949. * @param {Vector2} v2
  950. */
  951. function mul(out, v1, v2) {
  952. out[0] = v1[0] * v2[0];
  953. out[1] = v1[1] * v2[1];
  954. return out;
  955. }
  956. /**
  957. * 向量除法
  958. * @param {Vector2} out
  959. * @param {Vector2} v1
  960. * @param {Vector2} v2
  961. */
  962. function div(out, v1, v2) {
  963. out[0] = v1[0] / v2[0];
  964. out[1] = v1[1] / v2[1];
  965. return out;
  966. }
  967. /**
  968. * 向量点乘
  969. * @param {Vector2} v1
  970. * @param {Vector2} v2
  971. * @return {number}
  972. */
  973. function dot(v1, v2) {
  974. return v1[0] * v2[0] + v1[1] * v2[1];
  975. }
  976. /**
  977. * 向量缩放
  978. * @param {Vector2} out
  979. * @param {Vector2} v
  980. * @param {number} s
  981. */
  982. function scale(out, v, s) {
  983. out[0] = v[0] * s;
  984. out[1] = v[1] * s;
  985. return out;
  986. }
  987. /**
  988. * 向量归一化
  989. * @param {Vector2} out
  990. * @param {Vector2} v
  991. */
  992. function normalize(out, v) {
  993. var d = len(v);
  994. if (d === 0) {
  995. out[0] = 0;
  996. out[1] = 0;
  997. }
  998. else {
  999. out[0] = v[0] / d;
  1000. out[1] = v[1] / d;
  1001. }
  1002. return out;
  1003. }
  1004. /**
  1005. * 计算向量间距离
  1006. * @param {Vector2} v1
  1007. * @param {Vector2} v2
  1008. * @return {number}
  1009. */
  1010. function distance(v1, v2) {
  1011. return Math.sqrt(
  1012. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1013. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1014. );
  1015. }
  1016. var dist = distance;
  1017. /**
  1018. * 向量距离平方
  1019. * @param {Vector2} v1
  1020. * @param {Vector2} v2
  1021. * @return {number}
  1022. */
  1023. function distanceSquare(v1, v2) {
  1024. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1025. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1026. }
  1027. var distSquare = distanceSquare;
  1028. /**
  1029. * 求负向量
  1030. * @param {Vector2} out
  1031. * @param {Vector2} v
  1032. */
  1033. function negate(out, v) {
  1034. out[0] = -v[0];
  1035. out[1] = -v[1];
  1036. return out;
  1037. }
  1038. /**
  1039. * 插值两个点
  1040. * @param {Vector2} out
  1041. * @param {Vector2} v1
  1042. * @param {Vector2} v2
  1043. * @param {number} t
  1044. */
  1045. function lerp(out, v1, v2, t) {
  1046. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1047. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1048. return out;
  1049. }
  1050. /**
  1051. * 矩阵左乘向量
  1052. * @param {Vector2} out
  1053. * @param {Vector2} v
  1054. * @param {Vector2} m
  1055. */
  1056. function applyTransform(out, v, m) {
  1057. var x = v[0];
  1058. var y = v[1];
  1059. out[0] = m[0] * x + m[2] * y + m[4];
  1060. out[1] = m[1] * x + m[3] * y + m[5];
  1061. return out;
  1062. }
  1063. /**
  1064. * 求两个向量最小值
  1065. * @param {Vector2} out
  1066. * @param {Vector2} v1
  1067. * @param {Vector2} v2
  1068. */
  1069. function min(out, v1, v2) {
  1070. out[0] = Math.min(v1[0], v2[0]);
  1071. out[1] = Math.min(v1[1], v2[1]);
  1072. return out;
  1073. }
  1074. /**
  1075. * 求两个向量最大值
  1076. * @param {Vector2} out
  1077. * @param {Vector2} v1
  1078. * @param {Vector2} v2
  1079. */
  1080. function max(out, v1, v2) {
  1081. out[0] = Math.max(v1[0], v2[0]);
  1082. out[1] = Math.max(v1[1], v2[1]);
  1083. return out;
  1084. }
  1085. var vector = (Object.freeze || Object)({
  1086. create: create,
  1087. copy: copy,
  1088. clone: clone$1,
  1089. set: set,
  1090. add: add,
  1091. scaleAndAdd: scaleAndAdd,
  1092. sub: sub,
  1093. len: len,
  1094. length: length,
  1095. lenSquare: lenSquare,
  1096. lengthSquare: lengthSquare,
  1097. mul: mul,
  1098. div: div,
  1099. dot: dot,
  1100. scale: scale,
  1101. normalize: normalize,
  1102. distance: distance,
  1103. dist: dist,
  1104. distanceSquare: distanceSquare,
  1105. distSquare: distSquare,
  1106. negate: negate,
  1107. lerp: lerp,
  1108. applyTransform: applyTransform,
  1109. min: min,
  1110. max: max
  1111. });
  1112. // TODO Draggable for group
  1113. // FIXME Draggable on element which has parent rotation or scale
  1114. function Draggable() {
  1115. this.on('mousedown', this._dragStart, this);
  1116. this.on('mousemove', this._drag, this);
  1117. this.on('mouseup', this._dragEnd, this);
  1118. // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1119. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1120. // `_dragEnd` when globalout. That would brings better user experience.
  1121. // this.on('globalout', this._dragEnd, this);
  1122. // this._dropTarget = null;
  1123. // this._draggingTarget = null;
  1124. // this._x = 0;
  1125. // this._y = 0;
  1126. }
  1127. Draggable.prototype = {
  1128. constructor: Draggable,
  1129. _dragStart: function (e) {
  1130. var draggingTarget = e.target;
  1131. if (draggingTarget && draggingTarget.draggable) {
  1132. this._draggingTarget = draggingTarget;
  1133. draggingTarget.dragging = true;
  1134. this._x = e.offsetX;
  1135. this._y = e.offsetY;
  1136. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1137. }
  1138. },
  1139. _drag: function (e) {
  1140. var draggingTarget = this._draggingTarget;
  1141. if (draggingTarget) {
  1142. var x = e.offsetX;
  1143. var y = e.offsetY;
  1144. var dx = x - this._x;
  1145. var dy = y - this._y;
  1146. this._x = x;
  1147. this._y = y;
  1148. draggingTarget.drift(dx, dy, e);
  1149. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1150. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1151. var lastDropTarget = this._dropTarget;
  1152. this._dropTarget = dropTarget;
  1153. if (draggingTarget !== dropTarget) {
  1154. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1155. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1156. }
  1157. if (dropTarget && dropTarget !== lastDropTarget) {
  1158. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1159. }
  1160. }
  1161. }
  1162. },
  1163. _dragEnd: function (e) {
  1164. var draggingTarget = this._draggingTarget;
  1165. if (draggingTarget) {
  1166. draggingTarget.dragging = false;
  1167. }
  1168. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1169. if (this._dropTarget) {
  1170. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1171. }
  1172. this._draggingTarget = null;
  1173. this._dropTarget = null;
  1174. }
  1175. };
  1176. function param(target, e) {
  1177. return {target: target, topTarget: e && e.topTarget};
  1178. }
  1179. /**
  1180. * Event Mixin
  1181. * @module zrender/mixin/Eventful
  1182. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1183. * pissang (https://www.github.com/pissang)
  1184. */
  1185. var arrySlice = Array.prototype.slice;
  1186. /**
  1187. * Event dispatcher.
  1188. *
  1189. * @alias module:zrender/mixin/Eventful
  1190. * @constructor
  1191. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1192. * `eventProcessor.xxx` called.
  1193. * @param {Function} [eventProcessor.normalizeQuery]
  1194. * param: {string|Object} Raw query.
  1195. * return: {string|Object} Normalized query.
  1196. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1197. * if it returns `true`.
  1198. * param: {string} eventType
  1199. * param: {string|Object} query
  1200. * return: {boolean}
  1201. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1202. * param: {string} eventType
  1203. */
  1204. var Eventful = function (eventProcessor) {
  1205. this._$handlers = {};
  1206. this._$eventProcessor = eventProcessor;
  1207. };
  1208. Eventful.prototype = {
  1209. constructor: Eventful,
  1210. /**
  1211. * The handler can only be triggered once, then removed.
  1212. *
  1213. * @param {string} event The event name.
  1214. * @param {string|Object} [query] Condition used on event filter.
  1215. * @param {Function} handler The event handler.
  1216. * @param {Object} context
  1217. */
  1218. one: function (event, query, handler, context) {
  1219. return on(this, event, query, handler, context, true);
  1220. },
  1221. /**
  1222. * Bind a handler.
  1223. *
  1224. * @param {string} event The event name.
  1225. * @param {string|Object} [query] Condition used on event filter.
  1226. * @param {Function} handler The event handler.
  1227. * @param {Object} [context]
  1228. */
  1229. on: function (event, query, handler, context) {
  1230. return on(this, event, query, handler, context, false);
  1231. },
  1232. /**
  1233. * Whether any handler has bound.
  1234. *
  1235. * @param {string} event
  1236. * @return {boolean}
  1237. */
  1238. isSilent: function (event) {
  1239. var _h = this._$handlers;
  1240. return !_h[event] || !_h[event].length;
  1241. },
  1242. /**
  1243. * Unbind a event.
  1244. *
  1245. * @param {string} [event] The event name.
  1246. * If no `event` input, "off" all listeners.
  1247. * @param {Function} [handler] The event handler.
  1248. * If no `handler` input, "off" all listeners of the `event`.
  1249. */
  1250. off: function (event, handler) {
  1251. var _h = this._$handlers;
  1252. if (!event) {
  1253. this._$handlers = {};
  1254. return this;
  1255. }
  1256. if (handler) {
  1257. if (_h[event]) {
  1258. var newList = [];
  1259. for (var i = 0, l = _h[event].length; i < l; i++) {
  1260. if (_h[event][i].h !== handler) {
  1261. newList.push(_h[event][i]);
  1262. }
  1263. }
  1264. _h[event] = newList;
  1265. }
  1266. if (_h[event] && _h[event].length === 0) {
  1267. delete _h[event];
  1268. }
  1269. }
  1270. else {
  1271. delete _h[event];
  1272. }
  1273. return this;
  1274. },
  1275. /**
  1276. * Dispatch a event.
  1277. *
  1278. * @param {string} type The event name.
  1279. */
  1280. trigger: function (type) {
  1281. var _h = this._$handlers[type];
  1282. var eventProcessor = this._$eventProcessor;
  1283. if (_h) {
  1284. var args = arguments;
  1285. var argLen = args.length;
  1286. if (argLen > 3) {
  1287. args = arrySlice.call(args, 1);
  1288. }
  1289. var len = _h.length;
  1290. for (var i = 0; i < len;) {
  1291. var hItem = _h[i];
  1292. if (eventProcessor
  1293. && eventProcessor.filter
  1294. && hItem.query != null
  1295. && !eventProcessor.filter(type, hItem.query)
  1296. ) {
  1297. i++;
  1298. continue;
  1299. }
  1300. // Optimize advise from backbone
  1301. switch (argLen) {
  1302. case 1:
  1303. hItem.h.call(hItem.ctx);
  1304. break;
  1305. case 2:
  1306. hItem.h.call(hItem.ctx, args[1]);
  1307. break;
  1308. case 3:
  1309. hItem.h.call(hItem.ctx, args[1], args[2]);
  1310. break;
  1311. default:
  1312. // have more than 2 given arguments
  1313. hItem.h.apply(hItem.ctx, args);
  1314. break;
  1315. }
  1316. if (hItem.one) {
  1317. _h.splice(i, 1);
  1318. len--;
  1319. }
  1320. else {
  1321. i++;
  1322. }
  1323. }
  1324. }
  1325. eventProcessor && eventProcessor.afterTrigger
  1326. && eventProcessor.afterTrigger(type);
  1327. return this;
  1328. },
  1329. /**
  1330. * Dispatch a event with context, which is specified at the last parameter.
  1331. *
  1332. * @param {string} type The event name.
  1333. */
  1334. triggerWithContext: function (type) {
  1335. var _h = this._$handlers[type];
  1336. var eventProcessor = this._$eventProcessor;
  1337. if (_h) {
  1338. var args = arguments;
  1339. var argLen = args.length;
  1340. if (argLen > 4) {
  1341. args = arrySlice.call(args, 1, args.length - 1);
  1342. }
  1343. var ctx = args[args.length - 1];
  1344. var len = _h.length;
  1345. for (var i = 0; i < len;) {
  1346. var hItem = _h[i];
  1347. if (eventProcessor
  1348. && eventProcessor.filter
  1349. && hItem.query != null
  1350. && !eventProcessor.filter(type, hItem.query)
  1351. ) {
  1352. i++;
  1353. continue;
  1354. }
  1355. // Optimize advise from backbone
  1356. switch (argLen) {
  1357. case 1:
  1358. hItem.h.call(ctx);
  1359. break;
  1360. case 2:
  1361. hItem.h.call(ctx, args[1]);
  1362. break;
  1363. case 3:
  1364. hItem.h.call(ctx, args[1], args[2]);
  1365. break;
  1366. default:
  1367. // have more than 2 given arguments
  1368. hItem.h.apply(ctx, args);
  1369. break;
  1370. }
  1371. if (hItem.one) {
  1372. _h.splice(i, 1);
  1373. len--;
  1374. }
  1375. else {
  1376. i++;
  1377. }
  1378. }
  1379. }
  1380. eventProcessor && eventProcessor.afterTrigger
  1381. && eventProcessor.afterTrigger(type);
  1382. return this;
  1383. }
  1384. };
  1385. function normalizeQuery(host, query) {
  1386. var eventProcessor = host._$eventProcessor;
  1387. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1388. query = eventProcessor.normalizeQuery(query);
  1389. }
  1390. return query;
  1391. }
  1392. function on(eventful, event, query, handler, context, isOnce) {
  1393. var _h = eventful._$handlers;
  1394. if (typeof query === 'function') {
  1395. context = handler;
  1396. handler = query;
  1397. query = null;
  1398. }
  1399. if (!handler || !event) {
  1400. return eventful;
  1401. }
  1402. query = normalizeQuery(eventful, query);
  1403. if (!_h[event]) {
  1404. _h[event] = [];
  1405. }
  1406. for (var i = 0; i < _h[event].length; i++) {
  1407. if (_h[event][i].h === handler) {
  1408. return eventful;
  1409. }
  1410. }
  1411. var wrap = {
  1412. h: handler,
  1413. one: isOnce,
  1414. query: query,
  1415. ctx: context || eventful,
  1416. // FIXME
  1417. // Do not publish this feature util it is proved that it makes sense.
  1418. callAtLast: handler.zrEventfulCallAtLast
  1419. };
  1420. var lastIndex = _h[event].length - 1;
  1421. var lastWrap = _h[event][lastIndex];
  1422. (lastWrap && lastWrap.callAtLast)
  1423. ? _h[event].splice(lastIndex, 0, wrap)
  1424. : _h[event].push(wrap);
  1425. return eventful;
  1426. }
  1427. /**
  1428. * The algoritm is learnt from
  1429. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1430. * And we made some optimization for matrix inversion.
  1431. * Other similar approaches:
  1432. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1433. */
  1434. var LN2 = Math.log(2);
  1435. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1436. var cacheKey = rowMask + '-' + colMask;
  1437. var fullRank = rows.length;
  1438. if (detCache.hasOwnProperty(cacheKey)) {
  1439. return detCache[cacheKey];
  1440. }
  1441. if (rank === 1) {
  1442. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1443. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1444. return rows[rowStart][colStart];
  1445. }
  1446. var subRowMask = rowMask | (1 << rowStart);
  1447. var subRowStart = rowStart + 1;
  1448. while (rowMask & (1 << subRowStart)) {
  1449. subRowStart++;
  1450. }
  1451. var sum = 0;
  1452. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1453. var colTag = 1 << j;
  1454. if (!(colTag & colMask)) {
  1455. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1456. // det(subMatrix(0, j))
  1457. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1458. colLocalIdx++;
  1459. }
  1460. }
  1461. detCache[cacheKey] = sum;
  1462. return sum;
  1463. }
  1464. /**
  1465. * Usage:
  1466. * ```js
  1467. * var transformer = buildTransformer(
  1468. * [10, 44, 100, 44, 100, 300, 10, 300],
  1469. * [50, 54, 130, 14, 140, 330, 14, 220]
  1470. * );
  1471. * var out = [];
  1472. * transformer && transformer([11, 33], out);
  1473. * ```
  1474. *
  1475. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1476. *
  1477. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1478. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1479. * @return {Function} transformer If fail, return null/undefined.
  1480. */
  1481. function buildTransformer(src, dest) {
  1482. var mA = [
  1483. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1484. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1485. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1486. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1487. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1488. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1489. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1490. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1491. ];
  1492. var detCache = {};
  1493. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1494. if (det === 0) {
  1495. return;
  1496. }
  1497. // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1498. var vh = [];
  1499. for (var i = 0; i < 8; i++) {
  1500. for (var j = 0; j < 8; j++) {
  1501. vh[j] == null && (vh[j] = 0);
  1502. vh[j] += ((i + j) % 2 ? -1 : 1)
  1503. // det(subMatrix(i, j))
  1504. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1505. / det * dest[i];
  1506. }
  1507. }
  1508. return function (out, srcPointX, srcPointY) {
  1509. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1510. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1511. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1512. };
  1513. }
  1514. /**
  1515. * Utilities for mouse or touch events.
  1516. */
  1517. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1518. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1519. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1520. var _calcOut = [];
  1521. /**
  1522. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1523. * the input `el`.
  1524. * CSS transform (2D & 3D) is supported.
  1525. *
  1526. * The strategy to fetch the coords:
  1527. * + If `calculate` is not set as `true`, users of this method should
  1528. * ensure that `el` is the same or the same size & location as `e.target`.
  1529. * Otherwise the result coords are probably not expected. Because we
  1530. * firstly try to get coords from e.offsetX/e.offsetY.
  1531. * + If `calculate` is set as `true`, the input `el` can be any element
  1532. * and we force to calculate the coords based on `el`.
  1533. * + The input `el` should be positionable (not position:static).
  1534. *
  1535. * The force `calculate` can be used in case like:
  1536. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1537. *
  1538. * @param {HTMLElement} el DOM element.
  1539. * @param {Event} e Mouse event or touch event.
  1540. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1541. * @param {boolean} [calculate=false] Whether to force calculate
  1542. * the coordinates but not use ones provided by browser.
  1543. */
  1544. function clientToLocal(el, e, out, calculate) {
  1545. out = out || {};
  1546. // According to the W3C Working Draft, offsetX and offsetY should be relative
  1547. // to the padding edge of the target element. The only browser using this convention
  1548. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1549. // not support the properties.
  1550. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1551. // In zr painter.dom, padding edge equals to border edge.
  1552. if (calculate || !env$1.canvasSupported) {
  1553. calculateZrXY(el, e, out);
  1554. }
  1555. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1556. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1557. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1558. // zoom-factor, overflow / opacity layers, transforms ...)
  1559. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1560. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1561. // BTW3, In ff, offsetX/offsetY is always 0.
  1562. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1563. out.zrX = e.layerX;
  1564. out.zrY = e.layerY;
  1565. }
  1566. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1567. else if (e.offsetX != null) {
  1568. out.zrX = e.offsetX;
  1569. out.zrY = e.offsetY;
  1570. }
  1571. // For some other device, e.g., IOS safari.
  1572. else {
  1573. calculateZrXY(el, e, out);
  1574. }
  1575. return out;
  1576. }
  1577. function calculateZrXY(el, e, out) {
  1578. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1579. if (el.getBoundingClientRect && env$1.domSupported) {
  1580. var ex = e.clientX;
  1581. var ey = e.clientY;
  1582. if (el.nodeName.toUpperCase() === 'CANVAS') {
  1583. // Original approach, which do not support CSS transform.
  1584. // marker can not be locationed in a canvas container
  1585. // (getBoundingClientRect is always 0). We do not support
  1586. // that input a pre-created canvas to zr while using css
  1587. // transform in iOS.
  1588. var box = el.getBoundingClientRect();
  1589. out.zrX = ex - box.left;
  1590. out.zrY = ey - box.top;
  1591. return;
  1592. }
  1593. else {
  1594. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1595. var transformer = preparePointerTransformer(prepareCoordMarkers(el, saved), saved);
  1596. if (transformer) {
  1597. transformer(_calcOut, ex, ey);
  1598. out.zrX = _calcOut[0];
  1599. out.zrY = _calcOut[1];
  1600. return;
  1601. }
  1602. }
  1603. }
  1604. out.zrX = out.zrY = 0;
  1605. }
  1606. function prepareCoordMarkers(el, saved) {
  1607. var markers = saved.markers;
  1608. if (markers) {
  1609. return markers;
  1610. }
  1611. markers = saved.markers = [];
  1612. var propLR = ['left', 'right'];
  1613. var propTB = ['top', 'bottom'];
  1614. for (var i = 0; i < 4; i++) {
  1615. var marker = document.createElement('div');
  1616. var stl = marker.style;
  1617. var idxLR = i % 2;
  1618. var idxTB = (i >> 1) % 2;
  1619. stl.cssText = [
  1620. 'position:absolute',
  1621. 'visibility: hidden',
  1622. 'padding: 0',
  1623. 'margin: 0',
  1624. 'border-width: 0',
  1625. 'width:0',
  1626. 'height:0',
  1627. // 'width: 5px',
  1628. // 'height: 5px',
  1629. propLR[idxLR] + ':0',
  1630. propTB[idxTB] + ':0',
  1631. propLR[1 - idxLR] + ':auto',
  1632. propTB[1 - idxTB] + ':auto',
  1633. ''
  1634. ].join('!important;');
  1635. el.appendChild(marker);
  1636. markers.push(marker);
  1637. }
  1638. return markers;
  1639. }
  1640. function preparePointerTransformer(markers, saved) {
  1641. var transformer = saved.transformer;
  1642. var oldSrcCoords = saved.srcCoords;
  1643. var useOld = true;
  1644. var srcCoords = [];
  1645. var destCoords = [];
  1646. for (var i = 0; i < 4; i++) {
  1647. var rect = markers[i].getBoundingClientRect();
  1648. var ii = 2 * i;
  1649. var x = rect.left;
  1650. var y = rect.top;
  1651. srcCoords.push(x, y);
  1652. useOld &= oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1653. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1654. }
  1655. // Cache to avoid time consuming of `buildTransformer`.
  1656. return useOld
  1657. ? transformer
  1658. : (
  1659. saved.srcCoords = srcCoords,
  1660. saved.transformer = buildTransformer(srcCoords, destCoords)
  1661. );
  1662. }
  1663. /**
  1664. * Find native event compat for legency IE.
  1665. * Should be called at the begining of a native event listener.
  1666. *
  1667. * @param {Event} [e] Mouse event or touch event or pointer event.
  1668. * For lagency IE, we use `window.event` is used.
  1669. * @return {Event} The native event.
  1670. */
  1671. function getNativeEvent(e) {
  1672. return e || window.event;
  1673. }
  1674. /**
  1675. * Normalize the coordinates of the input event.
  1676. *
  1677. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1678. * the input `el`.
  1679. * Get `e.zrDelta` if using mouse wheel.
  1680. * Get `e.which`, see the comment inside this function.
  1681. *
  1682. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1683. *
  1684. * Notice: see comments in `clientToLocal`. check the relationship
  1685. * between the result coords and the parameters `el` and `calculate`.
  1686. *
  1687. * @param {HTMLElement} el DOM element.
  1688. * @param {Event} [e] See `getNativeEvent`.
  1689. * @param {boolean} [calculate=false] Whether to force calculate
  1690. * the coordinates but not use ones provided by browser.
  1691. * @return {UIEvent} The normalized native UIEvent.
  1692. */
  1693. function normalizeEvent(el, e, calculate) {
  1694. e = getNativeEvent(e);
  1695. if (e.zrX != null) {
  1696. return e;
  1697. }
  1698. var eventType = e.type;
  1699. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1700. if (!isTouch) {
  1701. clientToLocal(el, e, e, calculate);
  1702. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1703. }
  1704. else {
  1705. var touch = eventType !== 'touchend'
  1706. ? e.targetTouches[0]
  1707. : e.changedTouches[0];
  1708. touch && clientToLocal(el, touch, e, calculate);
  1709. }
  1710. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1711. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1712. // If e.which has been defined, it may be readonly,
  1713. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1714. var button = e.button;
  1715. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1716. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1717. }
  1718. // [Caution]: `e.which` from browser is not always reliable. For example,
  1719. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1720. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1721. // `mousedown (pointerdown)` is the same as Chrome does.
  1722. return e;
  1723. }
  1724. /**
  1725. * @param {HTMLElement} el
  1726. * @param {string} name
  1727. * @param {Function} handler
  1728. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1729. * @param {boolean} [opt.capture=false]
  1730. * @param {boolean} [opt.passive=false]
  1731. */
  1732. function addEventListener(el, name, handler, opt) {
  1733. if (isDomLevel2) {
  1734. // Reproduct the console warning:
  1735. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1736. // Consider marking event handler as 'passive' to make the page more responsive.
  1737. // Just set console log level: verbose in chrome dev tool.
  1738. // then the warning log will be printed when addEventListener called.
  1739. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1740. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1741. // listener delegate all of the upper events of element. Some of those events need
  1742. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1743. // Before passive can be adopted, these issues should be considered:
  1744. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1745. // passive or not.
  1746. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1747. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1748. // compatibility should be handled.
  1749. // var opts = (env.passiveSupported && name === 'mousewheel')
  1750. // ? {passive: true}
  1751. // // By default, the third param of el.addEventListener is `capture: false`.
  1752. // : void 0;
  1753. // el.addEventListener(name, handler /* , opts */);
  1754. el.addEventListener(name, handler, opt);
  1755. }
  1756. else {
  1757. // For simplicity, do not implement `setCapture` for IE9-.
  1758. el.attachEvent('on' + name, handler);
  1759. }
  1760. }
  1761. /**
  1762. * Parameter are the same as `addEventListener`.
  1763. *
  1764. * Notice that if a listener is registered twice, one with capture and one without,
  1765. * remove each one separately. Removal of a capturing listener does not affect a
  1766. * non-capturing version of the same listener, and vice versa.
  1767. */
  1768. function removeEventListener(el, name, handler, opt) {
  1769. if (isDomLevel2) {
  1770. el.removeEventListener(name, handler, opt);
  1771. }
  1772. else {
  1773. el.detachEvent('on' + name, handler);
  1774. }
  1775. }
  1776. /**
  1777. * preventDefault and stopPropagation.
  1778. * Notice: do not use this method in zrender. It can only be
  1779. * used by upper applications if necessary.
  1780. *
  1781. * @param {Event} e A mouse or touch event.
  1782. */
  1783. var stop = isDomLevel2
  1784. ? function (e) {
  1785. e.preventDefault();
  1786. e.stopPropagation();
  1787. e.cancelBubble = true;
  1788. }
  1789. : function (e) {
  1790. e.returnValue = false;
  1791. e.cancelBubble = true;
  1792. };
  1793. /**
  1794. * This method only works for mouseup and mousedown. The functionality is restricted
  1795. * for fault tolerance, See the `e.which` compatibility above.
  1796. *
  1797. * @param {MouseEvent} e
  1798. * @return {boolean}
  1799. */
  1800. /**
  1801. * To be removed.
  1802. * @deprecated
  1803. */
  1804. /**
  1805. * Only implements needed gestures for mobile.
  1806. */
  1807. var GestureMgr = function () {
  1808. /**
  1809. * @private
  1810. * @type {Array.<Object>}
  1811. */
  1812. this._track = [];
  1813. };
  1814. GestureMgr.prototype = {
  1815. constructor: GestureMgr,
  1816. recognize: function (event, target, root) {
  1817. this._doTrack(event, target, root);
  1818. return this._recognize(event);
  1819. },
  1820. clear: function () {
  1821. this._track.length = 0;
  1822. return this;
  1823. },
  1824. _doTrack: function (event, target, root) {
  1825. var touches = event.touches;
  1826. if (!touches) {
  1827. return;
  1828. }
  1829. var trackItem = {
  1830. points: [],
  1831. touches: [],
  1832. target: target,
  1833. event: event
  1834. };
  1835. for (var i = 0, len = touches.length; i < len; i++) {
  1836. var touch = touches[i];
  1837. var pos = clientToLocal(root, touch, {});
  1838. trackItem.points.push([pos.zrX, pos.zrY]);
  1839. trackItem.touches.push(touch);
  1840. }
  1841. this._track.push(trackItem);
  1842. },
  1843. _recognize: function (event) {
  1844. for (var eventName in recognizers) {
  1845. if (recognizers.hasOwnProperty(eventName)) {
  1846. var gestureInfo = recognizers[eventName](this._track, event);
  1847. if (gestureInfo) {
  1848. return gestureInfo;
  1849. }
  1850. }
  1851. }
  1852. }
  1853. };
  1854. function dist$1(pointPair) {
  1855. var dx = pointPair[1][0] - pointPair[0][0];
  1856. var dy = pointPair[1][1] - pointPair[0][1];
  1857. return Math.sqrt(dx * dx + dy * dy);
  1858. }
  1859. function center(pointPair) {
  1860. return [
  1861. (pointPair[0][0] + pointPair[1][0]) / 2,
  1862. (pointPair[0][1] + pointPair[1][1]) / 2
  1863. ];
  1864. }
  1865. var recognizers = {
  1866. pinch: function (track, event) {
  1867. var trackLen = track.length;
  1868. if (!trackLen) {
  1869. return;
  1870. }
  1871. var pinchEnd = (track[trackLen - 1] || {}).points;
  1872. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1873. if (pinchPre
  1874. && pinchPre.length > 1
  1875. && pinchEnd
  1876. && pinchEnd.length > 1
  1877. ) {
  1878. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1879. !isFinite(pinchScale) && (pinchScale = 1);
  1880. event.pinchScale = pinchScale;
  1881. var pinchCenter = center(pinchEnd);
  1882. event.pinchX = pinchCenter[0];
  1883. event.pinchY = pinchCenter[1];
  1884. return {
  1885. type: 'pinch',
  1886. target: track[0].target,
  1887. event: event
  1888. };
  1889. }
  1890. }
  1891. // Only pinch currently.
  1892. };
  1893. /**
  1894. * [The interface between `Handler` and `HandlerProxy`]:
  1895. *
  1896. * The default `HandlerProxy` only support the common standard web environment
  1897. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1898. * But `HandlerProxy` can be replaced to support more non-standard environment
  1899. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1900. * not provided (like echarts-gl did).
  1901. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1902. * make break changes util inevitable. The interface include the public methods
  1903. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1904. * drives `Handler`.
  1905. */
  1906. /**
  1907. * [Drag outside]:
  1908. *
  1909. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1910. * zrender area when dragging. That is important for the improvement of the user experience
  1911. * when dragging something near the boundary without being terminated unexpectedly.
  1912. *
  1913. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1914. * to resolve this issue. But some drawbacks of it is described in
  1915. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1916. *
  1917. * Instead, we referenced the specifications:
  1918. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1919. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1920. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1921. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1922. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1923. *
  1924. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1925. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1926. * to fire until release the pointer. That is implemented by listen to those event on
  1927. * `document`.
  1928. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1929. * The touch event support this feature by default.
  1930. *
  1931. * Note:
  1932. * There might be some cases that the mouse event can not be
  1933. * received on `document`. For example,
  1934. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1935. * of zr dom throw Error .
  1936. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1937. * zr dom call `stopPropagation`.
  1938. * In these cases, the `mousemove` event might be keep triggered event
  1939. * if the mouse is released. We try to reduce the side-effect in those cases.
  1940. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1941. *
  1942. * Note:
  1943. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1944. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1945. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1946. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1947. * But they are needed to work when the pointer inside the zrender dom.
  1948. */
  1949. var SILENT = 'silent';
  1950. function makeEventPacket(eveType, targetInfo, event) {
  1951. return {
  1952. type: eveType,
  1953. event: event,
  1954. // target can only be an element that is not silent.
  1955. target: targetInfo.target,
  1956. // topTarget can be a silent element.
  1957. topTarget: targetInfo.topTarget,
  1958. cancelBubble: false,
  1959. offsetX: event.zrX,
  1960. offsetY: event.zrY,
  1961. gestureEvent: event.gestureEvent,
  1962. pinchX: event.pinchX,
  1963. pinchY: event.pinchY,
  1964. pinchScale: event.pinchScale,
  1965. wheelDelta: event.zrDelta,
  1966. zrByTouch: event.zrByTouch,
  1967. which: event.which,
  1968. stop: stopEvent
  1969. };
  1970. }
  1971. function stopEvent() {
  1972. stop(this.event);
  1973. }
  1974. function EmptyProxy() {}
  1975. EmptyProxy.prototype.dispose = function () {};
  1976. var handlerNames = [
  1977. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1978. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1979. ];
  1980. /**
  1981. * @alias module:zrender/Handler
  1982. * @constructor
  1983. * @extends module:zrender/mixin/Eventful
  1984. * @param {module:zrender/Storage} storage Storage instance.
  1985. * @param {module:zrender/Painter} painter Painter instance.
  1986. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1987. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1988. */
  1989. var Handler = function (storage, painter, proxy, painterRoot) {
  1990. Eventful.call(this);
  1991. this.storage = storage;
  1992. this.painter = painter;
  1993. this.painterRoot = painterRoot;
  1994. proxy = proxy || new EmptyProxy();
  1995. /**
  1996. * Proxy of event. can be Dom, WebGLSurface, etc.
  1997. */
  1998. this.proxy = null;
  1999. /**
  2000. * {target, topTarget, x, y}
  2001. * @private
  2002. * @type {Object}
  2003. */
  2004. this._hovered = {};
  2005. /**
  2006. * @private
  2007. * @type {Date}
  2008. */
  2009. this._lastTouchMoment;
  2010. /**
  2011. * @private
  2012. * @type {number}
  2013. */
  2014. this._lastX;
  2015. /**
  2016. * @private
  2017. * @type {number}
  2018. */
  2019. this._lastY;
  2020. /**
  2021. * @private
  2022. * @type {module:zrender/core/GestureMgr}
  2023. */
  2024. this._gestureMgr;
  2025. Draggable.call(this);
  2026. this.setHandlerProxy(proxy);
  2027. };
  2028. Handler.prototype = {
  2029. constructor: Handler,
  2030. setHandlerProxy: function (proxy) {
  2031. if (this.proxy) {
  2032. this.proxy.dispose();
  2033. }
  2034. if (proxy) {
  2035. each(handlerNames, function (name) {
  2036. proxy.on && proxy.on(name, this[name], this);
  2037. }, this);
  2038. // Attach handler
  2039. proxy.handler = this;
  2040. }
  2041. this.proxy = proxy;
  2042. },
  2043. mousemove: function (event) {
  2044. var x = event.zrX;
  2045. var y = event.zrY;
  2046. var isOutside = isOutsideBoundary(this, x, y);
  2047. var lastHovered = this._hovered;
  2048. var lastHoveredTarget = lastHovered.target;
  2049. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2050. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2051. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2052. // See #6198.
  2053. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2054. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2055. lastHoveredTarget = lastHovered.target;
  2056. }
  2057. var hovered = this._hovered = isOutside ? {x: x, y: y} : this.findHover(x, y);
  2058. var hoveredTarget = hovered.target;
  2059. var proxy = this.proxy;
  2060. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  2061. // Mouse out on previous hovered element
  2062. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2063. this.dispatchToElement(lastHovered, 'mouseout', event);
  2064. }
  2065. // Mouse moving on one element
  2066. this.dispatchToElement(hovered, 'mousemove', event);
  2067. // Mouse over on a new element
  2068. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2069. this.dispatchToElement(hovered, 'mouseover', event);
  2070. }
  2071. },
  2072. mouseout: function (event) {
  2073. var eventControl = event.zrEventControl;
  2074. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2075. if (eventControl !== 'only_globalout') {
  2076. this.dispatchToElement(this._hovered, 'mouseout', event);
  2077. }
  2078. if (eventControl !== 'no_globalout') {
  2079. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2080. // the `globalout` should have been triggered. But currently not.
  2081. !zrIsToLocalDOM && this.trigger('globalout', {type: 'globalout', event: event});
  2082. }
  2083. },
  2084. /**
  2085. * Resize
  2086. */
  2087. resize: function (event) {
  2088. this._hovered = {};
  2089. },
  2090. /**
  2091. * Dispatch event
  2092. * @param {string} eventName
  2093. * @param {event=} eventArgs
  2094. */
  2095. dispatch: function (eventName, eventArgs) {
  2096. var handler = this[eventName];
  2097. handler && handler.call(this, eventArgs);
  2098. },
  2099. /**
  2100. * Dispose
  2101. */
  2102. dispose: function () {
  2103. this.proxy.dispose();
  2104. this.storage =
  2105. this.proxy =
  2106. this.painter = null;
  2107. },
  2108. /**
  2109. * 设置默认的cursor style
  2110. * @param {string} [cursorStyle='default'] 例如 crosshair
  2111. */
  2112. setCursorStyle: function (cursorStyle) {
  2113. var proxy = this.proxy;
  2114. proxy.setCursor && proxy.setCursor(cursorStyle);
  2115. },
  2116. /**
  2117. * 事件分发代理
  2118. *
  2119. * @private
  2120. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2121. * @param {string} eventName 事件名称
  2122. * @param {Object} event 事件对象
  2123. */
  2124. dispatchToElement: function (targetInfo, eventName, event) {
  2125. targetInfo = targetInfo || {};
  2126. var el = targetInfo.target;
  2127. if (el && el.silent) {
  2128. return;
  2129. }
  2130. var eventHandler = 'on' + eventName;
  2131. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2132. while (el) {
  2133. el[eventHandler]
  2134. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2135. el.trigger(eventName, eventPacket);
  2136. el = el.parent;
  2137. if (eventPacket.cancelBubble) {
  2138. break;
  2139. }
  2140. }
  2141. if (!eventPacket.cancelBubble) {
  2142. // 冒泡到顶级 zrender 对象
  2143. this.trigger(eventName, eventPacket);
  2144. // 分发事件到用户自定义层
  2145. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2146. this.painter && this.painter.eachOtherLayer(function (layer) {
  2147. if (typeof (layer[eventHandler]) === 'function') {
  2148. layer[eventHandler].call(layer, eventPacket);
  2149. }
  2150. if (layer.trigger) {
  2151. layer.trigger(eventName, eventPacket);
  2152. }
  2153. });
  2154. }
  2155. },
  2156. /**
  2157. * @private
  2158. * @param {number} x
  2159. * @param {number} y
  2160. * @param {module:zrender/graphic/Displayable} exclude
  2161. * @return {model:zrender/Element}
  2162. * @method
  2163. */
  2164. findHover: function (x, y, exclude) {
  2165. var list = this.storage.getDisplayList();
  2166. var out = {x: x, y: y};
  2167. for (var i = list.length - 1; i >= 0; i--) {
  2168. var hoverCheckResult;
  2169. if (list[i] !== exclude
  2170. // getDisplayList may include ignored item in VML mode
  2171. && !list[i].ignore
  2172. && (hoverCheckResult = isHover(list[i], x, y))
  2173. ) {
  2174. !out.topTarget && (out.topTarget = list[i]);
  2175. if (hoverCheckResult !== SILENT) {
  2176. out.target = list[i];
  2177. break;
  2178. }
  2179. }
  2180. }
  2181. return out;
  2182. },
  2183. processGesture: function (event, stage) {
  2184. if (!this._gestureMgr) {
  2185. this._gestureMgr = new GestureMgr();
  2186. }
  2187. var gestureMgr = this._gestureMgr;
  2188. stage === 'start' && gestureMgr.clear();
  2189. var gestureInfo = gestureMgr.recognize(
  2190. event,
  2191. this.findHover(event.zrX, event.zrY, null).target,
  2192. this.proxy.dom
  2193. );
  2194. stage === 'end' && gestureMgr.clear();
  2195. // Do not do any preventDefault here. Upper application do that if necessary.
  2196. if (gestureInfo) {
  2197. var type = gestureInfo.type;
  2198. event.gestureEvent = type;
  2199. this.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  2200. }
  2201. }
  2202. };
  2203. // Common handlers
  2204. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2205. Handler.prototype[name] = function (event) {
  2206. var x = event.zrX;
  2207. var y = event.zrY;
  2208. var isOutside = isOutsideBoundary(this, x, y);
  2209. var hovered;
  2210. var hoveredTarget;
  2211. if (name !== 'mouseup' || !isOutside) {
  2212. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2213. hovered = this.findHover(x, y);
  2214. hoveredTarget = hovered.target;
  2215. }
  2216. if (name === 'mousedown') {
  2217. this._downEl = hoveredTarget;
  2218. this._downPoint = [event.zrX, event.zrY];
  2219. // In case click triggered before mouseup
  2220. this._upEl = hoveredTarget;
  2221. }
  2222. else if (name === 'mouseup') {
  2223. this._upEl = hoveredTarget;
  2224. }
  2225. else if (name === 'click') {
  2226. if (this._downEl !== this._upEl
  2227. // Original click event is triggered on the whole canvas element,
  2228. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2229. // which should be filtered, otherwise it will bring trouble to
  2230. // pan and zoom.
  2231. || !this._downPoint
  2232. // Arbitrary value
  2233. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  2234. ) {
  2235. return;
  2236. }
  2237. this._downPoint = null;
  2238. }
  2239. this.dispatchToElement(hovered, name, event);
  2240. };
  2241. });
  2242. function isHover(displayable, x, y) {
  2243. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2244. var el = displayable;
  2245. var isSilent;
  2246. while (el) {
  2247. // If clipped by ancestor.
  2248. // FIXME: If clipPath has neither stroke nor fill,
  2249. // el.clipPath.contain(x, y) will always return false.
  2250. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2251. return false;
  2252. }
  2253. if (el.silent) {
  2254. isSilent = true;
  2255. }
  2256. el = el.parent;
  2257. }
  2258. return isSilent ? SILENT : true;
  2259. }
  2260. return false;
  2261. }
  2262. /**
  2263. * See [Drag outside].
  2264. */
  2265. function isOutsideBoundary(handlerInstance, x, y) {
  2266. var painter = handlerInstance.painter;
  2267. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2268. }
  2269. mixin(Handler, Eventful);
  2270. mixin(Handler, Draggable);
  2271. /**
  2272. * 3x2矩阵操作类
  2273. * @exports zrender/tool/matrix
  2274. */
  2275. /* global Float32Array */
  2276. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  2277. ? Array
  2278. : Float32Array;
  2279. /**
  2280. * Create a identity matrix.
  2281. * @return {Float32Array|Array.<number>}
  2282. */
  2283. function create$1() {
  2284. var out = new ArrayCtor$1(6);
  2285. identity(out);
  2286. return out;
  2287. }
  2288. /**
  2289. * 设置矩阵为单位矩阵
  2290. * @param {Float32Array|Array.<number>} out
  2291. */
  2292. function identity(out) {
  2293. out[0] = 1;
  2294. out[1] = 0;
  2295. out[2] = 0;
  2296. out[3] = 1;
  2297. out[4] = 0;
  2298. out[5] = 0;
  2299. return out;
  2300. }
  2301. /**
  2302. * 复制矩阵
  2303. * @param {Float32Array|Array.<number>} out
  2304. * @param {Float32Array|Array.<number>} m
  2305. */
  2306. function copy$1(out, m) {
  2307. out[0] = m[0];
  2308. out[1] = m[1];
  2309. out[2] = m[2];
  2310. out[3] = m[3];
  2311. out[4] = m[4];
  2312. out[5] = m[5];
  2313. return out;
  2314. }
  2315. /**
  2316. * 矩阵相乘
  2317. * @param {Float32Array|Array.<number>} out
  2318. * @param {Float32Array|Array.<number>} m1
  2319. * @param {Float32Array|Array.<number>} m2
  2320. */
  2321. function mul$1(out, m1, m2) {
  2322. // Consider matrix.mul(m, m2, m);
  2323. // where out is the same as m2.
  2324. // So use temp variable to escape error.
  2325. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2326. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2327. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2328. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2329. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2330. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2331. out[0] = out0;
  2332. out[1] = out1;
  2333. out[2] = out2;
  2334. out[3] = out3;
  2335. out[4] = out4;
  2336. out[5] = out5;
  2337. return out;
  2338. }
  2339. /**
  2340. * 平移变换
  2341. * @param {Float32Array|Array.<number>} out
  2342. * @param {Float32Array|Array.<number>} a
  2343. * @param {Float32Array|Array.<number>} v
  2344. */
  2345. function translate(out, a, v) {
  2346. out[0] = a[0];
  2347. out[1] = a[1];
  2348. out[2] = a[2];
  2349. out[3] = a[3];
  2350. out[4] = a[4] + v[0];
  2351. out[5] = a[5] + v[1];
  2352. return out;
  2353. }
  2354. /**
  2355. * 旋转变换
  2356. * @param {Float32Array|Array.<number>} out
  2357. * @param {Float32Array|Array.<number>} a
  2358. * @param {number} rad
  2359. */
  2360. function rotate(out, a, rad) {
  2361. var aa = a[0];
  2362. var ac = a[2];
  2363. var atx = a[4];
  2364. var ab = a[1];
  2365. var ad = a[3];
  2366. var aty = a[5];
  2367. var st = Math.sin(rad);
  2368. var ct = Math.cos(rad);
  2369. out[0] = aa * ct + ab * st;
  2370. out[1] = -aa * st + ab * ct;
  2371. out[2] = ac * ct + ad * st;
  2372. out[3] = -ac * st + ct * ad;
  2373. out[4] = ct * atx + st * aty;
  2374. out[5] = ct * aty - st * atx;
  2375. return out;
  2376. }
  2377. /**
  2378. * 缩放变换
  2379. * @param {Float32Array|Array.<number>} out
  2380. * @param {Float32Array|Array.<number>} a
  2381. * @param {Float32Array|Array.<number>} v
  2382. */
  2383. function scale$1(out, a, v) {
  2384. var vx = v[0];
  2385. var vy = v[1];
  2386. out[0] = a[0] * vx;
  2387. out[1] = a[1] * vy;
  2388. out[2] = a[2] * vx;
  2389. out[3] = a[3] * vy;
  2390. out[4] = a[4] * vx;
  2391. out[5] = a[5] * vy;
  2392. return out;
  2393. }
  2394. /**
  2395. * 求逆矩阵
  2396. * @param {Float32Array|Array.<number>} out
  2397. * @param {Float32Array|Array.<number>} a
  2398. */
  2399. function invert(out, a) {
  2400. var aa = a[0];
  2401. var ac = a[2];
  2402. var atx = a[4];
  2403. var ab = a[1];
  2404. var ad = a[3];
  2405. var aty = a[5];
  2406. var det = aa * ad - ab * ac;
  2407. if (!det) {
  2408. return null;
  2409. }
  2410. det = 1.0 / det;
  2411. out[0] = ad * det;
  2412. out[1] = -ab * det;
  2413. out[2] = -ac * det;
  2414. out[3] = aa * det;
  2415. out[4] = (ac * aty - ad * atx) * det;
  2416. out[5] = (ab * atx - aa * aty) * det;
  2417. return out;
  2418. }
  2419. /**
  2420. * Clone a new matrix.
  2421. * @param {Float32Array|Array.<number>} a
  2422. */
  2423. function clone$2(a) {
  2424. var b = create$1();
  2425. copy$1(b, a);
  2426. return b;
  2427. }
  2428. var matrix = (Object.freeze || Object)({
  2429. create: create$1,
  2430. identity: identity,
  2431. copy: copy$1,
  2432. mul: mul$1,
  2433. translate: translate,
  2434. rotate: rotate,
  2435. scale: scale$1,
  2436. invert: invert,
  2437. clone: clone$2
  2438. });
  2439. /**
  2440. * 提供变换扩展
  2441. * @module zrender/mixin/Transformable
  2442. * @author pissang (https://www.github.com/pissang)
  2443. */
  2444. var mIdentity = identity;
  2445. var EPSILON = 5e-5;
  2446. function isNotAroundZero(val) {
  2447. return val > EPSILON || val < -EPSILON;
  2448. }
  2449. /**
  2450. * @alias module:zrender/mixin/Transformable
  2451. * @constructor
  2452. */
  2453. var Transformable = function (opts) {
  2454. opts = opts || {};
  2455. // If there are no given position, rotation, scale
  2456. if (!opts.position) {
  2457. /**
  2458. * 平移
  2459. * @type {Array.<number>}
  2460. * @default [0, 0]
  2461. */
  2462. this.position = [0, 0];
  2463. }
  2464. if (opts.rotation == null) {
  2465. /**
  2466. * 旋转
  2467. * @type {Array.<number>}
  2468. * @default 0
  2469. */
  2470. this.rotation = 0;
  2471. }
  2472. if (!opts.scale) {
  2473. /**
  2474. * 缩放
  2475. * @type {Array.<number>}
  2476. * @default [1, 1]
  2477. */
  2478. this.scale = [1, 1];
  2479. }
  2480. /**
  2481. * 旋转和缩放的原点
  2482. * @type {Array.<number>}
  2483. * @default null
  2484. */
  2485. this.origin = this.origin || null;
  2486. };
  2487. var transformableProto = Transformable.prototype;
  2488. transformableProto.transform = null;
  2489. /**
  2490. * 判断是否需要有坐标变换
  2491. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2492. */
  2493. transformableProto.needLocalTransform = function () {
  2494. return isNotAroundZero(this.rotation)
  2495. || isNotAroundZero(this.position[0])
  2496. || isNotAroundZero(this.position[1])
  2497. || isNotAroundZero(this.scale[0] - 1)
  2498. || isNotAroundZero(this.scale[1] - 1);
  2499. };
  2500. var scaleTmp = [];
  2501. transformableProto.updateTransform = function () {
  2502. var parent = this.parent;
  2503. var parentHasTransform = parent && parent.transform;
  2504. var needLocalTransform = this.needLocalTransform();
  2505. var m = this.transform;
  2506. if (!(needLocalTransform || parentHasTransform)) {
  2507. m && mIdentity(m);
  2508. return;
  2509. }
  2510. m = m || create$1();
  2511. if (needLocalTransform) {
  2512. this.getLocalTransform(m);
  2513. }
  2514. else {
  2515. mIdentity(m);
  2516. }
  2517. // 应用父节点变换
  2518. if (parentHasTransform) {
  2519. if (needLocalTransform) {
  2520. mul$1(m, parent.transform, m);
  2521. }
  2522. else {
  2523. copy$1(m, parent.transform);
  2524. }
  2525. }
  2526. // 保存这个变换矩阵
  2527. this.transform = m;
  2528. var globalScaleRatio = this.globalScaleRatio;
  2529. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2530. this.getGlobalScale(scaleTmp);
  2531. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2532. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2533. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2534. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2535. m[0] *= sx;
  2536. m[1] *= sx;
  2537. m[2] *= sy;
  2538. m[3] *= sy;
  2539. }
  2540. this.invTransform = this.invTransform || create$1();
  2541. invert(this.invTransform, m);
  2542. };
  2543. transformableProto.getLocalTransform = function (m) {
  2544. return Transformable.getLocalTransform(this, m);
  2545. };
  2546. /**
  2547. * 将自己的transform应用到context上
  2548. * @param {CanvasRenderingContext2D} ctx
  2549. */
  2550. transformableProto.setTransform = function (ctx) {
  2551. var m = this.transform;
  2552. var dpr = ctx.dpr || 1;
  2553. if (m) {
  2554. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2555. }
  2556. else {
  2557. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2558. }
  2559. };
  2560. transformableProto.restoreTransform = function (ctx) {
  2561. var dpr = ctx.dpr || 1;
  2562. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2563. };
  2564. var tmpTransform = [];
  2565. var originTransform = create$1();
  2566. transformableProto.setLocalTransform = function (m) {
  2567. if (!m) {
  2568. // TODO return or set identity?
  2569. return;
  2570. }
  2571. var sx = m[0] * m[0] + m[1] * m[1];
  2572. var sy = m[2] * m[2] + m[3] * m[3];
  2573. var position = this.position;
  2574. var scale$$1 = this.scale;
  2575. if (isNotAroundZero(sx - 1)) {
  2576. sx = Math.sqrt(sx);
  2577. }
  2578. if (isNotAroundZero(sy - 1)) {
  2579. sy = Math.sqrt(sy);
  2580. }
  2581. if (m[0] < 0) {
  2582. sx = -sx;
  2583. }
  2584. if (m[3] < 0) {
  2585. sy = -sy;
  2586. }
  2587. position[0] = m[4];
  2588. position[1] = m[5];
  2589. scale$$1[0] = sx;
  2590. scale$$1[1] = sy;
  2591. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2592. };
  2593. /**
  2594. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2595. */
  2596. transformableProto.decomposeTransform = function () {
  2597. if (!this.transform) {
  2598. return;
  2599. }
  2600. var parent = this.parent;
  2601. var m = this.transform;
  2602. if (parent && parent.transform) {
  2603. // Get local transform and decompose them to position, scale, rotation
  2604. mul$1(tmpTransform, parent.invTransform, m);
  2605. m = tmpTransform;
  2606. }
  2607. var origin = this.origin;
  2608. if (origin && (origin[0] || origin[1])) {
  2609. originTransform[4] = origin[0];
  2610. originTransform[5] = origin[1];
  2611. mul$1(tmpTransform, m, originTransform);
  2612. tmpTransform[4] -= origin[0];
  2613. tmpTransform[5] -= origin[1];
  2614. m = tmpTransform;
  2615. }
  2616. this.setLocalTransform(m);
  2617. };
  2618. /**
  2619. * Get global scale
  2620. * @return {Array.<number>}
  2621. */
  2622. transformableProto.getGlobalScale = function (out) {
  2623. var m = this.transform;
  2624. out = out || [];
  2625. if (!m) {
  2626. out[0] = 1;
  2627. out[1] = 1;
  2628. return out;
  2629. }
  2630. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2631. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2632. if (m[0] < 0) {
  2633. out[0] = -out[0];
  2634. }
  2635. if (m[3] < 0) {
  2636. out[1] = -out[1];
  2637. }
  2638. return out;
  2639. };
  2640. /**
  2641. * 变换坐标位置到 shape 的局部坐标空间
  2642. * @method
  2643. * @param {number} x
  2644. * @param {number} y
  2645. * @return {Array.<number>}
  2646. */
  2647. transformableProto.transformCoordToLocal = function (x, y) {
  2648. var v2 = [x, y];
  2649. var invTransform = this.invTransform;
  2650. if (invTransform) {
  2651. applyTransform(v2, v2, invTransform);
  2652. }
  2653. return v2;
  2654. };
  2655. /**
  2656. * 变换局部坐标位置到全局坐标空间
  2657. * @method
  2658. * @param {number} x
  2659. * @param {number} y
  2660. * @return {Array.<number>}
  2661. */
  2662. transformableProto.transformCoordToGlobal = function (x, y) {
  2663. var v2 = [x, y];
  2664. var transform = this.transform;
  2665. if (transform) {
  2666. applyTransform(v2, v2, transform);
  2667. }
  2668. return v2;
  2669. };
  2670. /**
  2671. * @static
  2672. * @param {Object} target
  2673. * @param {Array.<number>} target.origin
  2674. * @param {number} target.rotation
  2675. * @param {Array.<number>} target.position
  2676. * @param {Array.<number>} [m]
  2677. */
  2678. Transformable.getLocalTransform = function (target, m) {
  2679. m = m || [];
  2680. mIdentity(m);
  2681. var origin = target.origin;
  2682. var scale$$1 = target.scale || [1, 1];
  2683. var rotation = target.rotation || 0;
  2684. var position = target.position || [0, 0];
  2685. if (origin) {
  2686. // Translate to origin
  2687. m[4] -= origin[0];
  2688. m[5] -= origin[1];
  2689. }
  2690. scale$1(m, m, scale$$1);
  2691. if (rotation) {
  2692. rotate(m, m, rotation);
  2693. }
  2694. if (origin) {
  2695. // Translate back from origin
  2696. m[4] += origin[0];
  2697. m[5] += origin[1];
  2698. }
  2699. m[4] += position[0];
  2700. m[5] += position[1];
  2701. return m;
  2702. };
  2703. /**
  2704. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2705. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2706. * @exports zrender/animation/easing
  2707. */
  2708. var easing = {
  2709. /**
  2710. * @param {number} k
  2711. * @return {number}
  2712. */
  2713. linear: function (k) {
  2714. return k;
  2715. },
  2716. /**
  2717. * @param {number} k
  2718. * @return {number}
  2719. */
  2720. quadraticIn: function (k) {
  2721. return k * k;
  2722. },
  2723. /**
  2724. * @param {number} k
  2725. * @return {number}
  2726. */
  2727. quadraticOut: function (k) {
  2728. return k * (2 - k);
  2729. },
  2730. /**
  2731. * @param {number} k
  2732. * @return {number}
  2733. */
  2734. quadraticInOut: function (k) {
  2735. if ((k *= 2) < 1) {
  2736. return 0.5 * k * k;
  2737. }
  2738. return -0.5 * (--k * (k - 2) - 1);
  2739. },
  2740. // 三次方的缓动(t^3)
  2741. /**
  2742. * @param {number} k
  2743. * @return {number}
  2744. */
  2745. cubicIn: function (k) {
  2746. return k * k * k;
  2747. },
  2748. /**
  2749. * @param {number} k
  2750. * @return {number}
  2751. */
  2752. cubicOut: function (k) {
  2753. return --k * k * k + 1;
  2754. },
  2755. /**
  2756. * @param {number} k
  2757. * @return {number}
  2758. */
  2759. cubicInOut: function (k) {
  2760. if ((k *= 2) < 1) {
  2761. return 0.5 * k * k * k;
  2762. }
  2763. return 0.5 * ((k -= 2) * k * k + 2);
  2764. },
  2765. // 四次方的缓动(t^4)
  2766. /**
  2767. * @param {number} k
  2768. * @return {number}
  2769. */
  2770. quarticIn: function (k) {
  2771. return k * k * k * k;
  2772. },
  2773. /**
  2774. * @param {number} k
  2775. * @return {number}
  2776. */
  2777. quarticOut: function (k) {
  2778. return 1 - (--k * k * k * k);
  2779. },
  2780. /**
  2781. * @param {number} k
  2782. * @return {number}
  2783. */
  2784. quarticInOut: function (k) {
  2785. if ((k *= 2) < 1) {
  2786. return 0.5 * k * k * k * k;
  2787. }
  2788. return -0.5 * ((k -= 2) * k * k * k - 2);
  2789. },
  2790. // 五次方的缓动(t^5)
  2791. /**
  2792. * @param {number} k
  2793. * @return {number}
  2794. */
  2795. quinticIn: function (k) {
  2796. return k * k * k * k * k;
  2797. },
  2798. /**
  2799. * @param {number} k
  2800. * @return {number}
  2801. */
  2802. quinticOut: function (k) {
  2803. return --k * k * k * k * k + 1;
  2804. },
  2805. /**
  2806. * @param {number} k
  2807. * @return {number}
  2808. */
  2809. quinticInOut: function (k) {
  2810. if ((k *= 2) < 1) {
  2811. return 0.5 * k * k * k * k * k;
  2812. }
  2813. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2814. },
  2815. // 正弦曲线的缓动(sin(t))
  2816. /**
  2817. * @param {number} k
  2818. * @return {number}
  2819. */
  2820. sinusoidalIn: function (k) {
  2821. return 1 - Math.cos(k * Math.PI / 2);
  2822. },
  2823. /**
  2824. * @param {number} k
  2825. * @return {number}
  2826. */
  2827. sinusoidalOut: function (k) {
  2828. return Math.sin(k * Math.PI / 2);
  2829. },
  2830. /**
  2831. * @param {number} k
  2832. * @return {number}
  2833. */
  2834. sinusoidalInOut: function (k) {
  2835. return 0.5 * (1 - Math.cos(Math.PI * k));
  2836. },
  2837. // 指数曲线的缓动(2^t)
  2838. /**
  2839. * @param {number} k
  2840. * @return {number}
  2841. */
  2842. exponentialIn: function (k) {
  2843. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2844. },
  2845. /**
  2846. * @param {number} k
  2847. * @return {number}
  2848. */
  2849. exponentialOut: function (k) {
  2850. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2851. },
  2852. /**
  2853. * @param {number} k
  2854. * @return {number}
  2855. */
  2856. exponentialInOut: function (k) {
  2857. if (k === 0) {
  2858. return 0;
  2859. }
  2860. if (k === 1) {
  2861. return 1;
  2862. }
  2863. if ((k *= 2) < 1) {
  2864. return 0.5 * Math.pow(1024, k - 1);
  2865. }
  2866. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2867. },
  2868. // 圆形曲线的缓动(sqrt(1-t^2))
  2869. /**
  2870. * @param {number} k
  2871. * @return {number}
  2872. */
  2873. circularIn: function (k) {
  2874. return 1 - Math.sqrt(1 - k * k);
  2875. },
  2876. /**
  2877. * @param {number} k
  2878. * @return {number}
  2879. */
  2880. circularOut: function (k) {
  2881. return Math.sqrt(1 - (--k * k));
  2882. },
  2883. /**
  2884. * @param {number} k
  2885. * @return {number}
  2886. */
  2887. circularInOut: function (k) {
  2888. if ((k *= 2) < 1) {
  2889. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2890. }
  2891. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2892. },
  2893. // 创建类似于弹簧在停止前来回振荡的动画
  2894. /**
  2895. * @param {number} k
  2896. * @return {number}
  2897. */
  2898. elasticIn: function (k) {
  2899. var s;
  2900. var a = 0.1;
  2901. var p = 0.4;
  2902. if (k === 0) {
  2903. return 0;
  2904. }
  2905. if (k === 1) {
  2906. return 1;
  2907. }
  2908. if (!a || a < 1) {
  2909. a = 1;
  2910. s = p / 4;
  2911. }
  2912. else {
  2913. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2914. }
  2915. return -(a * Math.pow(2, 10 * (k -= 1))
  2916. * Math.sin((k - s) * (2 * Math.PI) / p));
  2917. },
  2918. /**
  2919. * @param {number} k
  2920. * @return {number}
  2921. */
  2922. elasticOut: function (k) {
  2923. var s;
  2924. var a = 0.1;
  2925. var p = 0.4;
  2926. if (k === 0) {
  2927. return 0;
  2928. }
  2929. if (k === 1) {
  2930. return 1;
  2931. }
  2932. if (!a || a < 1) {
  2933. a = 1;
  2934. s = p / 4;
  2935. }
  2936. else {
  2937. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2938. }
  2939. return (a * Math.pow(2, -10 * k)
  2940. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2941. },
  2942. /**
  2943. * @param {number} k
  2944. * @return {number}
  2945. */
  2946. elasticInOut: function (k) {
  2947. var s;
  2948. var a = 0.1;
  2949. var p = 0.4;
  2950. if (k === 0) {
  2951. return 0;
  2952. }
  2953. if (k === 1) {
  2954. return 1;
  2955. }
  2956. if (!a || a < 1) {
  2957. a = 1;
  2958. s = p / 4;
  2959. }
  2960. else {
  2961. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2962. }
  2963. if ((k *= 2) < 1) {
  2964. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2965. * Math.sin((k - s) * (2 * Math.PI) / p));
  2966. }
  2967. return a * Math.pow(2, -10 * (k -= 1))
  2968. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2969. },
  2970. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2971. /**
  2972. * @param {number} k
  2973. * @return {number}
  2974. */
  2975. backIn: function (k) {
  2976. var s = 1.70158;
  2977. return k * k * ((s + 1) * k - s);
  2978. },
  2979. /**
  2980. * @param {number} k
  2981. * @return {number}
  2982. */
  2983. backOut: function (k) {
  2984. var s = 1.70158;
  2985. return --k * k * ((s + 1) * k + s) + 1;
  2986. },
  2987. /**
  2988. * @param {number} k
  2989. * @return {number}
  2990. */
  2991. backInOut: function (k) {
  2992. var s = 1.70158 * 1.525;
  2993. if ((k *= 2) < 1) {
  2994. return 0.5 * (k * k * ((s + 1) * k - s));
  2995. }
  2996. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2997. },
  2998. // 创建弹跳效果
  2999. /**
  3000. * @param {number} k
  3001. * @return {number}
  3002. */
  3003. bounceIn: function (k) {
  3004. return 1 - easing.bounceOut(1 - k);
  3005. },
  3006. /**
  3007. * @param {number} k
  3008. * @return {number}
  3009. */
  3010. bounceOut: function (k) {
  3011. if (k < (1 / 2.75)) {
  3012. return 7.5625 * k * k;
  3013. }
  3014. else if (k < (2 / 2.75)) {
  3015. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  3016. }
  3017. else if (k < (2.5 / 2.75)) {
  3018. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  3019. }
  3020. else {
  3021. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  3022. }
  3023. },
  3024. /**
  3025. * @param {number} k
  3026. * @return {number}
  3027. */
  3028. bounceInOut: function (k) {
  3029. if (k < 0.5) {
  3030. return easing.bounceIn(k * 2) * 0.5;
  3031. }
  3032. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  3033. }
  3034. };
  3035. /**
  3036. * 动画主控制器
  3037. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  3038. * @config life(1000) 动画时长
  3039. * @config delay(0) 动画延迟时间
  3040. * @config loop(true)
  3041. * @config gap(0) 循环的间隔时间
  3042. * @config onframe
  3043. * @config easing(optional)
  3044. * @config ondestroy(optional)
  3045. * @config onrestart(optional)
  3046. *
  3047. * TODO pause
  3048. */
  3049. function Clip(options) {
  3050. this._target = options.target;
  3051. // 生命周期
  3052. this._life = options.life || 1000;
  3053. // 延时
  3054. this._delay = options.delay || 0;
  3055. // 开始时间
  3056. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  3057. this._initialized = false;
  3058. // 是否循环
  3059. this.loop = options.loop == null ? false : options.loop;
  3060. this.gap = options.gap || 0;
  3061. this.easing = options.easing || 'Linear';
  3062. this.onframe = options.onframe;
  3063. this.ondestroy = options.ondestroy;
  3064. this.onrestart = options.onrestart;
  3065. this._pausedTime = 0;
  3066. this._paused = false;
  3067. }
  3068. Clip.prototype = {
  3069. constructor: Clip,
  3070. step: function (globalTime, deltaTime) {
  3071. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3072. // PENDING
  3073. if (!this._initialized) {
  3074. this._startTime = globalTime + this._delay;
  3075. this._initialized = true;
  3076. }
  3077. if (this._paused) {
  3078. this._pausedTime += deltaTime;
  3079. return;
  3080. }
  3081. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  3082. // 还没开始
  3083. if (percent < 0) {
  3084. return;
  3085. }
  3086. percent = Math.min(percent, 1);
  3087. var easing$$1 = this.easing;
  3088. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3089. var schedule = typeof easingFunc === 'function'
  3090. ? easingFunc(percent)
  3091. : percent;
  3092. this.fire('frame', schedule);
  3093. // 结束
  3094. if (percent === 1) {
  3095. if (this.loop) {
  3096. this.restart(globalTime);
  3097. // 重新开始周期
  3098. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3099. return 'restart';
  3100. }
  3101. // 动画完成将这个控制器标识为待删除
  3102. // 在Animation.update中进行批量删除
  3103. this._needsRemove = true;
  3104. return 'destroy';
  3105. }
  3106. return null;
  3107. },
  3108. restart: function (globalTime) {
  3109. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3110. this._startTime = globalTime - remainder + this.gap;
  3111. this._pausedTime = 0;
  3112. this._needsRemove = false;
  3113. },
  3114. fire: function (eventType, arg) {
  3115. eventType = 'on' + eventType;
  3116. if (this[eventType]) {
  3117. this[eventType](this._target, arg);
  3118. }
  3119. },
  3120. pause: function () {
  3121. this._paused = true;
  3122. },
  3123. resume: function () {
  3124. this._paused = false;
  3125. }
  3126. };
  3127. // Simple LRU cache use doubly linked list
  3128. // @module zrender/core/LRU
  3129. /**
  3130. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3131. * @constructor
  3132. */
  3133. var LinkedList = function () {
  3134. /**
  3135. * @type {module:zrender/core/LRU~Entry}
  3136. */
  3137. this.head = null;
  3138. /**
  3139. * @type {module:zrender/core/LRU~Entry}
  3140. */
  3141. this.tail = null;
  3142. this._len = 0;
  3143. };
  3144. var linkedListProto = LinkedList.prototype;
  3145. /**
  3146. * Insert a new value at the tail
  3147. * @param {} val
  3148. * @return {module:zrender/core/LRU~Entry}
  3149. */
  3150. linkedListProto.insert = function (val) {
  3151. var entry = new Entry(val);
  3152. this.insertEntry(entry);
  3153. return entry;
  3154. };
  3155. /**
  3156. * Insert an entry at the tail
  3157. * @param {module:zrender/core/LRU~Entry} entry
  3158. */
  3159. linkedListProto.insertEntry = function (entry) {
  3160. if (!this.head) {
  3161. this.head = this.tail = entry;
  3162. }
  3163. else {
  3164. this.tail.next = entry;
  3165. entry.prev = this.tail;
  3166. entry.next = null;
  3167. this.tail = entry;
  3168. }
  3169. this._len++;
  3170. };
  3171. /**
  3172. * Remove entry.
  3173. * @param {module:zrender/core/LRU~Entry} entry
  3174. */
  3175. linkedListProto.remove = function (entry) {
  3176. var prev = entry.prev;
  3177. var next = entry.next;
  3178. if (prev) {
  3179. prev.next = next;
  3180. }
  3181. else {
  3182. // Is head
  3183. this.head = next;
  3184. }
  3185. if (next) {
  3186. next.prev = prev;
  3187. }
  3188. else {
  3189. // Is tail
  3190. this.tail = prev;
  3191. }
  3192. entry.next = entry.prev = null;
  3193. this._len--;
  3194. };
  3195. /**
  3196. * @return {number}
  3197. */
  3198. linkedListProto.len = function () {
  3199. return this._len;
  3200. };
  3201. /**
  3202. * Clear list
  3203. */
  3204. linkedListProto.clear = function () {
  3205. this.head = this.tail = null;
  3206. this._len = 0;
  3207. };
  3208. /**
  3209. * @constructor
  3210. * @param {} val
  3211. */
  3212. var Entry = function (val) {
  3213. /**
  3214. * @type {}
  3215. */
  3216. this.value = val;
  3217. /**
  3218. * @type {module:zrender/core/LRU~Entry}
  3219. */
  3220. this.next;
  3221. /**
  3222. * @type {module:zrender/core/LRU~Entry}
  3223. */
  3224. this.prev;
  3225. };
  3226. /**
  3227. * LRU Cache
  3228. * @constructor
  3229. * @alias module:zrender/core/LRU
  3230. */
  3231. var LRU = function (maxSize) {
  3232. this._list = new LinkedList();
  3233. this._map = {};
  3234. this._maxSize = maxSize || 10;
  3235. this._lastRemovedEntry = null;
  3236. };
  3237. var LRUProto = LRU.prototype;
  3238. /**
  3239. * @param {string} key
  3240. * @param {} value
  3241. * @return {} Removed value
  3242. */
  3243. LRUProto.put = function (key, value) {
  3244. var list = this._list;
  3245. var map = this._map;
  3246. var removed = null;
  3247. if (map[key] == null) {
  3248. var len = list.len();
  3249. // Reuse last removed entry
  3250. var entry = this._lastRemovedEntry;
  3251. if (len >= this._maxSize && len > 0) {
  3252. // Remove the least recently used
  3253. var leastUsedEntry = list.head;
  3254. list.remove(leastUsedEntry);
  3255. delete map[leastUsedEntry.key];
  3256. removed = leastUsedEntry.value;
  3257. this._lastRemovedEntry = leastUsedEntry;
  3258. }
  3259. if (entry) {
  3260. entry.value = value;
  3261. }
  3262. else {
  3263. entry = new Entry(value);
  3264. }
  3265. entry.key = key;
  3266. list.insertEntry(entry);
  3267. map[key] = entry;
  3268. }
  3269. return removed;
  3270. };
  3271. /**
  3272. * @param {string} key
  3273. * @return {}
  3274. */
  3275. LRUProto.get = function (key) {
  3276. var entry = this._map[key];
  3277. var list = this._list;
  3278. if (entry != null) {
  3279. // Put the latest used entry in the tail
  3280. if (entry !== list.tail) {
  3281. list.remove(entry);
  3282. list.insertEntry(entry);
  3283. }
  3284. return entry.value;
  3285. }
  3286. };
  3287. /**
  3288. * Clear the cache
  3289. */
  3290. LRUProto.clear = function () {
  3291. this._list.clear();
  3292. this._map = {};
  3293. };
  3294. var kCSSColorTable = {
  3295. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  3296. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  3297. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  3298. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  3299. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  3300. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  3301. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  3302. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  3303. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  3304. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  3305. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  3306. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  3307. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  3308. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  3309. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  3310. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  3311. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  3312. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  3313. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  3314. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  3315. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  3316. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  3317. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  3318. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  3319. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  3320. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  3321. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  3322. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  3323. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  3324. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  3325. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  3326. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  3327. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  3328. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  3329. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  3330. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  3331. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  3332. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  3333. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  3334. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  3335. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  3336. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  3337. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  3338. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  3339. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  3340. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  3341. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  3342. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  3343. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  3344. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  3345. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  3346. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  3347. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  3348. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  3349. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  3350. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  3351. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  3352. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  3353. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  3354. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  3355. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  3356. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  3357. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  3358. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  3359. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  3360. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  3361. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  3362. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  3363. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  3364. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  3365. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  3366. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  3367. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  3368. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  3369. };
  3370. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  3371. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3372. return i < 0 ? 0 : i > 255 ? 255 : i;
  3373. }
  3374. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  3375. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3376. return i < 0 ? 0 : i > 360 ? 360 : i;
  3377. }
  3378. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  3379. return f < 0 ? 0 : f > 1 ? 1 : f;
  3380. }
  3381. function parseCssInt(str) { // int or percentage.
  3382. if (str.length && str.charAt(str.length - 1) === '%') {
  3383. return clampCssByte(parseFloat(str) / 100 * 255);
  3384. }
  3385. return clampCssByte(parseInt(str, 10));
  3386. }
  3387. function parseCssFloat(str) { // float or percentage.
  3388. if (str.length && str.charAt(str.length - 1) === '%') {
  3389. return clampCssFloat(parseFloat(str) / 100);
  3390. }
  3391. return clampCssFloat(parseFloat(str));
  3392. }
  3393. function cssHueToRgb(m1, m2, h) {
  3394. if (h < 0) {
  3395. h += 1;
  3396. }
  3397. else if (h > 1) {
  3398. h -= 1;
  3399. }
  3400. if (h * 6 < 1) {
  3401. return m1 + (m2 - m1) * h * 6;
  3402. }
  3403. if (h * 2 < 1) {
  3404. return m2;
  3405. }
  3406. if (h * 3 < 2) {
  3407. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3408. }
  3409. return m1;
  3410. }
  3411. function lerpNumber(a, b, p) {
  3412. return a + (b - a) * p;
  3413. }
  3414. function setRgba(out, r, g, b, a) {
  3415. out[0] = r;
  3416. out[1] = g;
  3417. out[2] = b;
  3418. out[3] = a;
  3419. return out;
  3420. }
  3421. function copyRgba(out, a) {
  3422. out[0] = a[0];
  3423. out[1] = a[1];
  3424. out[2] = a[2];
  3425. out[3] = a[3];
  3426. return out;
  3427. }
  3428. var colorCache = new LRU(20);
  3429. var lastRemovedArr = null;
  3430. function putToCache(colorStr, rgbaArr) {
  3431. // Reuse removed array
  3432. if (lastRemovedArr) {
  3433. copyRgba(lastRemovedArr, rgbaArr);
  3434. }
  3435. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  3436. }
  3437. /**
  3438. * @param {string} colorStr
  3439. * @param {Array.<number>} out
  3440. * @return {Array.<number>}
  3441. * @memberOf module:zrender/util/color
  3442. */
  3443. function parse(colorStr, rgbaArr) {
  3444. if (!colorStr) {
  3445. return;
  3446. }
  3447. rgbaArr = rgbaArr || [];
  3448. var cached = colorCache.get(colorStr);
  3449. if (cached) {
  3450. return copyRgba(rgbaArr, cached);
  3451. }
  3452. // colorStr may be not string
  3453. colorStr = colorStr + '';
  3454. // Remove all whitespace, not compliant, but should just be more accepting.
  3455. var str = colorStr.replace(/ /g, '').toLowerCase();
  3456. // Color keywords (and transparent) lookup.
  3457. if (str in kCSSColorTable) {
  3458. copyRgba(rgbaArr, kCSSColorTable[str]);
  3459. putToCache(colorStr, rgbaArr);
  3460. return rgbaArr;
  3461. }
  3462. // #abc and #abc123 syntax.
  3463. if (str.charAt(0) === '#') {
  3464. if (str.length === 4) {
  3465. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3466. if (!(iv >= 0 && iv <= 0xfff)) {
  3467. setRgba(rgbaArr, 0, 0, 0, 1);
  3468. return; // Covers NaN.
  3469. }
  3470. setRgba(rgbaArr,
  3471. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  3472. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  3473. (iv & 0xf) | ((iv & 0xf) << 4),
  3474. 1
  3475. );
  3476. putToCache(colorStr, rgbaArr);
  3477. return rgbaArr;
  3478. }
  3479. else if (str.length === 7) {
  3480. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3481. if (!(iv >= 0 && iv <= 0xffffff)) {
  3482. setRgba(rgbaArr, 0, 0, 0, 1);
  3483. return; // Covers NaN.
  3484. }
  3485. setRgba(rgbaArr,
  3486. (iv & 0xff0000) >> 16,
  3487. (iv & 0xff00) >> 8,
  3488. iv & 0xff,
  3489. 1
  3490. );
  3491. putToCache(colorStr, rgbaArr);
  3492. return rgbaArr;
  3493. }
  3494. return;
  3495. }
  3496. var op = str.indexOf('(');
  3497. var ep = str.indexOf(')');
  3498. if (op !== -1 && ep + 1 === str.length) {
  3499. var fname = str.substr(0, op);
  3500. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3501. var alpha = 1; // To allow case fallthrough.
  3502. switch (fname) {
  3503. case 'rgba':
  3504. if (params.length !== 4) {
  3505. setRgba(rgbaArr, 0, 0, 0, 1);
  3506. return;
  3507. }
  3508. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  3509. // Fall through.
  3510. case 'rgb':
  3511. if (params.length !== 3) {
  3512. setRgba(rgbaArr, 0, 0, 0, 1);
  3513. return;
  3514. }
  3515. setRgba(rgbaArr,
  3516. parseCssInt(params[0]),
  3517. parseCssInt(params[1]),
  3518. parseCssInt(params[2]),
  3519. alpha
  3520. );
  3521. putToCache(colorStr, rgbaArr);
  3522. return rgbaArr;
  3523. case 'hsla':
  3524. if (params.length !== 4) {
  3525. setRgba(rgbaArr, 0, 0, 0, 1);
  3526. return;
  3527. }
  3528. params[3] = parseCssFloat(params[3]);
  3529. hsla2rgba(params, rgbaArr);
  3530. putToCache(colorStr, rgbaArr);
  3531. return rgbaArr;
  3532. case 'hsl':
  3533. if (params.length !== 3) {
  3534. setRgba(rgbaArr, 0, 0, 0, 1);
  3535. return;
  3536. }
  3537. hsla2rgba(params, rgbaArr);
  3538. putToCache(colorStr, rgbaArr);
  3539. return rgbaArr;
  3540. default:
  3541. return;
  3542. }
  3543. }
  3544. setRgba(rgbaArr, 0, 0, 0, 1);
  3545. return;
  3546. }
  3547. /**
  3548. * @param {Array.<number>} hsla
  3549. * @param {Array.<number>} rgba
  3550. * @return {Array.<number>} rgba
  3551. */
  3552. function hsla2rgba(hsla, rgba) {
  3553. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  3554. // NOTE(deanm): According to the CSS spec s/l should only be
  3555. // percentages, but we don't bother and let float or percentage.
  3556. var s = parseCssFloat(hsla[1]);
  3557. var l = parseCssFloat(hsla[2]);
  3558. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3559. var m1 = l * 2 - m2;
  3560. rgba = rgba || [];
  3561. setRgba(rgba,
  3562. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  3563. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  3564. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  3565. 1
  3566. );
  3567. if (hsla.length === 4) {
  3568. rgba[3] = hsla[3];
  3569. }
  3570. return rgba;
  3571. }
  3572. /**
  3573. * @param {Array.<number>} rgba
  3574. * @return {Array.<number>} hsla
  3575. */
  3576. function rgba2hsla(rgba) {
  3577. if (!rgba) {
  3578. return;
  3579. }
  3580. // RGB from 0 to 255
  3581. var R = rgba[0] / 255;
  3582. var G = rgba[1] / 255;
  3583. var B = rgba[2] / 255;
  3584. var vMin = Math.min(R, G, B); // Min. value of RGB
  3585. var vMax = Math.max(R, G, B); // Max. value of RGB
  3586. var delta = vMax - vMin; // Delta RGB value
  3587. var L = (vMax + vMin) / 2;
  3588. var H;
  3589. var S;
  3590. // HSL results from 0 to 1
  3591. if (delta === 0) {
  3592. H = 0;
  3593. S = 0;
  3594. }
  3595. else {
  3596. if (L < 0.5) {
  3597. S = delta / (vMax + vMin);
  3598. }
  3599. else {
  3600. S = delta / (2 - vMax - vMin);
  3601. }
  3602. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  3603. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  3604. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  3605. if (R === vMax) {
  3606. H = deltaB - deltaG;
  3607. }
  3608. else if (G === vMax) {
  3609. H = (1 / 3) + deltaR - deltaB;
  3610. }
  3611. else if (B === vMax) {
  3612. H = (2 / 3) + deltaG - deltaR;
  3613. }
  3614. if (H < 0) {
  3615. H += 1;
  3616. }
  3617. if (H > 1) {
  3618. H -= 1;
  3619. }
  3620. }
  3621. var hsla = [H * 360, S, L];
  3622. if (rgba[3] != null) {
  3623. hsla.push(rgba[3]);
  3624. }
  3625. return hsla;
  3626. }
  3627. /**
  3628. * @param {string} color
  3629. * @param {number} level
  3630. * @return {string}
  3631. * @memberOf module:zrender/util/color
  3632. */
  3633. function lift(color, level) {
  3634. var colorArr = parse(color);
  3635. if (colorArr) {
  3636. for (var i = 0; i < 3; i++) {
  3637. if (level < 0) {
  3638. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3639. }
  3640. else {
  3641. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  3642. }
  3643. if (colorArr[i] > 255) {
  3644. colorArr[i] = 255;
  3645. }
  3646. else if (color[i] < 0) {
  3647. colorArr[i] = 0;
  3648. }
  3649. }
  3650. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3651. }
  3652. }
  3653. /**
  3654. * @param {string} color
  3655. * @return {string}
  3656. * @memberOf module:zrender/util/color
  3657. */
  3658. function toHex(color) {
  3659. var colorArr = parse(color);
  3660. if (colorArr) {
  3661. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3662. }
  3663. }
  3664. /**
  3665. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3666. * @param {number} normalizedValue A float between 0 and 1.
  3667. * @param {Array.<Array.<number>>} colors List of rgba color array
  3668. * @param {Array.<number>} [out] Mapped gba color array
  3669. * @return {Array.<number>} will be null/undefined if input illegal.
  3670. */
  3671. function fastLerp(normalizedValue, colors, out) {
  3672. if (!(colors && colors.length)
  3673. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3674. ) {
  3675. return;
  3676. }
  3677. out = out || [];
  3678. var value = normalizedValue * (colors.length - 1);
  3679. var leftIndex = Math.floor(value);
  3680. var rightIndex = Math.ceil(value);
  3681. var leftColor = colors[leftIndex];
  3682. var rightColor = colors[rightIndex];
  3683. var dv = value - leftIndex;
  3684. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3685. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3686. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3687. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3688. return out;
  3689. }
  3690. /**
  3691. * @deprecated
  3692. */
  3693. var fastMapToColor = fastLerp;
  3694. /**
  3695. * @param {number} normalizedValue A float between 0 and 1.
  3696. * @param {Array.<string>} colors Color list.
  3697. * @param {boolean=} fullOutput Default false.
  3698. * @return {(string|Object)} Result color. If fullOutput,
  3699. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3700. * @memberOf module:zrender/util/color
  3701. */
  3702. function lerp$1(normalizedValue, colors, fullOutput) {
  3703. if (!(colors && colors.length)
  3704. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3705. ) {
  3706. return;
  3707. }
  3708. var value = normalizedValue * (colors.length - 1);
  3709. var leftIndex = Math.floor(value);
  3710. var rightIndex = Math.ceil(value);
  3711. var leftColor = parse(colors[leftIndex]);
  3712. var rightColor = parse(colors[rightIndex]);
  3713. var dv = value - leftIndex;
  3714. var color = stringify(
  3715. [
  3716. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3717. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3718. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3719. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3720. ],
  3721. 'rgba'
  3722. );
  3723. return fullOutput
  3724. ? {
  3725. color: color,
  3726. leftIndex: leftIndex,
  3727. rightIndex: rightIndex,
  3728. value: value
  3729. }
  3730. : color;
  3731. }
  3732. /**
  3733. * @deprecated
  3734. */
  3735. var mapToColor = lerp$1;
  3736. /**
  3737. * @param {string} color
  3738. * @param {number=} h 0 ~ 360, ignore when null.
  3739. * @param {number=} s 0 ~ 1, ignore when null.
  3740. * @param {number=} l 0 ~ 1, ignore when null.
  3741. * @return {string} Color string in rgba format.
  3742. * @memberOf module:zrender/util/color
  3743. */
  3744. function modifyHSL(color, h, s, l) {
  3745. color = parse(color);
  3746. if (color) {
  3747. color = rgba2hsla(color);
  3748. h != null && (color[0] = clampCssAngle(h));
  3749. s != null && (color[1] = parseCssFloat(s));
  3750. l != null && (color[2] = parseCssFloat(l));
  3751. return stringify(hsla2rgba(color), 'rgba');
  3752. }
  3753. }
  3754. /**
  3755. * @param {string} color
  3756. * @param {number=} alpha 0 ~ 1
  3757. * @return {string} Color string in rgba format.
  3758. * @memberOf module:zrender/util/color
  3759. */
  3760. function modifyAlpha(color, alpha) {
  3761. color = parse(color);
  3762. if (color && alpha != null) {
  3763. color[3] = clampCssFloat(alpha);
  3764. return stringify(color, 'rgba');
  3765. }
  3766. }
  3767. /**
  3768. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3769. * @param {string} type 'rgba', 'hsva', ...
  3770. * @return {string} Result color. (If input illegal, return undefined).
  3771. */
  3772. function stringify(arrColor, type) {
  3773. if (!arrColor || !arrColor.length) {
  3774. return;
  3775. }
  3776. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3777. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3778. colorStr += ',' + arrColor[3];
  3779. }
  3780. return type + '(' + colorStr + ')';
  3781. }
  3782. var color = (Object.freeze || Object)({
  3783. parse: parse,
  3784. lift: lift,
  3785. toHex: toHex,
  3786. fastLerp: fastLerp,
  3787. fastMapToColor: fastMapToColor,
  3788. lerp: lerp$1,
  3789. mapToColor: mapToColor,
  3790. modifyHSL: modifyHSL,
  3791. modifyAlpha: modifyAlpha,
  3792. stringify: stringify
  3793. });
  3794. /**
  3795. * @module echarts/animation/Animator
  3796. */
  3797. var arraySlice = Array.prototype.slice;
  3798. function defaultGetter(target, key) {
  3799. return target[key];
  3800. }
  3801. function defaultSetter(target, key, value) {
  3802. target[key] = value;
  3803. }
  3804. /**
  3805. * @param {number} p0
  3806. * @param {number} p1
  3807. * @param {number} percent
  3808. * @return {number}
  3809. */
  3810. function interpolateNumber(p0, p1, percent) {
  3811. return (p1 - p0) * percent + p0;
  3812. }
  3813. /**
  3814. * @param {string} p0
  3815. * @param {string} p1
  3816. * @param {number} percent
  3817. * @return {string}
  3818. */
  3819. function interpolateString(p0, p1, percent) {
  3820. return percent > 0.5 ? p1 : p0;
  3821. }
  3822. /**
  3823. * @param {Array} p0
  3824. * @param {Array} p1
  3825. * @param {number} percent
  3826. * @param {Array} out
  3827. * @param {number} arrDim
  3828. */
  3829. function interpolateArray(p0, p1, percent, out, arrDim) {
  3830. var len = p0.length;
  3831. if (arrDim === 1) {
  3832. for (var i = 0; i < len; i++) {
  3833. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3834. }
  3835. }
  3836. else {
  3837. var len2 = len && p0[0].length;
  3838. for (var i = 0; i < len; i++) {
  3839. for (var j = 0; j < len2; j++) {
  3840. out[i][j] = interpolateNumber(
  3841. p0[i][j], p1[i][j], percent
  3842. );
  3843. }
  3844. }
  3845. }
  3846. }
  3847. // arr0 is source array, arr1 is target array.
  3848. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3849. function fillArr(arr0, arr1, arrDim) {
  3850. var arr0Len = arr0.length;
  3851. var arr1Len = arr1.length;
  3852. if (arr0Len !== arr1Len) {
  3853. // FIXME Not work for TypedArray
  3854. var isPreviousLarger = arr0Len > arr1Len;
  3855. if (isPreviousLarger) {
  3856. // Cut the previous
  3857. arr0.length = arr1Len;
  3858. }
  3859. else {
  3860. // Fill the previous
  3861. for (var i = arr0Len; i < arr1Len; i++) {
  3862. arr0.push(
  3863. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3864. );
  3865. }
  3866. }
  3867. }
  3868. // Handling NaN value
  3869. var len2 = arr0[0] && arr0[0].length;
  3870. for (var i = 0; i < arr0.length; i++) {
  3871. if (arrDim === 1) {
  3872. if (isNaN(arr0[i])) {
  3873. arr0[i] = arr1[i];
  3874. }
  3875. }
  3876. else {
  3877. for (var j = 0; j < len2; j++) {
  3878. if (isNaN(arr0[i][j])) {
  3879. arr0[i][j] = arr1[i][j];
  3880. }
  3881. }
  3882. }
  3883. }
  3884. }
  3885. /**
  3886. * @param {Array} arr0
  3887. * @param {Array} arr1
  3888. * @param {number} arrDim
  3889. * @return {boolean}
  3890. */
  3891. function isArraySame(arr0, arr1, arrDim) {
  3892. if (arr0 === arr1) {
  3893. return true;
  3894. }
  3895. var len = arr0.length;
  3896. if (len !== arr1.length) {
  3897. return false;
  3898. }
  3899. if (arrDim === 1) {
  3900. for (var i = 0; i < len; i++) {
  3901. if (arr0[i] !== arr1[i]) {
  3902. return false;
  3903. }
  3904. }
  3905. }
  3906. else {
  3907. var len2 = arr0[0].length;
  3908. for (var i = 0; i < len; i++) {
  3909. for (var j = 0; j < len2; j++) {
  3910. if (arr0[i][j] !== arr1[i][j]) {
  3911. return false;
  3912. }
  3913. }
  3914. }
  3915. }
  3916. return true;
  3917. }
  3918. /**
  3919. * Catmull Rom interpolate array
  3920. * @param {Array} p0
  3921. * @param {Array} p1
  3922. * @param {Array} p2
  3923. * @param {Array} p3
  3924. * @param {number} t
  3925. * @param {number} t2
  3926. * @param {number} t3
  3927. * @param {Array} out
  3928. * @param {number} arrDim
  3929. */
  3930. function catmullRomInterpolateArray(
  3931. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3932. ) {
  3933. var len = p0.length;
  3934. if (arrDim === 1) {
  3935. for (var i = 0; i < len; i++) {
  3936. out[i] = catmullRomInterpolate(
  3937. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3938. );
  3939. }
  3940. }
  3941. else {
  3942. var len2 = p0[0].length;
  3943. for (var i = 0; i < len; i++) {
  3944. for (var j = 0; j < len2; j++) {
  3945. out[i][j] = catmullRomInterpolate(
  3946. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3947. t, t2, t3
  3948. );
  3949. }
  3950. }
  3951. }
  3952. }
  3953. /**
  3954. * Catmull Rom interpolate number
  3955. * @param {number} p0
  3956. * @param {number} p1
  3957. * @param {number} p2
  3958. * @param {number} p3
  3959. * @param {number} t
  3960. * @param {number} t2
  3961. * @param {number} t3
  3962. * @return {number}
  3963. */
  3964. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3965. var v0 = (p2 - p0) * 0.5;
  3966. var v1 = (p3 - p1) * 0.5;
  3967. return (2 * (p1 - p2) + v0 + v1) * t3
  3968. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3969. + v0 * t + p1;
  3970. }
  3971. function cloneValue(value) {
  3972. if (isArrayLike(value)) {
  3973. var len = value.length;
  3974. if (isArrayLike(value[0])) {
  3975. var ret = [];
  3976. for (var i = 0; i < len; i++) {
  3977. ret.push(arraySlice.call(value[i]));
  3978. }
  3979. return ret;
  3980. }
  3981. return arraySlice.call(value);
  3982. }
  3983. return value;
  3984. }
  3985. function rgba2String(rgba) {
  3986. rgba[0] = Math.floor(rgba[0]);
  3987. rgba[1] = Math.floor(rgba[1]);
  3988. rgba[2] = Math.floor(rgba[2]);
  3989. return 'rgba(' + rgba.join(',') + ')';
  3990. }
  3991. function getArrayDim(keyframes) {
  3992. var lastValue = keyframes[keyframes.length - 1].value;
  3993. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3994. }
  3995. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3996. var getter = animator._getter;
  3997. var setter = animator._setter;
  3998. var useSpline = easing === 'spline';
  3999. var trackLen = keyframes.length;
  4000. if (!trackLen) {
  4001. return;
  4002. }
  4003. // Guess data type
  4004. var firstVal = keyframes[0].value;
  4005. var isValueArray = isArrayLike(firstVal);
  4006. var isValueColor = false;
  4007. var isValueString = false;
  4008. // For vertices morphing
  4009. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  4010. var trackMaxTime;
  4011. // Sort keyframe as ascending
  4012. keyframes.sort(function (a, b) {
  4013. return a.time - b.time;
  4014. });
  4015. trackMaxTime = keyframes[trackLen - 1].time;
  4016. // Percents of each keyframe
  4017. var kfPercents = [];
  4018. // Value of each keyframe
  4019. var kfValues = [];
  4020. var prevValue = keyframes[0].value;
  4021. var isAllValueEqual = true;
  4022. for (var i = 0; i < trackLen; i++) {
  4023. kfPercents.push(keyframes[i].time / trackMaxTime);
  4024. // Assume value is a color when it is a string
  4025. var value = keyframes[i].value;
  4026. // Check if value is equal, deep check if value is array
  4027. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  4028. || (!isValueArray && value === prevValue))) {
  4029. isAllValueEqual = false;
  4030. }
  4031. prevValue = value;
  4032. // Try converting a string to a color array
  4033. if (typeof value === 'string') {
  4034. var colorArray = parse(value);
  4035. if (colorArray) {
  4036. value = colorArray;
  4037. isValueColor = true;
  4038. }
  4039. else {
  4040. isValueString = true;
  4041. }
  4042. }
  4043. kfValues.push(value);
  4044. }
  4045. if (!forceAnimate && isAllValueEqual) {
  4046. return;
  4047. }
  4048. var lastValue = kfValues[trackLen - 1];
  4049. // Polyfill array and NaN value
  4050. for (var i = 0; i < trackLen - 1; i++) {
  4051. if (isValueArray) {
  4052. fillArr(kfValues[i], lastValue, arrDim);
  4053. }
  4054. else {
  4055. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  4056. kfValues[i] = lastValue;
  4057. }
  4058. }
  4059. }
  4060. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  4061. // Cache the key of last frame to speed up when
  4062. // animation playback is sequency
  4063. var lastFrame = 0;
  4064. var lastFramePercent = 0;
  4065. var start;
  4066. var w;
  4067. var p0;
  4068. var p1;
  4069. var p2;
  4070. var p3;
  4071. if (isValueColor) {
  4072. var rgba = [0, 0, 0, 0];
  4073. }
  4074. var onframe = function (target, percent) {
  4075. // Find the range keyframes
  4076. // kf1-----kf2---------current--------kf3
  4077. // find kf2 and kf3 and do interpolation
  4078. var frame;
  4079. // In the easing function like elasticOut, percent may less than 0
  4080. if (percent < 0) {
  4081. frame = 0;
  4082. }
  4083. else if (percent < lastFramePercent) {
  4084. // Start from next key
  4085. // PENDING start from lastFrame ?
  4086. start = Math.min(lastFrame + 1, trackLen - 1);
  4087. for (frame = start; frame >= 0; frame--) {
  4088. if (kfPercents[frame] <= percent) {
  4089. break;
  4090. }
  4091. }
  4092. // PENDING really need to do this ?
  4093. frame = Math.min(frame, trackLen - 2);
  4094. }
  4095. else {
  4096. for (frame = lastFrame; frame < trackLen; frame++) {
  4097. if (kfPercents[frame] > percent) {
  4098. break;
  4099. }
  4100. }
  4101. frame = Math.min(frame - 1, trackLen - 2);
  4102. }
  4103. lastFrame = frame;
  4104. lastFramePercent = percent;
  4105. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  4106. if (range === 0) {
  4107. return;
  4108. }
  4109. else {
  4110. w = (percent - kfPercents[frame]) / range;
  4111. }
  4112. if (useSpline) {
  4113. p1 = kfValues[frame];
  4114. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4115. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4116. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4117. if (isValueArray) {
  4118. catmullRomInterpolateArray(
  4119. p0, p1, p2, p3, w, w * w, w * w * w,
  4120. getter(target, propName),
  4121. arrDim
  4122. );
  4123. }
  4124. else {
  4125. var value;
  4126. if (isValueColor) {
  4127. value = catmullRomInterpolateArray(
  4128. p0, p1, p2, p3, w, w * w, w * w * w,
  4129. rgba, 1
  4130. );
  4131. value = rgba2String(rgba);
  4132. }
  4133. else if (isValueString) {
  4134. // String is step(0.5)
  4135. return interpolateString(p1, p2, w);
  4136. }
  4137. else {
  4138. value = catmullRomInterpolate(
  4139. p0, p1, p2, p3, w, w * w, w * w * w
  4140. );
  4141. }
  4142. setter(
  4143. target,
  4144. propName,
  4145. value
  4146. );
  4147. }
  4148. }
  4149. else {
  4150. if (isValueArray) {
  4151. interpolateArray(
  4152. kfValues[frame], kfValues[frame + 1], w,
  4153. getter(target, propName),
  4154. arrDim
  4155. );
  4156. }
  4157. else {
  4158. var value;
  4159. if (isValueColor) {
  4160. interpolateArray(
  4161. kfValues[frame], kfValues[frame + 1], w,
  4162. rgba, 1
  4163. );
  4164. value = rgba2String(rgba);
  4165. }
  4166. else if (isValueString) {
  4167. // String is step(0.5)
  4168. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4169. }
  4170. else {
  4171. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4172. }
  4173. setter(
  4174. target,
  4175. propName,
  4176. value
  4177. );
  4178. }
  4179. }
  4180. };
  4181. var clip = new Clip({
  4182. target: animator._target,
  4183. life: trackMaxTime,
  4184. loop: animator._loop,
  4185. delay: animator._delay,
  4186. onframe: onframe,
  4187. ondestroy: oneTrackDone
  4188. });
  4189. if (easing && easing !== 'spline') {
  4190. clip.easing = easing;
  4191. }
  4192. return clip;
  4193. }
  4194. /**
  4195. * @alias module:zrender/animation/Animator
  4196. * @constructor
  4197. * @param {Object} target
  4198. * @param {boolean} loop
  4199. * @param {Function} getter
  4200. * @param {Function} setter
  4201. */
  4202. var Animator = function (target, loop, getter, setter) {
  4203. this._tracks = {};
  4204. this._target = target;
  4205. this._loop = loop || false;
  4206. this._getter = getter || defaultGetter;
  4207. this._setter = setter || defaultSetter;
  4208. this._clipCount = 0;
  4209. this._delay = 0;
  4210. this._doneList = [];
  4211. this._onframeList = [];
  4212. this._clipList = [];
  4213. };
  4214. Animator.prototype = {
  4215. /**
  4216. * 设置动画关键帧
  4217. * @param {number} time 关键帧时间,单位是ms
  4218. * @param {Object} props 关键帧的属性值,key-value表示
  4219. * @return {module:zrender/animation/Animator}
  4220. */
  4221. when: function (time /* ms */, props) {
  4222. var tracks = this._tracks;
  4223. for (var propName in props) {
  4224. if (!props.hasOwnProperty(propName)) {
  4225. continue;
  4226. }
  4227. if (!tracks[propName]) {
  4228. tracks[propName] = [];
  4229. // Invalid value
  4230. var value = this._getter(this._target, propName);
  4231. if (value == null) {
  4232. // zrLog('Invalid property ' + propName);
  4233. continue;
  4234. }
  4235. // If time is 0
  4236. // Then props is given initialize value
  4237. // Else
  4238. // Initialize value from current prop value
  4239. if (time !== 0) {
  4240. tracks[propName].push({
  4241. time: 0,
  4242. value: cloneValue(value)
  4243. });
  4244. }
  4245. }
  4246. tracks[propName].push({
  4247. time: time,
  4248. value: props[propName]
  4249. });
  4250. }
  4251. return this;
  4252. },
  4253. /**
  4254. * 添加动画每一帧的回调函数
  4255. * @param {Function} callback
  4256. * @return {module:zrender/animation/Animator}
  4257. */
  4258. during: function (callback) {
  4259. this._onframeList.push(callback);
  4260. return this;
  4261. },
  4262. pause: function () {
  4263. for (var i = 0; i < this._clipList.length; i++) {
  4264. this._clipList[i].pause();
  4265. }
  4266. this._paused = true;
  4267. },
  4268. resume: function () {
  4269. for (var i = 0; i < this._clipList.length; i++) {
  4270. this._clipList[i].resume();
  4271. }
  4272. this._paused = false;
  4273. },
  4274. isPaused: function () {
  4275. return !!this._paused;
  4276. },
  4277. _doneCallback: function () {
  4278. // Clear all tracks
  4279. this._tracks = {};
  4280. // Clear all clips
  4281. this._clipList.length = 0;
  4282. var doneList = this._doneList;
  4283. var len = doneList.length;
  4284. for (var i = 0; i < len; i++) {
  4285. doneList[i].call(this);
  4286. }
  4287. },
  4288. /**
  4289. * 开始执行动画
  4290. * @param {string|Function} [easing]
  4291. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4292. * @param {boolean} forceAnimate
  4293. * @return {module:zrender/animation/Animator}
  4294. */
  4295. start: function (easing, forceAnimate) {
  4296. var self = this;
  4297. var clipCount = 0;
  4298. var oneTrackDone = function () {
  4299. clipCount--;
  4300. if (!clipCount) {
  4301. self._doneCallback();
  4302. }
  4303. };
  4304. var lastClip;
  4305. for (var propName in this._tracks) {
  4306. if (!this._tracks.hasOwnProperty(propName)) {
  4307. continue;
  4308. }
  4309. var clip = createTrackClip(
  4310. this, easing, oneTrackDone,
  4311. this._tracks[propName], propName, forceAnimate
  4312. );
  4313. if (clip) {
  4314. this._clipList.push(clip);
  4315. clipCount++;
  4316. // If start after added to animation
  4317. if (this.animation) {
  4318. this.animation.addClip(clip);
  4319. }
  4320. lastClip = clip;
  4321. }
  4322. }
  4323. // Add during callback on the last clip
  4324. if (lastClip) {
  4325. var oldOnFrame = lastClip.onframe;
  4326. lastClip.onframe = function (target, percent) {
  4327. oldOnFrame(target, percent);
  4328. for (var i = 0; i < self._onframeList.length; i++) {
  4329. self._onframeList[i](target, percent);
  4330. }
  4331. };
  4332. }
  4333. // This optimization will help the case that in the upper application
  4334. // the view may be refreshed frequently, where animation will be
  4335. // called repeatly but nothing changed.
  4336. if (!clipCount) {
  4337. this._doneCallback();
  4338. }
  4339. return this;
  4340. },
  4341. /**
  4342. * 停止动画
  4343. * @param {boolean} forwardToLast If move to last frame before stop
  4344. */
  4345. stop: function (forwardToLast) {
  4346. var clipList = this._clipList;
  4347. var animation = this.animation;
  4348. for (var i = 0; i < clipList.length; i++) {
  4349. var clip = clipList[i];
  4350. if (forwardToLast) {
  4351. // Move to last frame before stop
  4352. clip.onframe(this._target, 1);
  4353. }
  4354. animation && animation.removeClip(clip);
  4355. }
  4356. clipList.length = 0;
  4357. },
  4358. /**
  4359. * 设置动画延迟开始的时间
  4360. * @param {number} time 单位ms
  4361. * @return {module:zrender/animation/Animator}
  4362. */
  4363. delay: function (time) {
  4364. this._delay = time;
  4365. return this;
  4366. },
  4367. /**
  4368. * 添加动画结束的回调
  4369. * @param {Function} cb
  4370. * @return {module:zrender/animation/Animator}
  4371. */
  4372. done: function (cb) {
  4373. if (cb) {
  4374. this._doneList.push(cb);
  4375. }
  4376. return this;
  4377. },
  4378. /**
  4379. * @return {Array.<module:zrender/animation/Clip>}
  4380. */
  4381. getClips: function () {
  4382. return this._clipList;
  4383. }
  4384. };
  4385. var dpr = 1;
  4386. // If in browser environment
  4387. if (typeof window !== 'undefined') {
  4388. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4389. }
  4390. /**
  4391. * config默认配置项
  4392. * @exports zrender/config
  4393. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4394. */
  4395. /**
  4396. * Debug log mode:
  4397. * 0: Do nothing, for release.
  4398. * 1: console.error, for debug.
  4399. */
  4400. var debugMode = 0;
  4401. // retina 屏幕优化
  4402. var devicePixelRatio = dpr;
  4403. var logError = function () {
  4404. };
  4405. if (debugMode === 1) {
  4406. logError = console.error;
  4407. }
  4408. var logError$1 = logError;
  4409. /**
  4410. * @alias modue:zrender/mixin/Animatable
  4411. * @constructor
  4412. */
  4413. var Animatable = function () {
  4414. /**
  4415. * @type {Array.<module:zrender/animation/Animator>}
  4416. * @readOnly
  4417. */
  4418. this.animators = [];
  4419. };
  4420. Animatable.prototype = {
  4421. constructor: Animatable,
  4422. /**
  4423. * 动画
  4424. *
  4425. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4426. * @param {boolean} [loop] Whether to loop animation.
  4427. * @return {module:zrender/animation/Animator}
  4428. * @example:
  4429. * el.animate('style', false)
  4430. * .when(1000, {x: 10} )
  4431. * .done(function(){ // Animation done })
  4432. * .start()
  4433. */
  4434. animate: function (path, loop) {
  4435. var target;
  4436. var animatingShape = false;
  4437. var el = this;
  4438. var zr = this.__zr;
  4439. if (path) {
  4440. var pathSplitted = path.split('.');
  4441. var prop = el;
  4442. // If animating shape
  4443. animatingShape = pathSplitted[0] === 'shape';
  4444. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4445. if (!prop) {
  4446. continue;
  4447. }
  4448. prop = prop[pathSplitted[i]];
  4449. }
  4450. if (prop) {
  4451. target = prop;
  4452. }
  4453. }
  4454. else {
  4455. target = el;
  4456. }
  4457. if (!target) {
  4458. logError$1(
  4459. 'Property "'
  4460. + path
  4461. + '" is not existed in element '
  4462. + el.id
  4463. );
  4464. return;
  4465. }
  4466. var animators = el.animators;
  4467. var animator = new Animator(target, loop);
  4468. animator.during(function (target) {
  4469. el.dirty(animatingShape);
  4470. })
  4471. .done(function () {
  4472. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4473. animators.splice(indexOf(animators, animator), 1);
  4474. });
  4475. animators.push(animator);
  4476. // If animate after added to the zrender
  4477. if (zr) {
  4478. zr.animation.addAnimator(animator);
  4479. }
  4480. return animator;
  4481. },
  4482. /**
  4483. * 停止动画
  4484. * @param {boolean} forwardToLast If move to last frame before stop
  4485. */
  4486. stopAnimation: function (forwardToLast) {
  4487. var animators = this.animators;
  4488. var len = animators.length;
  4489. for (var i = 0; i < len; i++) {
  4490. animators[i].stop(forwardToLast);
  4491. }
  4492. animators.length = 0;
  4493. return this;
  4494. },
  4495. /**
  4496. * Caution: this method will stop previous animation.
  4497. * So do not use this method to one element twice before
  4498. * animation starts, unless you know what you are doing.
  4499. * @param {Object} target
  4500. * @param {number} [time=500] Time in ms
  4501. * @param {string} [easing='linear']
  4502. * @param {number} [delay=0]
  4503. * @param {Function} [callback]
  4504. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4505. * immediently when target values are the same as current values.
  4506. *
  4507. * @example
  4508. * // Animate position
  4509. * el.animateTo({
  4510. * position: [10, 10]
  4511. * }, function () { // done })
  4512. *
  4513. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4514. * el.animateTo({
  4515. * shape: {
  4516. * width: 500
  4517. * },
  4518. * style: {
  4519. * fill: 'red'
  4520. * }
  4521. * position: [10, 10]
  4522. * }, 100, 100, 'cubicOut', function () { // done })
  4523. */
  4524. // TODO Return animation key
  4525. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4526. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4527. },
  4528. /**
  4529. * Animate from the target state to current state.
  4530. * The params and the return value are the same as `this.animateTo`.
  4531. */
  4532. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4533. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4534. }
  4535. };
  4536. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4537. // animateTo(target, time, easing, callback);
  4538. if (isString(delay)) {
  4539. callback = easing;
  4540. easing = delay;
  4541. delay = 0;
  4542. }
  4543. // animateTo(target, time, delay, callback);
  4544. else if (isFunction(easing)) {
  4545. callback = easing;
  4546. easing = 'linear';
  4547. delay = 0;
  4548. }
  4549. // animateTo(target, time, callback);
  4550. else if (isFunction(delay)) {
  4551. callback = delay;
  4552. delay = 0;
  4553. }
  4554. // animateTo(target, callback)
  4555. else if (isFunction(time)) {
  4556. callback = time;
  4557. time = 500;
  4558. }
  4559. // animateTo(target)
  4560. else if (!time) {
  4561. time = 500;
  4562. }
  4563. // Stop all previous animations
  4564. animatable.stopAnimation();
  4565. animateToShallow(animatable, '', animatable, target, time, delay, reverse);
  4566. // Animators may be removed immediately after start
  4567. // if there is nothing to animate
  4568. var animators = animatable.animators.slice();
  4569. var count = animators.length;
  4570. function done() {
  4571. count--;
  4572. if (!count) {
  4573. callback && callback();
  4574. }
  4575. }
  4576. // No animators. This should be checked before animators[i].start(),
  4577. // because 'done' may be executed immediately if no need to animate.
  4578. if (!count) {
  4579. callback && callback();
  4580. }
  4581. // Start after all animators created
  4582. // Incase any animator is done immediately when all animation properties are not changed
  4583. for (var i = 0; i < animators.length; i++) {
  4584. animators[i]
  4585. .done(done)
  4586. .start(easing, forceAnimate);
  4587. }
  4588. }
  4589. /**
  4590. * @param {string} path=''
  4591. * @param {Object} source=animatable
  4592. * @param {Object} target
  4593. * @param {number} [time=500]
  4594. * @param {number} [delay=0]
  4595. * @param {boolean} [reverse] If `true`, animate
  4596. * from the `target` to current state.
  4597. *
  4598. * @example
  4599. * // Animate position
  4600. * el._animateToShallow({
  4601. * position: [10, 10]
  4602. * })
  4603. *
  4604. * // Animate shape, style and position in 100ms, delayed 100ms
  4605. * el._animateToShallow({
  4606. * shape: {
  4607. * width: 500
  4608. * },
  4609. * style: {
  4610. * fill: 'red'
  4611. * }
  4612. * position: [10, 10]
  4613. * }, 100, 100)
  4614. */
  4615. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4616. var objShallow = {};
  4617. var propertyCount = 0;
  4618. for (var name in target) {
  4619. if (!target.hasOwnProperty(name)) {
  4620. continue;
  4621. }
  4622. if (source[name] != null) {
  4623. if (isObject(target[name]) && !isArrayLike(target[name])) {
  4624. animateToShallow(
  4625. animatable,
  4626. path ? path + '.' + name : name,
  4627. source[name],
  4628. target[name],
  4629. time,
  4630. delay,
  4631. reverse
  4632. );
  4633. }
  4634. else {
  4635. if (reverse) {
  4636. objShallow[name] = source[name];
  4637. setAttrByPath(animatable, path, name, target[name]);
  4638. }
  4639. else {
  4640. objShallow[name] = target[name];
  4641. }
  4642. propertyCount++;
  4643. }
  4644. }
  4645. else if (target[name] != null && !reverse) {
  4646. setAttrByPath(animatable, path, name, target[name]);
  4647. }
  4648. }
  4649. if (propertyCount > 0) {
  4650. animatable.animate(path, false)
  4651. .when(time == null ? 500 : time, objShallow)
  4652. .delay(delay || 0);
  4653. }
  4654. }
  4655. function setAttrByPath(el, path, name, value) {
  4656. // Attr directly if not has property
  4657. // FIXME, if some property not needed for element ?
  4658. if (!path) {
  4659. el.attr(name, value);
  4660. }
  4661. else {
  4662. // Only support set shape or style
  4663. var props = {};
  4664. props[path] = {};
  4665. props[path][name] = value;
  4666. el.attr(props);
  4667. }
  4668. }
  4669. /**
  4670. * @alias module:zrender/Element
  4671. * @constructor
  4672. * @extends {module:zrender/mixin/Animatable}
  4673. * @extends {module:zrender/mixin/Transformable}
  4674. * @extends {module:zrender/mixin/Eventful}
  4675. */
  4676. var Element = function (opts) { // jshint ignore:line
  4677. Transformable.call(this, opts);
  4678. Eventful.call(this, opts);
  4679. Animatable.call(this, opts);
  4680. /**
  4681. * 画布元素ID
  4682. * @type {string}
  4683. */
  4684. this.id = opts.id || guid();
  4685. };
  4686. Element.prototype = {
  4687. /**
  4688. * 元素类型
  4689. * Element type
  4690. * @type {string}
  4691. */
  4692. type: 'element',
  4693. /**
  4694. * 元素名字
  4695. * Element name
  4696. * @type {string}
  4697. */
  4698. name: '',
  4699. /**
  4700. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4701. * ZRender instance will be assigned when element is associated with zrender
  4702. * @name module:/zrender/Element#__zr
  4703. * @type {module:zrender/ZRender}
  4704. */
  4705. __zr: null,
  4706. /**
  4707. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4708. * If ignore drawing and events of the element object
  4709. * @name module:/zrender/Element#ignore
  4710. * @type {boolean}
  4711. * @default false
  4712. */
  4713. ignore: false,
  4714. /**
  4715. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4716. * 该路径会继承被裁减对象的变换
  4717. * @type {module:zrender/graphic/Path}
  4718. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4719. * @readOnly
  4720. */
  4721. clipPath: null,
  4722. /**
  4723. * 是否是 Group
  4724. * @type {boolean}
  4725. */
  4726. isGroup: false,
  4727. /**
  4728. * Drift element
  4729. * @param {number} dx dx on the global space
  4730. * @param {number} dy dy on the global space
  4731. */
  4732. drift: function (dx, dy) {
  4733. switch (this.draggable) {
  4734. case 'horizontal':
  4735. dy = 0;
  4736. break;
  4737. case 'vertical':
  4738. dx = 0;
  4739. break;
  4740. }
  4741. var m = this.transform;
  4742. if (!m) {
  4743. m = this.transform = [1, 0, 0, 1, 0, 0];
  4744. }
  4745. m[4] += dx;
  4746. m[5] += dy;
  4747. this.decomposeTransform();
  4748. this.dirty(false);
  4749. },
  4750. /**
  4751. * Hook before update
  4752. */
  4753. beforeUpdate: function () {},
  4754. /**
  4755. * Hook after update
  4756. */
  4757. afterUpdate: function () {},
  4758. /**
  4759. * Update each frame
  4760. */
  4761. update: function () {
  4762. this.updateTransform();
  4763. },
  4764. /**
  4765. * @param {Function} cb
  4766. * @param {} context
  4767. */
  4768. traverse: function (cb, context) {},
  4769. /**
  4770. * @protected
  4771. */
  4772. attrKV: function (key, value) {
  4773. if (key === 'position' || key === 'scale' || key === 'origin') {
  4774. // Copy the array
  4775. if (value) {
  4776. var target = this[key];
  4777. if (!target) {
  4778. target = this[key] = [];
  4779. }
  4780. target[0] = value[0];
  4781. target[1] = value[1];
  4782. }
  4783. }
  4784. else {
  4785. this[key] = value;
  4786. }
  4787. },
  4788. /**
  4789. * Hide the element
  4790. */
  4791. hide: function () {
  4792. this.ignore = true;
  4793. this.__zr && this.__zr.refresh();
  4794. },
  4795. /**
  4796. * Show the element
  4797. */
  4798. show: function () {
  4799. this.ignore = false;
  4800. this.__zr && this.__zr.refresh();
  4801. },
  4802. /**
  4803. * @param {string|Object} key
  4804. * @param {*} value
  4805. */
  4806. attr: function (key, value) {
  4807. if (typeof key === 'string') {
  4808. this.attrKV(key, value);
  4809. }
  4810. else if (isObject(key)) {
  4811. for (var name in key) {
  4812. if (key.hasOwnProperty(name)) {
  4813. this.attrKV(name, key[name]);
  4814. }
  4815. }
  4816. }
  4817. this.dirty(false);
  4818. return this;
  4819. },
  4820. /**
  4821. * @param {module:zrender/graphic/Path} clipPath
  4822. */
  4823. setClipPath: function (clipPath) {
  4824. var zr = this.__zr;
  4825. if (zr) {
  4826. clipPath.addSelfToZr(zr);
  4827. }
  4828. // Remove previous clip path
  4829. if (this.clipPath && this.clipPath !== clipPath) {
  4830. this.removeClipPath();
  4831. }
  4832. this.clipPath = clipPath;
  4833. clipPath.__zr = zr;
  4834. clipPath.__clipTarget = this;
  4835. this.dirty(false);
  4836. },
  4837. /**
  4838. */
  4839. removeClipPath: function () {
  4840. var clipPath = this.clipPath;
  4841. if (clipPath) {
  4842. if (clipPath.__zr) {
  4843. clipPath.removeSelfFromZr(clipPath.__zr);
  4844. }
  4845. clipPath.__zr = null;
  4846. clipPath.__clipTarget = null;
  4847. this.clipPath = null;
  4848. this.dirty(false);
  4849. }
  4850. },
  4851. /**
  4852. * Add self from zrender instance.
  4853. * Not recursively because it will be invoked when element added to storage.
  4854. * @param {module:zrender/ZRender} zr
  4855. */
  4856. addSelfToZr: function (zr) {
  4857. this.__zr = zr;
  4858. // 添加动画
  4859. var animators = this.animators;
  4860. if (animators) {
  4861. for (var i = 0; i < animators.length; i++) {
  4862. zr.animation.addAnimator(animators[i]);
  4863. }
  4864. }
  4865. if (this.clipPath) {
  4866. this.clipPath.addSelfToZr(zr);
  4867. }
  4868. },
  4869. /**
  4870. * Remove self from zrender instance.
  4871. * Not recursively because it will be invoked when element added to storage.
  4872. * @param {module:zrender/ZRender} zr
  4873. */
  4874. removeSelfFromZr: function (zr) {
  4875. this.__zr = null;
  4876. // 移除动画
  4877. var animators = this.animators;
  4878. if (animators) {
  4879. for (var i = 0; i < animators.length; i++) {
  4880. zr.animation.removeAnimator(animators[i]);
  4881. }
  4882. }
  4883. if (this.clipPath) {
  4884. this.clipPath.removeSelfFromZr(zr);
  4885. }
  4886. }
  4887. };
  4888. mixin(Element, Animatable);
  4889. mixin(Element, Transformable);
  4890. mixin(Element, Eventful);
  4891. /**
  4892. * @module echarts/core/BoundingRect
  4893. */
  4894. var v2ApplyTransform = applyTransform;
  4895. var mathMin = Math.min;
  4896. var mathMax = Math.max;
  4897. /**
  4898. * @alias module:echarts/core/BoundingRect
  4899. */
  4900. function BoundingRect(x, y, width, height) {
  4901. if (width < 0) {
  4902. x = x + width;
  4903. width = -width;
  4904. }
  4905. if (height < 0) {
  4906. y = y + height;
  4907. height = -height;
  4908. }
  4909. /**
  4910. * @type {number}
  4911. */
  4912. this.x = x;
  4913. /**
  4914. * @type {number}
  4915. */
  4916. this.y = y;
  4917. /**
  4918. * @type {number}
  4919. */
  4920. this.width = width;
  4921. /**
  4922. * @type {number}
  4923. */
  4924. this.height = height;
  4925. }
  4926. BoundingRect.prototype = {
  4927. constructor: BoundingRect,
  4928. /**
  4929. * @param {module:echarts/core/BoundingRect} other
  4930. */
  4931. union: function (other) {
  4932. var x = mathMin(other.x, this.x);
  4933. var y = mathMin(other.y, this.y);
  4934. this.width = mathMax(
  4935. other.x + other.width,
  4936. this.x + this.width
  4937. ) - x;
  4938. this.height = mathMax(
  4939. other.y + other.height,
  4940. this.y + this.height
  4941. ) - y;
  4942. this.x = x;
  4943. this.y = y;
  4944. },
  4945. /**
  4946. * @param {Array.<number>} m
  4947. * @methods
  4948. */
  4949. applyTransform: (function () {
  4950. var lt = [];
  4951. var rb = [];
  4952. var lb = [];
  4953. var rt = [];
  4954. return function (m) {
  4955. // In case usage like this
  4956. // el.getBoundingRect().applyTransform(el.transform)
  4957. // And element has no transform
  4958. if (!m) {
  4959. return;
  4960. }
  4961. lt[0] = lb[0] = this.x;
  4962. lt[1] = rt[1] = this.y;
  4963. rb[0] = rt[0] = this.x + this.width;
  4964. rb[1] = lb[1] = this.y + this.height;
  4965. v2ApplyTransform(lt, lt, m);
  4966. v2ApplyTransform(rb, rb, m);
  4967. v2ApplyTransform(lb, lb, m);
  4968. v2ApplyTransform(rt, rt, m);
  4969. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4970. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4971. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4972. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4973. this.width = maxX - this.x;
  4974. this.height = maxY - this.y;
  4975. };
  4976. })(),
  4977. /**
  4978. * Calculate matrix of transforming from self to target rect
  4979. * @param {module:zrender/core/BoundingRect} b
  4980. * @return {Array.<number>}
  4981. */
  4982. calculateTransform: function (b) {
  4983. var a = this;
  4984. var sx = b.width / a.width;
  4985. var sy = b.height / a.height;
  4986. var m = create$1();
  4987. // 矩阵右乘
  4988. translate(m, m, [-a.x, -a.y]);
  4989. scale$1(m, m, [sx, sy]);
  4990. translate(m, m, [b.x, b.y]);
  4991. return m;
  4992. },
  4993. /**
  4994. * @param {(module:echarts/core/BoundingRect|Object)} b
  4995. * @return {boolean}
  4996. */
  4997. intersect: function (b) {
  4998. if (!b) {
  4999. return false;
  5000. }
  5001. if (!(b instanceof BoundingRect)) {
  5002. // Normalize negative width/height.
  5003. b = BoundingRect.create(b);
  5004. }
  5005. var a = this;
  5006. var ax0 = a.x;
  5007. var ax1 = a.x + a.width;
  5008. var ay0 = a.y;
  5009. var ay1 = a.y + a.height;
  5010. var bx0 = b.x;
  5011. var bx1 = b.x + b.width;
  5012. var by0 = b.y;
  5013. var by1 = b.y + b.height;
  5014. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  5015. },
  5016. contain: function (x, y) {
  5017. var rect = this;
  5018. return x >= rect.x
  5019. && x <= (rect.x + rect.width)
  5020. && y >= rect.y
  5021. && y <= (rect.y + rect.height);
  5022. },
  5023. /**
  5024. * @return {module:echarts/core/BoundingRect}
  5025. */
  5026. clone: function () {
  5027. return new BoundingRect(this.x, this.y, this.width, this.height);
  5028. },
  5029. /**
  5030. * Copy from another rect
  5031. */
  5032. copy: function (other) {
  5033. this.x = other.x;
  5034. this.y = other.y;
  5035. this.width = other.width;
  5036. this.height = other.height;
  5037. },
  5038. plain: function () {
  5039. return {
  5040. x: this.x,
  5041. y: this.y,
  5042. width: this.width,
  5043. height: this.height
  5044. };
  5045. }
  5046. };
  5047. /**
  5048. * @param {Object|module:zrender/core/BoundingRect} rect
  5049. * @param {number} rect.x
  5050. * @param {number} rect.y
  5051. * @param {number} rect.width
  5052. * @param {number} rect.height
  5053. * @return {module:zrender/core/BoundingRect}
  5054. */
  5055. BoundingRect.create = function (rect) {
  5056. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  5057. };
  5058. /**
  5059. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  5060. * @module zrender/graphic/Group
  5061. * @example
  5062. * var Group = require('zrender/container/Group');
  5063. * var Circle = require('zrender/graphic/shape/Circle');
  5064. * var g = new Group();
  5065. * g.position[0] = 100;
  5066. * g.position[1] = 100;
  5067. * g.add(new Circle({
  5068. * style: {
  5069. * x: 100,
  5070. * y: 100,
  5071. * r: 20,
  5072. * }
  5073. * }));
  5074. * zr.add(g);
  5075. */
  5076. /**
  5077. * @alias module:zrender/graphic/Group
  5078. * @constructor
  5079. * @extends module:zrender/mixin/Transformable
  5080. * @extends module:zrender/mixin/Eventful
  5081. */
  5082. var Group = function (opts) {
  5083. opts = opts || {};
  5084. Element.call(this, opts);
  5085. for (var key in opts) {
  5086. if (opts.hasOwnProperty(key)) {
  5087. this[key] = opts[key];
  5088. }
  5089. }
  5090. this._children = [];
  5091. this.__storage = null;
  5092. this.__dirty = true;
  5093. };
  5094. Group.prototype = {
  5095. constructor: Group,
  5096. isGroup: true,
  5097. /**
  5098. * @type {string}
  5099. */
  5100. type: 'group',
  5101. /**
  5102. * 所有子孙元素是否响应鼠标事件
  5103. * @name module:/zrender/container/Group#silent
  5104. * @type {boolean}
  5105. * @default false
  5106. */
  5107. silent: false,
  5108. /**
  5109. * @return {Array.<module:zrender/Element>}
  5110. */
  5111. children: function () {
  5112. return this._children.slice();
  5113. },
  5114. /**
  5115. * 获取指定 index 的儿子节点
  5116. * @param {number} idx
  5117. * @return {module:zrender/Element}
  5118. */
  5119. childAt: function (idx) {
  5120. return this._children[idx];
  5121. },
  5122. /**
  5123. * 获取指定名字的儿子节点
  5124. * @param {string} name
  5125. * @return {module:zrender/Element}
  5126. */
  5127. childOfName: function (name) {
  5128. var children = this._children;
  5129. for (var i = 0; i < children.length; i++) {
  5130. if (children[i].name === name) {
  5131. return children[i];
  5132. }
  5133. }
  5134. },
  5135. /**
  5136. * @return {number}
  5137. */
  5138. childCount: function () {
  5139. return this._children.length;
  5140. },
  5141. /**
  5142. * 添加子节点到最后
  5143. * @param {module:zrender/Element} child
  5144. */
  5145. add: function (child) {
  5146. if (child && child !== this && child.parent !== this) {
  5147. this._children.push(child);
  5148. this._doAdd(child);
  5149. }
  5150. return this;
  5151. },
  5152. /**
  5153. * 添加子节点在 nextSibling 之前
  5154. * @param {module:zrender/Element} child
  5155. * @param {module:zrender/Element} nextSibling
  5156. */
  5157. addBefore: function (child, nextSibling) {
  5158. if (child && child !== this && child.parent !== this
  5159. && nextSibling && nextSibling.parent === this) {
  5160. var children = this._children;
  5161. var idx = children.indexOf(nextSibling);
  5162. if (idx >= 0) {
  5163. children.splice(idx, 0, child);
  5164. this._doAdd(child);
  5165. }
  5166. }
  5167. return this;
  5168. },
  5169. _doAdd: function (child) {
  5170. if (child.parent) {
  5171. child.parent.remove(child);
  5172. }
  5173. child.parent = this;
  5174. var storage = this.__storage;
  5175. var zr = this.__zr;
  5176. if (storage && storage !== child.__storage) {
  5177. storage.addToStorage(child);
  5178. if (child instanceof Group) {
  5179. child.addChildrenToStorage(storage);
  5180. }
  5181. }
  5182. zr && zr.refresh();
  5183. },
  5184. /**
  5185. * 移除子节点
  5186. * @param {module:zrender/Element} child
  5187. */
  5188. remove: function (child) {
  5189. var zr = this.__zr;
  5190. var storage = this.__storage;
  5191. var children = this._children;
  5192. var idx = indexOf(children, child);
  5193. if (idx < 0) {
  5194. return this;
  5195. }
  5196. children.splice(idx, 1);
  5197. child.parent = null;
  5198. if (storage) {
  5199. storage.delFromStorage(child);
  5200. if (child instanceof Group) {
  5201. child.delChildrenFromStorage(storage);
  5202. }
  5203. }
  5204. zr && zr.refresh();
  5205. return this;
  5206. },
  5207. /**
  5208. * 移除所有子节点
  5209. */
  5210. removeAll: function () {
  5211. var children = this._children;
  5212. var storage = this.__storage;
  5213. var child;
  5214. var i;
  5215. for (i = 0; i < children.length; i++) {
  5216. child = children[i];
  5217. if (storage) {
  5218. storage.delFromStorage(child);
  5219. if (child instanceof Group) {
  5220. child.delChildrenFromStorage(storage);
  5221. }
  5222. }
  5223. child.parent = null;
  5224. }
  5225. children.length = 0;
  5226. return this;
  5227. },
  5228. /**
  5229. * 遍历所有子节点
  5230. * @param {Function} cb
  5231. * @param {} context
  5232. */
  5233. eachChild: function (cb, context) {
  5234. var children = this._children;
  5235. for (var i = 0; i < children.length; i++) {
  5236. var child = children[i];
  5237. cb.call(context, child, i);
  5238. }
  5239. return this;
  5240. },
  5241. /**
  5242. * 深度优先遍历所有子孙节点
  5243. * @param {Function} cb
  5244. * @param {} context
  5245. */
  5246. traverse: function (cb, context) {
  5247. for (var i = 0; i < this._children.length; i++) {
  5248. var child = this._children[i];
  5249. cb.call(context, child);
  5250. if (child.type === 'group') {
  5251. child.traverse(cb, context);
  5252. }
  5253. }
  5254. return this;
  5255. },
  5256. addChildrenToStorage: function (storage) {
  5257. for (var i = 0; i < this._children.length; i++) {
  5258. var child = this._children[i];
  5259. storage.addToStorage(child);
  5260. if (child instanceof Group) {
  5261. child.addChildrenToStorage(storage);
  5262. }
  5263. }
  5264. },
  5265. delChildrenFromStorage: function (storage) {
  5266. for (var i = 0; i < this._children.length; i++) {
  5267. var child = this._children[i];
  5268. storage.delFromStorage(child);
  5269. if (child instanceof Group) {
  5270. child.delChildrenFromStorage(storage);
  5271. }
  5272. }
  5273. },
  5274. dirty: function () {
  5275. this.__dirty = true;
  5276. this.__zr && this.__zr.refresh();
  5277. return this;
  5278. },
  5279. /**
  5280. * @return {module:zrender/core/BoundingRect}
  5281. */
  5282. getBoundingRect: function (includeChildren) {
  5283. // TODO Caching
  5284. var rect = null;
  5285. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5286. var children = includeChildren || this._children;
  5287. var tmpMat = [];
  5288. for (var i = 0; i < children.length; i++) {
  5289. var child = children[i];
  5290. if (child.ignore || child.invisible) {
  5291. continue;
  5292. }
  5293. var childRect = child.getBoundingRect();
  5294. var transform = child.getLocalTransform(tmpMat);
  5295. // TODO
  5296. // The boundingRect cacluated by transforming original
  5297. // rect may be bigger than the actual bundingRect when rotation
  5298. // is used. (Consider a circle rotated aginst its center, where
  5299. // the actual boundingRect should be the same as that not be
  5300. // rotated.) But we can not find better approach to calculate
  5301. // actual boundingRect yet, considering performance.
  5302. if (transform) {
  5303. tmpRect.copy(childRect);
  5304. tmpRect.applyTransform(transform);
  5305. rect = rect || tmpRect.clone();
  5306. rect.union(tmpRect);
  5307. }
  5308. else {
  5309. rect = rect || childRect.clone();
  5310. rect.union(childRect);
  5311. }
  5312. }
  5313. return rect || tmpRect;
  5314. }
  5315. };
  5316. inherits(Group, Element);
  5317. // https://github.com/mziccard/node-timsort
  5318. var DEFAULT_MIN_MERGE = 32;
  5319. var DEFAULT_MIN_GALLOPING = 7;
  5320. function minRunLength(n) {
  5321. var r = 0;
  5322. while (n >= DEFAULT_MIN_MERGE) {
  5323. r |= n & 1;
  5324. n >>= 1;
  5325. }
  5326. return n + r;
  5327. }
  5328. function makeAscendingRun(array, lo, hi, compare) {
  5329. var runHi = lo + 1;
  5330. if (runHi === hi) {
  5331. return 1;
  5332. }
  5333. if (compare(array[runHi++], array[lo]) < 0) {
  5334. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5335. runHi++;
  5336. }
  5337. reverseRun(array, lo, runHi);
  5338. }
  5339. else {
  5340. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5341. runHi++;
  5342. }
  5343. }
  5344. return runHi - lo;
  5345. }
  5346. function reverseRun(array, lo, hi) {
  5347. hi--;
  5348. while (lo < hi) {
  5349. var t = array[lo];
  5350. array[lo++] = array[hi];
  5351. array[hi--] = t;
  5352. }
  5353. }
  5354. function binaryInsertionSort(array, lo, hi, start, compare) {
  5355. if (start === lo) {
  5356. start++;
  5357. }
  5358. for (; start < hi; start++) {
  5359. var pivot = array[start];
  5360. var left = lo;
  5361. var right = start;
  5362. var mid;
  5363. while (left < right) {
  5364. mid = left + right >>> 1;
  5365. if (compare(pivot, array[mid]) < 0) {
  5366. right = mid;
  5367. }
  5368. else {
  5369. left = mid + 1;
  5370. }
  5371. }
  5372. var n = start - left;
  5373. switch (n) {
  5374. case 3:
  5375. array[left + 3] = array[left + 2];
  5376. case 2:
  5377. array[left + 2] = array[left + 1];
  5378. case 1:
  5379. array[left + 1] = array[left];
  5380. break;
  5381. default:
  5382. while (n > 0) {
  5383. array[left + n] = array[left + n - 1];
  5384. n--;
  5385. }
  5386. }
  5387. array[left] = pivot;
  5388. }
  5389. }
  5390. function gallopLeft(value, array, start, length, hint, compare) {
  5391. var lastOffset = 0;
  5392. var maxOffset = 0;
  5393. var offset = 1;
  5394. if (compare(value, array[start + hint]) > 0) {
  5395. maxOffset = length - hint;
  5396. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5397. lastOffset = offset;
  5398. offset = (offset << 1) + 1;
  5399. if (offset <= 0) {
  5400. offset = maxOffset;
  5401. }
  5402. }
  5403. if (offset > maxOffset) {
  5404. offset = maxOffset;
  5405. }
  5406. lastOffset += hint;
  5407. offset += hint;
  5408. }
  5409. else {
  5410. maxOffset = hint + 1;
  5411. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5412. lastOffset = offset;
  5413. offset = (offset << 1) + 1;
  5414. if (offset <= 0) {
  5415. offset = maxOffset;
  5416. }
  5417. }
  5418. if (offset > maxOffset) {
  5419. offset = maxOffset;
  5420. }
  5421. var tmp = lastOffset;
  5422. lastOffset = hint - offset;
  5423. offset = hint - tmp;
  5424. }
  5425. lastOffset++;
  5426. while (lastOffset < offset) {
  5427. var m = lastOffset + (offset - lastOffset >>> 1);
  5428. if (compare(value, array[start + m]) > 0) {
  5429. lastOffset = m + 1;
  5430. }
  5431. else {
  5432. offset = m;
  5433. }
  5434. }
  5435. return offset;
  5436. }
  5437. function gallopRight(value, array, start, length, hint, compare) {
  5438. var lastOffset = 0;
  5439. var maxOffset = 0;
  5440. var offset = 1;
  5441. if (compare(value, array[start + hint]) < 0) {
  5442. maxOffset = hint + 1;
  5443. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5444. lastOffset = offset;
  5445. offset = (offset << 1) + 1;
  5446. if (offset <= 0) {
  5447. offset = maxOffset;
  5448. }
  5449. }
  5450. if (offset > maxOffset) {
  5451. offset = maxOffset;
  5452. }
  5453. var tmp = lastOffset;
  5454. lastOffset = hint - offset;
  5455. offset = hint - tmp;
  5456. }
  5457. else {
  5458. maxOffset = length - hint;
  5459. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5460. lastOffset = offset;
  5461. offset = (offset << 1) + 1;
  5462. if (offset <= 0) {
  5463. offset = maxOffset;
  5464. }
  5465. }
  5466. if (offset > maxOffset) {
  5467. offset = maxOffset;
  5468. }
  5469. lastOffset += hint;
  5470. offset += hint;
  5471. }
  5472. lastOffset++;
  5473. while (lastOffset < offset) {
  5474. var m = lastOffset + (offset - lastOffset >>> 1);
  5475. if (compare(value, array[start + m]) < 0) {
  5476. offset = m;
  5477. }
  5478. else {
  5479. lastOffset = m + 1;
  5480. }
  5481. }
  5482. return offset;
  5483. }
  5484. function TimSort(array, compare) {
  5485. var minGallop = DEFAULT_MIN_GALLOPING;
  5486. var runStart;
  5487. var runLength;
  5488. var stackSize = 0;
  5489. var tmp = [];
  5490. runStart = [];
  5491. runLength = [];
  5492. function pushRun(_runStart, _runLength) {
  5493. runStart[stackSize] = _runStart;
  5494. runLength[stackSize] = _runLength;
  5495. stackSize += 1;
  5496. }
  5497. function mergeRuns() {
  5498. while (stackSize > 1) {
  5499. var n = stackSize - 2;
  5500. if (
  5501. (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5502. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])
  5503. ) {
  5504. if (runLength[n - 1] < runLength[n + 1]) {
  5505. n--;
  5506. }
  5507. }
  5508. else if (runLength[n] > runLength[n + 1]) {
  5509. break;
  5510. }
  5511. mergeAt(n);
  5512. }
  5513. }
  5514. function forceMergeRuns() {
  5515. while (stackSize > 1) {
  5516. var n = stackSize - 2;
  5517. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5518. n--;
  5519. }
  5520. mergeAt(n);
  5521. }
  5522. }
  5523. function mergeAt(i) {
  5524. var start1 = runStart[i];
  5525. var length1 = runLength[i];
  5526. var start2 = runStart[i + 1];
  5527. var length2 = runLength[i + 1];
  5528. runLength[i] = length1 + length2;
  5529. if (i === stackSize - 3) {
  5530. runStart[i + 1] = runStart[i + 2];
  5531. runLength[i + 1] = runLength[i + 2];
  5532. }
  5533. stackSize--;
  5534. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5535. start1 += k;
  5536. length1 -= k;
  5537. if (length1 === 0) {
  5538. return;
  5539. }
  5540. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5541. if (length2 === 0) {
  5542. return;
  5543. }
  5544. if (length1 <= length2) {
  5545. mergeLow(start1, length1, start2, length2);
  5546. }
  5547. else {
  5548. mergeHigh(start1, length1, start2, length2);
  5549. }
  5550. }
  5551. function mergeLow(start1, length1, start2, length2) {
  5552. var i = 0;
  5553. for (i = 0; i < length1; i++) {
  5554. tmp[i] = array[start1 + i];
  5555. }
  5556. var cursor1 = 0;
  5557. var cursor2 = start2;
  5558. var dest = start1;
  5559. array[dest++] = array[cursor2++];
  5560. if (--length2 === 0) {
  5561. for (i = 0; i < length1; i++) {
  5562. array[dest + i] = tmp[cursor1 + i];
  5563. }
  5564. return;
  5565. }
  5566. if (length1 === 1) {
  5567. for (i = 0; i < length2; i++) {
  5568. array[dest + i] = array[cursor2 + i];
  5569. }
  5570. array[dest + length2] = tmp[cursor1];
  5571. return;
  5572. }
  5573. var _minGallop = minGallop;
  5574. var count1;
  5575. var count2;
  5576. var exit;
  5577. while (1) {
  5578. count1 = 0;
  5579. count2 = 0;
  5580. exit = false;
  5581. do {
  5582. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5583. array[dest++] = array[cursor2++];
  5584. count2++;
  5585. count1 = 0;
  5586. if (--length2 === 0) {
  5587. exit = true;
  5588. break;
  5589. }
  5590. }
  5591. else {
  5592. array[dest++] = tmp[cursor1++];
  5593. count1++;
  5594. count2 = 0;
  5595. if (--length1 === 1) {
  5596. exit = true;
  5597. break;
  5598. }
  5599. }
  5600. } while ((count1 | count2) < _minGallop);
  5601. if (exit) {
  5602. break;
  5603. }
  5604. do {
  5605. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5606. if (count1 !== 0) {
  5607. for (i = 0; i < count1; i++) {
  5608. array[dest + i] = tmp[cursor1 + i];
  5609. }
  5610. dest += count1;
  5611. cursor1 += count1;
  5612. length1 -= count1;
  5613. if (length1 <= 1) {
  5614. exit = true;
  5615. break;
  5616. }
  5617. }
  5618. array[dest++] = array[cursor2++];
  5619. if (--length2 === 0) {
  5620. exit = true;
  5621. break;
  5622. }
  5623. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5624. if (count2 !== 0) {
  5625. for (i = 0; i < count2; i++) {
  5626. array[dest + i] = array[cursor2 + i];
  5627. }
  5628. dest += count2;
  5629. cursor2 += count2;
  5630. length2 -= count2;
  5631. if (length2 === 0) {
  5632. exit = true;
  5633. break;
  5634. }
  5635. }
  5636. array[dest++] = tmp[cursor1++];
  5637. if (--length1 === 1) {
  5638. exit = true;
  5639. break;
  5640. }
  5641. _minGallop--;
  5642. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5643. if (exit) {
  5644. break;
  5645. }
  5646. if (_minGallop < 0) {
  5647. _minGallop = 0;
  5648. }
  5649. _minGallop += 2;
  5650. }
  5651. minGallop = _minGallop;
  5652. minGallop < 1 && (minGallop = 1);
  5653. if (length1 === 1) {
  5654. for (i = 0; i < length2; i++) {
  5655. array[dest + i] = array[cursor2 + i];
  5656. }
  5657. array[dest + length2] = tmp[cursor1];
  5658. }
  5659. else if (length1 === 0) {
  5660. throw new Error();
  5661. // throw new Error('mergeLow preconditions were not respected');
  5662. }
  5663. else {
  5664. for (i = 0; i < length1; i++) {
  5665. array[dest + i] = tmp[cursor1 + i];
  5666. }
  5667. }
  5668. }
  5669. function mergeHigh(start1, length1, start2, length2) {
  5670. var i = 0;
  5671. for (i = 0; i < length2; i++) {
  5672. tmp[i] = array[start2 + i];
  5673. }
  5674. var cursor1 = start1 + length1 - 1;
  5675. var cursor2 = length2 - 1;
  5676. var dest = start2 + length2 - 1;
  5677. var customCursor = 0;
  5678. var customDest = 0;
  5679. array[dest--] = array[cursor1--];
  5680. if (--length1 === 0) {
  5681. customCursor = dest - (length2 - 1);
  5682. for (i = 0; i < length2; i++) {
  5683. array[customCursor + i] = tmp[i];
  5684. }
  5685. return;
  5686. }
  5687. if (length2 === 1) {
  5688. dest -= length1;
  5689. cursor1 -= length1;
  5690. customDest = dest + 1;
  5691. customCursor = cursor1 + 1;
  5692. for (i = length1 - 1; i >= 0; i--) {
  5693. array[customDest + i] = array[customCursor + i];
  5694. }
  5695. array[dest] = tmp[cursor2];
  5696. return;
  5697. }
  5698. var _minGallop = minGallop;
  5699. while (true) {
  5700. var count1 = 0;
  5701. var count2 = 0;
  5702. var exit = false;
  5703. do {
  5704. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5705. array[dest--] = array[cursor1--];
  5706. count1++;
  5707. count2 = 0;
  5708. if (--length1 === 0) {
  5709. exit = true;
  5710. break;
  5711. }
  5712. }
  5713. else {
  5714. array[dest--] = tmp[cursor2--];
  5715. count2++;
  5716. count1 = 0;
  5717. if (--length2 === 1) {
  5718. exit = true;
  5719. break;
  5720. }
  5721. }
  5722. } while ((count1 | count2) < _minGallop);
  5723. if (exit) {
  5724. break;
  5725. }
  5726. do {
  5727. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5728. if (count1 !== 0) {
  5729. dest -= count1;
  5730. cursor1 -= count1;
  5731. length1 -= count1;
  5732. customDest = dest + 1;
  5733. customCursor = cursor1 + 1;
  5734. for (i = count1 - 1; i >= 0; i--) {
  5735. array[customDest + i] = array[customCursor + i];
  5736. }
  5737. if (length1 === 0) {
  5738. exit = true;
  5739. break;
  5740. }
  5741. }
  5742. array[dest--] = tmp[cursor2--];
  5743. if (--length2 === 1) {
  5744. exit = true;
  5745. break;
  5746. }
  5747. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5748. if (count2 !== 0) {
  5749. dest -= count2;
  5750. cursor2 -= count2;
  5751. length2 -= count2;
  5752. customDest = dest + 1;
  5753. customCursor = cursor2 + 1;
  5754. for (i = 0; i < count2; i++) {
  5755. array[customDest + i] = tmp[customCursor + i];
  5756. }
  5757. if (length2 <= 1) {
  5758. exit = true;
  5759. break;
  5760. }
  5761. }
  5762. array[dest--] = array[cursor1--];
  5763. if (--length1 === 0) {
  5764. exit = true;
  5765. break;
  5766. }
  5767. _minGallop--;
  5768. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5769. if (exit) {
  5770. break;
  5771. }
  5772. if (_minGallop < 0) {
  5773. _minGallop = 0;
  5774. }
  5775. _minGallop += 2;
  5776. }
  5777. minGallop = _minGallop;
  5778. if (minGallop < 1) {
  5779. minGallop = 1;
  5780. }
  5781. if (length2 === 1) {
  5782. dest -= length1;
  5783. cursor1 -= length1;
  5784. customDest = dest + 1;
  5785. customCursor = cursor1 + 1;
  5786. for (i = length1 - 1; i >= 0; i--) {
  5787. array[customDest + i] = array[customCursor + i];
  5788. }
  5789. array[dest] = tmp[cursor2];
  5790. }
  5791. else if (length2 === 0) {
  5792. throw new Error();
  5793. // throw new Error('mergeHigh preconditions were not respected');
  5794. }
  5795. else {
  5796. customCursor = dest - (length2 - 1);
  5797. for (i = 0; i < length2; i++) {
  5798. array[customCursor + i] = tmp[i];
  5799. }
  5800. }
  5801. }
  5802. this.mergeRuns = mergeRuns;
  5803. this.forceMergeRuns = forceMergeRuns;
  5804. this.pushRun = pushRun;
  5805. }
  5806. function sort(array, compare, lo, hi) {
  5807. if (!lo) {
  5808. lo = 0;
  5809. }
  5810. if (!hi) {
  5811. hi = array.length;
  5812. }
  5813. var remaining = hi - lo;
  5814. if (remaining < 2) {
  5815. return;
  5816. }
  5817. var runLength = 0;
  5818. if (remaining < DEFAULT_MIN_MERGE) {
  5819. runLength = makeAscendingRun(array, lo, hi, compare);
  5820. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5821. return;
  5822. }
  5823. var ts = new TimSort(array, compare);
  5824. var minRun = minRunLength(remaining);
  5825. do {
  5826. runLength = makeAscendingRun(array, lo, hi, compare);
  5827. if (runLength < minRun) {
  5828. var force = remaining;
  5829. if (force > minRun) {
  5830. force = minRun;
  5831. }
  5832. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5833. runLength = force;
  5834. }
  5835. ts.pushRun(lo, runLength);
  5836. ts.mergeRuns();
  5837. remaining -= runLength;
  5838. lo += runLength;
  5839. } while (remaining !== 0);
  5840. ts.forceMergeRuns();
  5841. }
  5842. // Use timsort because in most case elements are partially sorted
  5843. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5844. function shapeCompareFunc(a, b) {
  5845. if (a.zlevel === b.zlevel) {
  5846. if (a.z === b.z) {
  5847. // if (a.z2 === b.z2) {
  5848. // // FIXME Slow has renderidx compare
  5849. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5850. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5851. // return a.__renderidx - b.__renderidx;
  5852. // }
  5853. return a.z2 - b.z2;
  5854. }
  5855. return a.z - b.z;
  5856. }
  5857. return a.zlevel - b.zlevel;
  5858. }
  5859. /**
  5860. * 内容仓库 (M)
  5861. * @alias module:zrender/Storage
  5862. * @constructor
  5863. */
  5864. var Storage = function () { // jshint ignore:line
  5865. this._roots = [];
  5866. this._displayList = [];
  5867. this._displayListLen = 0;
  5868. };
  5869. Storage.prototype = {
  5870. constructor: Storage,
  5871. /**
  5872. * @param {Function} cb
  5873. *
  5874. */
  5875. traverse: function (cb, context) {
  5876. for (var i = 0; i < this._roots.length; i++) {
  5877. this._roots[i].traverse(cb, context);
  5878. }
  5879. },
  5880. /**
  5881. * 返回所有图形的绘制队列
  5882. * @param {boolean} [update=false] 是否在返回前更新该数组
  5883. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5884. *
  5885. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5886. * @return {Array.<module:zrender/graphic/Displayable>}
  5887. */
  5888. getDisplayList: function (update, includeIgnore) {
  5889. includeIgnore = includeIgnore || false;
  5890. if (update) {
  5891. this.updateDisplayList(includeIgnore);
  5892. }
  5893. return this._displayList;
  5894. },
  5895. /**
  5896. * 更新图形的绘制队列。
  5897. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5898. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5899. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5900. */
  5901. updateDisplayList: function (includeIgnore) {
  5902. this._displayListLen = 0;
  5903. var roots = this._roots;
  5904. var displayList = this._displayList;
  5905. for (var i = 0, len = roots.length; i < len; i++) {
  5906. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5907. }
  5908. displayList.length = this._displayListLen;
  5909. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5910. },
  5911. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5912. if (el.ignore && !includeIgnore) {
  5913. return;
  5914. }
  5915. el.beforeUpdate();
  5916. if (el.__dirty) {
  5917. el.update();
  5918. }
  5919. el.afterUpdate();
  5920. var userSetClipPath = el.clipPath;
  5921. if (userSetClipPath) {
  5922. // FIXME 效率影响
  5923. if (clipPaths) {
  5924. clipPaths = clipPaths.slice();
  5925. }
  5926. else {
  5927. clipPaths = [];
  5928. }
  5929. var currentClipPath = userSetClipPath;
  5930. var parentClipPath = el;
  5931. // Recursively add clip path
  5932. while (currentClipPath) {
  5933. // clipPath 的变换是基于使用这个 clipPath 的元素
  5934. currentClipPath.parent = parentClipPath;
  5935. currentClipPath.updateTransform();
  5936. clipPaths.push(currentClipPath);
  5937. parentClipPath = currentClipPath;
  5938. currentClipPath = currentClipPath.clipPath;
  5939. }
  5940. }
  5941. if (el.isGroup) {
  5942. var children = el._children;
  5943. for (var i = 0; i < children.length; i++) {
  5944. var child = children[i];
  5945. // Force to mark as dirty if group is dirty
  5946. // FIXME __dirtyPath ?
  5947. if (el.__dirty) {
  5948. child.__dirty = true;
  5949. }
  5950. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5951. }
  5952. // Mark group clean here
  5953. el.__dirty = false;
  5954. }
  5955. else {
  5956. el.__clipPaths = clipPaths;
  5957. this._displayList[this._displayListLen++] = el;
  5958. }
  5959. },
  5960. /**
  5961. * 添加图形(Shape)或者组(Group)到根节点
  5962. * @param {module:zrender/Element} el
  5963. */
  5964. addRoot: function (el) {
  5965. if (el.__storage === this) {
  5966. return;
  5967. }
  5968. if (el instanceof Group) {
  5969. el.addChildrenToStorage(this);
  5970. }
  5971. this.addToStorage(el);
  5972. this._roots.push(el);
  5973. },
  5974. /**
  5975. * 删除指定的图形(Shape)或者组(Group)
  5976. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5977. */
  5978. delRoot: function (el) {
  5979. if (el == null) {
  5980. // 不指定el清空
  5981. for (var i = 0; i < this._roots.length; i++) {
  5982. var root = this._roots[i];
  5983. if (root instanceof Group) {
  5984. root.delChildrenFromStorage(this);
  5985. }
  5986. }
  5987. this._roots = [];
  5988. this._displayList = [];
  5989. this._displayListLen = 0;
  5990. return;
  5991. }
  5992. if (el instanceof Array) {
  5993. for (var i = 0, l = el.length; i < l; i++) {
  5994. this.delRoot(el[i]);
  5995. }
  5996. return;
  5997. }
  5998. var idx = indexOf(this._roots, el);
  5999. if (idx >= 0) {
  6000. this.delFromStorage(el);
  6001. this._roots.splice(idx, 1);
  6002. if (el instanceof Group) {
  6003. el.delChildrenFromStorage(this);
  6004. }
  6005. }
  6006. },
  6007. addToStorage: function (el) {
  6008. if (el) {
  6009. el.__storage = this;
  6010. el.dirty(false);
  6011. }
  6012. return this;
  6013. },
  6014. delFromStorage: function (el) {
  6015. if (el) {
  6016. el.__storage = null;
  6017. }
  6018. return this;
  6019. },
  6020. /**
  6021. * 清空并且释放Storage
  6022. */
  6023. dispose: function () {
  6024. this._renderList =
  6025. this._roots = null;
  6026. },
  6027. displayableSortFunc: shapeCompareFunc
  6028. };
  6029. var SHADOW_PROPS = {
  6030. 'shadowBlur': 1,
  6031. 'shadowOffsetX': 1,
  6032. 'shadowOffsetY': 1,
  6033. 'textShadowBlur': 1,
  6034. 'textShadowOffsetX': 1,
  6035. 'textShadowOffsetY': 1,
  6036. 'textBoxShadowBlur': 1,
  6037. 'textBoxShadowOffsetX': 1,
  6038. 'textBoxShadowOffsetY': 1
  6039. };
  6040. var fixShadow = function (ctx, propName, value) {
  6041. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  6042. return value *= ctx.dpr;
  6043. }
  6044. return value;
  6045. };
  6046. var ContextCachedBy = {
  6047. NONE: 0,
  6048. STYLE_BIND: 1,
  6049. PLAIN_TEXT: 2
  6050. };
  6051. // Avoid confused with 0/false.
  6052. var WILL_BE_RESTORED = 9;
  6053. var STYLE_COMMON_PROPS = [
  6054. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  6055. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  6056. ];
  6057. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  6058. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  6059. var Style = function (opts) {
  6060. this.extendFrom(opts, false);
  6061. };
  6062. function createLinearGradient(ctx, obj, rect) {
  6063. var x = obj.x == null ? 0 : obj.x;
  6064. var x2 = obj.x2 == null ? 1 : obj.x2;
  6065. var y = obj.y == null ? 0 : obj.y;
  6066. var y2 = obj.y2 == null ? 0 : obj.y2;
  6067. if (!obj.global) {
  6068. x = x * rect.width + rect.x;
  6069. x2 = x2 * rect.width + rect.x;
  6070. y = y * rect.height + rect.y;
  6071. y2 = y2 * rect.height + rect.y;
  6072. }
  6073. // Fix NaN when rect is Infinity
  6074. x = isNaN(x) ? 0 : x;
  6075. x2 = isNaN(x2) ? 1 : x2;
  6076. y = isNaN(y) ? 0 : y;
  6077. y2 = isNaN(y2) ? 0 : y2;
  6078. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  6079. return canvasGradient;
  6080. }
  6081. function createRadialGradient(ctx, obj, rect) {
  6082. var width = rect.width;
  6083. var height = rect.height;
  6084. var min = Math.min(width, height);
  6085. var x = obj.x == null ? 0.5 : obj.x;
  6086. var y = obj.y == null ? 0.5 : obj.y;
  6087. var r = obj.r == null ? 0.5 : obj.r;
  6088. if (!obj.global) {
  6089. x = x * width + rect.x;
  6090. y = y * height + rect.y;
  6091. r = r * min;
  6092. }
  6093. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  6094. return canvasGradient;
  6095. }
  6096. Style.prototype = {
  6097. constructor: Style,
  6098. /**
  6099. * @type {string}
  6100. */
  6101. fill: '#000',
  6102. /**
  6103. * @type {string}
  6104. */
  6105. stroke: null,
  6106. /**
  6107. * @type {number}
  6108. */
  6109. opacity: 1,
  6110. /**
  6111. * @type {number}
  6112. */
  6113. fillOpacity: null,
  6114. /**
  6115. * @type {number}
  6116. */
  6117. strokeOpacity: null,
  6118. /**
  6119. * `true` is not supported.
  6120. * `false`/`null`/`undefined` are the same.
  6121. * `false` is used to remove lineDash in some
  6122. * case that `null`/`undefined` can not be set.
  6123. * (e.g., emphasis.lineStyle in echarts)
  6124. * @type {Array.<number>|boolean}
  6125. */
  6126. lineDash: null,
  6127. /**
  6128. * @type {number}
  6129. */
  6130. lineDashOffset: 0,
  6131. /**
  6132. * @type {number}
  6133. */
  6134. shadowBlur: 0,
  6135. /**
  6136. * @type {number}
  6137. */
  6138. shadowOffsetX: 0,
  6139. /**
  6140. * @type {number}
  6141. */
  6142. shadowOffsetY: 0,
  6143. /**
  6144. * @type {number}
  6145. */
  6146. lineWidth: 1,
  6147. /**
  6148. * If stroke ignore scale
  6149. * @type {Boolean}
  6150. */
  6151. strokeNoScale: false,
  6152. // Bounding rect text configuration
  6153. // Not affected by element transform
  6154. /**
  6155. * @type {string}
  6156. */
  6157. text: null,
  6158. /**
  6159. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  6160. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  6161. * So do not visit it directly in upper application (like echarts),
  6162. * but use `contain/text#makeFont` instead.
  6163. * @type {string}
  6164. */
  6165. font: null,
  6166. /**
  6167. * The same as font. Use font please.
  6168. * @deprecated
  6169. * @type {string}
  6170. */
  6171. textFont: null,
  6172. /**
  6173. * It helps merging respectively, rather than parsing an entire font string.
  6174. * @type {string}
  6175. */
  6176. fontStyle: null,
  6177. /**
  6178. * It helps merging respectively, rather than parsing an entire font string.
  6179. * @type {string}
  6180. */
  6181. fontWeight: null,
  6182. /**
  6183. * It helps merging respectively, rather than parsing an entire font string.
  6184. * Should be 12 but not '12px'.
  6185. * @type {number}
  6186. */
  6187. fontSize: null,
  6188. /**
  6189. * It helps merging respectively, rather than parsing an entire font string.
  6190. * @type {string}
  6191. */
  6192. fontFamily: null,
  6193. /**
  6194. * Reserved for special functinality, like 'hr'.
  6195. * @type {string}
  6196. */
  6197. textTag: null,
  6198. /**
  6199. * @type {string}
  6200. */
  6201. textFill: '#000',
  6202. /**
  6203. * @type {string}
  6204. */
  6205. textStroke: null,
  6206. /**
  6207. * @type {number}
  6208. */
  6209. textWidth: null,
  6210. /**
  6211. * Only for textBackground.
  6212. * @type {number}
  6213. */
  6214. textHeight: null,
  6215. /**
  6216. * textStroke may be set as some color as a default
  6217. * value in upper applicaion, where the default value
  6218. * of textStrokeWidth should be 0 to make sure that
  6219. * user can choose to do not use text stroke.
  6220. * @type {number}
  6221. */
  6222. textStrokeWidth: 0,
  6223. /**
  6224. * @type {number}
  6225. */
  6226. textLineHeight: null,
  6227. /**
  6228. * 'inside', 'left', 'right', 'top', 'bottom'
  6229. * [x, y]
  6230. * Based on x, y of rect.
  6231. * @type {string|Array.<number>}
  6232. * @default 'inside'
  6233. */
  6234. textPosition: 'inside',
  6235. /**
  6236. * If not specified, use the boundingRect of a `displayable`.
  6237. * @type {Object}
  6238. */
  6239. textRect: null,
  6240. /**
  6241. * [x, y]
  6242. * @type {Array.<number>}
  6243. */
  6244. textOffset: null,
  6245. /**
  6246. * @type {string}
  6247. */
  6248. textAlign: null,
  6249. /**
  6250. * @type {string}
  6251. */
  6252. textVerticalAlign: null,
  6253. /**
  6254. * @type {number}
  6255. */
  6256. textDistance: 5,
  6257. /**
  6258. * @type {string}
  6259. */
  6260. textShadowColor: 'transparent',
  6261. /**
  6262. * @type {number}
  6263. */
  6264. textShadowBlur: 0,
  6265. /**
  6266. * @type {number}
  6267. */
  6268. textShadowOffsetX: 0,
  6269. /**
  6270. * @type {number}
  6271. */
  6272. textShadowOffsetY: 0,
  6273. /**
  6274. * @type {string}
  6275. */
  6276. textBoxShadowColor: 'transparent',
  6277. /**
  6278. * @type {number}
  6279. */
  6280. textBoxShadowBlur: 0,
  6281. /**
  6282. * @type {number}
  6283. */
  6284. textBoxShadowOffsetX: 0,
  6285. /**
  6286. * @type {number}
  6287. */
  6288. textBoxShadowOffsetY: 0,
  6289. /**
  6290. * Whether transform text.
  6291. * Only available in Path and Image element,
  6292. * where the text is called as `RectText`.
  6293. * @type {boolean}
  6294. */
  6295. transformText: false,
  6296. /**
  6297. * Text rotate around position of Path or Image.
  6298. * The origin of the rotation can be specified by `textOrigin`.
  6299. * Only available in Path and Image element,
  6300. * where the text is called as `RectText`.
  6301. */
  6302. textRotation: 0,
  6303. /**
  6304. * Text origin of text rotation.
  6305. * Useful in the case like label rotation of circular symbol.
  6306. * Only available in Path and Image element, where the text is called
  6307. * as `RectText` and the element is called as "host element".
  6308. * The value can be:
  6309. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6310. * base on the left-top corner of the rect of its host element.
  6311. * + If specified as a string `center`, it is the center of the rect of
  6312. * its host element.
  6313. * + By default, this origin is the `textPosition`.
  6314. * @type {string|Array.<number>}
  6315. */
  6316. textOrigin: null,
  6317. /**
  6318. * @type {string}
  6319. */
  6320. textBackgroundColor: null,
  6321. /**
  6322. * @type {string}
  6323. */
  6324. textBorderColor: null,
  6325. /**
  6326. * @type {number}
  6327. */
  6328. textBorderWidth: 0,
  6329. /**
  6330. * @type {number}
  6331. */
  6332. textBorderRadius: 0,
  6333. /**
  6334. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6335. * @type {number|Array.<number>}
  6336. */
  6337. textPadding: null,
  6338. /**
  6339. * Text styles for rich text.
  6340. * @type {Object}
  6341. */
  6342. rich: null,
  6343. /**
  6344. * {outerWidth, outerHeight, ellipsis, placeholder}
  6345. * @type {Object}
  6346. */
  6347. truncate: null,
  6348. /**
  6349. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6350. * @type {string}
  6351. */
  6352. blend: null,
  6353. /**
  6354. * @param {CanvasRenderingContext2D} ctx
  6355. */
  6356. bind: function (ctx, el, prevEl) {
  6357. var style = this;
  6358. var prevStyle = prevEl && prevEl.style;
  6359. // If no prevStyle, it means first draw.
  6360. // Only apply cache if the last time cachced by this function.
  6361. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6362. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6363. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6364. var prop = STYLE_COMMON_PROPS[i];
  6365. var styleName = prop[0];
  6366. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6367. // FIXME Invalid property value will cause style leak from previous element.
  6368. ctx[styleName] =
  6369. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6370. }
  6371. }
  6372. if ((notCheckCache || style.fill !== prevStyle.fill)) {
  6373. ctx.fillStyle = style.fill;
  6374. }
  6375. if ((notCheckCache || style.stroke !== prevStyle.stroke)) {
  6376. ctx.strokeStyle = style.stroke;
  6377. }
  6378. if ((notCheckCache || style.opacity !== prevStyle.opacity)) {
  6379. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6380. }
  6381. if ((notCheckCache || style.blend !== prevStyle.blend)) {
  6382. ctx.globalCompositeOperation = style.blend || 'source-over';
  6383. }
  6384. if (this.hasStroke()) {
  6385. var lineWidth = style.lineWidth;
  6386. ctx.lineWidth = lineWidth / (
  6387. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  6388. );
  6389. }
  6390. },
  6391. hasFill: function () {
  6392. var fill = this.fill;
  6393. return fill != null && fill !== 'none';
  6394. },
  6395. hasStroke: function () {
  6396. var stroke = this.stroke;
  6397. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6398. },
  6399. /**
  6400. * Extend from other style
  6401. * @param {zrender/graphic/Style} otherStyle
  6402. * @param {boolean} overwrite true: overwrirte any way.
  6403. * false: overwrite only when !target.hasOwnProperty
  6404. * others: overwrite when property is not null/undefined.
  6405. */
  6406. extendFrom: function (otherStyle, overwrite) {
  6407. if (otherStyle) {
  6408. for (var name in otherStyle) {
  6409. if (otherStyle.hasOwnProperty(name)
  6410. && (overwrite === true
  6411. || (
  6412. overwrite === false
  6413. ? !this.hasOwnProperty(name)
  6414. : otherStyle[name] != null
  6415. )
  6416. )
  6417. ) {
  6418. this[name] = otherStyle[name];
  6419. }
  6420. }
  6421. }
  6422. },
  6423. /**
  6424. * Batch setting style with a given object
  6425. * @param {Object|string} obj
  6426. * @param {*} [obj]
  6427. */
  6428. set: function (obj, value) {
  6429. if (typeof obj === 'string') {
  6430. this[obj] = value;
  6431. }
  6432. else {
  6433. this.extendFrom(obj, true);
  6434. }
  6435. },
  6436. /**
  6437. * Clone
  6438. * @return {zrender/graphic/Style} [description]
  6439. */
  6440. clone: function () {
  6441. var newStyle = new this.constructor();
  6442. newStyle.extendFrom(this, true);
  6443. return newStyle;
  6444. },
  6445. getGradient: function (ctx, obj, rect) {
  6446. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6447. var canvasGradient = method(ctx, obj, rect);
  6448. var colorStops = obj.colorStops;
  6449. for (var i = 0; i < colorStops.length; i++) {
  6450. canvasGradient.addColorStop(
  6451. colorStops[i].offset, colorStops[i].color
  6452. );
  6453. }
  6454. return canvasGradient;
  6455. }
  6456. };
  6457. var styleProto = Style.prototype;
  6458. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6459. var prop = STYLE_COMMON_PROPS[i];
  6460. if (!(prop[0] in styleProto)) {
  6461. styleProto[prop[0]] = prop[1];
  6462. }
  6463. }
  6464. // Provide for others
  6465. Style.getGradient = styleProto.getGradient;
  6466. var Pattern = function (image, repeat) {
  6467. // Should do nothing more in this constructor. Because gradient can be
  6468. // declard by `color: {image: ...}`, where this constructor will not be called.
  6469. this.image = image;
  6470. this.repeat = repeat;
  6471. // Can be cloned
  6472. this.type = 'pattern';
  6473. };
  6474. Pattern.prototype.getCanvasPattern = function (ctx) {
  6475. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6476. };
  6477. /**
  6478. * @module zrender/Layer
  6479. * @author pissang(https://www.github.com/pissang)
  6480. */
  6481. function returnFalse() {
  6482. return false;
  6483. }
  6484. /**
  6485. * 创建dom
  6486. *
  6487. * @inner
  6488. * @param {string} id dom id 待用
  6489. * @param {Painter} painter painter instance
  6490. * @param {number} number
  6491. */
  6492. function createDom(id, painter, dpr) {
  6493. var newDom = createCanvas();
  6494. var width = painter.getWidth();
  6495. var height = painter.getHeight();
  6496. var newDomStyle = newDom.style;
  6497. if (newDomStyle) { // In node or some other non-browser environment
  6498. newDomStyle.position = 'absolute';
  6499. newDomStyle.left = 0;
  6500. newDomStyle.top = 0;
  6501. newDomStyle.width = width + 'px';
  6502. newDomStyle.height = height + 'px';
  6503. newDom.setAttribute('data-zr-dom-id', id);
  6504. }
  6505. newDom.width = width * dpr;
  6506. newDom.height = height * dpr;
  6507. return newDom;
  6508. }
  6509. /**
  6510. * @alias module:zrender/Layer
  6511. * @constructor
  6512. * @extends module:zrender/mixin/Transformable
  6513. * @param {string} id
  6514. * @param {module:zrender/Painter} painter
  6515. * @param {number} [dpr]
  6516. */
  6517. var Layer = function (id, painter, dpr) {
  6518. var dom;
  6519. dpr = dpr || devicePixelRatio;
  6520. if (typeof id === 'string') {
  6521. dom = createDom(id, painter, dpr);
  6522. }
  6523. // Not using isDom because in node it will return false
  6524. else if (isObject(id)) {
  6525. dom = id;
  6526. id = dom.id;
  6527. }
  6528. this.id = id;
  6529. this.dom = dom;
  6530. var domStyle = dom.style;
  6531. if (domStyle) { // Not in node
  6532. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6533. domStyle['-webkit-user-select'] = 'none';
  6534. domStyle['user-select'] = 'none';
  6535. domStyle['-webkit-touch-callout'] = 'none';
  6536. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6537. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6538. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6539. domStyle['border-width'] = 0;
  6540. }
  6541. this.domBack = null;
  6542. this.ctxBack = null;
  6543. this.painter = painter;
  6544. this.config = null;
  6545. // Configs
  6546. /**
  6547. * 每次清空画布的颜色
  6548. * @type {string}
  6549. * @default 0
  6550. */
  6551. this.clearColor = 0;
  6552. /**
  6553. * 是否开启动态模糊
  6554. * @type {boolean}
  6555. * @default false
  6556. */
  6557. this.motionBlur = false;
  6558. /**
  6559. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6560. * @type {number}
  6561. * @default 0.7
  6562. */
  6563. this.lastFrameAlpha = 0.7;
  6564. /**
  6565. * Layer dpr
  6566. * @type {number}
  6567. */
  6568. this.dpr = dpr;
  6569. };
  6570. Layer.prototype = {
  6571. constructor: Layer,
  6572. __dirty: true,
  6573. __used: false,
  6574. __drawIndex: 0,
  6575. __startIndex: 0,
  6576. __endIndex: 0,
  6577. incremental: false,
  6578. getElementCount: function () {
  6579. return this.__endIndex - this.__startIndex;
  6580. },
  6581. initContext: function () {
  6582. this.ctx = this.dom.getContext('2d');
  6583. this.ctx.dpr = this.dpr;
  6584. },
  6585. createBackBuffer: function () {
  6586. var dpr = this.dpr;
  6587. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6588. this.ctxBack = this.domBack.getContext('2d');
  6589. if (dpr !== 1) {
  6590. this.ctxBack.scale(dpr, dpr);
  6591. }
  6592. },
  6593. /**
  6594. * @param {number} width
  6595. * @param {number} height
  6596. */
  6597. resize: function (width, height) {
  6598. var dpr = this.dpr;
  6599. var dom = this.dom;
  6600. var domStyle = dom.style;
  6601. var domBack = this.domBack;
  6602. if (domStyle) {
  6603. domStyle.width = width + 'px';
  6604. domStyle.height = height + 'px';
  6605. }
  6606. dom.width = width * dpr;
  6607. dom.height = height * dpr;
  6608. if (domBack) {
  6609. domBack.width = width * dpr;
  6610. domBack.height = height * dpr;
  6611. if (dpr !== 1) {
  6612. this.ctxBack.scale(dpr, dpr);
  6613. }
  6614. }
  6615. },
  6616. /**
  6617. * 清空该层画布
  6618. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6619. * @param {Color} [clearColor]
  6620. */
  6621. clear: function (clearAll, clearColor) {
  6622. var dom = this.dom;
  6623. var ctx = this.ctx;
  6624. var width = dom.width;
  6625. var height = dom.height;
  6626. var clearColor = clearColor || this.clearColor;
  6627. var haveMotionBLur = this.motionBlur && !clearAll;
  6628. var lastFrameAlpha = this.lastFrameAlpha;
  6629. var dpr = this.dpr;
  6630. if (haveMotionBLur) {
  6631. if (!this.domBack) {
  6632. this.createBackBuffer();
  6633. }
  6634. this.ctxBack.globalCompositeOperation = 'copy';
  6635. this.ctxBack.drawImage(
  6636. dom, 0, 0,
  6637. width / dpr,
  6638. height / dpr
  6639. );
  6640. }
  6641. ctx.clearRect(0, 0, width, height);
  6642. if (clearColor && clearColor !== 'transparent') {
  6643. var clearColorGradientOrPattern;
  6644. // Gradient
  6645. if (clearColor.colorStops) {
  6646. // Cache canvas gradient
  6647. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6648. x: 0,
  6649. y: 0,
  6650. width: width,
  6651. height: height
  6652. });
  6653. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6654. }
  6655. // Pattern
  6656. else if (clearColor.image) {
  6657. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6658. }
  6659. ctx.save();
  6660. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6661. ctx.fillRect(0, 0, width, height);
  6662. ctx.restore();
  6663. }
  6664. if (haveMotionBLur) {
  6665. var domBack = this.domBack;
  6666. ctx.save();
  6667. ctx.globalAlpha = lastFrameAlpha;
  6668. ctx.drawImage(domBack, 0, 0, width, height);
  6669. ctx.restore();
  6670. }
  6671. }
  6672. };
  6673. var requestAnimationFrame = (
  6674. typeof window !== 'undefined'
  6675. && (
  6676. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  6677. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6678. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  6679. || window.mozRequestAnimationFrame
  6680. || window.webkitRequestAnimationFrame
  6681. )
  6682. ) || function (func) {
  6683. setTimeout(func, 16);
  6684. };
  6685. var globalImageCache = new LRU(50);
  6686. /**
  6687. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6688. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6689. */
  6690. function findExistImage(newImageOrSrc) {
  6691. if (typeof newImageOrSrc === 'string') {
  6692. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6693. return cachedImgObj && cachedImgObj.image;
  6694. }
  6695. else {
  6696. return newImageOrSrc;
  6697. }
  6698. }
  6699. /**
  6700. * Caution: User should cache loaded images, but not just count on LRU.
  6701. * Consider if required images more than LRU size, will dead loop occur?
  6702. *
  6703. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6704. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6705. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6706. * @param {Function} [cb] params: (image, cbPayload)
  6707. * @param {Object} [cbPayload] Payload on cb calling.
  6708. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6709. */
  6710. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6711. if (!newImageOrSrc) {
  6712. return image;
  6713. }
  6714. else if (typeof newImageOrSrc === 'string') {
  6715. // Image should not be loaded repeatly.
  6716. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6717. return image;
  6718. }
  6719. // Only when there is no existent image or existent image src
  6720. // is different, this method is responsible for load.
  6721. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6722. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6723. if (cachedImgObj) {
  6724. image = cachedImgObj.image;
  6725. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6726. }
  6727. else {
  6728. image = new Image();
  6729. image.onload = image.onerror = imageOnLoad;
  6730. globalImageCache.put(
  6731. newImageOrSrc,
  6732. image.__cachedImgObj = {
  6733. image: image,
  6734. pending: [pendingWrap]
  6735. }
  6736. );
  6737. image.src = image.__zrImageSrc = newImageOrSrc;
  6738. }
  6739. return image;
  6740. }
  6741. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6742. else {
  6743. return newImageOrSrc;
  6744. }
  6745. }
  6746. function imageOnLoad() {
  6747. var cachedImgObj = this.__cachedImgObj;
  6748. this.onload = this.onerror = this.__cachedImgObj = null;
  6749. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6750. var pendingWrap = cachedImgObj.pending[i];
  6751. var cb = pendingWrap.cb;
  6752. cb && cb(this, pendingWrap.cbPayload);
  6753. pendingWrap.hostEl.dirty();
  6754. }
  6755. cachedImgObj.pending.length = 0;
  6756. }
  6757. function isImageReady(image) {
  6758. return image && image.width && image.height;
  6759. }
  6760. var textWidthCache = {};
  6761. var textWidthCacheCounter = 0;
  6762. var TEXT_CACHE_MAX = 5000;
  6763. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6764. var DEFAULT_FONT$1 = '12px sans-serif';
  6765. // Avoid assign to an exported variable, for transforming to cjs.
  6766. var methods$1 = {};
  6767. function $override$1(name, fn) {
  6768. methods$1[name] = fn;
  6769. }
  6770. /**
  6771. * @public
  6772. * @param {string} text
  6773. * @param {string} font
  6774. * @return {number} width
  6775. */
  6776. function getWidth(text, font) {
  6777. font = font || DEFAULT_FONT$1;
  6778. var key = text + ':' + font;
  6779. if (textWidthCache[key]) {
  6780. return textWidthCache[key];
  6781. }
  6782. var textLines = (text + '').split('\n');
  6783. var width = 0;
  6784. for (var i = 0, l = textLines.length; i < l; i++) {
  6785. // textContain.measureText may be overrided in SVG or VML
  6786. width = Math.max(measureText(textLines[i], font).width, width);
  6787. }
  6788. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6789. textWidthCacheCounter = 0;
  6790. textWidthCache = {};
  6791. }
  6792. textWidthCacheCounter++;
  6793. textWidthCache[key] = width;
  6794. return width;
  6795. }
  6796. /**
  6797. * @public
  6798. * @param {string} text
  6799. * @param {string} font
  6800. * @param {string} [textAlign='left']
  6801. * @param {string} [textVerticalAlign='top']
  6802. * @param {Array.<number>} [textPadding]
  6803. * @param {Object} [rich]
  6804. * @param {Object} [truncate]
  6805. * @return {Object} {x, y, width, height, lineHeight}
  6806. */
  6807. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6808. return rich
  6809. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate)
  6810. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6811. }
  6812. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6813. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6814. var outerWidth = getWidth(text, font);
  6815. if (textPadding) {
  6816. outerWidth += textPadding[1] + textPadding[3];
  6817. }
  6818. var outerHeight = contentBlock.outerHeight;
  6819. var x = adjustTextX(0, outerWidth, textAlign);
  6820. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6821. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6822. rect.lineHeight = contentBlock.lineHeight;
  6823. return rect;
  6824. }
  6825. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6826. var contentBlock = parseRichText(text, {
  6827. rich: rich,
  6828. truncate: truncate,
  6829. font: font,
  6830. textAlign: textAlign,
  6831. textPadding: textPadding,
  6832. textLineHeight: textLineHeight
  6833. });
  6834. var outerWidth = contentBlock.outerWidth;
  6835. var outerHeight = contentBlock.outerHeight;
  6836. var x = adjustTextX(0, outerWidth, textAlign);
  6837. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6838. return new BoundingRect(x, y, outerWidth, outerHeight);
  6839. }
  6840. /**
  6841. * @public
  6842. * @param {number} x
  6843. * @param {number} width
  6844. * @param {string} [textAlign='left']
  6845. * @return {number} Adjusted x.
  6846. */
  6847. function adjustTextX(x, width, textAlign) {
  6848. // FIXME Right to left language
  6849. if (textAlign === 'right') {
  6850. x -= width;
  6851. }
  6852. else if (textAlign === 'center') {
  6853. x -= width / 2;
  6854. }
  6855. return x;
  6856. }
  6857. /**
  6858. * @public
  6859. * @param {number} y
  6860. * @param {number} height
  6861. * @param {string} [textVerticalAlign='top']
  6862. * @return {number} Adjusted y.
  6863. */
  6864. function adjustTextY(y, height, textVerticalAlign) {
  6865. if (textVerticalAlign === 'middle') {
  6866. y -= height / 2;
  6867. }
  6868. else if (textVerticalAlign === 'bottom') {
  6869. y -= height;
  6870. }
  6871. return y;
  6872. }
  6873. /**
  6874. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6875. * @public
  6876. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6877. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6878. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6879. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6880. */
  6881. function calculateTextPosition(out, style, rect) {
  6882. var textPosition = style.textPosition;
  6883. var distance = style.textDistance;
  6884. var x = rect.x;
  6885. var y = rect.y;
  6886. distance = distance || 0;
  6887. var height = rect.height;
  6888. var width = rect.width;
  6889. var halfHeight = height / 2;
  6890. var textAlign = 'left';
  6891. var textVerticalAlign = 'top';
  6892. switch (textPosition) {
  6893. case 'left':
  6894. x -= distance;
  6895. y += halfHeight;
  6896. textAlign = 'right';
  6897. textVerticalAlign = 'middle';
  6898. break;
  6899. case 'right':
  6900. x += distance + width;
  6901. y += halfHeight;
  6902. textVerticalAlign = 'middle';
  6903. break;
  6904. case 'top':
  6905. x += width / 2;
  6906. y -= distance;
  6907. textAlign = 'center';
  6908. textVerticalAlign = 'bottom';
  6909. break;
  6910. case 'bottom':
  6911. x += width / 2;
  6912. y += height + distance;
  6913. textAlign = 'center';
  6914. break;
  6915. case 'inside':
  6916. x += width / 2;
  6917. y += halfHeight;
  6918. textAlign = 'center';
  6919. textVerticalAlign = 'middle';
  6920. break;
  6921. case 'insideLeft':
  6922. x += distance;
  6923. y += halfHeight;
  6924. textVerticalAlign = 'middle';
  6925. break;
  6926. case 'insideRight':
  6927. x += width - distance;
  6928. y += halfHeight;
  6929. textAlign = 'right';
  6930. textVerticalAlign = 'middle';
  6931. break;
  6932. case 'insideTop':
  6933. x += width / 2;
  6934. y += distance;
  6935. textAlign = 'center';
  6936. break;
  6937. case 'insideBottom':
  6938. x += width / 2;
  6939. y += height - distance;
  6940. textAlign = 'center';
  6941. textVerticalAlign = 'bottom';
  6942. break;
  6943. case 'insideTopLeft':
  6944. x += distance;
  6945. y += distance;
  6946. break;
  6947. case 'insideTopRight':
  6948. x += width - distance;
  6949. y += distance;
  6950. textAlign = 'right';
  6951. break;
  6952. case 'insideBottomLeft':
  6953. x += distance;
  6954. y += height - distance;
  6955. textVerticalAlign = 'bottom';
  6956. break;
  6957. case 'insideBottomRight':
  6958. x += width - distance;
  6959. y += height - distance;
  6960. textAlign = 'right';
  6961. textVerticalAlign = 'bottom';
  6962. break;
  6963. }
  6964. out = out || {};
  6965. out.x = x;
  6966. out.y = y;
  6967. out.textAlign = textAlign;
  6968. out.textVerticalAlign = textVerticalAlign;
  6969. return out;
  6970. }
  6971. /**
  6972. * To be removed. But still do not remove in case that some one has imported it.
  6973. * @deprecated
  6974. * @public
  6975. * @param {stirng} textPosition
  6976. * @param {Object} rect {x, y, width, height}
  6977. * @param {number} distance
  6978. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6979. */
  6980. /**
  6981. * Show ellipsis if overflow.
  6982. *
  6983. * @public
  6984. * @param {string} text
  6985. * @param {string} containerWidth
  6986. * @param {string} font
  6987. * @param {number} [ellipsis='...']
  6988. * @param {Object} [options]
  6989. * @param {number} [options.maxIterations=3]
  6990. * @param {number} [options.minChar=0] If truncate result are less
  6991. * then minChar, ellipsis will not show, which is
  6992. * better for user hint in some cases.
  6993. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6994. * @return {string}
  6995. */
  6996. function truncateText(text, containerWidth, font, ellipsis, options) {
  6997. if (!containerWidth) {
  6998. return '';
  6999. }
  7000. var textLines = (text + '').split('\n');
  7001. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  7002. // FIXME
  7003. // It is not appropriate that every line has '...' when truncate multiple lines.
  7004. for (var i = 0, len = textLines.length; i < len; i++) {
  7005. textLines[i] = truncateSingleLine(textLines[i], options);
  7006. }
  7007. return textLines.join('\n');
  7008. }
  7009. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  7010. options = extend({}, options);
  7011. options.font = font;
  7012. var ellipsis = retrieve2(ellipsis, '...');
  7013. options.maxIterations = retrieve2(options.maxIterations, 2);
  7014. var minChar = options.minChar = retrieve2(options.minChar, 0);
  7015. // FIXME
  7016. // Other languages?
  7017. options.cnCharWidth = getWidth('国', font);
  7018. // FIXME
  7019. // Consider proportional font?
  7020. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  7021. options.placeholder = retrieve2(options.placeholder, '');
  7022. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  7023. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  7024. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  7025. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  7026. contentWidth -= ascCharWidth;
  7027. }
  7028. var ellipsisWidth = getWidth(ellipsis, font);
  7029. if (ellipsisWidth > contentWidth) {
  7030. ellipsis = '';
  7031. ellipsisWidth = 0;
  7032. }
  7033. contentWidth = containerWidth - ellipsisWidth;
  7034. options.ellipsis = ellipsis;
  7035. options.ellipsisWidth = ellipsisWidth;
  7036. options.contentWidth = contentWidth;
  7037. options.containerWidth = containerWidth;
  7038. return options;
  7039. }
  7040. function truncateSingleLine(textLine, options) {
  7041. var containerWidth = options.containerWidth;
  7042. var font = options.font;
  7043. var contentWidth = options.contentWidth;
  7044. if (!containerWidth) {
  7045. return '';
  7046. }
  7047. var lineWidth = getWidth(textLine, font);
  7048. if (lineWidth <= containerWidth) {
  7049. return textLine;
  7050. }
  7051. for (var j = 0; ; j++) {
  7052. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  7053. textLine += options.ellipsis;
  7054. break;
  7055. }
  7056. var subLength = j === 0
  7057. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  7058. : lineWidth > 0
  7059. ? Math.floor(textLine.length * contentWidth / lineWidth)
  7060. : 0;
  7061. textLine = textLine.substr(0, subLength);
  7062. lineWidth = getWidth(textLine, font);
  7063. }
  7064. if (textLine === '') {
  7065. textLine = options.placeholder;
  7066. }
  7067. return textLine;
  7068. }
  7069. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  7070. var width = 0;
  7071. var i = 0;
  7072. for (var len = text.length; i < len && width < contentWidth; i++) {
  7073. var charCode = text.charCodeAt(i);
  7074. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  7075. }
  7076. return i;
  7077. }
  7078. /**
  7079. * @public
  7080. * @param {string} font
  7081. * @return {number} line height
  7082. */
  7083. function getLineHeight(font) {
  7084. // FIXME A rough approach.
  7085. return getWidth('国', font);
  7086. }
  7087. /**
  7088. * @public
  7089. * @param {string} text
  7090. * @param {string} font
  7091. * @return {Object} width
  7092. */
  7093. function measureText(text, font) {
  7094. return methods$1.measureText(text, font);
  7095. }
  7096. // Avoid assign to an exported variable, for transforming to cjs.
  7097. methods$1.measureText = function (text, font) {
  7098. var ctx = getContext();
  7099. ctx.font = font || DEFAULT_FONT$1;
  7100. return ctx.measureText(text);
  7101. };
  7102. /**
  7103. * @public
  7104. * @param {string} text
  7105. * @param {string} font
  7106. * @param {Object} [truncate]
  7107. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  7108. * Notice: for performance, do not calculate outerWidth util needed.
  7109. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  7110. * Thus we can simply comparing the `input` text to determin whether the result changed,
  7111. * without travel the result `lines`.
  7112. */
  7113. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  7114. text != null && (text += '');
  7115. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  7116. var lines = text ? text.split('\n') : [];
  7117. var height = lines.length * lineHeight;
  7118. var outerHeight = height;
  7119. var canCacheByTextString = true;
  7120. if (padding) {
  7121. outerHeight += padding[0] + padding[2];
  7122. }
  7123. if (text && truncate) {
  7124. canCacheByTextString = false;
  7125. var truncOuterHeight = truncate.outerHeight;
  7126. var truncOuterWidth = truncate.outerWidth;
  7127. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  7128. text = '';
  7129. lines = [];
  7130. }
  7131. else if (truncOuterWidth != null) {
  7132. var options = prepareTruncateOptions(
  7133. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  7134. font,
  7135. truncate.ellipsis,
  7136. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  7137. );
  7138. // FIXME
  7139. // It is not appropriate that every line has '...' when truncate multiple lines.
  7140. for (var i = 0, len = lines.length; i < len; i++) {
  7141. lines[i] = truncateSingleLine(lines[i], options);
  7142. }
  7143. }
  7144. }
  7145. return {
  7146. lines: lines,
  7147. height: height,
  7148. outerHeight: outerHeight,
  7149. lineHeight: lineHeight,
  7150. canCacheByTextString: canCacheByTextString
  7151. };
  7152. }
  7153. /**
  7154. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  7155. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  7156. *
  7157. * @public
  7158. * @param {string} text
  7159. * @param {Object} style
  7160. * @return {Object} block
  7161. * {
  7162. * width,
  7163. * height,
  7164. * lines: [{
  7165. * lineHeight,
  7166. * width,
  7167. * tokens: [[{
  7168. * styleName,
  7169. * text,
  7170. * width, // include textPadding
  7171. * height, // include textPadding
  7172. * textWidth, // pure text width
  7173. * textHeight, // pure text height
  7174. * lineHeihgt,
  7175. * font,
  7176. * textAlign,
  7177. * textVerticalAlign
  7178. * }], [...], ...]
  7179. * }, ...]
  7180. * }
  7181. * If styleName is undefined, it is plain text.
  7182. */
  7183. function parseRichText(text, style) {
  7184. var contentBlock = {lines: [], width: 0, height: 0};
  7185. text != null && (text += '');
  7186. if (!text) {
  7187. return contentBlock;
  7188. }
  7189. var lastIndex = STYLE_REG.lastIndex = 0;
  7190. var result;
  7191. while ((result = STYLE_REG.exec(text)) != null) {
  7192. var matchedIndex = result.index;
  7193. if (matchedIndex > lastIndex) {
  7194. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  7195. }
  7196. pushTokens(contentBlock, result[2], result[1]);
  7197. lastIndex = STYLE_REG.lastIndex;
  7198. }
  7199. if (lastIndex < text.length) {
  7200. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  7201. }
  7202. var lines = contentBlock.lines;
  7203. var contentHeight = 0;
  7204. var contentWidth = 0;
  7205. // For `textWidth: 100%`
  7206. var pendingList = [];
  7207. var stlPadding = style.textPadding;
  7208. var truncate = style.truncate;
  7209. var truncateWidth = truncate && truncate.outerWidth;
  7210. var truncateHeight = truncate && truncate.outerHeight;
  7211. if (stlPadding) {
  7212. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  7213. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  7214. }
  7215. // Calculate layout info of tokens.
  7216. for (var i = 0; i < lines.length; i++) {
  7217. var line = lines[i];
  7218. var lineHeight = 0;
  7219. var lineWidth = 0;
  7220. for (var j = 0; j < line.tokens.length; j++) {
  7221. var token = line.tokens[j];
  7222. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  7223. // textPadding should not inherit from style.
  7224. var textPadding = token.textPadding = tokenStyle.textPadding;
  7225. // textFont has been asigned to font by `normalizeStyle`.
  7226. var font = token.font = tokenStyle.font || style.font;
  7227. // textHeight can be used when textVerticalAlign is specified in token.
  7228. var tokenHeight = token.textHeight = retrieve2(
  7229. // textHeight should not be inherited, consider it can be specified
  7230. // as box height of the block.
  7231. tokenStyle.textHeight, getLineHeight(font)
  7232. );
  7233. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  7234. token.height = tokenHeight;
  7235. token.lineHeight = retrieve3(
  7236. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  7237. );
  7238. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  7239. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  7240. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  7241. return {lines: [], width: 0, height: 0};
  7242. }
  7243. token.textWidth = getWidth(token.text, font);
  7244. var tokenWidth = tokenStyle.textWidth;
  7245. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  7246. // Percent width, can be `100%`, can be used in drawing separate
  7247. // line when box width is needed to be auto.
  7248. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  7249. token.percentWidth = tokenWidth;
  7250. pendingList.push(token);
  7251. tokenWidth = 0;
  7252. // Do not truncate in this case, because there is no user case
  7253. // and it is too complicated.
  7254. }
  7255. else {
  7256. if (tokenWidthNotSpecified) {
  7257. tokenWidth = token.textWidth;
  7258. // FIXME: If image is not loaded and textWidth is not specified, calling
  7259. // `getBoundingRect()` will not get correct result.
  7260. var textBackgroundColor = tokenStyle.textBackgroundColor;
  7261. var bgImg = textBackgroundColor && textBackgroundColor.image;
  7262. // Use cases:
  7263. // (1) If image is not loaded, it will be loaded at render phase and call
  7264. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7265. // image, and then the right size will be calculated here at the next tick.
  7266. // See `graphic/helper/text.js`.
  7267. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7268. // use `imageHelper.findExistImage` to find cached image.
  7269. // `imageHelper.findExistImage` will always be called here before
  7270. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7271. // which ensures that image will not be rendered before correct size calcualted.
  7272. if (bgImg) {
  7273. bgImg = findExistImage(bgImg);
  7274. if (isImageReady(bgImg)) {
  7275. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7276. }
  7277. }
  7278. }
  7279. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7280. tokenWidth += paddingW;
  7281. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7282. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7283. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7284. token.text = '';
  7285. token.textWidth = tokenWidth = 0;
  7286. }
  7287. else {
  7288. token.text = truncateText(
  7289. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  7290. {minChar: truncate.minChar}
  7291. );
  7292. token.textWidth = getWidth(token.text, font);
  7293. tokenWidth = token.textWidth + paddingW;
  7294. }
  7295. }
  7296. }
  7297. lineWidth += (token.width = tokenWidth);
  7298. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7299. }
  7300. line.width = lineWidth;
  7301. line.lineHeight = lineHeight;
  7302. contentHeight += lineHeight;
  7303. contentWidth = Math.max(contentWidth, lineWidth);
  7304. }
  7305. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7306. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7307. if (stlPadding) {
  7308. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7309. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7310. }
  7311. for (var i = 0; i < pendingList.length; i++) {
  7312. var token = pendingList[i];
  7313. var percentWidth = token.percentWidth;
  7314. // Should not base on outerWidth, because token can not be placed out of padding.
  7315. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7316. }
  7317. return contentBlock;
  7318. }
  7319. function pushTokens(block, str, styleName) {
  7320. var isEmptyStr = str === '';
  7321. var strs = str.split('\n');
  7322. var lines = block.lines;
  7323. for (var i = 0; i < strs.length; i++) {
  7324. var text = strs[i];
  7325. var token = {
  7326. styleName: styleName,
  7327. text: text,
  7328. isLineHolder: !text && !isEmptyStr
  7329. };
  7330. // The first token should be appended to the last line.
  7331. if (!i) {
  7332. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  7333. // Consider cases:
  7334. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7335. // (which is a placeholder) should be replaced by new token.
  7336. // (2) A image backage, where token likes {a|}.
  7337. // (3) A redundant '' will affect textAlign in line.
  7338. // (4) tokens with the same tplName should not be merged, because
  7339. // they should be displayed in different box (with border and padding).
  7340. var tokensLen = tokens.length;
  7341. (tokensLen === 1 && tokens[0].isLineHolder)
  7342. ? (tokens[0] = token)
  7343. // Consider text is '', only insert when it is the "lineHolder" or
  7344. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7345. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  7346. }
  7347. // Other tokens always start a new line.
  7348. else {
  7349. // If there is '', insert it as a placeholder.
  7350. lines.push({tokens: [token]});
  7351. }
  7352. }
  7353. }
  7354. function makeFont(style) {
  7355. // FIXME in node-canvas fontWeight is before fontStyle
  7356. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7357. var font = (style.fontSize || style.fontFamily) && [
  7358. style.fontStyle,
  7359. style.fontWeight,
  7360. (style.fontSize || 12) + 'px',
  7361. // If font properties are defined, `fontFamily` should not be ignored.
  7362. style.fontFamily || 'sans-serif'
  7363. ].join(' ');
  7364. return font && trim(font) || style.textFont || style.font;
  7365. }
  7366. /**
  7367. * @param {Object} ctx
  7368. * @param {Object} shape
  7369. * @param {number} shape.x
  7370. * @param {number} shape.y
  7371. * @param {number} shape.width
  7372. * @param {number} shape.height
  7373. * @param {number} shape.r
  7374. */
  7375. function buildPath(ctx, shape) {
  7376. var x = shape.x;
  7377. var y = shape.y;
  7378. var width = shape.width;
  7379. var height = shape.height;
  7380. var r = shape.r;
  7381. var r1;
  7382. var r2;
  7383. var r3;
  7384. var r4;
  7385. // Convert width and height to positive for better borderRadius
  7386. if (width < 0) {
  7387. x = x + width;
  7388. width = -width;
  7389. }
  7390. if (height < 0) {
  7391. y = y + height;
  7392. height = -height;
  7393. }
  7394. if (typeof r === 'number') {
  7395. r1 = r2 = r3 = r4 = r;
  7396. }
  7397. else if (r instanceof Array) {
  7398. if (r.length === 1) {
  7399. r1 = r2 = r3 = r4 = r[0];
  7400. }
  7401. else if (r.length === 2) {
  7402. r1 = r3 = r[0];
  7403. r2 = r4 = r[1];
  7404. }
  7405. else if (r.length === 3) {
  7406. r1 = r[0];
  7407. r2 = r4 = r[1];
  7408. r3 = r[2];
  7409. }
  7410. else {
  7411. r1 = r[0];
  7412. r2 = r[1];
  7413. r3 = r[2];
  7414. r4 = r[3];
  7415. }
  7416. }
  7417. else {
  7418. r1 = r2 = r3 = r4 = 0;
  7419. }
  7420. var total;
  7421. if (r1 + r2 > width) {
  7422. total = r1 + r2;
  7423. r1 *= width / total;
  7424. r2 *= width / total;
  7425. }
  7426. if (r3 + r4 > width) {
  7427. total = r3 + r4;
  7428. r3 *= width / total;
  7429. r4 *= width / total;
  7430. }
  7431. if (r2 + r3 > height) {
  7432. total = r2 + r3;
  7433. r2 *= height / total;
  7434. r3 *= height / total;
  7435. }
  7436. if (r1 + r4 > height) {
  7437. total = r1 + r4;
  7438. r1 *= height / total;
  7439. r4 *= height / total;
  7440. }
  7441. ctx.moveTo(x + r1, y);
  7442. ctx.lineTo(x + width - r2, y);
  7443. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7444. ctx.lineTo(x + width, y + height - r3);
  7445. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7446. ctx.lineTo(x + r4, y + height);
  7447. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7448. ctx.lineTo(x, y + r1);
  7449. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7450. }
  7451. var DEFAULT_FONT = DEFAULT_FONT$1;
  7452. // TODO: Have not support 'start', 'end' yet.
  7453. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  7454. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  7455. // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7456. // the default value of shadowColor is `'transparent'`.
  7457. var SHADOW_STYLE_COMMON_PROPS = [
  7458. ['textShadowBlur', 'shadowBlur', 0],
  7459. ['textShadowOffsetX', 'shadowOffsetX', 0],
  7460. ['textShadowOffsetY', 'shadowOffsetY', 0],
  7461. ['textShadowColor', 'shadowColor', 'transparent']
  7462. ];
  7463. var _tmpTextPositionResult = {};
  7464. var _tmpBoxPositionResult = {};
  7465. /**
  7466. * @param {module:zrender/graphic/Style} style
  7467. * @return {module:zrender/graphic/Style} The input style.
  7468. */
  7469. function normalizeTextStyle(style) {
  7470. normalizeStyle(style);
  7471. each(style.rich, normalizeStyle);
  7472. return style;
  7473. }
  7474. function normalizeStyle(style) {
  7475. if (style) {
  7476. style.font = makeFont(style);
  7477. var textAlign = style.textAlign;
  7478. textAlign === 'middle' && (textAlign = 'center');
  7479. style.textAlign = (
  7480. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  7481. ) ? textAlign : 'left';
  7482. // Compatible with textBaseline.
  7483. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7484. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7485. style.textVerticalAlign = (
  7486. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  7487. ) ? textVerticalAlign : 'top';
  7488. var textPadding = style.textPadding;
  7489. if (textPadding) {
  7490. style.textPadding = normalizeCssArray(style.textPadding);
  7491. }
  7492. }
  7493. }
  7494. /**
  7495. * @param {CanvasRenderingContext2D} ctx
  7496. * @param {string} text
  7497. * @param {module:zrender/graphic/Style} style
  7498. * @param {Object|boolean} [rect] {x, y, width, height}
  7499. * If set false, rect text is not used.
  7500. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7501. */
  7502. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7503. style.rich
  7504. ? renderRichText(hostEl, ctx, text, style, rect, prevEl)
  7505. : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7506. }
  7507. // Avoid setting to ctx according to prevEl if possible for
  7508. // performance in scenarios of large amount text.
  7509. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7510. 'use strict';
  7511. var needDrawBg = needDrawBackground(style);
  7512. var prevStyle;
  7513. var checkCache = false;
  7514. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT;
  7515. // Only take and check cache for `Text` el, but not RectText.
  7516. if (prevEl !== WILL_BE_RESTORED) {
  7517. if (prevEl) {
  7518. prevStyle = prevEl.style;
  7519. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7520. }
  7521. // Prevent from using cache in `Style::bind`, because of the case:
  7522. // ctx property is modified by other properties than `Style::bind`
  7523. // used, and Style::bind is called next.
  7524. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7525. }
  7526. // Since this will be restored, prevent from using these props to check cache in the next
  7527. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7528. else if (cachedByMe) {
  7529. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7530. }
  7531. var styleFont = style.font || DEFAULT_FONT;
  7532. // PENDING
  7533. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7534. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7535. // But layer save/restore needed to be considered.
  7536. // if (styleFont !== ctx.__fontCache) {
  7537. // ctx.font = styleFont;
  7538. // if (prevEl !== WILL_BE_RESTORED) {
  7539. // ctx.__fontCache = styleFont;
  7540. // }
  7541. // }
  7542. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7543. ctx.font = styleFont;
  7544. }
  7545. // Use the final font from context-2d, because the final
  7546. // font might not be the style.font when it is illegal.
  7547. // But get `ctx.font` might be time consuming.
  7548. var computedFont = hostEl.__computedFont;
  7549. if (hostEl.__styleFont !== styleFont) {
  7550. hostEl.__styleFont = styleFont;
  7551. computedFont = hostEl.__computedFont = ctx.font;
  7552. }
  7553. var textPadding = style.textPadding;
  7554. var textLineHeight = style.textLineHeight;
  7555. var contentBlock = hostEl.__textCotentBlock;
  7556. if (!contentBlock || hostEl.__dirtyText) {
  7557. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  7558. text, computedFont, textPadding, textLineHeight, style.truncate
  7559. );
  7560. }
  7561. var outerHeight = contentBlock.outerHeight;
  7562. var textLines = contentBlock.lines;
  7563. var lineHeight = contentBlock.lineHeight;
  7564. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7565. var baseX = boxPos.baseX;
  7566. var baseY = boxPos.baseY;
  7567. var textAlign = boxPos.textAlign || 'left';
  7568. var textVerticalAlign = boxPos.textVerticalAlign;
  7569. // Origin of textRotation should be the base point of text drawing.
  7570. applyTextRotation(ctx, style, rect, baseX, baseY);
  7571. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7572. var textX = baseX;
  7573. var textY = boxY;
  7574. if (needDrawBg || textPadding) {
  7575. // Consider performance, do not call getTextWidth util necessary.
  7576. var textWidth = getWidth(text, computedFont);
  7577. var outerWidth = textWidth;
  7578. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7579. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7580. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7581. if (textPadding) {
  7582. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7583. textY += textPadding[0];
  7584. }
  7585. }
  7586. // Always set textAlign and textBase line, because it is difficute to calculate
  7587. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7588. // font set happened.
  7589. ctx.textAlign = textAlign;
  7590. // Force baseline to be "middle". Otherwise, if using "top", the
  7591. // text will offset downward a little bit in font "Microsoft YaHei".
  7592. ctx.textBaseline = 'middle';
  7593. // Set text opacity
  7594. ctx.globalAlpha = style.opacity || 1;
  7595. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7596. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7597. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7598. var styleProp = propItem[0];
  7599. var ctxProp = propItem[1];
  7600. var val = style[styleProp];
  7601. if (!checkCache || val !== prevStyle[styleProp]) {
  7602. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7603. }
  7604. }
  7605. // `textBaseline` is set as 'middle'.
  7606. textY += lineHeight / 2;
  7607. var textStrokeWidth = style.textStrokeWidth;
  7608. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7609. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7610. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7611. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7612. var textFill = getFill(style.textFill);
  7613. if (textStroke) {
  7614. if (strokeWidthChanged) {
  7615. ctx.lineWidth = textStrokeWidth;
  7616. }
  7617. if (strokeChanged) {
  7618. ctx.strokeStyle = textStroke;
  7619. }
  7620. }
  7621. if (textFill) {
  7622. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7623. ctx.fillStyle = textFill;
  7624. }
  7625. }
  7626. // Optimize simply, in most cases only one line exists.
  7627. if (textLines.length === 1) {
  7628. // Fill after stroke so the outline will not cover the main part.
  7629. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7630. textFill && ctx.fillText(textLines[0], textX, textY);
  7631. }
  7632. else {
  7633. for (var i = 0; i < textLines.length; i++) {
  7634. // Fill after stroke so the outline will not cover the main part.
  7635. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7636. textFill && ctx.fillText(textLines[i], textX, textY);
  7637. textY += lineHeight;
  7638. }
  7639. }
  7640. }
  7641. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7642. // Do not do cache for rich text because of the complexity.
  7643. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7644. if (prevEl !== WILL_BE_RESTORED) {
  7645. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7646. }
  7647. var contentBlock = hostEl.__textCotentBlock;
  7648. if (!contentBlock || hostEl.__dirtyText) {
  7649. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7650. }
  7651. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7652. }
  7653. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7654. var contentWidth = contentBlock.width;
  7655. var outerWidth = contentBlock.outerWidth;
  7656. var outerHeight = contentBlock.outerHeight;
  7657. var textPadding = style.textPadding;
  7658. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7659. var baseX = boxPos.baseX;
  7660. var baseY = boxPos.baseY;
  7661. var textAlign = boxPos.textAlign;
  7662. var textVerticalAlign = boxPos.textVerticalAlign;
  7663. // Origin of textRotation should be the base point of text drawing.
  7664. applyTextRotation(ctx, style, rect, baseX, baseY);
  7665. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7666. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7667. var xLeft = boxX;
  7668. var lineTop = boxY;
  7669. if (textPadding) {
  7670. xLeft += textPadding[3];
  7671. lineTop += textPadding[0];
  7672. }
  7673. var xRight = xLeft + contentWidth;
  7674. needDrawBackground(style) && drawBackground(
  7675. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  7676. );
  7677. for (var i = 0; i < contentBlock.lines.length; i++) {
  7678. var line = contentBlock.lines[i];
  7679. var tokens = line.tokens;
  7680. var tokenCount = tokens.length;
  7681. var lineHeight = line.lineHeight;
  7682. var usedWidth = line.width;
  7683. var leftIndex = 0;
  7684. var lineXLeft = xLeft;
  7685. var lineXRight = xRight;
  7686. var rightIndex = tokenCount - 1;
  7687. var token;
  7688. while (
  7689. leftIndex < tokenCount
  7690. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  7691. ) {
  7692. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7693. usedWidth -= token.width;
  7694. lineXLeft += token.width;
  7695. leftIndex++;
  7696. }
  7697. while (
  7698. rightIndex >= 0
  7699. && (token = tokens[rightIndex], token.textAlign === 'right')
  7700. ) {
  7701. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7702. usedWidth -= token.width;
  7703. lineXRight -= token.width;
  7704. rightIndex--;
  7705. }
  7706. // The other tokens are placed as textAlign 'center' if there is enough space.
  7707. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7708. while (leftIndex <= rightIndex) {
  7709. token = tokens[leftIndex];
  7710. // Consider width specified by user, use 'center' rather than 'left'.
  7711. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7712. lineXLeft += token.width;
  7713. leftIndex++;
  7714. }
  7715. lineTop += lineHeight;
  7716. }
  7717. }
  7718. function applyTextRotation(ctx, style, rect, x, y) {
  7719. // textRotation only apply in RectText.
  7720. if (rect && style.textRotation) {
  7721. var origin = style.textOrigin;
  7722. if (origin === 'center') {
  7723. x = rect.width / 2 + rect.x;
  7724. y = rect.height / 2 + rect.y;
  7725. }
  7726. else if (origin) {
  7727. x = origin[0] + rect.x;
  7728. y = origin[1] + rect.y;
  7729. }
  7730. ctx.translate(x, y);
  7731. // Positive: anticlockwise
  7732. ctx.rotate(-style.textRotation);
  7733. ctx.translate(-x, -y);
  7734. }
  7735. }
  7736. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7737. var tokenStyle = style.rich[token.styleName] || {};
  7738. tokenStyle.text = token.text;
  7739. // 'ctx.textBaseline' is always set as 'middle', for sake of
  7740. // the bias of "Microsoft YaHei".
  7741. var textVerticalAlign = token.textVerticalAlign;
  7742. var y = lineTop + lineHeight / 2;
  7743. if (textVerticalAlign === 'top') {
  7744. y = lineTop + token.height / 2;
  7745. }
  7746. else if (textVerticalAlign === 'bottom') {
  7747. y = lineTop + lineHeight - token.height / 2;
  7748. }
  7749. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  7750. hostEl,
  7751. ctx,
  7752. tokenStyle,
  7753. textAlign === 'right'
  7754. ? x - token.width
  7755. : textAlign === 'center'
  7756. ? x - token.width / 2
  7757. : x,
  7758. y - token.height / 2,
  7759. token.width,
  7760. token.height
  7761. );
  7762. var textPadding = token.textPadding;
  7763. if (textPadding) {
  7764. x = getTextXForPadding(x, textAlign, textPadding);
  7765. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7766. }
  7767. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7768. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7769. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7770. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7771. setCtx(ctx, 'textAlign', textAlign);
  7772. // Force baseline to be "middle". Otherwise, if using "top", the
  7773. // text will offset downward a little bit in font "Microsoft YaHei".
  7774. setCtx(ctx, 'textBaseline', 'middle');
  7775. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7776. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7777. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7778. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  7779. // Fill after stroke so the outline will not cover the main part.
  7780. if (textStroke) {
  7781. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7782. setCtx(ctx, 'strokeStyle', textStroke);
  7783. ctx.strokeText(token.text, x, y);
  7784. }
  7785. if (textFill) {
  7786. setCtx(ctx, 'fillStyle', textFill);
  7787. ctx.fillText(token.text, x, y);
  7788. }
  7789. }
  7790. function needDrawBackground(style) {
  7791. return !!(
  7792. style.textBackgroundColor
  7793. || (style.textBorderWidth && style.textBorderColor)
  7794. );
  7795. }
  7796. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7797. // shape: {x, y, width, height}
  7798. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7799. var textBackgroundColor = style.textBackgroundColor;
  7800. var textBorderWidth = style.textBorderWidth;
  7801. var textBorderColor = style.textBorderColor;
  7802. var isPlainBg = isString(textBackgroundColor);
  7803. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7804. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7805. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7806. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7807. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7808. ctx.beginPath();
  7809. var textBorderRadius = style.textBorderRadius;
  7810. if (!textBorderRadius) {
  7811. ctx.rect(x, y, width, height);
  7812. }
  7813. else {
  7814. buildPath(ctx, {
  7815. x: x, y: y, width: width, height: height, r: textBorderRadius
  7816. });
  7817. }
  7818. ctx.closePath();
  7819. }
  7820. if (isPlainBg) {
  7821. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7822. if (style.fillOpacity != null) {
  7823. var originalGlobalAlpha = ctx.globalAlpha;
  7824. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7825. ctx.fill();
  7826. ctx.globalAlpha = originalGlobalAlpha;
  7827. }
  7828. else {
  7829. ctx.fill();
  7830. }
  7831. }
  7832. else if (isObject(textBackgroundColor)) {
  7833. var image = textBackgroundColor.image;
  7834. image = createOrUpdateImage(
  7835. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7836. );
  7837. if (image && isImageReady(image)) {
  7838. ctx.drawImage(image, x, y, width, height);
  7839. }
  7840. }
  7841. if (textBorderWidth && textBorderColor) {
  7842. setCtx(ctx, 'lineWidth', textBorderWidth);
  7843. setCtx(ctx, 'strokeStyle', textBorderColor);
  7844. if (style.strokeOpacity != null) {
  7845. var originalGlobalAlpha = ctx.globalAlpha;
  7846. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7847. ctx.stroke();
  7848. ctx.globalAlpha = originalGlobalAlpha;
  7849. }
  7850. else {
  7851. ctx.stroke();
  7852. }
  7853. }
  7854. }
  7855. function onBgImageLoaded(image, textBackgroundColor) {
  7856. // Replace image, so that `contain/text.js#parseRichText`
  7857. // will get correct result in next tick.
  7858. textBackgroundColor.image = image;
  7859. }
  7860. function getBoxPosition(out, hostEl, style, rect) {
  7861. var baseX = style.x || 0;
  7862. var baseY = style.y || 0;
  7863. var textAlign = style.textAlign;
  7864. var textVerticalAlign = style.textVerticalAlign;
  7865. // Text position represented by coord
  7866. if (rect) {
  7867. var textPosition = style.textPosition;
  7868. if (textPosition instanceof Array) {
  7869. // Percent
  7870. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7871. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7872. }
  7873. else {
  7874. var res = (hostEl && hostEl.calculateTextPosition)
  7875. ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect)
  7876. : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7877. baseX = res.x;
  7878. baseY = res.y;
  7879. // Default align and baseline when has textPosition
  7880. textAlign = textAlign || res.textAlign;
  7881. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7882. }
  7883. // textOffset is only support in RectText, otherwise
  7884. // we have to adjust boundingRect for textOffset.
  7885. var textOffset = style.textOffset;
  7886. if (textOffset) {
  7887. baseX += textOffset[0];
  7888. baseY += textOffset[1];
  7889. }
  7890. }
  7891. out = out || {};
  7892. out.baseX = baseX;
  7893. out.baseY = baseY;
  7894. out.textAlign = textAlign;
  7895. out.textVerticalAlign = textVerticalAlign;
  7896. return out;
  7897. }
  7898. function setCtx(ctx, prop, value) {
  7899. ctx[prop] = fixShadow(ctx, prop, value);
  7900. return ctx[prop];
  7901. }
  7902. /**
  7903. * @param {string} [stroke] If specified, do not check style.textStroke.
  7904. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7905. * @param {number} style
  7906. */
  7907. function getStroke(stroke, lineWidth) {
  7908. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7909. ? null
  7910. // TODO pattern and gradient?
  7911. : (stroke.image || stroke.colorStops)
  7912. ? '#000'
  7913. : stroke;
  7914. }
  7915. function getFill(fill) {
  7916. return (fill == null || fill === 'none')
  7917. ? null
  7918. // TODO pattern and gradient?
  7919. : (fill.image || fill.colorStops)
  7920. ? '#000'
  7921. : fill;
  7922. }
  7923. function parsePercent(value, maxValue) {
  7924. if (typeof value === 'string') {
  7925. if (value.lastIndexOf('%') >= 0) {
  7926. return parseFloat(value) / 100 * maxValue;
  7927. }
  7928. return parseFloat(value);
  7929. }
  7930. return value;
  7931. }
  7932. function getTextXForPadding(x, textAlign, textPadding) {
  7933. return textAlign === 'right'
  7934. ? (x - textPadding[1])
  7935. : textAlign === 'center'
  7936. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7937. : (x + textPadding[3]);
  7938. }
  7939. /**
  7940. * @param {string} text
  7941. * @param {module:zrender/Style} style
  7942. * @return {boolean}
  7943. */
  7944. function needDrawText(text, style) {
  7945. return text != null
  7946. && (text
  7947. || style.textBackgroundColor
  7948. || (style.textBorderWidth && style.textBorderColor)
  7949. || style.textPadding
  7950. );
  7951. }
  7952. /**
  7953. * Mixin for drawing text in a element bounding rect
  7954. * @module zrender/mixin/RectText
  7955. */
  7956. var tmpRect$1 = new BoundingRect();
  7957. var RectText = function () {};
  7958. RectText.prototype = {
  7959. constructor: RectText,
  7960. /**
  7961. * Draw text in a rect with specified position.
  7962. * @param {CanvasRenderingContext2D} ctx
  7963. * @param {Object} rect Displayable rect
  7964. */
  7965. drawRectText: function (ctx, rect) {
  7966. var style = this.style;
  7967. rect = style.textRect || rect;
  7968. // Optimize, avoid normalize every time.
  7969. this.__dirty && normalizeTextStyle(style, true);
  7970. var text = style.text;
  7971. // Convert to string
  7972. text != null && (text += '');
  7973. if (!needDrawText(text, style)) {
  7974. return;
  7975. }
  7976. // FIXME
  7977. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7978. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7979. // text propably break the cache for its host elements.
  7980. ctx.save();
  7981. // Transform rect to view space
  7982. var transform = this.transform;
  7983. if (!style.transformText) {
  7984. if (transform) {
  7985. tmpRect$1.copy(rect);
  7986. tmpRect$1.applyTransform(transform);
  7987. rect = tmpRect$1;
  7988. }
  7989. }
  7990. else {
  7991. this.setTransform(ctx);
  7992. }
  7993. // transformText and textRotation can not be used at the same time.
  7994. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7995. ctx.restore();
  7996. }
  7997. };
  7998. /**
  7999. * Base class of all displayable graphic objects
  8000. * @module zrender/graphic/Displayable
  8001. */
  8002. /**
  8003. * @alias module:zrender/graphic/Displayable
  8004. * @extends module:zrender/Element
  8005. * @extends module:zrender/graphic/mixin/RectText
  8006. */
  8007. function Displayable(opts) {
  8008. opts = opts || {};
  8009. Element.call(this, opts);
  8010. // Extend properties
  8011. for (var name in opts) {
  8012. if (
  8013. opts.hasOwnProperty(name)
  8014. && name !== 'style'
  8015. ) {
  8016. this[name] = opts[name];
  8017. }
  8018. }
  8019. /**
  8020. * @type {module:zrender/graphic/Style}
  8021. */
  8022. this.style = new Style(opts.style, this);
  8023. this._rect = null;
  8024. // Shapes for cascade clipping.
  8025. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  8026. // because it is easy to only using null to check whether clipPaths changed.
  8027. this.__clipPaths = null;
  8028. // FIXME Stateful must be mixined after style is setted
  8029. // Stateful.call(this, opts);
  8030. }
  8031. Displayable.prototype = {
  8032. constructor: Displayable,
  8033. type: 'displayable',
  8034. /**
  8035. * Dirty flag. From which painter will determine if this displayable object needs brush.
  8036. * @name module:zrender/graphic/Displayable#__dirty
  8037. * @type {boolean}
  8038. */
  8039. __dirty: true,
  8040. /**
  8041. * Whether the displayable object is visible. when it is true, the displayable object
  8042. * is not drawn, but the mouse event can still trigger the object.
  8043. * @name module:/zrender/graphic/Displayable#invisible
  8044. * @type {boolean}
  8045. * @default false
  8046. */
  8047. invisible: false,
  8048. /**
  8049. * @name module:/zrender/graphic/Displayable#z
  8050. * @type {number}
  8051. * @default 0
  8052. */
  8053. z: 0,
  8054. /**
  8055. * @name module:/zrender/graphic/Displayable#z
  8056. * @type {number}
  8057. * @default 0
  8058. */
  8059. z2: 0,
  8060. /**
  8061. * The z level determines the displayable object can be drawn in which layer canvas.
  8062. * @name module:/zrender/graphic/Displayable#zlevel
  8063. * @type {number}
  8064. * @default 0
  8065. */
  8066. zlevel: 0,
  8067. /**
  8068. * Whether it can be dragged.
  8069. * @name module:/zrender/graphic/Displayable#draggable
  8070. * @type {boolean}
  8071. * @default false
  8072. */
  8073. draggable: false,
  8074. /**
  8075. * Whether is it dragging.
  8076. * @name module:/zrender/graphic/Displayable#draggable
  8077. * @type {boolean}
  8078. * @default false
  8079. */
  8080. dragging: false,
  8081. /**
  8082. * Whether to respond to mouse events.
  8083. * @name module:/zrender/graphic/Displayable#silent
  8084. * @type {boolean}
  8085. * @default false
  8086. */
  8087. silent: false,
  8088. /**
  8089. * If enable culling
  8090. * @type {boolean}
  8091. * @default false
  8092. */
  8093. culling: false,
  8094. /**
  8095. * Mouse cursor when hovered
  8096. * @name module:/zrender/graphic/Displayable#cursor
  8097. * @type {string}
  8098. */
  8099. cursor: 'pointer',
  8100. /**
  8101. * If hover area is bounding rect
  8102. * @name module:/zrender/graphic/Displayable#rectHover
  8103. * @type {string}
  8104. */
  8105. rectHover: false,
  8106. /**
  8107. * Render the element progressively when the value >= 0,
  8108. * usefull for large data.
  8109. * @type {boolean}
  8110. */
  8111. progressive: false,
  8112. /**
  8113. * @type {boolean}
  8114. */
  8115. incremental: false,
  8116. /**
  8117. * Scale ratio for global scale.
  8118. * @type {boolean}
  8119. */
  8120. globalScaleRatio: 1,
  8121. beforeBrush: function (ctx) {},
  8122. afterBrush: function (ctx) {},
  8123. /**
  8124. * Graphic drawing method.
  8125. * @param {CanvasRenderingContext2D} ctx
  8126. */
  8127. // Interface
  8128. brush: function (ctx, prevEl) {},
  8129. /**
  8130. * Get the minimum bounding box.
  8131. * @return {module:zrender/core/BoundingRect}
  8132. */
  8133. // Interface
  8134. getBoundingRect: function () {},
  8135. /**
  8136. * If displayable element contain coord x, y
  8137. * @param {number} x
  8138. * @param {number} y
  8139. * @return {boolean}
  8140. */
  8141. contain: function (x, y) {
  8142. return this.rectContain(x, y);
  8143. },
  8144. /**
  8145. * @param {Function} cb
  8146. * @param {} context
  8147. */
  8148. traverse: function (cb, context) {
  8149. cb.call(context, this);
  8150. },
  8151. /**
  8152. * If bounding rect of element contain coord x, y
  8153. * @param {number} x
  8154. * @param {number} y
  8155. * @return {boolean}
  8156. */
  8157. rectContain: function (x, y) {
  8158. var coord = this.transformCoordToLocal(x, y);
  8159. var rect = this.getBoundingRect();
  8160. return rect.contain(coord[0], coord[1]);
  8161. },
  8162. /**
  8163. * Mark displayable element dirty and refresh next frame
  8164. */
  8165. dirty: function () {
  8166. this.__dirty = this.__dirtyText = true;
  8167. this._rect = null;
  8168. this.__zr && this.__zr.refresh();
  8169. },
  8170. /**
  8171. * If displayable object binded any event
  8172. * @return {boolean}
  8173. */
  8174. // TODO, events bound by bind
  8175. // isSilent: function () {
  8176. // return !(
  8177. // this.hoverable || this.draggable
  8178. // || this.onmousemove || this.onmouseover || this.onmouseout
  8179. // || this.onmousedown || this.onmouseup || this.onclick
  8180. // || this.ondragenter || this.ondragover || this.ondragleave
  8181. // || this.ondrop
  8182. // );
  8183. // },
  8184. /**
  8185. * Alias for animate('style')
  8186. * @param {boolean} loop
  8187. */
  8188. animateStyle: function (loop) {
  8189. return this.animate('style', loop);
  8190. },
  8191. attrKV: function (key, value) {
  8192. if (key !== 'style') {
  8193. Element.prototype.attrKV.call(this, key, value);
  8194. }
  8195. else {
  8196. this.style.set(value);
  8197. }
  8198. },
  8199. /**
  8200. * @param {Object|string} key
  8201. * @param {*} value
  8202. */
  8203. setStyle: function (key, value) {
  8204. this.style.set(key, value);
  8205. this.dirty(false);
  8206. return this;
  8207. },
  8208. /**
  8209. * Use given style object
  8210. * @param {Object} obj
  8211. */
  8212. useStyle: function (obj) {
  8213. this.style = new Style(obj, this);
  8214. this.dirty(false);
  8215. return this;
  8216. },
  8217. /**
  8218. * The string value of `textPosition` needs to be calculated to a real postion.
  8219. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  8220. * by default. See `contain/text.js#calculateTextPosition` for more details.
  8221. * But some coutom shapes like "pin", "flag" have center that is not exactly
  8222. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  8223. * for those shapes. It will be called if the `style.textPosition` is a string.
  8224. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  8225. * be responsible for creating one.
  8226. * @param {module:zrender/graphic/Style} style
  8227. * @param {Object} rect {x, y, width, height}
  8228. * @return {Obejct} out The same as the input out.
  8229. * {
  8230. * x: number. mandatory.
  8231. * y: number. mandatory.
  8232. * textAlign: string. optional. use style.textAlign by default.
  8233. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  8234. * }
  8235. */
  8236. calculateTextPosition: null
  8237. };
  8238. inherits(Displayable, Element);
  8239. mixin(Displayable, RectText);
  8240. /**
  8241. * @alias zrender/graphic/Image
  8242. * @extends module:zrender/graphic/Displayable
  8243. * @constructor
  8244. * @param {Object} opts
  8245. */
  8246. function ZImage(opts) {
  8247. Displayable.call(this, opts);
  8248. }
  8249. ZImage.prototype = {
  8250. constructor: ZImage,
  8251. type: 'image',
  8252. brush: function (ctx, prevEl) {
  8253. var style = this.style;
  8254. var src = style.image;
  8255. // Must bind each time
  8256. style.bind(ctx, this, prevEl);
  8257. var image = this._image = createOrUpdateImage(
  8258. src,
  8259. this._image,
  8260. this,
  8261. this.onload
  8262. );
  8263. if (!image || !isImageReady(image)) {
  8264. return;
  8265. }
  8266. // 图片已经加载完成
  8267. // if (image.nodeName.toUpperCase() == 'IMG') {
  8268. // if (!image.complete) {
  8269. // return;
  8270. // }
  8271. // }
  8272. // Else is canvas
  8273. var x = style.x || 0;
  8274. var y = style.y || 0;
  8275. var width = style.width;
  8276. var height = style.height;
  8277. var aspect = image.width / image.height;
  8278. if (width == null && height != null) {
  8279. // Keep image/height ratio
  8280. width = height * aspect;
  8281. }
  8282. else if (height == null && width != null) {
  8283. height = width / aspect;
  8284. }
  8285. else if (width == null && height == null) {
  8286. width = image.width;
  8287. height = image.height;
  8288. }
  8289. // 设置transform
  8290. this.setTransform(ctx);
  8291. if (style.sWidth && style.sHeight) {
  8292. var sx = style.sx || 0;
  8293. var sy = style.sy || 0;
  8294. ctx.drawImage(
  8295. image,
  8296. sx, sy, style.sWidth, style.sHeight,
  8297. x, y, width, height
  8298. );
  8299. }
  8300. else if (style.sx && style.sy) {
  8301. var sx = style.sx;
  8302. var sy = style.sy;
  8303. var sWidth = width - sx;
  8304. var sHeight = height - sy;
  8305. ctx.drawImage(
  8306. image,
  8307. sx, sy, sWidth, sHeight,
  8308. x, y, width, height
  8309. );
  8310. }
  8311. else {
  8312. ctx.drawImage(image, x, y, width, height);
  8313. }
  8314. // Draw rect text
  8315. if (style.text != null) {
  8316. // Only restore transform when needs draw text.
  8317. this.restoreTransform(ctx);
  8318. this.drawRectText(ctx, this.getBoundingRect());
  8319. }
  8320. },
  8321. getBoundingRect: function () {
  8322. var style = this.style;
  8323. if (!this._rect) {
  8324. this._rect = new BoundingRect(
  8325. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  8326. );
  8327. }
  8328. return this._rect;
  8329. }
  8330. };
  8331. inherits(ZImage, Displayable);
  8332. var HOVER_LAYER_ZLEVEL = 1e5;
  8333. var CANVAS_ZLEVEL = 314159;
  8334. var EL_AFTER_INCREMENTAL_INC = 0.01;
  8335. var INCREMENTAL_INC = 0.001;
  8336. function parseInt10(val) {
  8337. return parseInt(val, 10);
  8338. }
  8339. function isLayerValid(layer) {
  8340. if (!layer) {
  8341. return false;
  8342. }
  8343. if (layer.__builtin__) {
  8344. return true;
  8345. }
  8346. if (typeof (layer.resize) !== 'function'
  8347. || typeof (layer.refresh) !== 'function'
  8348. ) {
  8349. return false;
  8350. }
  8351. return true;
  8352. }
  8353. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8354. var viewRect = new BoundingRect(0, 0, 0, 0);
  8355. function isDisplayableCulled(el, width, height) {
  8356. tmpRect.copy(el.getBoundingRect());
  8357. if (el.transform) {
  8358. tmpRect.applyTransform(el.transform);
  8359. }
  8360. viewRect.width = width;
  8361. viewRect.height = height;
  8362. return !tmpRect.intersect(viewRect);
  8363. }
  8364. function isClipPathChanged(clipPaths, prevClipPaths) {
  8365. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  8366. if (clipPaths === prevClipPaths) {
  8367. return false;
  8368. }
  8369. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  8370. return true;
  8371. }
  8372. for (var i = 0; i < clipPaths.length; i++) {
  8373. if (clipPaths[i] !== prevClipPaths[i]) {
  8374. return true;
  8375. }
  8376. }
  8377. return false;
  8378. }
  8379. function doClip(clipPaths, ctx) {
  8380. for (var i = 0; i < clipPaths.length; i++) {
  8381. var clipPath = clipPaths[i];
  8382. clipPath.setTransform(ctx);
  8383. ctx.beginPath();
  8384. clipPath.buildPath(ctx, clipPath.shape);
  8385. ctx.clip();
  8386. // Transform back
  8387. clipPath.restoreTransform(ctx);
  8388. }
  8389. }
  8390. function createRoot(width, height) {
  8391. var domRoot = document.createElement('div');
  8392. // domRoot.onselectstart = returnFalse; // Avoid page selected
  8393. domRoot.style.cssText = [
  8394. 'position:relative',
  8395. // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  8396. // dom does not act as expected) when some of the parent dom has
  8397. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  8398. // the canvas is not at the top part of the page.
  8399. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  8400. // this `overflow:hidden` to avoid the bug.
  8401. // 'overflow:hidden',
  8402. 'width:' + width + 'px',
  8403. 'height:' + height + 'px',
  8404. 'padding:0',
  8405. 'margin:0',
  8406. 'border-width:0'
  8407. ].join(';') + ';';
  8408. return domRoot;
  8409. }
  8410. /**
  8411. * @alias module:zrender/Painter
  8412. * @constructor
  8413. * @param {HTMLElement} root 绘图容器
  8414. * @param {module:zrender/Storage} storage
  8415. * @param {Object} opts
  8416. */
  8417. var Painter = function (root, storage, opts) {
  8418. this.type = 'canvas';
  8419. // In node environment using node-canvas
  8420. var singleCanvas = !root.nodeName // In node ?
  8421. || root.nodeName.toUpperCase() === 'CANVAS';
  8422. this._opts = opts = extend({}, opts || {});
  8423. /**
  8424. * @type {number}
  8425. */
  8426. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8427. /**
  8428. * @type {boolean}
  8429. * @private
  8430. */
  8431. this._singleCanvas = singleCanvas;
  8432. /**
  8433. * 绘图容器
  8434. * @type {HTMLElement}
  8435. */
  8436. this.root = root;
  8437. var rootStyle = root.style;
  8438. if (rootStyle) {
  8439. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8440. rootStyle['-webkit-user-select'] =
  8441. rootStyle['user-select'] =
  8442. rootStyle['-webkit-touch-callout'] = 'none';
  8443. root.innerHTML = '';
  8444. }
  8445. /**
  8446. * @type {module:zrender/Storage}
  8447. */
  8448. this.storage = storage;
  8449. /**
  8450. * @type {Array.<number>}
  8451. * @private
  8452. */
  8453. var zlevelList = this._zlevelList = [];
  8454. /**
  8455. * @type {Object.<string, module:zrender/Layer>}
  8456. * @private
  8457. */
  8458. var layers = this._layers = {};
  8459. /**
  8460. * @type {Object.<string, Object>}
  8461. * @private
  8462. */
  8463. this._layerConfig = {};
  8464. /**
  8465. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8466. */
  8467. this._needsManuallyCompositing = false;
  8468. if (!singleCanvas) {
  8469. this._width = this._getSize(0);
  8470. this._height = this._getSize(1);
  8471. var domRoot = this._domRoot = createRoot(
  8472. this._width, this._height
  8473. );
  8474. root.appendChild(domRoot);
  8475. }
  8476. else {
  8477. var width = root.width;
  8478. var height = root.height;
  8479. if (opts.width != null) {
  8480. width = opts.width;
  8481. }
  8482. if (opts.height != null) {
  8483. height = opts.height;
  8484. }
  8485. this.dpr = opts.devicePixelRatio || 1;
  8486. // Use canvas width and height directly
  8487. root.width = width * this.dpr;
  8488. root.height = height * this.dpr;
  8489. this._width = width;
  8490. this._height = height;
  8491. // Create layer if only one given canvas
  8492. // Device can be specified to create a high dpi image.
  8493. var mainLayer = new Layer(root, this, this.dpr);
  8494. mainLayer.__builtin__ = true;
  8495. mainLayer.initContext();
  8496. // FIXME Use canvas width and height
  8497. // mainLayer.resize(width, height);
  8498. layers[CANVAS_ZLEVEL] = mainLayer;
  8499. mainLayer.zlevel = CANVAS_ZLEVEL;
  8500. // Not use common zlevel.
  8501. zlevelList.push(CANVAS_ZLEVEL);
  8502. this._domRoot = root;
  8503. }
  8504. /**
  8505. * @type {module:zrender/Layer}
  8506. * @private
  8507. */
  8508. this._hoverlayer = null;
  8509. this._hoverElements = [];
  8510. };
  8511. Painter.prototype = {
  8512. constructor: Painter,
  8513. getType: function () {
  8514. return 'canvas';
  8515. },
  8516. /**
  8517. * If painter use a single canvas
  8518. * @return {boolean}
  8519. */
  8520. isSingleCanvas: function () {
  8521. return this._singleCanvas;
  8522. },
  8523. /**
  8524. * @return {HTMLDivElement}
  8525. */
  8526. getViewportRoot: function () {
  8527. return this._domRoot;
  8528. },
  8529. getViewportRootOffset: function () {
  8530. var viewportRoot = this.getViewportRoot();
  8531. if (viewportRoot) {
  8532. return {
  8533. offsetLeft: viewportRoot.offsetLeft || 0,
  8534. offsetTop: viewportRoot.offsetTop || 0
  8535. };
  8536. }
  8537. },
  8538. /**
  8539. * 刷新
  8540. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8541. */
  8542. refresh: function (paintAll) {
  8543. var list = this.storage.getDisplayList(true);
  8544. var zlevelList = this._zlevelList;
  8545. this._redrawId = Math.random();
  8546. this._paintList(list, paintAll, this._redrawId);
  8547. // Paint custum layers
  8548. for (var i = 0; i < zlevelList.length; i++) {
  8549. var z = zlevelList[i];
  8550. var layer = this._layers[z];
  8551. if (!layer.__builtin__ && layer.refresh) {
  8552. var clearColor = i === 0 ? this._backgroundColor : null;
  8553. layer.refresh(clearColor);
  8554. }
  8555. }
  8556. this.refreshHover();
  8557. return this;
  8558. },
  8559. addHover: function (el, hoverStyle) {
  8560. if (el.__hoverMir) {
  8561. return;
  8562. }
  8563. var elMirror = new el.constructor({
  8564. style: el.style,
  8565. shape: el.shape,
  8566. z: el.z,
  8567. z2: el.z2,
  8568. silent: el.silent
  8569. });
  8570. elMirror.__from = el;
  8571. el.__hoverMir = elMirror;
  8572. hoverStyle && elMirror.setStyle(hoverStyle);
  8573. this._hoverElements.push(elMirror);
  8574. return elMirror;
  8575. },
  8576. removeHover: function (el) {
  8577. var elMirror = el.__hoverMir;
  8578. var hoverElements = this._hoverElements;
  8579. var idx = indexOf(hoverElements, elMirror);
  8580. if (idx >= 0) {
  8581. hoverElements.splice(idx, 1);
  8582. }
  8583. el.__hoverMir = null;
  8584. },
  8585. clearHover: function (el) {
  8586. var hoverElements = this._hoverElements;
  8587. for (var i = 0; i < hoverElements.length; i++) {
  8588. var from = hoverElements[i].__from;
  8589. if (from) {
  8590. from.__hoverMir = null;
  8591. }
  8592. }
  8593. hoverElements.length = 0;
  8594. },
  8595. refreshHover: function () {
  8596. var hoverElements = this._hoverElements;
  8597. var len = hoverElements.length;
  8598. var hoverLayer = this._hoverlayer;
  8599. hoverLayer && hoverLayer.clear();
  8600. if (!len) {
  8601. return;
  8602. }
  8603. sort(hoverElements, this.storage.displayableSortFunc);
  8604. // Use a extream large zlevel
  8605. // FIXME?
  8606. if (!hoverLayer) {
  8607. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8608. }
  8609. var scope = {};
  8610. hoverLayer.ctx.save();
  8611. for (var i = 0; i < len;) {
  8612. var el = hoverElements[i];
  8613. var originalEl = el.__from;
  8614. // Original el is removed
  8615. // PENDING
  8616. if (!(originalEl && originalEl.__zr)) {
  8617. hoverElements.splice(i, 1);
  8618. originalEl.__hoverMir = null;
  8619. len--;
  8620. continue;
  8621. }
  8622. i++;
  8623. // Use transform
  8624. // FIXME style and shape ?
  8625. if (!originalEl.invisible) {
  8626. el.transform = originalEl.transform;
  8627. el.invTransform = originalEl.invTransform;
  8628. el.__clipPaths = originalEl.__clipPaths;
  8629. // el.
  8630. this._doPaintEl(el, hoverLayer, true, scope);
  8631. }
  8632. }
  8633. hoverLayer.ctx.restore();
  8634. },
  8635. getHoverLayer: function () {
  8636. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8637. },
  8638. _paintList: function (list, paintAll, redrawId) {
  8639. if (this._redrawId !== redrawId) {
  8640. return;
  8641. }
  8642. paintAll = paintAll || false;
  8643. this._updateLayerStatus(list);
  8644. var finished = this._doPaintList(list, paintAll);
  8645. if (this._needsManuallyCompositing) {
  8646. this._compositeManually();
  8647. }
  8648. if (!finished) {
  8649. var self = this;
  8650. requestAnimationFrame(function () {
  8651. self._paintList(list, paintAll, redrawId);
  8652. });
  8653. }
  8654. },
  8655. _compositeManually: function () {
  8656. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8657. var width = this._domRoot.width;
  8658. var height = this._domRoot.height;
  8659. ctx.clearRect(0, 0, width, height);
  8660. // PENDING, If only builtin layer?
  8661. this.eachBuiltinLayer(function (layer) {
  8662. if (layer.virtual) {
  8663. ctx.drawImage(layer.dom, 0, 0, width, height);
  8664. }
  8665. });
  8666. },
  8667. _doPaintList: function (list, paintAll) {
  8668. var layerList = [];
  8669. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8670. var zlevel = this._zlevelList[zi];
  8671. var layer = this._layers[zlevel];
  8672. if (layer.__builtin__
  8673. && layer !== this._hoverlayer
  8674. && (layer.__dirty || paintAll)
  8675. ) {
  8676. layerList.push(layer);
  8677. }
  8678. }
  8679. var finished = true;
  8680. for (var k = 0; k < layerList.length; k++) {
  8681. var layer = layerList[k];
  8682. var ctx = layer.ctx;
  8683. var scope = {};
  8684. ctx.save();
  8685. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8686. var useTimer = !paintAll && layer.incremental && Date.now;
  8687. var startTime = useTimer && Date.now();
  8688. var clearColor = layer.zlevel === this._zlevelList[0]
  8689. ? this._backgroundColor : null;
  8690. // All elements in this layer are cleared.
  8691. if (layer.__startIndex === layer.__endIndex) {
  8692. layer.clear(false, clearColor);
  8693. }
  8694. else if (start === layer.__startIndex) {
  8695. var firstEl = list[start];
  8696. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8697. layer.clear(false, clearColor);
  8698. }
  8699. }
  8700. if (start === -1) {
  8701. console.error('For some unknown reason. drawIndex is -1');
  8702. start = layer.__startIndex;
  8703. }
  8704. for (var i = start; i < layer.__endIndex; i++) {
  8705. var el = list[i];
  8706. this._doPaintEl(el, layer, paintAll, scope);
  8707. el.__dirty = el.__dirtyText = false;
  8708. if (useTimer) {
  8709. // Date.now can be executed in 13,025,305 ops/second.
  8710. var dTime = Date.now() - startTime;
  8711. // Give 15 millisecond to draw.
  8712. // The rest elements will be drawn in the next frame.
  8713. if (dTime > 15) {
  8714. break;
  8715. }
  8716. }
  8717. }
  8718. layer.__drawIndex = i;
  8719. if (layer.__drawIndex < layer.__endIndex) {
  8720. finished = false;
  8721. }
  8722. if (scope.prevElClipPaths) {
  8723. // Needs restore the state. If last drawn element is in the clipping area.
  8724. ctx.restore();
  8725. }
  8726. ctx.restore();
  8727. }
  8728. if (env$1.wxa) {
  8729. // Flush for weixin application
  8730. each(this._layers, function (layer) {
  8731. if (layer && layer.ctx && layer.ctx.draw) {
  8732. layer.ctx.draw();
  8733. }
  8734. });
  8735. }
  8736. return finished;
  8737. },
  8738. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8739. var ctx = currentLayer.ctx;
  8740. var m = el.transform;
  8741. if (
  8742. (currentLayer.__dirty || forcePaint)
  8743. // Ignore invisible element
  8744. && !el.invisible
  8745. // Ignore transparent element
  8746. && el.style.opacity !== 0
  8747. // Ignore scale 0 element, in some environment like node-canvas
  8748. // Draw a scale 0 element can cause all following draw wrong
  8749. // And setTransform with scale 0 will cause set back transform failed.
  8750. && !(m && !m[0] && !m[3])
  8751. // Ignore culled element
  8752. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  8753. ) {
  8754. var clipPaths = el.__clipPaths;
  8755. var prevElClipPaths = scope.prevElClipPaths;
  8756. // Optimize when clipping on group with several elements
  8757. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8758. // If has previous clipping state, restore from it
  8759. if (prevElClipPaths) {
  8760. ctx.restore();
  8761. scope.prevElClipPaths = null;
  8762. // Reset prevEl since context has been restored
  8763. scope.prevEl = null;
  8764. }
  8765. // New clipping state
  8766. if (clipPaths) {
  8767. ctx.save();
  8768. doClip(clipPaths, ctx);
  8769. scope.prevElClipPaths = clipPaths;
  8770. }
  8771. }
  8772. el.beforeBrush && el.beforeBrush(ctx);
  8773. el.brush(ctx, scope.prevEl || null);
  8774. scope.prevEl = el;
  8775. el.afterBrush && el.afterBrush(ctx);
  8776. }
  8777. },
  8778. /**
  8779. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8780. * @param {number} zlevel
  8781. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8782. * @return {module:zrender/Layer}
  8783. */
  8784. getLayer: function (zlevel, virtual) {
  8785. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8786. zlevel = CANVAS_ZLEVEL;
  8787. }
  8788. var layer = this._layers[zlevel];
  8789. if (!layer) {
  8790. // Create a new layer
  8791. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8792. layer.zlevel = zlevel;
  8793. layer.__builtin__ = true;
  8794. if (this._layerConfig[zlevel]) {
  8795. merge(layer, this._layerConfig[zlevel], true);
  8796. }
  8797. if (virtual) {
  8798. layer.virtual = virtual;
  8799. }
  8800. this.insertLayer(zlevel, layer);
  8801. // Context is created after dom inserted to document
  8802. // Or excanvas will get 0px clientWidth and clientHeight
  8803. layer.initContext();
  8804. }
  8805. return layer;
  8806. },
  8807. insertLayer: function (zlevel, layer) {
  8808. var layersMap = this._layers;
  8809. var zlevelList = this._zlevelList;
  8810. var len = zlevelList.length;
  8811. var prevLayer = null;
  8812. var i = -1;
  8813. var domRoot = this._domRoot;
  8814. if (layersMap[zlevel]) {
  8815. logError$1('ZLevel ' + zlevel + ' has been used already');
  8816. return;
  8817. }
  8818. // Check if is a valid layer
  8819. if (!isLayerValid(layer)) {
  8820. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8821. return;
  8822. }
  8823. if (len > 0 && zlevel > zlevelList[0]) {
  8824. for (i = 0; i < len - 1; i++) {
  8825. if (
  8826. zlevelList[i] < zlevel
  8827. && zlevelList[i + 1] > zlevel
  8828. ) {
  8829. break;
  8830. }
  8831. }
  8832. prevLayer = layersMap[zlevelList[i]];
  8833. }
  8834. zlevelList.splice(i + 1, 0, zlevel);
  8835. layersMap[zlevel] = layer;
  8836. // Vitual layer will not directly show on the screen.
  8837. // (It can be a WebGL layer and assigned to a ZImage element)
  8838. // But it still under management of zrender.
  8839. if (!layer.virtual) {
  8840. if (prevLayer) {
  8841. var prevDom = prevLayer.dom;
  8842. if (prevDom.nextSibling) {
  8843. domRoot.insertBefore(
  8844. layer.dom,
  8845. prevDom.nextSibling
  8846. );
  8847. }
  8848. else {
  8849. domRoot.appendChild(layer.dom);
  8850. }
  8851. }
  8852. else {
  8853. if (domRoot.firstChild) {
  8854. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8855. }
  8856. else {
  8857. domRoot.appendChild(layer.dom);
  8858. }
  8859. }
  8860. }
  8861. },
  8862. // Iterate each layer
  8863. eachLayer: function (cb, context) {
  8864. var zlevelList = this._zlevelList;
  8865. var z;
  8866. var i;
  8867. for (i = 0; i < zlevelList.length; i++) {
  8868. z = zlevelList[i];
  8869. cb.call(context, this._layers[z], z);
  8870. }
  8871. },
  8872. // Iterate each buildin layer
  8873. eachBuiltinLayer: function (cb, context) {
  8874. var zlevelList = this._zlevelList;
  8875. var layer;
  8876. var z;
  8877. var i;
  8878. for (i = 0; i < zlevelList.length; i++) {
  8879. z = zlevelList[i];
  8880. layer = this._layers[z];
  8881. if (layer.__builtin__) {
  8882. cb.call(context, layer, z);
  8883. }
  8884. }
  8885. },
  8886. // Iterate each other layer except buildin layer
  8887. eachOtherLayer: function (cb, context) {
  8888. var zlevelList = this._zlevelList;
  8889. var layer;
  8890. var z;
  8891. var i;
  8892. for (i = 0; i < zlevelList.length; i++) {
  8893. z = zlevelList[i];
  8894. layer = this._layers[z];
  8895. if (!layer.__builtin__) {
  8896. cb.call(context, layer, z);
  8897. }
  8898. }
  8899. },
  8900. /**
  8901. * 获取所有已创建的层
  8902. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8903. */
  8904. getLayers: function () {
  8905. return this._layers;
  8906. },
  8907. _updateLayerStatus: function (list) {
  8908. this.eachBuiltinLayer(function (layer, z) {
  8909. layer.__dirty = layer.__used = false;
  8910. });
  8911. function updatePrevLayer(idx) {
  8912. if (prevLayer) {
  8913. if (prevLayer.__endIndex !== idx) {
  8914. prevLayer.__dirty = true;
  8915. }
  8916. prevLayer.__endIndex = idx;
  8917. }
  8918. }
  8919. if (this._singleCanvas) {
  8920. for (var i = 1; i < list.length; i++) {
  8921. var el = list[i];
  8922. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8923. this._needsManuallyCompositing = true;
  8924. break;
  8925. }
  8926. }
  8927. }
  8928. var prevLayer = null;
  8929. var incrementalLayerCount = 0;
  8930. for (var i = 0; i < list.length; i++) {
  8931. var el = list[i];
  8932. var zlevel = el.zlevel;
  8933. var layer;
  8934. // PENDING If change one incremental element style ?
  8935. // TODO Where there are non-incremental elements between incremental elements.
  8936. if (el.incremental) {
  8937. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8938. layer.incremental = true;
  8939. incrementalLayerCount = 1;
  8940. }
  8941. else {
  8942. layer = this.getLayer(
  8943. zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0),
  8944. this._needsManuallyCompositing
  8945. );
  8946. }
  8947. if (!layer.__builtin__) {
  8948. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8949. }
  8950. if (layer !== prevLayer) {
  8951. layer.__used = true;
  8952. if (layer.__startIndex !== i) {
  8953. layer.__dirty = true;
  8954. }
  8955. layer.__startIndex = i;
  8956. if (!layer.incremental) {
  8957. layer.__drawIndex = i;
  8958. }
  8959. else {
  8960. // Mark layer draw index needs to update.
  8961. layer.__drawIndex = -1;
  8962. }
  8963. updatePrevLayer(i);
  8964. prevLayer = layer;
  8965. }
  8966. if (el.__dirty) {
  8967. layer.__dirty = true;
  8968. if (layer.incremental && layer.__drawIndex < 0) {
  8969. // Start draw from the first dirty element.
  8970. layer.__drawIndex = i;
  8971. }
  8972. }
  8973. }
  8974. updatePrevLayer(i);
  8975. this.eachBuiltinLayer(function (layer, z) {
  8976. // Used in last frame but not in this frame. Needs clear
  8977. if (!layer.__used && layer.getElementCount() > 0) {
  8978. layer.__dirty = true;
  8979. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8980. }
  8981. // For incremental layer. In case start index changed and no elements are dirty.
  8982. if (layer.__dirty && layer.__drawIndex < 0) {
  8983. layer.__drawIndex = layer.__startIndex;
  8984. }
  8985. });
  8986. },
  8987. /**
  8988. * 清除hover层外所有内容
  8989. */
  8990. clear: function () {
  8991. this.eachBuiltinLayer(this._clearLayer);
  8992. return this;
  8993. },
  8994. _clearLayer: function (layer) {
  8995. layer.clear();
  8996. },
  8997. setBackgroundColor: function (backgroundColor) {
  8998. this._backgroundColor = backgroundColor;
  8999. },
  9000. /**
  9001. * 修改指定zlevel的绘制参数
  9002. *
  9003. * @param {string} zlevel
  9004. * @param {Object} config 配置对象
  9005. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  9006. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  9007. * @param {number} [config.lastFrameAlpha=0.7]
  9008. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  9009. */
  9010. configLayer: function (zlevel, config) {
  9011. if (config) {
  9012. var layerConfig = this._layerConfig;
  9013. if (!layerConfig[zlevel]) {
  9014. layerConfig[zlevel] = config;
  9015. }
  9016. else {
  9017. merge(layerConfig[zlevel], config, true);
  9018. }
  9019. for (var i = 0; i < this._zlevelList.length; i++) {
  9020. var _zlevel = this._zlevelList[i];
  9021. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  9022. var layer = this._layers[_zlevel];
  9023. merge(layer, layerConfig[zlevel], true);
  9024. }
  9025. }
  9026. }
  9027. },
  9028. /**
  9029. * 删除指定层
  9030. * @param {number} zlevel 层所在的zlevel
  9031. */
  9032. delLayer: function (zlevel) {
  9033. var layers = this._layers;
  9034. var zlevelList = this._zlevelList;
  9035. var layer = layers[zlevel];
  9036. if (!layer) {
  9037. return;
  9038. }
  9039. layer.dom.parentNode.removeChild(layer.dom);
  9040. delete layers[zlevel];
  9041. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  9042. },
  9043. /**
  9044. * 区域大小变化后重绘
  9045. */
  9046. resize: function (width, height) {
  9047. if (!this._domRoot.style) { // Maybe in node or worker
  9048. if (width == null || height == null) {
  9049. return;
  9050. }
  9051. this._width = width;
  9052. this._height = height;
  9053. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  9054. }
  9055. else {
  9056. var domRoot = this._domRoot;
  9057. // FIXME Why ?
  9058. domRoot.style.display = 'none';
  9059. // Save input w/h
  9060. var opts = this._opts;
  9061. width != null && (opts.width = width);
  9062. height != null && (opts.height = height);
  9063. width = this._getSize(0);
  9064. height = this._getSize(1);
  9065. domRoot.style.display = '';
  9066. // 优化没有实际改变的resize
  9067. if (this._width !== width || height !== this._height) {
  9068. domRoot.style.width = width + 'px';
  9069. domRoot.style.height = height + 'px';
  9070. for (var id in this._layers) {
  9071. if (this._layers.hasOwnProperty(id)) {
  9072. this._layers[id].resize(width, height);
  9073. }
  9074. }
  9075. each(this._progressiveLayers, function (layer) {
  9076. layer.resize(width, height);
  9077. });
  9078. this.refresh(true);
  9079. }
  9080. this._width = width;
  9081. this._height = height;
  9082. }
  9083. return this;
  9084. },
  9085. /**
  9086. * 清除单独的一个层
  9087. * @param {number} zlevel
  9088. */
  9089. clearLayer: function (zlevel) {
  9090. var layer = this._layers[zlevel];
  9091. if (layer) {
  9092. layer.clear();
  9093. }
  9094. },
  9095. /**
  9096. * 释放
  9097. */
  9098. dispose: function () {
  9099. this.root.innerHTML = '';
  9100. this.root =
  9101. this.storage =
  9102. this._domRoot =
  9103. this._layers = null;
  9104. },
  9105. /**
  9106. * Get canvas which has all thing rendered
  9107. * @param {Object} opts
  9108. * @param {string} [opts.backgroundColor]
  9109. * @param {number} [opts.pixelRatio]
  9110. */
  9111. getRenderedCanvas: function (opts) {
  9112. opts = opts || {};
  9113. if (this._singleCanvas && !this._compositeManually) {
  9114. return this._layers[CANVAS_ZLEVEL].dom;
  9115. }
  9116. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  9117. imageLayer.initContext();
  9118. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  9119. if (opts.pixelRatio <= this.dpr) {
  9120. this.refresh();
  9121. var width = imageLayer.dom.width;
  9122. var height = imageLayer.dom.height;
  9123. var ctx = imageLayer.ctx;
  9124. this.eachLayer(function (layer) {
  9125. if (layer.__builtin__) {
  9126. ctx.drawImage(layer.dom, 0, 0, width, height);
  9127. }
  9128. else if (layer.renderToCanvas) {
  9129. imageLayer.ctx.save();
  9130. layer.renderToCanvas(imageLayer.ctx);
  9131. imageLayer.ctx.restore();
  9132. }
  9133. });
  9134. }
  9135. else {
  9136. // PENDING, echarts-gl and incremental rendering.
  9137. var scope = {};
  9138. var displayList = this.storage.getDisplayList(true);
  9139. for (var i = 0; i < displayList.length; i++) {
  9140. var el = displayList[i];
  9141. this._doPaintEl(el, imageLayer, true, scope);
  9142. }
  9143. }
  9144. return imageLayer.dom;
  9145. },
  9146. /**
  9147. * 获取绘图区域宽度
  9148. */
  9149. getWidth: function () {
  9150. return this._width;
  9151. },
  9152. /**
  9153. * 获取绘图区域高度
  9154. */
  9155. getHeight: function () {
  9156. return this._height;
  9157. },
  9158. _getSize: function (whIdx) {
  9159. var opts = this._opts;
  9160. var wh = ['width', 'height'][whIdx];
  9161. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  9162. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  9163. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  9164. if (opts[wh] != null && opts[wh] !== 'auto') {
  9165. return parseFloat(opts[wh]);
  9166. }
  9167. var root = this.root;
  9168. // IE8 does not support getComputedStyle, but it use VML.
  9169. var stl = document.defaultView.getComputedStyle(root);
  9170. return (
  9171. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  9172. - (parseInt10(stl[plt]) || 0)
  9173. - (parseInt10(stl[prb]) || 0)
  9174. ) | 0;
  9175. },
  9176. pathToImage: function (path, dpr) {
  9177. dpr = dpr || this.dpr;
  9178. var canvas = document.createElement('canvas');
  9179. var ctx = canvas.getContext('2d');
  9180. var rect = path.getBoundingRect();
  9181. var style = path.style;
  9182. var shadowBlurSize = style.shadowBlur * dpr;
  9183. var shadowOffsetX = style.shadowOffsetX * dpr;
  9184. var shadowOffsetY = style.shadowOffsetY * dpr;
  9185. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  9186. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  9187. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  9188. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  9189. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  9190. var width = rect.width + leftMargin + rightMargin;
  9191. var height = rect.height + topMargin + bottomMargin;
  9192. canvas.width = width * dpr;
  9193. canvas.height = height * dpr;
  9194. ctx.scale(dpr, dpr);
  9195. ctx.clearRect(0, 0, width, height);
  9196. ctx.dpr = dpr;
  9197. var pathTransform = {
  9198. position: path.position,
  9199. rotation: path.rotation,
  9200. scale: path.scale
  9201. };
  9202. path.position = [leftMargin - rect.x, topMargin - rect.y];
  9203. path.rotation = 0;
  9204. path.scale = [1, 1];
  9205. path.updateTransform();
  9206. if (path) {
  9207. path.brush(ctx);
  9208. }
  9209. var ImageShape = ZImage;
  9210. var imgShape = new ImageShape({
  9211. style: {
  9212. x: 0,
  9213. y: 0,
  9214. image: canvas
  9215. }
  9216. });
  9217. if (pathTransform.position != null) {
  9218. imgShape.position = path.position = pathTransform.position;
  9219. }
  9220. if (pathTransform.rotation != null) {
  9221. imgShape.rotation = path.rotation = pathTransform.rotation;
  9222. }
  9223. if (pathTransform.scale != null) {
  9224. imgShape.scale = path.scale = pathTransform.scale;
  9225. }
  9226. return imgShape;
  9227. }
  9228. };
  9229. /**
  9230. * 动画主类, 调度和管理所有动画控制器
  9231. *
  9232. * @module zrender/animation/Animation
  9233. * @author pissang(https://github.com/pissang)
  9234. */
  9235. // TODO Additive animation
  9236. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  9237. // https://developer.apple.com/videos/wwdc2014/#236
  9238. /**
  9239. * @typedef {Object} IZRenderStage
  9240. * @property {Function} update
  9241. */
  9242. /**
  9243. * @alias module:zrender/animation/Animation
  9244. * @constructor
  9245. * @param {Object} [options]
  9246. * @param {Function} [options.onframe]
  9247. * @param {IZRenderStage} [options.stage]
  9248. * @example
  9249. * var animation = new Animation();
  9250. * var obj = {
  9251. * x: 100,
  9252. * y: 100
  9253. * };
  9254. * animation.animate(node.position)
  9255. * .when(1000, {
  9256. * x: 500,
  9257. * y: 500
  9258. * })
  9259. * .when(2000, {
  9260. * x: 100,
  9261. * y: 100
  9262. * })
  9263. * .start('spline');
  9264. */
  9265. var Animation = function (options) {
  9266. options = options || {};
  9267. this.stage = options.stage || {};
  9268. this.onframe = options.onframe || function () {};
  9269. // private properties
  9270. this._clips = [];
  9271. this._running = false;
  9272. this._time;
  9273. this._pausedTime;
  9274. this._pauseStart;
  9275. this._paused = false;
  9276. Eventful.call(this);
  9277. };
  9278. Animation.prototype = {
  9279. constructor: Animation,
  9280. /**
  9281. * 添加 clip
  9282. * @param {module:zrender/animation/Clip} clip
  9283. */
  9284. addClip: function (clip) {
  9285. this._clips.push(clip);
  9286. },
  9287. /**
  9288. * 添加 animator
  9289. * @param {module:zrender/animation/Animator} animator
  9290. */
  9291. addAnimator: function (animator) {
  9292. animator.animation = this;
  9293. var clips = animator.getClips();
  9294. for (var i = 0; i < clips.length; i++) {
  9295. this.addClip(clips[i]);
  9296. }
  9297. },
  9298. /**
  9299. * 删除动画片段
  9300. * @param {module:zrender/animation/Clip} clip
  9301. */
  9302. removeClip: function (clip) {
  9303. var idx = indexOf(this._clips, clip);
  9304. if (idx >= 0) {
  9305. this._clips.splice(idx, 1);
  9306. }
  9307. },
  9308. /**
  9309. * 删除动画片段
  9310. * @param {module:zrender/animation/Animator} animator
  9311. */
  9312. removeAnimator: function (animator) {
  9313. var clips = animator.getClips();
  9314. for (var i = 0; i < clips.length; i++) {
  9315. this.removeClip(clips[i]);
  9316. }
  9317. animator.animation = null;
  9318. },
  9319. _update: function () {
  9320. var time = new Date().getTime() - this._pausedTime;
  9321. var delta = time - this._time;
  9322. var clips = this._clips;
  9323. var len = clips.length;
  9324. var deferredEvents = [];
  9325. var deferredClips = [];
  9326. for (var i = 0; i < len; i++) {
  9327. var clip = clips[i];
  9328. var e = clip.step(time, delta);
  9329. // Throw out the events need to be called after
  9330. // stage.update, like destroy
  9331. if (e) {
  9332. deferredEvents.push(e);
  9333. deferredClips.push(clip);
  9334. }
  9335. }
  9336. // Remove the finished clip
  9337. for (var i = 0; i < len;) {
  9338. if (clips[i]._needsRemove) {
  9339. clips[i] = clips[len - 1];
  9340. clips.pop();
  9341. len--;
  9342. }
  9343. else {
  9344. i++;
  9345. }
  9346. }
  9347. len = deferredEvents.length;
  9348. for (var i = 0; i < len; i++) {
  9349. deferredClips[i].fire(deferredEvents[i]);
  9350. }
  9351. this._time = time;
  9352. this.onframe(delta);
  9353. // 'frame' should be triggered before stage, because upper application
  9354. // depends on the sequence (e.g., echarts-stream and finish
  9355. // event judge)
  9356. this.trigger('frame', delta);
  9357. if (this.stage.update) {
  9358. this.stage.update();
  9359. }
  9360. },
  9361. _startLoop: function () {
  9362. var self = this;
  9363. this._running = true;
  9364. function step() {
  9365. if (self._running) {
  9366. requestAnimationFrame(step);
  9367. !self._paused && self._update();
  9368. }
  9369. }
  9370. requestAnimationFrame(step);
  9371. },
  9372. /**
  9373. * Start animation.
  9374. */
  9375. start: function () {
  9376. this._time = new Date().getTime();
  9377. this._pausedTime = 0;
  9378. this._startLoop();
  9379. },
  9380. /**
  9381. * Stop animation.
  9382. */
  9383. stop: function () {
  9384. this._running = false;
  9385. },
  9386. /**
  9387. * Pause animation.
  9388. */
  9389. pause: function () {
  9390. if (!this._paused) {
  9391. this._pauseStart = new Date().getTime();
  9392. this._paused = true;
  9393. }
  9394. },
  9395. /**
  9396. * Resume animation.
  9397. */
  9398. resume: function () {
  9399. if (this._paused) {
  9400. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  9401. this._paused = false;
  9402. }
  9403. },
  9404. /**
  9405. * Clear animation.
  9406. */
  9407. clear: function () {
  9408. this._clips = [];
  9409. },
  9410. /**
  9411. * Whether animation finished.
  9412. */
  9413. isFinished: function () {
  9414. return !this._clips.length;
  9415. },
  9416. /**
  9417. * Creat animator for a target, whose props can be animated.
  9418. *
  9419. * @param {Object} target
  9420. * @param {Object} options
  9421. * @param {boolean} [options.loop=false] Whether loop animation.
  9422. * @param {Function} [options.getter=null] Get value from target.
  9423. * @param {Function} [options.setter=null] Set value to target.
  9424. * @return {module:zrender/animation/Animation~Animator}
  9425. */
  9426. // TODO Gap
  9427. animate: function (target, options) {
  9428. options = options || {};
  9429. var animator = new Animator(
  9430. target,
  9431. options.loop,
  9432. options.getter,
  9433. options.setter
  9434. );
  9435. this.addAnimator(animator);
  9436. return animator;
  9437. }
  9438. };
  9439. mixin(Animation, Eventful);
  9440. /* global document */
  9441. var TOUCH_CLICK_DELAY = 300;
  9442. var globalEventSupported = env$1.domSupported;
  9443. var localNativeListenerNames = (function () {
  9444. var mouseHandlerNames = [
  9445. 'click', 'dblclick', 'mousewheel', 'mouseout',
  9446. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  9447. ];
  9448. var touchHandlerNames = [
  9449. 'touchstart', 'touchend', 'touchmove'
  9450. ];
  9451. var pointerEventNameMap = {
  9452. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  9453. };
  9454. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  9455. var nm = name.replace('mouse', 'pointer');
  9456. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  9457. });
  9458. return {
  9459. mouse: mouseHandlerNames,
  9460. touch: touchHandlerNames,
  9461. pointer: pointerHandlerNames
  9462. };
  9463. })();
  9464. var globalNativeListenerNames = {
  9465. mouse: ['mousemove', 'mouseup'],
  9466. pointer: ['pointermove', 'pointerup']
  9467. };
  9468. function eventNameFix(name) {
  9469. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  9470. }
  9471. function isPointerFromTouch(event) {
  9472. var pointerType = event.pointerType;
  9473. return pointerType === 'pen' || pointerType === 'touch';
  9474. }
  9475. // function useMSGuesture(handlerProxy, event) {
  9476. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9477. // }
  9478. // function onMSGestureChange(proxy, event) {
  9479. // if (event.translationX || event.translationY) {
  9480. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9481. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9482. // }
  9483. // if (event.scale !== 1) {
  9484. // event.pinchX = event.offsetX;
  9485. // event.pinchY = event.offsetY;
  9486. // event.pinchScale = event.scale;
  9487. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9488. // }
  9489. // }
  9490. /**
  9491. * Prevent mouse event from being dispatched after Touch Events action
  9492. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9493. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9494. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9495. * Result: Blocking Mouse Events for 700ms.
  9496. *
  9497. * @param {DOMHandlerScope} scope
  9498. */
  9499. function setTouchTimer(scope) {
  9500. scope.touching = true;
  9501. if (scope.touchTimer != null) {
  9502. clearTimeout(scope.touchTimer);
  9503. scope.touchTimer = null;
  9504. }
  9505. scope.touchTimer = setTimeout(function () {
  9506. scope.touching = false;
  9507. scope.touchTimer = null;
  9508. }, 700);
  9509. }
  9510. // Mark touch, which is useful in distinguish touch and
  9511. // mouse event in upper applicatoin.
  9512. function markTouch(event) {
  9513. event && (event.zrByTouch = true);
  9514. }
  9515. // function markTriggeredFromLocal(event) {
  9516. // event && (event.__zrIsFromLocal = true);
  9517. // }
  9518. // function isTriggeredFromLocal(instance, event) {
  9519. // return !!(event && event.__zrIsFromLocal);
  9520. // }
  9521. function normalizeGlobalEvent(instance, event) {
  9522. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9523. // handlers of the upper applications. Set `true` to force calculate them.
  9524. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9525. }
  9526. /**
  9527. * Detect whether the given el is in `painterRoot`.
  9528. */
  9529. function isLocalEl(instance, el) {
  9530. var isLocal = false;
  9531. do {
  9532. el = el && el.parentNode;
  9533. }
  9534. while (el && el.nodeType !== 9 && !(
  9535. isLocal = el === instance.painterRoot
  9536. ));
  9537. return isLocal;
  9538. }
  9539. /**
  9540. * Make a fake event but not change the original event,
  9541. * becuase the global event probably be used by other
  9542. * listeners not belonging to zrender.
  9543. * @class
  9544. */
  9545. function FakeGlobalEvent(instance, event) {
  9546. this.type = event.type;
  9547. this.target = this.currentTarget = instance.dom;
  9548. this.pointerType = event.pointerType;
  9549. // Necessray for the force calculation of zrX, zrY
  9550. this.clientX = event.clientX;
  9551. this.clientY = event.clientY;
  9552. // Because we do not mount global listeners to touch events,
  9553. // we do not copy `targetTouches` and `changedTouches` here.
  9554. }
  9555. var fakeGlobalEventProto = FakeGlobalEvent.prototype;
  9556. // we make the default methods on the event do nothing,
  9557. // otherwise it is dangerous. See more details in
  9558. // [Drag outside] in `Handler.js`.
  9559. fakeGlobalEventProto.stopPropagation =
  9560. fakeGlobalEventProto.stopImmediatePropagation =
  9561. fakeGlobalEventProto.preventDefault = noop;
  9562. /**
  9563. * Local DOM Handlers
  9564. * @this {HandlerProxy}
  9565. */
  9566. var localDOMHandlers = {
  9567. mousedown: function (event) {
  9568. event = normalizeEvent(this.dom, event);
  9569. this._mayPointerCapture = [event.zrX, event.zrY];
  9570. this.trigger('mousedown', event);
  9571. },
  9572. mousemove: function (event) {
  9573. event = normalizeEvent(this.dom, event);
  9574. var downPoint = this._mayPointerCapture;
  9575. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9576. togglePointerCapture(this, true);
  9577. }
  9578. this.trigger('mousemove', event);
  9579. },
  9580. mouseup: function (event) {
  9581. event = normalizeEvent(this.dom, event);
  9582. togglePointerCapture(this, false);
  9583. this.trigger('mouseup', event);
  9584. },
  9585. mouseout: function (event) {
  9586. event = normalizeEvent(this.dom, event);
  9587. // Similarly to the browser did on `document` and touch event,
  9588. // `globalout` will be delayed to final pointer cature release.
  9589. if (this._pointerCapturing) {
  9590. event.zrEventControl = 'no_globalout';
  9591. }
  9592. // There might be some doms created by upper layer application
  9593. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9594. // dom created by echarts), where 'globalout' event should not
  9595. // be triggered when mouse enters these doms. (But 'mouseout'
  9596. // should be triggered at the original hovered element as usual).
  9597. var element = event.toElement || event.relatedTarget;
  9598. event.zrIsToLocalDOM = isLocalEl(this, element);
  9599. this.trigger('mouseout', event);
  9600. },
  9601. touchstart: function (event) {
  9602. // Default mouse behaviour should not be disabled here.
  9603. // For example, page may needs to be slided.
  9604. event = normalizeEvent(this.dom, event);
  9605. markTouch(event);
  9606. this._lastTouchMoment = new Date();
  9607. this.handler.processGesture(event, 'start');
  9608. // For consistent event listener for both touch device and mouse device,
  9609. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9610. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9611. // `mousedown`.
  9612. localDOMHandlers.mousemove.call(this, event);
  9613. localDOMHandlers.mousedown.call(this, event);
  9614. },
  9615. touchmove: function (event) {
  9616. event = normalizeEvent(this.dom, event);
  9617. markTouch(event);
  9618. this.handler.processGesture(event, 'change');
  9619. // Mouse move should always be triggered no matter whether
  9620. // there is gestrue event, because mouse move and pinch may
  9621. // be used at the same time.
  9622. localDOMHandlers.mousemove.call(this, event);
  9623. },
  9624. touchend: function (event) {
  9625. event = normalizeEvent(this.dom, event);
  9626. markTouch(event);
  9627. this.handler.processGesture(event, 'end');
  9628. localDOMHandlers.mouseup.call(this, event);
  9629. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9630. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9631. // we can conveniently implement "hover style" in both PC and touch device just
  9632. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9633. // to remove "hover style" on an element, without any additional code for
  9634. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9635. // style" will remain for user view)
  9636. // click event should always be triggered no matter whether
  9637. // there is gestrue event. System click can not be prevented.
  9638. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9639. localDOMHandlers.click.call(this, event);
  9640. }
  9641. },
  9642. pointerdown: function (event) {
  9643. localDOMHandlers.mousedown.call(this, event);
  9644. // if (useMSGuesture(this, event)) {
  9645. // this._msGesture.addPointer(event.pointerId);
  9646. // }
  9647. },
  9648. pointermove: function (event) {
  9649. // FIXME
  9650. // pointermove is so sensitive that it always triggered when
  9651. // tap(click) on touch screen, which affect some judgement in
  9652. // upper application. So, we dont support mousemove on MS touch
  9653. // device yet.
  9654. if (!isPointerFromTouch(event)) {
  9655. localDOMHandlers.mousemove.call(this, event);
  9656. }
  9657. },
  9658. pointerup: function (event) {
  9659. localDOMHandlers.mouseup.call(this, event);
  9660. },
  9661. pointerout: function (event) {
  9662. // pointerout will be triggered when tap on touch screen
  9663. // (IE11+/Edge on MS Surface) after click event triggered,
  9664. // which is inconsistent with the mousout behavior we defined
  9665. // in touchend. So we unify them.
  9666. // (check localDOMHandlers.touchend for detailed explanation)
  9667. if (!isPointerFromTouch(event)) {
  9668. localDOMHandlers.mouseout.call(this, event);
  9669. }
  9670. }
  9671. };
  9672. /**
  9673. * Othere DOM UI Event handlers for zr dom.
  9674. * @this {HandlerProxy}
  9675. */
  9676. each(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9677. localDOMHandlers[name] = function (event) {
  9678. event = normalizeEvent(this.dom, event);
  9679. this.trigger(name, event);
  9680. };
  9681. });
  9682. /**
  9683. * DOM UI Event handlers for global page.
  9684. *
  9685. * [Caution]:
  9686. * those handlers should both support in capture phase and bubble phase!
  9687. *
  9688. * @this {HandlerProxy}
  9689. */
  9690. var globalDOMHandlers = {
  9691. pointermove: function (event) {
  9692. // FIXME
  9693. // pointermove is so sensitive that it always triggered when
  9694. // tap(click) on touch screen, which affect some judgement in
  9695. // upper application. So, we dont support mousemove on MS touch
  9696. // device yet.
  9697. if (!isPointerFromTouch(event)) {
  9698. globalDOMHandlers.mousemove.call(this, event);
  9699. }
  9700. },
  9701. pointerup: function (event) {
  9702. globalDOMHandlers.mouseup.call(this, event);
  9703. },
  9704. mousemove: function (event) {
  9705. this.trigger('mousemove', event);
  9706. },
  9707. mouseup: function (event) {
  9708. var pointerCaptureReleasing = this._pointerCapturing;
  9709. togglePointerCapture(this, false);
  9710. this.trigger('mouseup', event);
  9711. if (pointerCaptureReleasing) {
  9712. event.zrEventControl = 'only_globalout';
  9713. this.trigger('mouseout', event);
  9714. }
  9715. }
  9716. };
  9717. /**
  9718. * @param {HandlerProxy} instance
  9719. * @param {DOMHandlerScope} scope
  9720. */
  9721. function mountLocalDOMEventListeners(instance, scope) {
  9722. var domHandlers = scope.domHandlers;
  9723. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9724. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9725. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9726. // at the same time.
  9727. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9728. // screen, which do not occurs in pointer event.
  9729. // So we use pointer event to both detect touch gesture and mouse behavior.
  9730. each(localNativeListenerNames.pointer, function (nativeEventName) {
  9731. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9732. // markTriggeredFromLocal(event);
  9733. domHandlers[nativeEventName].call(instance, event);
  9734. });
  9735. });
  9736. // FIXME
  9737. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9738. // which does not prevent defuault behavior occasionally (which may cause view port
  9739. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9740. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9741. // touch screen. And we only support click behavior on MS touch screen now.
  9742. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9743. // We dont support touch on IE on win7.
  9744. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9745. // if (typeof MSGesture === 'function') {
  9746. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9747. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9748. // }
  9749. }
  9750. else {
  9751. if (env$1.touchEventsSupported) {
  9752. each(localNativeListenerNames.touch, function (nativeEventName) {
  9753. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9754. // markTriggeredFromLocal(event);
  9755. domHandlers[nativeEventName].call(instance, event);
  9756. setTouchTimer(scope);
  9757. });
  9758. });
  9759. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9760. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9761. }
  9762. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9763. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9764. // mouse event can not be handle in those devices.
  9765. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9766. // mouseevent after touch event triggered, see `setTouchTimer`.
  9767. each(localNativeListenerNames.mouse, function (nativeEventName) {
  9768. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9769. event = getNativeEvent(event);
  9770. if (!scope.touching) {
  9771. // markTriggeredFromLocal(event);
  9772. domHandlers[nativeEventName].call(instance, event);
  9773. }
  9774. });
  9775. });
  9776. }
  9777. }
  9778. /**
  9779. * @param {HandlerProxy} instance
  9780. * @param {DOMHandlerScope} scope
  9781. */
  9782. function mountGlobalDOMEventListeners(instance, scope) {
  9783. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9784. if (env$1.pointerEventsSupported) {
  9785. each(globalNativeListenerNames.pointer, mount);
  9786. }
  9787. // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9788. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9789. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9790. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9791. else if (!env$1.touchEventsSupported) {
  9792. each(globalNativeListenerNames.mouse, mount);
  9793. }
  9794. function mount(nativeEventName) {
  9795. function nativeEventListener(event) {
  9796. event = getNativeEvent(event);
  9797. // See the reason in [Drag outside] in `Handler.js`
  9798. // This checking supports both `useCapture` or not.
  9799. // PENDING: if there is performance issue in some devices,
  9800. // we probably can not use `useCapture` and change a easier
  9801. // to judes whether local (mark).
  9802. if (!isLocalEl(instance, event.target)) {
  9803. event = normalizeGlobalEvent(instance, event);
  9804. scope.domHandlers[nativeEventName].call(instance, event);
  9805. }
  9806. }
  9807. mountSingleDOMEventListener(
  9808. scope, nativeEventName, nativeEventListener,
  9809. {capture: true} // See [Drag Outside] in `Handler.js`
  9810. );
  9811. }
  9812. }
  9813. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9814. scope.mounted[nativeEventName] = listener;
  9815. scope.listenerOpts[nativeEventName] = opt;
  9816. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9817. }
  9818. function unmountDOMEventListeners(scope) {
  9819. var mounted = scope.mounted;
  9820. for (var nativeEventName in mounted) {
  9821. if (mounted.hasOwnProperty(nativeEventName)) {
  9822. removeEventListener(
  9823. scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName],
  9824. scope.listenerOpts[nativeEventName]
  9825. );
  9826. }
  9827. }
  9828. scope.mounted = {};
  9829. }
  9830. /**
  9831. * See [Drag Outside] in `Handler.js`.
  9832. * @implement
  9833. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9834. * `true`: start to capture pointer if it is not capturing.
  9835. * `false`: end the capture if it is capturing.
  9836. */
  9837. function togglePointerCapture(instance, isPointerCapturing) {
  9838. instance._mayPointerCapture = null;
  9839. if (globalEventSupported && (instance._pointerCapturing ^ isPointerCapturing)) {
  9840. instance._pointerCapturing = isPointerCapturing;
  9841. var globalHandlerScope = instance._globalHandlerScope;
  9842. isPointerCapturing
  9843. ? mountGlobalDOMEventListeners(instance, globalHandlerScope)
  9844. : unmountDOMEventListeners(globalHandlerScope);
  9845. }
  9846. }
  9847. /**
  9848. * @inner
  9849. * @class
  9850. */
  9851. function DOMHandlerScope(domTarget, domHandlers) {
  9852. this.domTarget = domTarget;
  9853. this.domHandlers = domHandlers;
  9854. // Key: eventName, value: mounted handler funcitons.
  9855. // Used for unmount.
  9856. this.mounted = {};
  9857. this.listenerOpts = {};
  9858. this.touchTimer = null;
  9859. this.touching = false;
  9860. }
  9861. /**
  9862. * @public
  9863. * @class
  9864. */
  9865. function HandlerDomProxy(dom, painterRoot) {
  9866. Eventful.call(this);
  9867. this.dom = dom;
  9868. this.painterRoot = painterRoot;
  9869. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9870. if (globalEventSupported) {
  9871. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9872. }
  9873. /**
  9874. * @type {boolean}
  9875. */
  9876. this._pointerCapturing = false;
  9877. /**
  9878. * @type {Array.<number>} [x, y] or null.
  9879. */
  9880. this._mayPointerCapture = null;
  9881. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9882. }
  9883. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9884. handlerDomProxyProto.dispose = function () {
  9885. unmountDOMEventListeners(this._localHandlerScope);
  9886. if (globalEventSupported) {
  9887. unmountDOMEventListeners(this._globalHandlerScope);
  9888. }
  9889. };
  9890. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9891. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9892. };
  9893. mixin(HandlerDomProxy, Eventful);
  9894. /*!
  9895. * ZRender, a high performance 2d drawing library.
  9896. *
  9897. * Copyright (c) 2013, Baidu Inc.
  9898. * All rights reserved.
  9899. *
  9900. * LICENSE
  9901. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9902. */
  9903. var useVML = !env$1.canvasSupported;
  9904. var painterCtors = {
  9905. canvas: Painter
  9906. };
  9907. var instances = {}; // ZRender实例map索引
  9908. /**
  9909. * @type {string}
  9910. */
  9911. var version = '4.2.0';
  9912. /**
  9913. * Initializing a zrender instance
  9914. * @param {HTMLElement} dom
  9915. * @param {Object} [opts]
  9916. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9917. * @param {number} [opts.devicePixelRatio]
  9918. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9919. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9920. * @return {module:zrender/ZRender}
  9921. */
  9922. function init(dom, opts) {
  9923. var zr = new ZRender(guid(), dom, opts);
  9924. instances[zr.id] = zr;
  9925. return zr;
  9926. }
  9927. /**
  9928. * Dispose zrender instance
  9929. * @param {module:zrender/ZRender} zr
  9930. */
  9931. function dispose(zr) {
  9932. if (zr) {
  9933. zr.dispose();
  9934. }
  9935. else {
  9936. for (var key in instances) {
  9937. if (instances.hasOwnProperty(key)) {
  9938. instances[key].dispose();
  9939. }
  9940. }
  9941. instances = {};
  9942. }
  9943. return this;
  9944. }
  9945. /**
  9946. * Get zrender instance by id
  9947. * @param {string} id zrender instance id
  9948. * @return {module:zrender/ZRender}
  9949. */
  9950. function getInstance(id) {
  9951. return instances[id];
  9952. }
  9953. function registerPainter(name, Ctor) {
  9954. painterCtors[name] = Ctor;
  9955. }
  9956. function delInstance(id) {
  9957. delete instances[id];
  9958. }
  9959. /**
  9960. * @module zrender/ZRender
  9961. */
  9962. /**
  9963. * @constructor
  9964. * @alias module:zrender/ZRender
  9965. * @param {string} id
  9966. * @param {HTMLElement} dom
  9967. * @param {Object} opts
  9968. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9969. * @param {number} [opts.devicePixelRatio]
  9970. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9971. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9972. */
  9973. var ZRender = function (id, dom, opts) {
  9974. opts = opts || {};
  9975. /**
  9976. * @type {HTMLDomElement}
  9977. */
  9978. this.dom = dom;
  9979. /**
  9980. * @type {string}
  9981. */
  9982. this.id = id;
  9983. var self = this;
  9984. var storage = new Storage();
  9985. var rendererType = opts.renderer;
  9986. // TODO WebGL
  9987. if (useVML) {
  9988. if (!painterCtors.vml) {
  9989. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9990. }
  9991. rendererType = 'vml';
  9992. }
  9993. else if (!rendererType || !painterCtors[rendererType]) {
  9994. rendererType = 'canvas';
  9995. }
  9996. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9997. this.storage = storage;
  9998. this.painter = painter;
  9999. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  10000. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  10001. /**
  10002. * @type {module:zrender/animation/Animation}
  10003. */
  10004. this.animation = new Animation({
  10005. stage: {
  10006. update: bind(this.flush, this)
  10007. }
  10008. });
  10009. this.animation.start();
  10010. /**
  10011. * @type {boolean}
  10012. * @private
  10013. */
  10014. this._needsRefresh;
  10015. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  10016. // FIXME 有点ugly
  10017. var oldDelFromStorage = storage.delFromStorage;
  10018. var oldAddToStorage = storage.addToStorage;
  10019. storage.delFromStorage = function (el) {
  10020. oldDelFromStorage.call(storage, el);
  10021. el && el.removeSelfFromZr(self);
  10022. };
  10023. storage.addToStorage = function (el) {
  10024. oldAddToStorage.call(storage, el);
  10025. el.addSelfToZr(self);
  10026. };
  10027. };
  10028. ZRender.prototype = {
  10029. constructor: ZRender,
  10030. /**
  10031. * 获取实例唯一标识
  10032. * @return {string}
  10033. */
  10034. getId: function () {
  10035. return this.id;
  10036. },
  10037. /**
  10038. * 添加元素
  10039. * @param {module:zrender/Element} el
  10040. */
  10041. add: function (el) {
  10042. this.storage.addRoot(el);
  10043. this._needsRefresh = true;
  10044. },
  10045. /**
  10046. * 删除元素
  10047. * @param {module:zrender/Element} el
  10048. */
  10049. remove: function (el) {
  10050. this.storage.delRoot(el);
  10051. this._needsRefresh = true;
  10052. },
  10053. /**
  10054. * Change configuration of layer
  10055. * @param {string} zLevel
  10056. * @param {Object} config
  10057. * @param {string} [config.clearColor=0] Clear color
  10058. * @param {string} [config.motionBlur=false] If enable motion blur
  10059. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  10060. */
  10061. configLayer: function (zLevel, config) {
  10062. if (this.painter.configLayer) {
  10063. this.painter.configLayer(zLevel, config);
  10064. }
  10065. this._needsRefresh = true;
  10066. },
  10067. /**
  10068. * Set background color
  10069. * @param {string} backgroundColor
  10070. */
  10071. setBackgroundColor: function (backgroundColor) {
  10072. if (this.painter.setBackgroundColor) {
  10073. this.painter.setBackgroundColor(backgroundColor);
  10074. }
  10075. this._needsRefresh = true;
  10076. },
  10077. /**
  10078. * Repaint the canvas immediately
  10079. */
  10080. refreshImmediately: function () {
  10081. // var start = new Date();
  10082. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  10083. // Or it will cause zrender refreshes again and again.
  10084. this._needsRefresh = this._needsRefreshHover = false;
  10085. this.painter.refresh();
  10086. // Avoid trigger zr.refresh in Element#beforeUpdate hook
  10087. this._needsRefresh = this._needsRefreshHover = false;
  10088. // var end = new Date();
  10089. // var log = document.getElementById('log');
  10090. // if (log) {
  10091. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  10092. // }
  10093. },
  10094. /**
  10095. * Mark and repaint the canvas in the next frame of browser
  10096. */
  10097. refresh: function () {
  10098. this._needsRefresh = true;
  10099. },
  10100. /**
  10101. * Perform all refresh
  10102. */
  10103. flush: function () {
  10104. var triggerRendered;
  10105. if (this._needsRefresh) {
  10106. triggerRendered = true;
  10107. this.refreshImmediately();
  10108. }
  10109. if (this._needsRefreshHover) {
  10110. triggerRendered = true;
  10111. this.refreshHoverImmediately();
  10112. }
  10113. triggerRendered && this.trigger('rendered');
  10114. },
  10115. /**
  10116. * Add element to hover layer
  10117. * @param {module:zrender/Element} el
  10118. * @param {Object} style
  10119. */
  10120. addHover: function (el, style) {
  10121. if (this.painter.addHover) {
  10122. var elMirror = this.painter.addHover(el, style);
  10123. this.refreshHover();
  10124. return elMirror;
  10125. }
  10126. },
  10127. /**
  10128. * Add element from hover layer
  10129. * @param {module:zrender/Element} el
  10130. */
  10131. removeHover: function (el) {
  10132. if (this.painter.removeHover) {
  10133. this.painter.removeHover(el);
  10134. this.refreshHover();
  10135. }
  10136. },
  10137. /**
  10138. * Clear all hover elements in hover layer
  10139. * @param {module:zrender/Element} el
  10140. */
  10141. clearHover: function () {
  10142. if (this.painter.clearHover) {
  10143. this.painter.clearHover();
  10144. this.refreshHover();
  10145. }
  10146. },
  10147. /**
  10148. * Refresh hover in next frame
  10149. */
  10150. refreshHover: function () {
  10151. this._needsRefreshHover = true;
  10152. },
  10153. /**
  10154. * Refresh hover immediately
  10155. */
  10156. refreshHoverImmediately: function () {
  10157. this._needsRefreshHover = false;
  10158. this.painter.refreshHover && this.painter.refreshHover();
  10159. },
  10160. /**
  10161. * Resize the canvas.
  10162. * Should be invoked when container size is changed
  10163. * @param {Object} [opts]
  10164. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  10165. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  10166. */
  10167. resize: function (opts) {
  10168. opts = opts || {};
  10169. this.painter.resize(opts.width, opts.height);
  10170. this.handler.resize();
  10171. },
  10172. /**
  10173. * Stop and clear all animation immediately
  10174. */
  10175. clearAnimation: function () {
  10176. this.animation.clear();
  10177. },
  10178. /**
  10179. * Get container width
  10180. */
  10181. getWidth: function () {
  10182. return this.painter.getWidth();
  10183. },
  10184. /**
  10185. * Get container height
  10186. */
  10187. getHeight: function () {
  10188. return this.painter.getHeight();
  10189. },
  10190. /**
  10191. * Export the canvas as Base64 URL
  10192. * @param {string} type
  10193. * @param {string} [backgroundColor='#fff']
  10194. * @return {string} Base64 URL
  10195. */
  10196. // toDataURL: function(type, backgroundColor) {
  10197. // return this.painter.getRenderedCanvas({
  10198. // backgroundColor: backgroundColor
  10199. // }).toDataURL(type);
  10200. // },
  10201. /**
  10202. * Converting a path to image.
  10203. * It has much better performance of drawing image rather than drawing a vector path.
  10204. * @param {module:zrender/graphic/Path} e
  10205. * @param {number} width
  10206. * @param {number} height
  10207. */
  10208. pathToImage: function (e, dpr) {
  10209. return this.painter.pathToImage(e, dpr);
  10210. },
  10211. /**
  10212. * Set default cursor
  10213. * @param {string} [cursorStyle='default'] 例如 crosshair
  10214. */
  10215. setCursorStyle: function (cursorStyle) {
  10216. this.handler.setCursorStyle(cursorStyle);
  10217. },
  10218. /**
  10219. * Find hovered element
  10220. * @param {number} x
  10221. * @param {number} y
  10222. * @return {Object} {target, topTarget}
  10223. */
  10224. findHover: function (x, y) {
  10225. return this.handler.findHover(x, y);
  10226. },
  10227. /**
  10228. * Bind event
  10229. *
  10230. * @param {string} eventName Event name
  10231. * @param {Function} eventHandler Handler function
  10232. * @param {Object} [context] Context object
  10233. */
  10234. on: function (eventName, eventHandler, context) {
  10235. this.handler.on(eventName, eventHandler, context);
  10236. },
  10237. /**
  10238. * Unbind event
  10239. * @param {string} eventName Event name
  10240. * @param {Function} [eventHandler] Handler function
  10241. */
  10242. off: function (eventName, eventHandler) {
  10243. this.handler.off(eventName, eventHandler);
  10244. },
  10245. /**
  10246. * Trigger event manually
  10247. *
  10248. * @param {string} eventName Event name
  10249. * @param {event=} event Event object
  10250. */
  10251. trigger: function (eventName, event) {
  10252. this.handler.trigger(eventName, event);
  10253. },
  10254. /**
  10255. * Clear all objects and the canvas.
  10256. */
  10257. clear: function () {
  10258. this.storage.delRoot();
  10259. this.painter.clear();
  10260. },
  10261. /**
  10262. * Dispose self.
  10263. */
  10264. dispose: function () {
  10265. this.animation.stop();
  10266. this.clear();
  10267. this.storage.dispose();
  10268. this.painter.dispose();
  10269. this.handler.dispose();
  10270. this.animation =
  10271. this.storage =
  10272. this.painter =
  10273. this.handler = null;
  10274. delInstance(this.id);
  10275. }
  10276. };
  10277. /**
  10278. * 曲线辅助模块
  10279. * @module zrender/core/curve
  10280. * @author pissang(https://www.github.com/pissang)
  10281. */
  10282. var mathPow = Math.pow;
  10283. var mathSqrt$2 = Math.sqrt;
  10284. var EPSILON$1 = 1e-8;
  10285. var EPSILON_NUMERIC = 1e-4;
  10286. var THREE_SQRT = mathSqrt$2(3);
  10287. var ONE_THIRD = 1 / 3;
  10288. // 临时变量
  10289. var _v0 = create();
  10290. var _v1 = create();
  10291. var _v2 = create();
  10292. function isAroundZero(val) {
  10293. return val > -EPSILON$1 && val < EPSILON$1;
  10294. }
  10295. function isNotAroundZero$1(val) {
  10296. return val > EPSILON$1 || val < -EPSILON$1;
  10297. }
  10298. /**
  10299. * 计算三次贝塞尔值
  10300. * @memberOf module:zrender/core/curve
  10301. * @param {number} p0
  10302. * @param {number} p1
  10303. * @param {number} p2
  10304. * @param {number} p3
  10305. * @param {number} t
  10306. * @return {number}
  10307. */
  10308. function cubicAt(p0, p1, p2, p3, t) {
  10309. var onet = 1 - t;
  10310. return onet * onet * (onet * p0 + 3 * t * p1)
  10311. + t * t * (t * p3 + 3 * onet * p2);
  10312. }
  10313. /**
  10314. * 计算三次贝塞尔导数值
  10315. * @memberOf module:zrender/core/curve
  10316. * @param {number} p0
  10317. * @param {number} p1
  10318. * @param {number} p2
  10319. * @param {number} p3
  10320. * @param {number} t
  10321. * @return {number}
  10322. */
  10323. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10324. var onet = 1 - t;
  10325. return 3 * (
  10326. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10327. + (p3 - p2) * t * t
  10328. );
  10329. }
  10330. /**
  10331. * 计算三次贝塞尔方程根,使用盛金公式
  10332. * @memberOf module:zrender/core/curve
  10333. * @param {number} p0
  10334. * @param {number} p1
  10335. * @param {number} p2
  10336. * @param {number} p3
  10337. * @param {number} val
  10338. * @param {Array.<number>} roots
  10339. * @return {number} 有效根数目
  10340. */
  10341. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10342. // Evaluate roots of cubic functions
  10343. var a = p3 + 3 * (p1 - p2) - p0;
  10344. var b = 3 * (p2 - p1 * 2 + p0);
  10345. var c = 3 * (p1 - p0);
  10346. var d = p0 - val;
  10347. var A = b * b - 3 * a * c;
  10348. var B = b * c - 9 * a * d;
  10349. var C = c * c - 3 * b * d;
  10350. var n = 0;
  10351. if (isAroundZero(A) && isAroundZero(B)) {
  10352. if (isAroundZero(b)) {
  10353. roots[0] = 0;
  10354. }
  10355. else {
  10356. var t1 = -c / b; //t1, t2, t3, b is not zero
  10357. if (t1 >= 0 && t1 <= 1) {
  10358. roots[n++] = t1;
  10359. }
  10360. }
  10361. }
  10362. else {
  10363. var disc = B * B - 4 * A * C;
  10364. if (isAroundZero(disc)) {
  10365. var K = B / A;
  10366. var t1 = -b / a + K; // t1, a is not zero
  10367. var t2 = -K / 2; // t2, t3
  10368. if (t1 >= 0 && t1 <= 1) {
  10369. roots[n++] = t1;
  10370. }
  10371. if (t2 >= 0 && t2 <= 1) {
  10372. roots[n++] = t2;
  10373. }
  10374. }
  10375. else if (disc > 0) {
  10376. var discSqrt = mathSqrt$2(disc);
  10377. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10378. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10379. if (Y1 < 0) {
  10380. Y1 = -mathPow(-Y1, ONE_THIRD);
  10381. }
  10382. else {
  10383. Y1 = mathPow(Y1, ONE_THIRD);
  10384. }
  10385. if (Y2 < 0) {
  10386. Y2 = -mathPow(-Y2, ONE_THIRD);
  10387. }
  10388. else {
  10389. Y2 = mathPow(Y2, ONE_THIRD);
  10390. }
  10391. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10392. if (t1 >= 0 && t1 <= 1) {
  10393. roots[n++] = t1;
  10394. }
  10395. }
  10396. else {
  10397. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10398. var theta = Math.acos(T) / 3;
  10399. var ASqrt = mathSqrt$2(A);
  10400. var tmp = Math.cos(theta);
  10401. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10402. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10403. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10404. if (t1 >= 0 && t1 <= 1) {
  10405. roots[n++] = t1;
  10406. }
  10407. if (t2 >= 0 && t2 <= 1) {
  10408. roots[n++] = t2;
  10409. }
  10410. if (t3 >= 0 && t3 <= 1) {
  10411. roots[n++] = t3;
  10412. }
  10413. }
  10414. }
  10415. return n;
  10416. }
  10417. /**
  10418. * 计算三次贝塞尔方程极限值的位置
  10419. * @memberOf module:zrender/core/curve
  10420. * @param {number} p0
  10421. * @param {number} p1
  10422. * @param {number} p2
  10423. * @param {number} p3
  10424. * @param {Array.<number>} extrema
  10425. * @return {number} 有效数目
  10426. */
  10427. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10428. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10429. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10430. var c = 3 * p1 - 3 * p0;
  10431. var n = 0;
  10432. if (isAroundZero(a)) {
  10433. if (isNotAroundZero$1(b)) {
  10434. var t1 = -c / b;
  10435. if (t1 >= 0 && t1 <= 1) {
  10436. extrema[n++] = t1;
  10437. }
  10438. }
  10439. }
  10440. else {
  10441. var disc = b * b - 4 * a * c;
  10442. if (isAroundZero(disc)) {
  10443. extrema[0] = -b / (2 * a);
  10444. }
  10445. else if (disc > 0) {
  10446. var discSqrt = mathSqrt$2(disc);
  10447. var t1 = (-b + discSqrt) / (2 * a);
  10448. var t2 = (-b - discSqrt) / (2 * a);
  10449. if (t1 >= 0 && t1 <= 1) {
  10450. extrema[n++] = t1;
  10451. }
  10452. if (t2 >= 0 && t2 <= 1) {
  10453. extrema[n++] = t2;
  10454. }
  10455. }
  10456. }
  10457. return n;
  10458. }
  10459. /**
  10460. * 细分三次贝塞尔曲线
  10461. * @memberOf module:zrender/core/curve
  10462. * @param {number} p0
  10463. * @param {number} p1
  10464. * @param {number} p2
  10465. * @param {number} p3
  10466. * @param {number} t
  10467. * @param {Array.<number>} out
  10468. */
  10469. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10470. var p01 = (p1 - p0) * t + p0;
  10471. var p12 = (p2 - p1) * t + p1;
  10472. var p23 = (p3 - p2) * t + p2;
  10473. var p012 = (p12 - p01) * t + p01;
  10474. var p123 = (p23 - p12) * t + p12;
  10475. var p0123 = (p123 - p012) * t + p012;
  10476. // Seg0
  10477. out[0] = p0;
  10478. out[1] = p01;
  10479. out[2] = p012;
  10480. out[3] = p0123;
  10481. // Seg1
  10482. out[4] = p0123;
  10483. out[5] = p123;
  10484. out[6] = p23;
  10485. out[7] = p3;
  10486. }
  10487. /**
  10488. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10489. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10490. * @param {number} x0
  10491. * @param {number} y0
  10492. * @param {number} x1
  10493. * @param {number} y1
  10494. * @param {number} x2
  10495. * @param {number} y2
  10496. * @param {number} x3
  10497. * @param {number} y3
  10498. * @param {number} x
  10499. * @param {number} y
  10500. * @param {Array.<number>} [out] 投射点
  10501. * @return {number}
  10502. */
  10503. function cubicProjectPoint(
  10504. x0, y0, x1, y1, x2, y2, x3, y3,
  10505. x, y, out
  10506. ) {
  10507. // http://pomax.github.io/bezierinfo/#projections
  10508. var t;
  10509. var interval = 0.005;
  10510. var d = Infinity;
  10511. var prev;
  10512. var next;
  10513. var d1;
  10514. var d2;
  10515. _v0[0] = x;
  10516. _v0[1] = y;
  10517. // 先粗略估计一下可能的最小距离的 t 值
  10518. // PENDING
  10519. for (var _t = 0; _t < 1; _t += 0.05) {
  10520. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10521. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10522. d1 = distSquare(_v0, _v1);
  10523. if (d1 < d) {
  10524. t = _t;
  10525. d = d1;
  10526. }
  10527. }
  10528. d = Infinity;
  10529. // At most 32 iteration
  10530. for (var i = 0; i < 32; i++) {
  10531. if (interval < EPSILON_NUMERIC) {
  10532. break;
  10533. }
  10534. prev = t - interval;
  10535. next = t + interval;
  10536. // t - interval
  10537. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10538. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10539. d1 = distSquare(_v1, _v0);
  10540. if (prev >= 0 && d1 < d) {
  10541. t = prev;
  10542. d = d1;
  10543. }
  10544. else {
  10545. // t + interval
  10546. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10547. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10548. d2 = distSquare(_v2, _v0);
  10549. if (next <= 1 && d2 < d) {
  10550. t = next;
  10551. d = d2;
  10552. }
  10553. else {
  10554. interval *= 0.5;
  10555. }
  10556. }
  10557. }
  10558. // t
  10559. if (out) {
  10560. out[0] = cubicAt(x0, x1, x2, x3, t);
  10561. out[1] = cubicAt(y0, y1, y2, y3, t);
  10562. }
  10563. // console.log(interval, i);
  10564. return mathSqrt$2(d);
  10565. }
  10566. /**
  10567. * 计算二次方贝塞尔值
  10568. * @param {number} p0
  10569. * @param {number} p1
  10570. * @param {number} p2
  10571. * @param {number} t
  10572. * @return {number}
  10573. */
  10574. function quadraticAt(p0, p1, p2, t) {
  10575. var onet = 1 - t;
  10576. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10577. }
  10578. /**
  10579. * 计算二次方贝塞尔导数值
  10580. * @param {number} p0
  10581. * @param {number} p1
  10582. * @param {number} p2
  10583. * @param {number} t
  10584. * @return {number}
  10585. */
  10586. function quadraticDerivativeAt(p0, p1, p2, t) {
  10587. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10588. }
  10589. /**
  10590. * 计算二次方贝塞尔方程根
  10591. * @param {number} p0
  10592. * @param {number} p1
  10593. * @param {number} p2
  10594. * @param {number} t
  10595. * @param {Array.<number>} roots
  10596. * @return {number} 有效根数目
  10597. */
  10598. function quadraticRootAt(p0, p1, p2, val, roots) {
  10599. var a = p0 - 2 * p1 + p2;
  10600. var b = 2 * (p1 - p0);
  10601. var c = p0 - val;
  10602. var n = 0;
  10603. if (isAroundZero(a)) {
  10604. if (isNotAroundZero$1(b)) {
  10605. var t1 = -c / b;
  10606. if (t1 >= 0 && t1 <= 1) {
  10607. roots[n++] = t1;
  10608. }
  10609. }
  10610. }
  10611. else {
  10612. var disc = b * b - 4 * a * c;
  10613. if (isAroundZero(disc)) {
  10614. var t1 = -b / (2 * a);
  10615. if (t1 >= 0 && t1 <= 1) {
  10616. roots[n++] = t1;
  10617. }
  10618. }
  10619. else if (disc > 0) {
  10620. var discSqrt = mathSqrt$2(disc);
  10621. var t1 = (-b + discSqrt) / (2 * a);
  10622. var t2 = (-b - discSqrt) / (2 * a);
  10623. if (t1 >= 0 && t1 <= 1) {
  10624. roots[n++] = t1;
  10625. }
  10626. if (t2 >= 0 && t2 <= 1) {
  10627. roots[n++] = t2;
  10628. }
  10629. }
  10630. }
  10631. return n;
  10632. }
  10633. /**
  10634. * 计算二次贝塞尔方程极限值
  10635. * @memberOf module:zrender/core/curve
  10636. * @param {number} p0
  10637. * @param {number} p1
  10638. * @param {number} p2
  10639. * @return {number}
  10640. */
  10641. function quadraticExtremum(p0, p1, p2) {
  10642. var divider = p0 + p2 - 2 * p1;
  10643. if (divider === 0) {
  10644. // p1 is center of p0 and p2
  10645. return 0.5;
  10646. }
  10647. else {
  10648. return (p0 - p1) / divider;
  10649. }
  10650. }
  10651. /**
  10652. * 细分二次贝塞尔曲线
  10653. * @memberOf module:zrender/core/curve
  10654. * @param {number} p0
  10655. * @param {number} p1
  10656. * @param {number} p2
  10657. * @param {number} t
  10658. * @param {Array.<number>} out
  10659. */
  10660. function quadraticSubdivide(p0, p1, p2, t, out) {
  10661. var p01 = (p1 - p0) * t + p0;
  10662. var p12 = (p2 - p1) * t + p1;
  10663. var p012 = (p12 - p01) * t + p01;
  10664. // Seg0
  10665. out[0] = p0;
  10666. out[1] = p01;
  10667. out[2] = p012;
  10668. // Seg1
  10669. out[3] = p012;
  10670. out[4] = p12;
  10671. out[5] = p2;
  10672. }
  10673. /**
  10674. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10675. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10676. * @param {number} x0
  10677. * @param {number} y0
  10678. * @param {number} x1
  10679. * @param {number} y1
  10680. * @param {number} x2
  10681. * @param {number} y2
  10682. * @param {number} x
  10683. * @param {number} y
  10684. * @param {Array.<number>} out 投射点
  10685. * @return {number}
  10686. */
  10687. function quadraticProjectPoint(
  10688. x0, y0, x1, y1, x2, y2,
  10689. x, y, out
  10690. ) {
  10691. // http://pomax.github.io/bezierinfo/#projections
  10692. var t;
  10693. var interval = 0.005;
  10694. var d = Infinity;
  10695. _v0[0] = x;
  10696. _v0[1] = y;
  10697. // 先粗略估计一下可能的最小距离的 t 值
  10698. // PENDING
  10699. for (var _t = 0; _t < 1; _t += 0.05) {
  10700. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10701. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10702. var d1 = distSquare(_v0, _v1);
  10703. if (d1 < d) {
  10704. t = _t;
  10705. d = d1;
  10706. }
  10707. }
  10708. d = Infinity;
  10709. // At most 32 iteration
  10710. for (var i = 0; i < 32; i++) {
  10711. if (interval < EPSILON_NUMERIC) {
  10712. break;
  10713. }
  10714. var prev = t - interval;
  10715. var next = t + interval;
  10716. // t - interval
  10717. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10718. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10719. var d1 = distSquare(_v1, _v0);
  10720. if (prev >= 0 && d1 < d) {
  10721. t = prev;
  10722. d = d1;
  10723. }
  10724. else {
  10725. // t + interval
  10726. _v2[0] = quadraticAt(x0, x1, x2, next);
  10727. _v2[1] = quadraticAt(y0, y1, y2, next);
  10728. var d2 = distSquare(_v2, _v0);
  10729. if (next <= 1 && d2 < d) {
  10730. t = next;
  10731. d = d2;
  10732. }
  10733. else {
  10734. interval *= 0.5;
  10735. }
  10736. }
  10737. }
  10738. // t
  10739. if (out) {
  10740. out[0] = quadraticAt(x0, x1, x2, t);
  10741. out[1] = quadraticAt(y0, y1, y2, t);
  10742. }
  10743. // console.log(interval, i);
  10744. return mathSqrt$2(d);
  10745. }
  10746. /**
  10747. * @author Yi Shen(https://github.com/pissang)
  10748. */
  10749. var mathMin$2 = Math.min;
  10750. var mathMax$2 = Math.max;
  10751. var mathSin$2 = Math.sin;
  10752. var mathCos$2 = Math.cos;
  10753. var PI2 = Math.PI * 2;
  10754. var start = create();
  10755. var end = create();
  10756. var extremity = create();
  10757. /**
  10758. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10759. * @module zrender/core/bbox
  10760. * @param {Array<Object>} points 顶点数组
  10761. * @param {number} min
  10762. * @param {number} max
  10763. */
  10764. /**
  10765. * @memberOf module:zrender/core/bbox
  10766. * @param {number} x0
  10767. * @param {number} y0
  10768. * @param {number} x1
  10769. * @param {number} y1
  10770. * @param {Array.<number>} min
  10771. * @param {Array.<number>} max
  10772. */
  10773. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10774. min$$1[0] = mathMin$2(x0, x1);
  10775. min$$1[1] = mathMin$2(y0, y1);
  10776. max$$1[0] = mathMax$2(x0, x1);
  10777. max$$1[1] = mathMax$2(y0, y1);
  10778. }
  10779. var xDim = [];
  10780. var yDim = [];
  10781. /**
  10782. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10783. * @memberOf module:zrender/core/bbox
  10784. * @param {number} x0
  10785. * @param {number} y0
  10786. * @param {number} x1
  10787. * @param {number} y1
  10788. * @param {number} x2
  10789. * @param {number} y2
  10790. * @param {number} x3
  10791. * @param {number} y3
  10792. * @param {Array.<number>} min
  10793. * @param {Array.<number>} max
  10794. */
  10795. function fromCubic(
  10796. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10797. ) {
  10798. var cubicExtrema$$1 = cubicExtrema;
  10799. var cubicAt$$1 = cubicAt;
  10800. var i;
  10801. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10802. min$$1[0] = Infinity;
  10803. min$$1[1] = Infinity;
  10804. max$$1[0] = -Infinity;
  10805. max$$1[1] = -Infinity;
  10806. for (i = 0; i < n; i++) {
  10807. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10808. min$$1[0] = mathMin$2(x, min$$1[0]);
  10809. max$$1[0] = mathMax$2(x, max$$1[0]);
  10810. }
  10811. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10812. for (i = 0; i < n; i++) {
  10813. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10814. min$$1[1] = mathMin$2(y, min$$1[1]);
  10815. max$$1[1] = mathMax$2(y, max$$1[1]);
  10816. }
  10817. min$$1[0] = mathMin$2(x0, min$$1[0]);
  10818. max$$1[0] = mathMax$2(x0, max$$1[0]);
  10819. min$$1[0] = mathMin$2(x3, min$$1[0]);
  10820. max$$1[0] = mathMax$2(x3, max$$1[0]);
  10821. min$$1[1] = mathMin$2(y0, min$$1[1]);
  10822. max$$1[1] = mathMax$2(y0, max$$1[1]);
  10823. min$$1[1] = mathMin$2(y3, min$$1[1]);
  10824. max$$1[1] = mathMax$2(y3, max$$1[1]);
  10825. }
  10826. /**
  10827. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10828. * @memberOf module:zrender/core/bbox
  10829. * @param {number} x0
  10830. * @param {number} y0
  10831. * @param {number} x1
  10832. * @param {number} y1
  10833. * @param {number} x2
  10834. * @param {number} y2
  10835. * @param {Array.<number>} min
  10836. * @param {Array.<number>} max
  10837. */
  10838. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10839. var quadraticExtremum$$1 = quadraticExtremum;
  10840. var quadraticAt$$1 = quadraticAt;
  10841. // Find extremities, where derivative in x dim or y dim is zero
  10842. var tx =
  10843. mathMax$2(
  10844. mathMin$2(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10845. );
  10846. var ty =
  10847. mathMax$2(
  10848. mathMin$2(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10849. );
  10850. var x = quadraticAt$$1(x0, x1, x2, tx);
  10851. var y = quadraticAt$$1(y0, y1, y2, ty);
  10852. min$$1[0] = mathMin$2(x0, x2, x);
  10853. min$$1[1] = mathMin$2(y0, y2, y);
  10854. max$$1[0] = mathMax$2(x0, x2, x);
  10855. max$$1[1] = mathMax$2(y0, y2, y);
  10856. }
  10857. /**
  10858. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10859. * @method
  10860. * @memberOf module:zrender/core/bbox
  10861. * @param {number} x
  10862. * @param {number} y
  10863. * @param {number} rx
  10864. * @param {number} ry
  10865. * @param {number} startAngle
  10866. * @param {number} endAngle
  10867. * @param {number} anticlockwise
  10868. * @param {Array.<number>} min
  10869. * @param {Array.<number>} max
  10870. */
  10871. function fromArc(
  10872. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10873. ) {
  10874. var vec2Min = min;
  10875. var vec2Max = max;
  10876. var diff = Math.abs(startAngle - endAngle);
  10877. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10878. // Is a circle
  10879. min$$1[0] = x - rx;
  10880. min$$1[1] = y - ry;
  10881. max$$1[0] = x + rx;
  10882. max$$1[1] = y + ry;
  10883. return;
  10884. }
  10885. start[0] = mathCos$2(startAngle) * rx + x;
  10886. start[1] = mathSin$2(startAngle) * ry + y;
  10887. end[0] = mathCos$2(endAngle) * rx + x;
  10888. end[1] = mathSin$2(endAngle) * ry + y;
  10889. vec2Min(min$$1, start, end);
  10890. vec2Max(max$$1, start, end);
  10891. // Thresh to [0, Math.PI * 2]
  10892. startAngle = startAngle % (PI2);
  10893. if (startAngle < 0) {
  10894. startAngle = startAngle + PI2;
  10895. }
  10896. endAngle = endAngle % (PI2);
  10897. if (endAngle < 0) {
  10898. endAngle = endAngle + PI2;
  10899. }
  10900. if (startAngle > endAngle && !anticlockwise) {
  10901. endAngle += PI2;
  10902. }
  10903. else if (startAngle < endAngle && anticlockwise) {
  10904. startAngle += PI2;
  10905. }
  10906. if (anticlockwise) {
  10907. var tmp = endAngle;
  10908. endAngle = startAngle;
  10909. startAngle = tmp;
  10910. }
  10911. // var number = 0;
  10912. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10913. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10914. if (angle > startAngle) {
  10915. extremity[0] = mathCos$2(angle) * rx + x;
  10916. extremity[1] = mathSin$2(angle) * ry + y;
  10917. vec2Min(min$$1, extremity, min$$1);
  10918. vec2Max(max$$1, extremity, max$$1);
  10919. }
  10920. }
  10921. }
  10922. /**
  10923. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10924. * 可以用于 isInsidePath 判断以及获取boundingRect
  10925. *
  10926. * @module zrender/core/PathProxy
  10927. * @author Yi Shen (http://www.github.com/pissang)
  10928. */
  10929. // TODO getTotalLength, getPointAtLength
  10930. /* global Float32Array */
  10931. var CMD = {
  10932. M: 1,
  10933. L: 2,
  10934. C: 3,
  10935. Q: 4,
  10936. A: 5,
  10937. Z: 6,
  10938. // Rect
  10939. R: 7
  10940. };
  10941. // var CMD_MEM_SIZE = {
  10942. // M: 3,
  10943. // L: 3,
  10944. // C: 7,
  10945. // Q: 5,
  10946. // A: 9,
  10947. // R: 5,
  10948. // Z: 1
  10949. // };
  10950. var min$1 = [];
  10951. var max$1 = [];
  10952. var min2 = [];
  10953. var max2 = [];
  10954. var mathMin$1 = Math.min;
  10955. var mathMax$1 = Math.max;
  10956. var mathCos$1 = Math.cos;
  10957. var mathSin$1 = Math.sin;
  10958. var mathSqrt$1 = Math.sqrt;
  10959. var mathAbs = Math.abs;
  10960. var hasTypedArray = typeof Float32Array !== 'undefined';
  10961. /**
  10962. * @alias module:zrender/core/PathProxy
  10963. * @constructor
  10964. */
  10965. var PathProxy = function (notSaveData) {
  10966. this._saveData = !(notSaveData || false);
  10967. if (this._saveData) {
  10968. /**
  10969. * Path data. Stored as flat array
  10970. * @type {Array.<Object>}
  10971. */
  10972. this.data = [];
  10973. }
  10974. this._ctx = null;
  10975. };
  10976. /**
  10977. * 快速计算Path包围盒(并不是最小包围盒)
  10978. * @return {Object}
  10979. */
  10980. PathProxy.prototype = {
  10981. constructor: PathProxy,
  10982. _xi: 0,
  10983. _yi: 0,
  10984. _x0: 0,
  10985. _y0: 0,
  10986. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  10987. _ux: 0,
  10988. _uy: 0,
  10989. _len: 0,
  10990. _lineDash: null,
  10991. _dashOffset: 0,
  10992. _dashIdx: 0,
  10993. _dashSum: 0,
  10994. /**
  10995. * @readOnly
  10996. */
  10997. setScale: function (sx, sy, segmentIgnoreThreshold) {
  10998. // Compat. Previously there is no segmentIgnoreThreshold.
  10999. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11000. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11001. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11002. },
  11003. getContext: function () {
  11004. return this._ctx;
  11005. },
  11006. /**
  11007. * @param {CanvasRenderingContext2D} ctx
  11008. * @return {module:zrender/core/PathProxy}
  11009. */
  11010. beginPath: function (ctx) {
  11011. this._ctx = ctx;
  11012. ctx && ctx.beginPath();
  11013. ctx && (this.dpr = ctx.dpr);
  11014. // Reset
  11015. if (this._saveData) {
  11016. this._len = 0;
  11017. }
  11018. if (this._lineDash) {
  11019. this._lineDash = null;
  11020. this._dashOffset = 0;
  11021. }
  11022. return this;
  11023. },
  11024. /**
  11025. * @param {number} x
  11026. * @param {number} y
  11027. * @return {module:zrender/core/PathProxy}
  11028. */
  11029. moveTo: function (x, y) {
  11030. this.addData(CMD.M, x, y);
  11031. this._ctx && this._ctx.moveTo(x, y);
  11032. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11033. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11034. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11035. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11036. this._x0 = x;
  11037. this._y0 = y;
  11038. this._xi = x;
  11039. this._yi = y;
  11040. return this;
  11041. },
  11042. /**
  11043. * @param {number} x
  11044. * @param {number} y
  11045. * @return {module:zrender/core/PathProxy}
  11046. */
  11047. lineTo: function (x, y) {
  11048. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11049. || mathAbs(y - this._yi) > this._uy
  11050. // Force draw the first segment
  11051. || this._len < 5;
  11052. this.addData(CMD.L, x, y);
  11053. if (this._ctx && exceedUnit) {
  11054. this._needsDash() ? this._dashedLineTo(x, y)
  11055. : this._ctx.lineTo(x, y);
  11056. }
  11057. if (exceedUnit) {
  11058. this._xi = x;
  11059. this._yi = y;
  11060. }
  11061. return this;
  11062. },
  11063. /**
  11064. * @param {number} x1
  11065. * @param {number} y1
  11066. * @param {number} x2
  11067. * @param {number} y2
  11068. * @param {number} x3
  11069. * @param {number} y3
  11070. * @return {module:zrender/core/PathProxy}
  11071. */
  11072. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11073. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11074. if (this._ctx) {
  11075. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11076. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11077. }
  11078. this._xi = x3;
  11079. this._yi = y3;
  11080. return this;
  11081. },
  11082. /**
  11083. * @param {number} x1
  11084. * @param {number} y1
  11085. * @param {number} x2
  11086. * @param {number} y2
  11087. * @return {module:zrender/core/PathProxy}
  11088. */
  11089. quadraticCurveTo: function (x1, y1, x2, y2) {
  11090. this.addData(CMD.Q, x1, y1, x2, y2);
  11091. if (this._ctx) {
  11092. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11093. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11094. }
  11095. this._xi = x2;
  11096. this._yi = y2;
  11097. return this;
  11098. },
  11099. /**
  11100. * @param {number} cx
  11101. * @param {number} cy
  11102. * @param {number} r
  11103. * @param {number} startAngle
  11104. * @param {number} endAngle
  11105. * @param {boolean} anticlockwise
  11106. * @return {module:zrender/core/PathProxy}
  11107. */
  11108. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11109. this.addData(
  11110. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11111. );
  11112. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11113. this._xi = mathCos$1(endAngle) * r + cx;
  11114. this._yi = mathSin$1(endAngle) * r + cy;
  11115. return this;
  11116. },
  11117. // TODO
  11118. arcTo: function (x1, y1, x2, y2, radius) {
  11119. if (this._ctx) {
  11120. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11121. }
  11122. return this;
  11123. },
  11124. // TODO
  11125. rect: function (x, y, w, h) {
  11126. this._ctx && this._ctx.rect(x, y, w, h);
  11127. this.addData(CMD.R, x, y, w, h);
  11128. return this;
  11129. },
  11130. /**
  11131. * @return {module:zrender/core/PathProxy}
  11132. */
  11133. closePath: function () {
  11134. this.addData(CMD.Z);
  11135. var ctx = this._ctx;
  11136. var x0 = this._x0;
  11137. var y0 = this._y0;
  11138. if (ctx) {
  11139. this._needsDash() && this._dashedLineTo(x0, y0);
  11140. ctx.closePath();
  11141. }
  11142. this._xi = x0;
  11143. this._yi = y0;
  11144. return this;
  11145. },
  11146. /**
  11147. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11148. * stroke 同样
  11149. * @param {CanvasRenderingContext2D} ctx
  11150. * @return {module:zrender/core/PathProxy}
  11151. */
  11152. fill: function (ctx) {
  11153. ctx && ctx.fill();
  11154. this.toStatic();
  11155. },
  11156. /**
  11157. * @param {CanvasRenderingContext2D} ctx
  11158. * @return {module:zrender/core/PathProxy}
  11159. */
  11160. stroke: function (ctx) {
  11161. ctx && ctx.stroke();
  11162. this.toStatic();
  11163. },
  11164. /**
  11165. * 必须在其它绘制命令前调用
  11166. * Must be invoked before all other path drawing methods
  11167. * @return {module:zrender/core/PathProxy}
  11168. */
  11169. setLineDash: function (lineDash) {
  11170. if (lineDash instanceof Array) {
  11171. this._lineDash = lineDash;
  11172. this._dashIdx = 0;
  11173. var lineDashSum = 0;
  11174. for (var i = 0; i < lineDash.length; i++) {
  11175. lineDashSum += lineDash[i];
  11176. }
  11177. this._dashSum = lineDashSum;
  11178. }
  11179. return this;
  11180. },
  11181. /**
  11182. * 必须在其它绘制命令前调用
  11183. * Must be invoked before all other path drawing methods
  11184. * @return {module:zrender/core/PathProxy}
  11185. */
  11186. setLineDashOffset: function (offset) {
  11187. this._dashOffset = offset;
  11188. return this;
  11189. },
  11190. /**
  11191. *
  11192. * @return {boolean}
  11193. */
  11194. len: function () {
  11195. return this._len;
  11196. },
  11197. /**
  11198. * 直接设置 Path 数据
  11199. */
  11200. setData: function (data) {
  11201. var len$$1 = data.length;
  11202. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11203. this.data = new Float32Array(len$$1);
  11204. }
  11205. for (var i = 0; i < len$$1; i++) {
  11206. this.data[i] = data[i];
  11207. }
  11208. this._len = len$$1;
  11209. },
  11210. /**
  11211. * 添加子路径
  11212. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11213. */
  11214. appendPath: function (path) {
  11215. if (!(path instanceof Array)) {
  11216. path = [path];
  11217. }
  11218. var len$$1 = path.length;
  11219. var appendSize = 0;
  11220. var offset = this._len;
  11221. for (var i = 0; i < len$$1; i++) {
  11222. appendSize += path[i].len();
  11223. }
  11224. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11225. this.data = new Float32Array(offset + appendSize);
  11226. }
  11227. for (var i = 0; i < len$$1; i++) {
  11228. var appendPathData = path[i].data;
  11229. for (var k = 0; k < appendPathData.length; k++) {
  11230. this.data[offset++] = appendPathData[k];
  11231. }
  11232. }
  11233. this._len = offset;
  11234. },
  11235. /**
  11236. * 填充 Path 数据。
  11237. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11238. */
  11239. addData: function (cmd) {
  11240. if (!this._saveData) {
  11241. return;
  11242. }
  11243. var data = this.data;
  11244. if (this._len + arguments.length > data.length) {
  11245. // 因为之前的数组已经转换成静态的 Float32Array
  11246. // 所以不够用时需要扩展一个新的动态数组
  11247. this._expandData();
  11248. data = this.data;
  11249. }
  11250. for (var i = 0; i < arguments.length; i++) {
  11251. data[this._len++] = arguments[i];
  11252. }
  11253. this._prevCmd = cmd;
  11254. },
  11255. _expandData: function () {
  11256. // Only if data is Float32Array
  11257. if (!(this.data instanceof Array)) {
  11258. var newData = [];
  11259. for (var i = 0; i < this._len; i++) {
  11260. newData[i] = this.data[i];
  11261. }
  11262. this.data = newData;
  11263. }
  11264. },
  11265. /**
  11266. * If needs js implemented dashed line
  11267. * @return {boolean}
  11268. * @private
  11269. */
  11270. _needsDash: function () {
  11271. return this._lineDash;
  11272. },
  11273. _dashedLineTo: function (x1, y1) {
  11274. var dashSum = this._dashSum;
  11275. var offset = this._dashOffset;
  11276. var lineDash = this._lineDash;
  11277. var ctx = this._ctx;
  11278. var x0 = this._xi;
  11279. var y0 = this._yi;
  11280. var dx = x1 - x0;
  11281. var dy = y1 - y0;
  11282. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11283. var x = x0;
  11284. var y = y0;
  11285. var dash;
  11286. var nDash = lineDash.length;
  11287. var idx;
  11288. dx /= dist$$1;
  11289. dy /= dist$$1;
  11290. if (offset < 0) {
  11291. // Convert to positive offset
  11292. offset = dashSum + offset;
  11293. }
  11294. offset %= dashSum;
  11295. x -= offset * dx;
  11296. y -= offset * dy;
  11297. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11298. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11299. idx = this._dashIdx;
  11300. dash = lineDash[idx];
  11301. x += dx * dash;
  11302. y += dy * dash;
  11303. this._dashIdx = (idx + 1) % nDash;
  11304. // Skip positive offset
  11305. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11306. continue;
  11307. }
  11308. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11309. dx >= 0 ? mathMin$1(x, x1) : mathMax$1(x, x1),
  11310. dy >= 0 ? mathMin$1(y, y1) : mathMax$1(y, y1)
  11311. );
  11312. }
  11313. // Offset for next lineTo
  11314. dx = x - x1;
  11315. dy = y - y1;
  11316. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11317. },
  11318. // Not accurate dashed line to
  11319. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11320. var dashSum = this._dashSum;
  11321. var offset = this._dashOffset;
  11322. var lineDash = this._lineDash;
  11323. var ctx = this._ctx;
  11324. var x0 = this._xi;
  11325. var y0 = this._yi;
  11326. var t;
  11327. var dx;
  11328. var dy;
  11329. var cubicAt$$1 = cubicAt;
  11330. var bezierLen = 0;
  11331. var idx = this._dashIdx;
  11332. var nDash = lineDash.length;
  11333. var x;
  11334. var y;
  11335. var tmpLen = 0;
  11336. if (offset < 0) {
  11337. // Convert to positive offset
  11338. offset = dashSum + offset;
  11339. }
  11340. offset %= dashSum;
  11341. // Bezier approx length
  11342. for (t = 0; t < 1; t += 0.1) {
  11343. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11344. - cubicAt$$1(x0, x1, x2, x3, t);
  11345. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11346. - cubicAt$$1(y0, y1, y2, y3, t);
  11347. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11348. }
  11349. // Find idx after add offset
  11350. for (; idx < nDash; idx++) {
  11351. tmpLen += lineDash[idx];
  11352. if (tmpLen > offset) {
  11353. break;
  11354. }
  11355. }
  11356. t = (tmpLen - offset) / bezierLen;
  11357. while (t <= 1) {
  11358. x = cubicAt$$1(x0, x1, x2, x3, t);
  11359. y = cubicAt$$1(y0, y1, y2, y3, t);
  11360. // Use line to approximate dashed bezier
  11361. // Bad result if dash is long
  11362. idx % 2 ? ctx.moveTo(x, y)
  11363. : ctx.lineTo(x, y);
  11364. t += lineDash[idx] / bezierLen;
  11365. idx = (idx + 1) % nDash;
  11366. }
  11367. // Finish the last segment and calculate the new offset
  11368. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11369. dx = x3 - x;
  11370. dy = y3 - y;
  11371. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11372. },
  11373. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11374. // Convert quadratic to cubic using degree elevation
  11375. var x3 = x2;
  11376. var y3 = y2;
  11377. x2 = (x2 + 2 * x1) / 3;
  11378. y2 = (y2 + 2 * y1) / 3;
  11379. x1 = (this._xi + 2 * x1) / 3;
  11380. y1 = (this._yi + 2 * y1) / 3;
  11381. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11382. },
  11383. /**
  11384. * 转成静态的 Float32Array 减少堆内存占用
  11385. * Convert dynamic array to static Float32Array
  11386. */
  11387. toStatic: function () {
  11388. var data = this.data;
  11389. if (data instanceof Array) {
  11390. data.length = this._len;
  11391. if (hasTypedArray) {
  11392. this.data = new Float32Array(data);
  11393. }
  11394. }
  11395. },
  11396. /**
  11397. * @return {module:zrender/core/BoundingRect}
  11398. */
  11399. getBoundingRect: function () {
  11400. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11401. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11402. var data = this.data;
  11403. var xi = 0;
  11404. var yi = 0;
  11405. var x0 = 0;
  11406. var y0 = 0;
  11407. for (var i = 0; i < data.length;) {
  11408. var cmd = data[i++];
  11409. if (i === 1) {
  11410. // 如果第一个命令是 L, C, Q
  11411. // 则 previous point 同绘制命令的第一个 point
  11412. //
  11413. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11414. xi = data[i];
  11415. yi = data[i + 1];
  11416. x0 = xi;
  11417. y0 = yi;
  11418. }
  11419. switch (cmd) {
  11420. case CMD.M:
  11421. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11422. // 在 closePath 的时候使用
  11423. x0 = data[i++];
  11424. y0 = data[i++];
  11425. xi = x0;
  11426. yi = y0;
  11427. min2[0] = x0;
  11428. min2[1] = y0;
  11429. max2[0] = x0;
  11430. max2[1] = y0;
  11431. break;
  11432. case CMD.L:
  11433. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11434. xi = data[i++];
  11435. yi = data[i++];
  11436. break;
  11437. case CMD.C:
  11438. fromCubic(
  11439. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11440. min2, max2
  11441. );
  11442. xi = data[i++];
  11443. yi = data[i++];
  11444. break;
  11445. case CMD.Q:
  11446. fromQuadratic(
  11447. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11448. min2, max2
  11449. );
  11450. xi = data[i++];
  11451. yi = data[i++];
  11452. break;
  11453. case CMD.A:
  11454. // TODO Arc 判断的开销比较大
  11455. var cx = data[i++];
  11456. var cy = data[i++];
  11457. var rx = data[i++];
  11458. var ry = data[i++];
  11459. var startAngle = data[i++];
  11460. var endAngle = data[i++] + startAngle;
  11461. // TODO Arc 旋转
  11462. i += 1;
  11463. var anticlockwise = 1 - data[i++];
  11464. if (i === 1) {
  11465. // 直接使用 arc 命令
  11466. // 第一个命令起点还未定义
  11467. x0 = mathCos$1(startAngle) * rx + cx;
  11468. y0 = mathSin$1(startAngle) * ry + cy;
  11469. }
  11470. fromArc(
  11471. cx, cy, rx, ry, startAngle, endAngle,
  11472. anticlockwise, min2, max2
  11473. );
  11474. xi = mathCos$1(endAngle) * rx + cx;
  11475. yi = mathSin$1(endAngle) * ry + cy;
  11476. break;
  11477. case CMD.R:
  11478. x0 = xi = data[i++];
  11479. y0 = yi = data[i++];
  11480. var width = data[i++];
  11481. var height = data[i++];
  11482. // Use fromLine
  11483. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11484. break;
  11485. case CMD.Z:
  11486. xi = x0;
  11487. yi = y0;
  11488. break;
  11489. }
  11490. // Union
  11491. min(min$1, min$1, min2);
  11492. max(max$1, max$1, max2);
  11493. }
  11494. // No data
  11495. if (i === 0) {
  11496. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11497. }
  11498. return new BoundingRect(
  11499. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11500. );
  11501. },
  11502. /**
  11503. * Rebuild path from current data
  11504. * Rebuild path will not consider javascript implemented line dash.
  11505. * @param {CanvasRenderingContext2D} ctx
  11506. */
  11507. rebuildPath: function (ctx) {
  11508. var d = this.data;
  11509. var x0;
  11510. var y0;
  11511. var xi;
  11512. var yi;
  11513. var x;
  11514. var y;
  11515. var ux = this._ux;
  11516. var uy = this._uy;
  11517. var len$$1 = this._len;
  11518. for (var i = 0; i < len$$1;) {
  11519. var cmd = d[i++];
  11520. if (i === 1) {
  11521. // 如果第一个命令是 L, C, Q
  11522. // 则 previous point 同绘制命令的第一个 point
  11523. //
  11524. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11525. xi = d[i];
  11526. yi = d[i + 1];
  11527. x0 = xi;
  11528. y0 = yi;
  11529. }
  11530. switch (cmd) {
  11531. case CMD.M:
  11532. x0 = xi = d[i++];
  11533. y0 = yi = d[i++];
  11534. ctx.moveTo(xi, yi);
  11535. break;
  11536. case CMD.L:
  11537. x = d[i++];
  11538. y = d[i++];
  11539. // Not draw too small seg between
  11540. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11541. ctx.lineTo(x, y);
  11542. xi = x;
  11543. yi = y;
  11544. }
  11545. break;
  11546. case CMD.C:
  11547. ctx.bezierCurveTo(
  11548. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11549. );
  11550. xi = d[i - 2];
  11551. yi = d[i - 1];
  11552. break;
  11553. case CMD.Q:
  11554. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11555. xi = d[i - 2];
  11556. yi = d[i - 1];
  11557. break;
  11558. case CMD.A:
  11559. var cx = d[i++];
  11560. var cy = d[i++];
  11561. var rx = d[i++];
  11562. var ry = d[i++];
  11563. var theta = d[i++];
  11564. var dTheta = d[i++];
  11565. var psi = d[i++];
  11566. var fs = d[i++];
  11567. var r = (rx > ry) ? rx : ry;
  11568. var scaleX = (rx > ry) ? 1 : rx / ry;
  11569. var scaleY = (rx > ry) ? ry / rx : 1;
  11570. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11571. var endAngle = theta + dTheta;
  11572. if (isEllipse) {
  11573. ctx.translate(cx, cy);
  11574. ctx.rotate(psi);
  11575. ctx.scale(scaleX, scaleY);
  11576. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11577. ctx.scale(1 / scaleX, 1 / scaleY);
  11578. ctx.rotate(-psi);
  11579. ctx.translate(-cx, -cy);
  11580. }
  11581. else {
  11582. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11583. }
  11584. if (i === 1) {
  11585. // 直接使用 arc 命令
  11586. // 第一个命令起点还未定义
  11587. x0 = mathCos$1(theta) * rx + cx;
  11588. y0 = mathSin$1(theta) * ry + cy;
  11589. }
  11590. xi = mathCos$1(endAngle) * rx + cx;
  11591. yi = mathSin$1(endAngle) * ry + cy;
  11592. break;
  11593. case CMD.R:
  11594. x0 = xi = d[i];
  11595. y0 = yi = d[i + 1];
  11596. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11597. break;
  11598. case CMD.Z:
  11599. ctx.closePath();
  11600. xi = x0;
  11601. yi = y0;
  11602. }
  11603. }
  11604. }
  11605. };
  11606. PathProxy.CMD = CMD;
  11607. /**
  11608. * 线段包含判断
  11609. * @param {number} x0
  11610. * @param {number} y0
  11611. * @param {number} x1
  11612. * @param {number} y1
  11613. * @param {number} lineWidth
  11614. * @param {number} x
  11615. * @param {number} y
  11616. * @return {boolean}
  11617. */
  11618. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11619. if (lineWidth === 0) {
  11620. return false;
  11621. }
  11622. var _l = lineWidth;
  11623. var _a = 0;
  11624. var _b = x0;
  11625. // Quick reject
  11626. if (
  11627. (y > y0 + _l && y > y1 + _l)
  11628. || (y < y0 - _l && y < y1 - _l)
  11629. || (x > x0 + _l && x > x1 + _l)
  11630. || (x < x0 - _l && x < x1 - _l)
  11631. ) {
  11632. return false;
  11633. }
  11634. if (x0 !== x1) {
  11635. _a = (y0 - y1) / (x0 - x1);
  11636. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  11637. }
  11638. else {
  11639. return Math.abs(x - x0) <= _l / 2;
  11640. }
  11641. var tmp = _a * x - y + _b;
  11642. var _s = tmp * tmp / (_a * _a + 1);
  11643. return _s <= _l / 2 * _l / 2;
  11644. }
  11645. /**
  11646. * 三次贝塞尔曲线描边包含判断
  11647. * @param {number} x0
  11648. * @param {number} y0
  11649. * @param {number} x1
  11650. * @param {number} y1
  11651. * @param {number} x2
  11652. * @param {number} y2
  11653. * @param {number} x3
  11654. * @param {number} y3
  11655. * @param {number} lineWidth
  11656. * @param {number} x
  11657. * @param {number} y
  11658. * @return {boolean}
  11659. */
  11660. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11661. if (lineWidth === 0) {
  11662. return false;
  11663. }
  11664. var _l = lineWidth;
  11665. // Quick reject
  11666. if (
  11667. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11668. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11669. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11670. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11671. ) {
  11672. return false;
  11673. }
  11674. var d = cubicProjectPoint(
  11675. x0, y0, x1, y1, x2, y2, x3, y3,
  11676. x, y, null
  11677. );
  11678. return d <= _l / 2;
  11679. }
  11680. /**
  11681. * 二次贝塞尔曲线描边包含判断
  11682. * @param {number} x0
  11683. * @param {number} y0
  11684. * @param {number} x1
  11685. * @param {number} y1
  11686. * @param {number} x2
  11687. * @param {number} y2
  11688. * @param {number} lineWidth
  11689. * @param {number} x
  11690. * @param {number} y
  11691. * @return {boolean}
  11692. */
  11693. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11694. if (lineWidth === 0) {
  11695. return false;
  11696. }
  11697. var _l = lineWidth;
  11698. // Quick reject
  11699. if (
  11700. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11701. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11702. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11703. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11704. ) {
  11705. return false;
  11706. }
  11707. var d = quadraticProjectPoint(
  11708. x0, y0, x1, y1, x2, y2,
  11709. x, y, null
  11710. );
  11711. return d <= _l / 2;
  11712. }
  11713. var PI2$3 = Math.PI * 2;
  11714. function normalizeRadian(angle) {
  11715. angle %= PI2$3;
  11716. if (angle < 0) {
  11717. angle += PI2$3;
  11718. }
  11719. return angle;
  11720. }
  11721. var PI2$2 = Math.PI * 2;
  11722. /**
  11723. * 圆弧描边包含判断
  11724. * @param {number} cx
  11725. * @param {number} cy
  11726. * @param {number} r
  11727. * @param {number} startAngle
  11728. * @param {number} endAngle
  11729. * @param {boolean} anticlockwise
  11730. * @param {number} lineWidth
  11731. * @param {number} x
  11732. * @param {number} y
  11733. * @return {Boolean}
  11734. */
  11735. function containStroke$4(
  11736. cx, cy, r, startAngle, endAngle, anticlockwise,
  11737. lineWidth, x, y
  11738. ) {
  11739. if (lineWidth === 0) {
  11740. return false;
  11741. }
  11742. var _l = lineWidth;
  11743. x -= cx;
  11744. y -= cy;
  11745. var d = Math.sqrt(x * x + y * y);
  11746. if ((d - _l > r) || (d + _l < r)) {
  11747. return false;
  11748. }
  11749. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11750. // Is a circle
  11751. return true;
  11752. }
  11753. if (anticlockwise) {
  11754. var tmp = startAngle;
  11755. startAngle = normalizeRadian(endAngle);
  11756. endAngle = normalizeRadian(tmp);
  11757. }
  11758. else {
  11759. startAngle = normalizeRadian(startAngle);
  11760. endAngle = normalizeRadian(endAngle);
  11761. }
  11762. if (startAngle > endAngle) {
  11763. endAngle += PI2$2;
  11764. }
  11765. var angle = Math.atan2(y, x);
  11766. if (angle < 0) {
  11767. angle += PI2$2;
  11768. }
  11769. return (angle >= startAngle && angle <= endAngle)
  11770. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11771. }
  11772. function windingLine(x0, y0, x1, y1, x, y) {
  11773. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11774. return 0;
  11775. }
  11776. // Ignore horizontal line
  11777. if (y1 === y0) {
  11778. return 0;
  11779. }
  11780. var dir = y1 < y0 ? 1 : -1;
  11781. var t = (y - y0) / (y1 - y0);
  11782. // Avoid winding error when intersection point is the connect point of two line of polygon
  11783. if (t === 1 || t === 0) {
  11784. dir = y1 < y0 ? 0.5 : -0.5;
  11785. }
  11786. var x_ = t * (x1 - x0) + x0;
  11787. // If (x, y) on the line, considered as "contain".
  11788. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11789. }
  11790. var CMD$1 = PathProxy.CMD;
  11791. var PI2$1 = Math.PI * 2;
  11792. var EPSILON$2 = 1e-4;
  11793. function isAroundEqual(a, b) {
  11794. return Math.abs(a - b) < EPSILON$2;
  11795. }
  11796. // 临时数组
  11797. var roots = [-1, -1, -1];
  11798. var extrema = [-1, -1];
  11799. function swapExtrema() {
  11800. var tmp = extrema[0];
  11801. extrema[0] = extrema[1];
  11802. extrema[1] = tmp;
  11803. }
  11804. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11805. // Quick reject
  11806. if (
  11807. (y > y0 && y > y1 && y > y2 && y > y3)
  11808. || (y < y0 && y < y1 && y < y2 && y < y3)
  11809. ) {
  11810. return 0;
  11811. }
  11812. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11813. if (nRoots === 0) {
  11814. return 0;
  11815. }
  11816. else {
  11817. var w = 0;
  11818. var nExtrema = -1;
  11819. var y0_;
  11820. var y1_;
  11821. for (var i = 0; i < nRoots; i++) {
  11822. var t = roots[i];
  11823. // Avoid winding error when intersection point is the connect point of two line of polygon
  11824. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11825. var x_ = cubicAt(x0, x1, x2, x3, t);
  11826. if (x_ < x) { // Quick reject
  11827. continue;
  11828. }
  11829. if (nExtrema < 0) {
  11830. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11831. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11832. swapExtrema();
  11833. }
  11834. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11835. if (nExtrema > 1) {
  11836. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11837. }
  11838. }
  11839. if (nExtrema === 2) {
  11840. // 分成三段单调函数
  11841. if (t < extrema[0]) {
  11842. w += y0_ < y0 ? unit : -unit;
  11843. }
  11844. else if (t < extrema[1]) {
  11845. w += y1_ < y0_ ? unit : -unit;
  11846. }
  11847. else {
  11848. w += y3 < y1_ ? unit : -unit;
  11849. }
  11850. }
  11851. else {
  11852. // 分成两段单调函数
  11853. if (t < extrema[0]) {
  11854. w += y0_ < y0 ? unit : -unit;
  11855. }
  11856. else {
  11857. w += y3 < y0_ ? unit : -unit;
  11858. }
  11859. }
  11860. }
  11861. return w;
  11862. }
  11863. }
  11864. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11865. // Quick reject
  11866. if (
  11867. (y > y0 && y > y1 && y > y2)
  11868. || (y < y0 && y < y1 && y < y2)
  11869. ) {
  11870. return 0;
  11871. }
  11872. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11873. if (nRoots === 0) {
  11874. return 0;
  11875. }
  11876. else {
  11877. var t = quadraticExtremum(y0, y1, y2);
  11878. if (t >= 0 && t <= 1) {
  11879. var w = 0;
  11880. var y_ = quadraticAt(y0, y1, y2, t);
  11881. for (var i = 0; i < nRoots; i++) {
  11882. // Remove one endpoint.
  11883. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11884. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11885. if (x_ < x) { // Quick reject
  11886. continue;
  11887. }
  11888. if (roots[i] < t) {
  11889. w += y_ < y0 ? unit : -unit;
  11890. }
  11891. else {
  11892. w += y2 < y_ ? unit : -unit;
  11893. }
  11894. }
  11895. return w;
  11896. }
  11897. else {
  11898. // Remove one endpoint.
  11899. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11900. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11901. if (x_ < x) { // Quick reject
  11902. return 0;
  11903. }
  11904. return y2 < y0 ? unit : -unit;
  11905. }
  11906. }
  11907. }
  11908. // TODO
  11909. // Arc 旋转
  11910. function windingArc(
  11911. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11912. ) {
  11913. y -= cy;
  11914. if (y > r || y < -r) {
  11915. return 0;
  11916. }
  11917. var tmp = Math.sqrt(r * r - y * y);
  11918. roots[0] = -tmp;
  11919. roots[1] = tmp;
  11920. var diff = Math.abs(startAngle - endAngle);
  11921. if (diff < 1e-4) {
  11922. return 0;
  11923. }
  11924. if (diff % PI2$1 < 1e-4) {
  11925. // Is a circle
  11926. startAngle = 0;
  11927. endAngle = PI2$1;
  11928. var dir = anticlockwise ? 1 : -1;
  11929. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11930. return dir;
  11931. }
  11932. else {
  11933. return 0;
  11934. }
  11935. }
  11936. if (anticlockwise) {
  11937. var tmp = startAngle;
  11938. startAngle = normalizeRadian(endAngle);
  11939. endAngle = normalizeRadian(tmp);
  11940. }
  11941. else {
  11942. startAngle = normalizeRadian(startAngle);
  11943. endAngle = normalizeRadian(endAngle);
  11944. }
  11945. if (startAngle > endAngle) {
  11946. endAngle += PI2$1;
  11947. }
  11948. var w = 0;
  11949. for (var i = 0; i < 2; i++) {
  11950. var x_ = roots[i];
  11951. if (x_ + cx > x) {
  11952. var angle = Math.atan2(y, x_);
  11953. var dir = anticlockwise ? 1 : -1;
  11954. if (angle < 0) {
  11955. angle = PI2$1 + angle;
  11956. }
  11957. if (
  11958. (angle >= startAngle && angle <= endAngle)
  11959. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  11960. ) {
  11961. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  11962. dir = -dir;
  11963. }
  11964. w += dir;
  11965. }
  11966. }
  11967. }
  11968. return w;
  11969. }
  11970. function containPath(data, lineWidth, isStroke, x, y) {
  11971. var w = 0;
  11972. var xi = 0;
  11973. var yi = 0;
  11974. var x0 = 0;
  11975. var y0 = 0;
  11976. for (var i = 0; i < data.length;) {
  11977. var cmd = data[i++];
  11978. // Begin a new subpath
  11979. if (cmd === CMD$1.M && i > 1) {
  11980. // Close previous subpath
  11981. if (!isStroke) {
  11982. w += windingLine(xi, yi, x0, y0, x, y);
  11983. }
  11984. // 如果被任何一个 subpath 包含
  11985. // if (w !== 0) {
  11986. // return true;
  11987. // }
  11988. }
  11989. if (i === 1) {
  11990. // 如果第一个命令是 L, C, Q
  11991. // 则 previous point 同绘制命令的第一个 point
  11992. //
  11993. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11994. xi = data[i];
  11995. yi = data[i + 1];
  11996. x0 = xi;
  11997. y0 = yi;
  11998. }
  11999. switch (cmd) {
  12000. case CMD$1.M:
  12001. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12002. // 在 closePath 的时候使用
  12003. x0 = data[i++];
  12004. y0 = data[i++];
  12005. xi = x0;
  12006. yi = y0;
  12007. break;
  12008. case CMD$1.L:
  12009. if (isStroke) {
  12010. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12011. return true;
  12012. }
  12013. }
  12014. else {
  12015. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12016. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12017. }
  12018. xi = data[i++];
  12019. yi = data[i++];
  12020. break;
  12021. case CMD$1.C:
  12022. if (isStroke) {
  12023. if (containStroke$2(xi, yi,
  12024. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12025. lineWidth, x, y
  12026. )) {
  12027. return true;
  12028. }
  12029. }
  12030. else {
  12031. w += windingCubic(
  12032. xi, yi,
  12033. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12034. x, y
  12035. ) || 0;
  12036. }
  12037. xi = data[i++];
  12038. yi = data[i++];
  12039. break;
  12040. case CMD$1.Q:
  12041. if (isStroke) {
  12042. if (containStroke$3(xi, yi,
  12043. data[i++], data[i++], data[i], data[i + 1],
  12044. lineWidth, x, y
  12045. )) {
  12046. return true;
  12047. }
  12048. }
  12049. else {
  12050. w += windingQuadratic(
  12051. xi, yi,
  12052. data[i++], data[i++], data[i], data[i + 1],
  12053. x, y
  12054. ) || 0;
  12055. }
  12056. xi = data[i++];
  12057. yi = data[i++];
  12058. break;
  12059. case CMD$1.A:
  12060. // TODO Arc 判断的开销比较大
  12061. var cx = data[i++];
  12062. var cy = data[i++];
  12063. var rx = data[i++];
  12064. var ry = data[i++];
  12065. var theta = data[i++];
  12066. var dTheta = data[i++];
  12067. // TODO Arc 旋转
  12068. i += 1;
  12069. var anticlockwise = 1 - data[i++];
  12070. var x1 = Math.cos(theta) * rx + cx;
  12071. var y1 = Math.sin(theta) * ry + cy;
  12072. // 不是直接使用 arc 命令
  12073. if (i > 1) {
  12074. w += windingLine(xi, yi, x1, y1, x, y);
  12075. }
  12076. else {
  12077. // 第一个命令起点还未定义
  12078. x0 = x1;
  12079. y0 = y1;
  12080. }
  12081. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12082. var _x = (x - cx) * ry / rx + cx;
  12083. if (isStroke) {
  12084. if (containStroke$4(
  12085. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12086. lineWidth, _x, y
  12087. )) {
  12088. return true;
  12089. }
  12090. }
  12091. else {
  12092. w += windingArc(
  12093. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12094. _x, y
  12095. );
  12096. }
  12097. xi = Math.cos(theta + dTheta) * rx + cx;
  12098. yi = Math.sin(theta + dTheta) * ry + cy;
  12099. break;
  12100. case CMD$1.R:
  12101. x0 = xi = data[i++];
  12102. y0 = yi = data[i++];
  12103. var width = data[i++];
  12104. var height = data[i++];
  12105. var x1 = x0 + width;
  12106. var y1 = y0 + height;
  12107. if (isStroke) {
  12108. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12109. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12110. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12111. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12112. ) {
  12113. return true;
  12114. }
  12115. }
  12116. else {
  12117. // FIXME Clockwise ?
  12118. w += windingLine(x1, y0, x1, y1, x, y);
  12119. w += windingLine(x0, y1, x0, y0, x, y);
  12120. }
  12121. break;
  12122. case CMD$1.Z:
  12123. if (isStroke) {
  12124. if (containStroke$1(
  12125. xi, yi, x0, y0, lineWidth, x, y
  12126. )) {
  12127. return true;
  12128. }
  12129. }
  12130. else {
  12131. // Close a subpath
  12132. w += windingLine(xi, yi, x0, y0, x, y);
  12133. // 如果被任何一个 subpath 包含
  12134. // FIXME subpaths may overlap
  12135. // if (w !== 0) {
  12136. // return true;
  12137. // }
  12138. }
  12139. xi = x0;
  12140. yi = y0;
  12141. break;
  12142. }
  12143. }
  12144. if (!isStroke && !isAroundEqual(yi, y0)) {
  12145. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12146. }
  12147. return w !== 0;
  12148. }
  12149. function contain(pathData, x, y) {
  12150. return containPath(pathData, 0, false, x, y);
  12151. }
  12152. function containStroke(pathData, lineWidth, x, y) {
  12153. return containPath(pathData, lineWidth, true, x, y);
  12154. }
  12155. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12156. var abs = Math.abs;
  12157. var pathProxyForDraw = new PathProxy(true);
  12158. /**
  12159. * @alias module:zrender/graphic/Path
  12160. * @extends module:zrender/graphic/Displayable
  12161. * @constructor
  12162. * @param {Object} opts
  12163. */
  12164. function Path(opts) {
  12165. Displayable.call(this, opts);
  12166. /**
  12167. * @type {module:zrender/core/PathProxy}
  12168. * @readOnly
  12169. */
  12170. this.path = null;
  12171. }
  12172. Path.prototype = {
  12173. constructor: Path,
  12174. type: 'path',
  12175. __dirtyPath: true,
  12176. strokeContainThreshold: 5,
  12177. // This item default to be false. But in map series in echarts,
  12178. // in order to improve performance, it should be set to true,
  12179. // so the shorty segment won't draw.
  12180. segmentIgnoreThreshold: 0,
  12181. /**
  12182. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12183. * @type {boolean}
  12184. */
  12185. subPixelOptimize: false,
  12186. brush: function (ctx, prevEl) {
  12187. var style = this.style;
  12188. var path = this.path || pathProxyForDraw;
  12189. var hasStroke = style.hasStroke();
  12190. var hasFill = style.hasFill();
  12191. var fill = style.fill;
  12192. var stroke = style.stroke;
  12193. var hasFillGradient = hasFill && !!(fill.colorStops);
  12194. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12195. var hasFillPattern = hasFill && !!(fill.image);
  12196. var hasStrokePattern = hasStroke && !!(stroke.image);
  12197. style.bind(ctx, this, prevEl);
  12198. this.setTransform(ctx);
  12199. if (this.__dirty) {
  12200. var rect;
  12201. // Update gradient because bounding rect may changed
  12202. if (hasFillGradient) {
  12203. rect = rect || this.getBoundingRect();
  12204. this._fillGradient = style.getGradient(ctx, fill, rect);
  12205. }
  12206. if (hasStrokeGradient) {
  12207. rect = rect || this.getBoundingRect();
  12208. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12209. }
  12210. }
  12211. // Use the gradient or pattern
  12212. if (hasFillGradient) {
  12213. // PENDING If may have affect the state
  12214. ctx.fillStyle = this._fillGradient;
  12215. }
  12216. else if (hasFillPattern) {
  12217. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12218. }
  12219. if (hasStrokeGradient) {
  12220. ctx.strokeStyle = this._strokeGradient;
  12221. }
  12222. else if (hasStrokePattern) {
  12223. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12224. }
  12225. var lineDash = style.lineDash;
  12226. var lineDashOffset = style.lineDashOffset;
  12227. var ctxLineDash = !!ctx.setLineDash;
  12228. // Update path sx, sy
  12229. var scale = this.getGlobalScale();
  12230. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold);
  12231. // Proxy context
  12232. // Rebuild path in following 2 cases
  12233. // 1. Path is dirty
  12234. // 2. Path needs javascript implemented lineDash stroking.
  12235. // In this case, lineDash information will not be saved in PathProxy
  12236. if (this.__dirtyPath
  12237. || (lineDash && !ctxLineDash && hasStroke)
  12238. ) {
  12239. path.beginPath(ctx);
  12240. // Setting line dash before build path
  12241. if (lineDash && !ctxLineDash) {
  12242. path.setLineDash(lineDash);
  12243. path.setLineDashOffset(lineDashOffset);
  12244. }
  12245. this.buildPath(path, this.shape, false);
  12246. // Clear path dirty flag
  12247. if (this.path) {
  12248. this.__dirtyPath = false;
  12249. }
  12250. }
  12251. else {
  12252. // Replay path building
  12253. ctx.beginPath();
  12254. this.path.rebuildPath(ctx);
  12255. }
  12256. if (hasFill) {
  12257. if (style.fillOpacity != null) {
  12258. var originalGlobalAlpha = ctx.globalAlpha;
  12259. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12260. path.fill(ctx);
  12261. ctx.globalAlpha = originalGlobalAlpha;
  12262. }
  12263. else {
  12264. path.fill(ctx);
  12265. }
  12266. }
  12267. if (lineDash && ctxLineDash) {
  12268. ctx.setLineDash(lineDash);
  12269. ctx.lineDashOffset = lineDashOffset;
  12270. }
  12271. if (hasStroke) {
  12272. if (style.strokeOpacity != null) {
  12273. var originalGlobalAlpha = ctx.globalAlpha;
  12274. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12275. path.stroke(ctx);
  12276. ctx.globalAlpha = originalGlobalAlpha;
  12277. }
  12278. else {
  12279. path.stroke(ctx);
  12280. }
  12281. }
  12282. if (lineDash && ctxLineDash) {
  12283. // PENDING
  12284. // Remove lineDash
  12285. ctx.setLineDash([]);
  12286. }
  12287. // Draw rect text
  12288. if (style.text != null) {
  12289. // Only restore transform when needs draw text.
  12290. this.restoreTransform(ctx);
  12291. this.drawRectText(ctx, this.getBoundingRect());
  12292. }
  12293. },
  12294. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12295. // Like in circle
  12296. buildPath: function (ctx, shapeCfg, inBundle) {},
  12297. createPathProxy: function () {
  12298. this.path = new PathProxy();
  12299. },
  12300. getBoundingRect: function () {
  12301. var rect = this._rect;
  12302. var style = this.style;
  12303. var needsUpdateRect = !rect;
  12304. if (needsUpdateRect) {
  12305. var path = this.path;
  12306. if (!path) {
  12307. // Create path on demand.
  12308. path = this.path = new PathProxy();
  12309. }
  12310. if (this.__dirtyPath) {
  12311. path.beginPath();
  12312. this.buildPath(path, this.shape, false);
  12313. }
  12314. rect = path.getBoundingRect();
  12315. }
  12316. this._rect = rect;
  12317. if (style.hasStroke()) {
  12318. // Needs update rect with stroke lineWidth when
  12319. // 1. Element changes scale or lineWidth
  12320. // 2. Shape is changed
  12321. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12322. if (this.__dirty || needsUpdateRect) {
  12323. rectWithStroke.copy(rect);
  12324. // FIXME Must after updateTransform
  12325. var w = style.lineWidth;
  12326. // PENDING, Min line width is needed when line is horizontal or vertical
  12327. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12328. // Only add extra hover lineWidth when there are no fill
  12329. if (!style.hasFill()) {
  12330. w = Math.max(w, this.strokeContainThreshold || 4);
  12331. }
  12332. // Consider line width
  12333. // Line scale can't be 0;
  12334. if (lineScale > 1e-10) {
  12335. rectWithStroke.width += w / lineScale;
  12336. rectWithStroke.height += w / lineScale;
  12337. rectWithStroke.x -= w / lineScale / 2;
  12338. rectWithStroke.y -= w / lineScale / 2;
  12339. }
  12340. }
  12341. // Return rect with stroke
  12342. return rectWithStroke;
  12343. }
  12344. return rect;
  12345. },
  12346. contain: function (x, y) {
  12347. var localPos = this.transformCoordToLocal(x, y);
  12348. var rect = this.getBoundingRect();
  12349. var style = this.style;
  12350. x = localPos[0];
  12351. y = localPos[1];
  12352. if (rect.contain(x, y)) {
  12353. var pathData = this.path.data;
  12354. if (style.hasStroke()) {
  12355. var lineWidth = style.lineWidth;
  12356. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12357. // Line scale can't be 0;
  12358. if (lineScale > 1e-10) {
  12359. // Only add extra hover lineWidth when there are no fill
  12360. if (!style.hasFill()) {
  12361. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12362. }
  12363. if (containStroke(
  12364. pathData, lineWidth / lineScale, x, y
  12365. )) {
  12366. return true;
  12367. }
  12368. }
  12369. }
  12370. if (style.hasFill()) {
  12371. return contain(pathData, x, y);
  12372. }
  12373. }
  12374. return false;
  12375. },
  12376. /**
  12377. * @param {boolean} dirtyPath
  12378. */
  12379. dirty: function (dirtyPath) {
  12380. if (dirtyPath == null) {
  12381. dirtyPath = true;
  12382. }
  12383. // Only mark dirty, not mark clean
  12384. if (dirtyPath) {
  12385. this.__dirtyPath = dirtyPath;
  12386. this._rect = null;
  12387. }
  12388. this.__dirty = this.__dirtyText = true;
  12389. this.__zr && this.__zr.refresh();
  12390. // Used as a clipping path
  12391. if (this.__clipTarget) {
  12392. this.__clipTarget.dirty();
  12393. }
  12394. },
  12395. /**
  12396. * Alias for animate('shape')
  12397. * @param {boolean} loop
  12398. */
  12399. animateShape: function (loop) {
  12400. return this.animate('shape', loop);
  12401. },
  12402. // Overwrite attrKV
  12403. attrKV: function (key, value) {
  12404. // FIXME
  12405. if (key === 'shape') {
  12406. this.setShape(value);
  12407. this.__dirtyPath = true;
  12408. this._rect = null;
  12409. }
  12410. else {
  12411. Displayable.prototype.attrKV.call(this, key, value);
  12412. }
  12413. },
  12414. /**
  12415. * @param {Object|string} key
  12416. * @param {*} value
  12417. */
  12418. setShape: function (key, value) {
  12419. var shape = this.shape;
  12420. // Path from string may not have shape
  12421. if (shape) {
  12422. if (isObject(key)) {
  12423. for (var name in key) {
  12424. if (key.hasOwnProperty(name)) {
  12425. shape[name] = key[name];
  12426. }
  12427. }
  12428. }
  12429. else {
  12430. shape[key] = value;
  12431. }
  12432. this.dirty(true);
  12433. }
  12434. return this;
  12435. },
  12436. getLineScale: function () {
  12437. var m = this.transform;
  12438. // Get the line scale.
  12439. // Determinant of `m` means how much the area is enlarged by the
  12440. // transformation. So its square root can be used as a scale factor
  12441. // for width.
  12442. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12443. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12444. : 1;
  12445. }
  12446. };
  12447. /**
  12448. * 扩展一个 Path element, 比如星形,圆等。
  12449. * Extend a path element
  12450. * @param {Object} props
  12451. * @param {string} props.type Path type
  12452. * @param {Function} props.init Initialize
  12453. * @param {Function} props.buildPath Overwrite buildPath method
  12454. * @param {Object} [props.style] Extended default style config
  12455. * @param {Object} [props.shape] Extended default shape config
  12456. */
  12457. Path.extend = function (defaults$$1) {
  12458. var Sub = function (opts) {
  12459. Path.call(this, opts);
  12460. if (defaults$$1.style) {
  12461. // Extend default style
  12462. this.style.extendFrom(defaults$$1.style, false);
  12463. }
  12464. // Extend default shape
  12465. var defaultShape = defaults$$1.shape;
  12466. if (defaultShape) {
  12467. this.shape = this.shape || {};
  12468. var thisShape = this.shape;
  12469. for (var name in defaultShape) {
  12470. if (
  12471. !thisShape.hasOwnProperty(name)
  12472. && defaultShape.hasOwnProperty(name)
  12473. ) {
  12474. thisShape[name] = defaultShape[name];
  12475. }
  12476. }
  12477. }
  12478. defaults$$1.init && defaults$$1.init.call(this, opts);
  12479. };
  12480. inherits(Sub, Path);
  12481. // FIXME 不能 extend position, rotation 等引用对象
  12482. for (var name in defaults$$1) {
  12483. // Extending prototype values and methods
  12484. if (name !== 'style' && name !== 'shape') {
  12485. Sub.prototype[name] = defaults$$1[name];
  12486. }
  12487. }
  12488. return Sub;
  12489. };
  12490. inherits(Path, Displayable);
  12491. var CMD$2 = PathProxy.CMD;
  12492. var points = [[], [], []];
  12493. var mathSqrt$3 = Math.sqrt;
  12494. var mathAtan2 = Math.atan2;
  12495. var transformPath = function (path, m) {
  12496. var data = path.data;
  12497. var cmd;
  12498. var nPoint;
  12499. var i;
  12500. var j;
  12501. var k;
  12502. var p;
  12503. var M = CMD$2.M;
  12504. var C = CMD$2.C;
  12505. var L = CMD$2.L;
  12506. var R = CMD$2.R;
  12507. var A = CMD$2.A;
  12508. var Q = CMD$2.Q;
  12509. for (i = 0, j = 0; i < data.length;) {
  12510. cmd = data[i++];
  12511. j = i;
  12512. nPoint = 0;
  12513. switch (cmd) {
  12514. case M:
  12515. nPoint = 1;
  12516. break;
  12517. case L:
  12518. nPoint = 1;
  12519. break;
  12520. case C:
  12521. nPoint = 3;
  12522. break;
  12523. case Q:
  12524. nPoint = 2;
  12525. break;
  12526. case A:
  12527. var x = m[4];
  12528. var y = m[5];
  12529. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12530. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12531. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12532. // cx
  12533. data[i] *= sx;
  12534. data[i++] += x;
  12535. // cy
  12536. data[i] *= sy;
  12537. data[i++] += y;
  12538. // Scale rx and ry
  12539. // FIXME Assume psi is 0 here
  12540. data[i++] *= sx;
  12541. data[i++] *= sy;
  12542. // Start angle
  12543. data[i++] += angle;
  12544. // end angle
  12545. data[i++] += angle;
  12546. // FIXME psi
  12547. i += 2;
  12548. j = i;
  12549. break;
  12550. case R:
  12551. // x0, y0
  12552. p[0] = data[i++];
  12553. p[1] = data[i++];
  12554. applyTransform(p, p, m);
  12555. data[j++] = p[0];
  12556. data[j++] = p[1];
  12557. // x1, y1
  12558. p[0] += data[i++];
  12559. p[1] += data[i++];
  12560. applyTransform(p, p, m);
  12561. data[j++] = p[0];
  12562. data[j++] = p[1];
  12563. }
  12564. for (k = 0; k < nPoint; k++) {
  12565. var p = points[k];
  12566. p[0] = data[i++];
  12567. p[1] = data[i++];
  12568. applyTransform(p, p, m);
  12569. // Write back
  12570. data[j++] = p[0];
  12571. data[j++] = p[1];
  12572. }
  12573. }
  12574. };
  12575. // command chars
  12576. // var cc = [
  12577. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12578. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12579. // ];
  12580. var mathSqrt = Math.sqrt;
  12581. var mathSin = Math.sin;
  12582. var mathCos = Math.cos;
  12583. var PI = Math.PI;
  12584. var vMag = function (v) {
  12585. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12586. };
  12587. var vRatio = function (u, v) {
  12588. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12589. };
  12590. var vAngle = function (u, v) {
  12591. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12592. * Math.acos(vRatio(u, v));
  12593. };
  12594. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12595. var psi = psiDeg * (PI / 180.0);
  12596. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12597. + mathSin(psi) * (y1 - y2) / 2.0;
  12598. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12599. + mathCos(psi) * (y1 - y2) / 2.0;
  12600. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12601. if (lambda > 1) {
  12602. rx *= mathSqrt(lambda);
  12603. ry *= mathSqrt(lambda);
  12604. }
  12605. var f = (fa === fs ? -1 : 1)
  12606. * mathSqrt((((rx * rx) * (ry * ry))
  12607. - ((rx * rx) * (yp * yp))
  12608. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12609. + (ry * ry) * (xp * xp))
  12610. ) || 0;
  12611. var cxp = f * rx * yp / ry;
  12612. var cyp = f * -ry * xp / rx;
  12613. var cx = (x1 + x2) / 2.0
  12614. + mathCos(psi) * cxp
  12615. - mathSin(psi) * cyp;
  12616. var cy = (y1 + y2) / 2.0
  12617. + mathSin(psi) * cxp
  12618. + mathCos(psi) * cyp;
  12619. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12620. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12621. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12622. var dTheta = vAngle(u, v);
  12623. if (vRatio(u, v) <= -1) {
  12624. dTheta = PI;
  12625. }
  12626. if (vRatio(u, v) >= 1) {
  12627. dTheta = 0;
  12628. }
  12629. if (fs === 0 && dTheta > 0) {
  12630. dTheta = dTheta - 2 * PI;
  12631. }
  12632. if (fs === 1 && dTheta < 0) {
  12633. dTheta = dTheta + 2 * PI;
  12634. }
  12635. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12636. }
  12637. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12638. // Consider case:
  12639. // (1) delimiter can be comma or space, where continuous commas
  12640. // or spaces should be seen as one comma.
  12641. // (2) value can be like:
  12642. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12643. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12644. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12645. // var valueSplitReg = /[\s,]+/;
  12646. function createPathProxyFromString(data) {
  12647. if (!data) {
  12648. return new PathProxy();
  12649. }
  12650. // var data = data.replace(/-/g, ' -')
  12651. // .replace(/ /g, ' ')
  12652. // .replace(/ /g, ',')
  12653. // .replace(/,,/g, ',');
  12654. // var n;
  12655. // create pipes so that we can split the data
  12656. // for (n = 0; n < cc.length; n++) {
  12657. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12658. // }
  12659. // data = data.replace(/-/g, ',-');
  12660. // create array
  12661. // var arr = cs.split('|');
  12662. // init context point
  12663. var cpx = 0;
  12664. var cpy = 0;
  12665. var subpathX = cpx;
  12666. var subpathY = cpy;
  12667. var prevCmd;
  12668. var path = new PathProxy();
  12669. var CMD = PathProxy.CMD;
  12670. // commandReg.lastIndex = 0;
  12671. // var cmdResult;
  12672. // while ((cmdResult = commandReg.exec(data)) != null) {
  12673. // var cmdStr = cmdResult[1];
  12674. // var cmdContent = cmdResult[2];
  12675. var cmdList = data.match(commandReg);
  12676. for (var l = 0; l < cmdList.length; l++) {
  12677. var cmdText = cmdList[l];
  12678. var cmdStr = cmdText.charAt(0);
  12679. var cmd;
  12680. // String#split is faster a little bit than String#replace or RegExp#exec.
  12681. // var p = cmdContent.split(valueSplitReg);
  12682. // var pLen = 0;
  12683. // for (var i = 0; i < p.length; i++) {
  12684. // // '' and other invalid str => NaN
  12685. // var val = parseFloat(p[i]);
  12686. // !isNaN(val) && (p[pLen++] = val);
  12687. // }
  12688. var p = cmdText.match(numberReg) || [];
  12689. var pLen = p.length;
  12690. for (var i = 0; i < pLen; i++) {
  12691. p[i] = parseFloat(p[i]);
  12692. }
  12693. var off = 0;
  12694. while (off < pLen) {
  12695. var ctlPtx;
  12696. var ctlPty;
  12697. var rx;
  12698. var ry;
  12699. var psi;
  12700. var fa;
  12701. var fs;
  12702. var x1 = cpx;
  12703. var y1 = cpy;
  12704. // convert l, H, h, V, and v to L
  12705. switch (cmdStr) {
  12706. case 'l':
  12707. cpx += p[off++];
  12708. cpy += p[off++];
  12709. cmd = CMD.L;
  12710. path.addData(cmd, cpx, cpy);
  12711. break;
  12712. case 'L':
  12713. cpx = p[off++];
  12714. cpy = p[off++];
  12715. cmd = CMD.L;
  12716. path.addData(cmd, cpx, cpy);
  12717. break;
  12718. case 'm':
  12719. cpx += p[off++];
  12720. cpy += p[off++];
  12721. cmd = CMD.M;
  12722. path.addData(cmd, cpx, cpy);
  12723. subpathX = cpx;
  12724. subpathY = cpy;
  12725. cmdStr = 'l';
  12726. break;
  12727. case 'M':
  12728. cpx = p[off++];
  12729. cpy = p[off++];
  12730. cmd = CMD.M;
  12731. path.addData(cmd, cpx, cpy);
  12732. subpathX = cpx;
  12733. subpathY = cpy;
  12734. cmdStr = 'L';
  12735. break;
  12736. case 'h':
  12737. cpx += p[off++];
  12738. cmd = CMD.L;
  12739. path.addData(cmd, cpx, cpy);
  12740. break;
  12741. case 'H':
  12742. cpx = p[off++];
  12743. cmd = CMD.L;
  12744. path.addData(cmd, cpx, cpy);
  12745. break;
  12746. case 'v':
  12747. cpy += p[off++];
  12748. cmd = CMD.L;
  12749. path.addData(cmd, cpx, cpy);
  12750. break;
  12751. case 'V':
  12752. cpy = p[off++];
  12753. cmd = CMD.L;
  12754. path.addData(cmd, cpx, cpy);
  12755. break;
  12756. case 'C':
  12757. cmd = CMD.C;
  12758. path.addData(
  12759. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12760. );
  12761. cpx = p[off - 2];
  12762. cpy = p[off - 1];
  12763. break;
  12764. case 'c':
  12765. cmd = CMD.C;
  12766. path.addData(
  12767. cmd,
  12768. p[off++] + cpx, p[off++] + cpy,
  12769. p[off++] + cpx, p[off++] + cpy,
  12770. p[off++] + cpx, p[off++] + cpy
  12771. );
  12772. cpx += p[off - 2];
  12773. cpy += p[off - 1];
  12774. break;
  12775. case 'S':
  12776. ctlPtx = cpx;
  12777. ctlPty = cpy;
  12778. var len = path.len();
  12779. var pathData = path.data;
  12780. if (prevCmd === CMD.C) {
  12781. ctlPtx += cpx - pathData[len - 4];
  12782. ctlPty += cpy - pathData[len - 3];
  12783. }
  12784. cmd = CMD.C;
  12785. x1 = p[off++];
  12786. y1 = p[off++];
  12787. cpx = p[off++];
  12788. cpy = p[off++];
  12789. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12790. break;
  12791. case 's':
  12792. ctlPtx = cpx;
  12793. ctlPty = cpy;
  12794. var len = path.len();
  12795. var pathData = path.data;
  12796. if (prevCmd === CMD.C) {
  12797. ctlPtx += cpx - pathData[len - 4];
  12798. ctlPty += cpy - pathData[len - 3];
  12799. }
  12800. cmd = CMD.C;
  12801. x1 = cpx + p[off++];
  12802. y1 = cpy + p[off++];
  12803. cpx += p[off++];
  12804. cpy += p[off++];
  12805. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12806. break;
  12807. case 'Q':
  12808. x1 = p[off++];
  12809. y1 = p[off++];
  12810. cpx = p[off++];
  12811. cpy = p[off++];
  12812. cmd = CMD.Q;
  12813. path.addData(cmd, x1, y1, cpx, cpy);
  12814. break;
  12815. case 'q':
  12816. x1 = p[off++] + cpx;
  12817. y1 = p[off++] + cpy;
  12818. cpx += p[off++];
  12819. cpy += p[off++];
  12820. cmd = CMD.Q;
  12821. path.addData(cmd, x1, y1, cpx, cpy);
  12822. break;
  12823. case 'T':
  12824. ctlPtx = cpx;
  12825. ctlPty = cpy;
  12826. var len = path.len();
  12827. var pathData = path.data;
  12828. if (prevCmd === CMD.Q) {
  12829. ctlPtx += cpx - pathData[len - 4];
  12830. ctlPty += cpy - pathData[len - 3];
  12831. }
  12832. cpx = p[off++];
  12833. cpy = p[off++];
  12834. cmd = CMD.Q;
  12835. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12836. break;
  12837. case 't':
  12838. ctlPtx = cpx;
  12839. ctlPty = cpy;
  12840. var len = path.len();
  12841. var pathData = path.data;
  12842. if (prevCmd === CMD.Q) {
  12843. ctlPtx += cpx - pathData[len - 4];
  12844. ctlPty += cpy - pathData[len - 3];
  12845. }
  12846. cpx += p[off++];
  12847. cpy += p[off++];
  12848. cmd = CMD.Q;
  12849. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12850. break;
  12851. case 'A':
  12852. rx = p[off++];
  12853. ry = p[off++];
  12854. psi = p[off++];
  12855. fa = p[off++];
  12856. fs = p[off++];
  12857. x1 = cpx, y1 = cpy;
  12858. cpx = p[off++];
  12859. cpy = p[off++];
  12860. cmd = CMD.A;
  12861. processArc(
  12862. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12863. );
  12864. break;
  12865. case 'a':
  12866. rx = p[off++];
  12867. ry = p[off++];
  12868. psi = p[off++];
  12869. fa = p[off++];
  12870. fs = p[off++];
  12871. x1 = cpx, y1 = cpy;
  12872. cpx += p[off++];
  12873. cpy += p[off++];
  12874. cmd = CMD.A;
  12875. processArc(
  12876. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12877. );
  12878. break;
  12879. }
  12880. }
  12881. if (cmdStr === 'z' || cmdStr === 'Z') {
  12882. cmd = CMD.Z;
  12883. path.addData(cmd);
  12884. // z may be in the middle of the path.
  12885. cpx = subpathX;
  12886. cpy = subpathY;
  12887. }
  12888. prevCmd = cmd;
  12889. }
  12890. path.toStatic();
  12891. return path;
  12892. }
  12893. // TODO Optimize double memory cost problem
  12894. function createPathOptions(str, opts) {
  12895. var pathProxy = createPathProxyFromString(str);
  12896. opts = opts || {};
  12897. opts.buildPath = function (path) {
  12898. if (path.setData) {
  12899. path.setData(pathProxy.data);
  12900. // Svg and vml renderer don't have context
  12901. var ctx = path.getContext();
  12902. if (ctx) {
  12903. path.rebuildPath(ctx);
  12904. }
  12905. }
  12906. else {
  12907. var ctx = path;
  12908. pathProxy.rebuildPath(ctx);
  12909. }
  12910. };
  12911. opts.applyTransform = function (m) {
  12912. transformPath(pathProxy, m);
  12913. this.dirty(true);
  12914. };
  12915. return opts;
  12916. }
  12917. /**
  12918. * Create a Path object from path string data
  12919. * http://www.w3.org/TR/SVG/paths.html#PathData
  12920. * @param {Object} opts Other options
  12921. */
  12922. function createFromString(str, opts) {
  12923. return new Path(createPathOptions(str, opts));
  12924. }
  12925. /**
  12926. * Create a Path class from path string data
  12927. * @param {string} str
  12928. * @param {Object} opts Other options
  12929. */
  12930. function extendFromString(str, opts) {
  12931. return Path.extend(createPathOptions(str, opts));
  12932. }
  12933. /**
  12934. * Merge multiple paths
  12935. */
  12936. // TODO Apply transform
  12937. // TODO stroke dash
  12938. // TODO Optimize double memory cost problem
  12939. function mergePath(pathEls, opts) {
  12940. var pathList = [];
  12941. var len = pathEls.length;
  12942. for (var i = 0; i < len; i++) {
  12943. var pathEl = pathEls[i];
  12944. if (!pathEl.path) {
  12945. pathEl.createPathProxy();
  12946. }
  12947. if (pathEl.__dirtyPath) {
  12948. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12949. }
  12950. pathList.push(pathEl.path);
  12951. }
  12952. var pathBundle = new Path(opts);
  12953. // Need path proxy.
  12954. pathBundle.createPathProxy();
  12955. pathBundle.buildPath = function (path) {
  12956. path.appendPath(pathList);
  12957. // Svg and vml renderer don't have context
  12958. var ctx = path.getContext();
  12959. if (ctx) {
  12960. path.rebuildPath(ctx);
  12961. }
  12962. };
  12963. return pathBundle;
  12964. }
  12965. var path = (Object.freeze || Object)({
  12966. createFromString: createFromString,
  12967. extendFromString: extendFromString,
  12968. mergePath: mergePath
  12969. });
  12970. /**
  12971. * @alias zrender/graphic/Text
  12972. * @extends module:zrender/graphic/Displayable
  12973. * @constructor
  12974. * @param {Object} opts
  12975. */
  12976. var Text = function (opts) { // jshint ignore:line
  12977. Displayable.call(this, opts);
  12978. };
  12979. Text.prototype = {
  12980. constructor: Text,
  12981. type: 'text',
  12982. brush: function (ctx, prevEl) {
  12983. var style = this.style;
  12984. // Optimize, avoid normalize every time.
  12985. this.__dirty && normalizeTextStyle(style, true);
  12986. // Use props with prefix 'text'.
  12987. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12988. style.shadowOffsetX = style.shadowOffsetY = null;
  12989. var text = style.text;
  12990. // Convert to string
  12991. text != null && (text += '');
  12992. // Do not apply style.bind in Text node. Because the real bind job
  12993. // is in textHelper.renderText, and performance of text render should
  12994. // be considered.
  12995. // style.bind(ctx, this, prevEl);
  12996. if (!needDrawText(text, style)) {
  12997. // The current el.style is not applied
  12998. // and should not be used as cache.
  12999. ctx.__attrCachedBy = ContextCachedBy.NONE;
  13000. return;
  13001. }
  13002. this.setTransform(ctx);
  13003. renderText(this, ctx, text, style, null, prevEl);
  13004. this.restoreTransform(ctx);
  13005. },
  13006. getBoundingRect: function () {
  13007. var style = this.style;
  13008. // Optimize, avoid normalize every time.
  13009. this.__dirty && normalizeTextStyle(style, true);
  13010. if (!this._rect) {
  13011. var text = style.text;
  13012. text != null ? (text += '') : (text = '');
  13013. var rect = getBoundingRect(
  13014. style.text + '',
  13015. style.font,
  13016. style.textAlign,
  13017. style.textVerticalAlign,
  13018. style.textPadding,
  13019. style.textLineHeight,
  13020. style.rich
  13021. );
  13022. rect.x += style.x || 0;
  13023. rect.y += style.y || 0;
  13024. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13025. var w = style.textStrokeWidth;
  13026. rect.x -= w / 2;
  13027. rect.y -= w / 2;
  13028. rect.width += w;
  13029. rect.height += w;
  13030. }
  13031. this._rect = rect;
  13032. }
  13033. return this._rect;
  13034. }
  13035. };
  13036. inherits(Text, Displayable);
  13037. /**
  13038. * 圆形
  13039. * @module zrender/shape/Circle
  13040. */
  13041. var Circle = Path.extend({
  13042. type: 'circle',
  13043. shape: {
  13044. cx: 0,
  13045. cy: 0,
  13046. r: 0
  13047. },
  13048. buildPath: function (ctx, shape, inBundle) {
  13049. // Better stroking in ShapeBundle
  13050. // Always do it may have performence issue ( fill may be 2x more cost)
  13051. if (inBundle) {
  13052. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13053. }
  13054. // else {
  13055. // if (ctx.allocate && !ctx.data.length) {
  13056. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13057. // }
  13058. // }
  13059. // Better stroking in ShapeBundle
  13060. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13061. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13062. }
  13063. });
  13064. /**
  13065. * Sub-pixel optimize for canvas rendering, prevent from blur
  13066. * when rendering a thin vertical/horizontal line.
  13067. */
  13068. var round = Math.round;
  13069. /**
  13070. * Sub pixel optimize line for canvas
  13071. *
  13072. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13073. * `outputShape` and `inputShape` can be the same object.
  13074. * `outputShape` object can be used repeatly, because all of
  13075. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13076. * @param {Object} [inputShape]
  13077. * @param {number} [inputShape.x1]
  13078. * @param {number} [inputShape.y1]
  13079. * @param {number} [inputShape.x2]
  13080. * @param {number} [inputShape.y2]
  13081. * @param {Object} [style]
  13082. * @param {number} [style.lineWidth]
  13083. */
  13084. function subPixelOptimizeLine(outputShape, inputShape, style) {
  13085. var lineWidth = style && style.lineWidth;
  13086. if (!inputShape || !lineWidth) {
  13087. return;
  13088. }
  13089. var x1 = inputShape.x1;
  13090. var x2 = inputShape.x2;
  13091. var y1 = inputShape.y1;
  13092. var y2 = inputShape.y2;
  13093. if (round(x1 * 2) === round(x2 * 2)) {
  13094. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  13095. }
  13096. else {
  13097. outputShape.x1 = x1;
  13098. outputShape.x2 = x2;
  13099. }
  13100. if (round(y1 * 2) === round(y2 * 2)) {
  13101. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  13102. }
  13103. else {
  13104. outputShape.y1 = y1;
  13105. outputShape.y2 = y2;
  13106. }
  13107. }
  13108. /**
  13109. * Sub pixel optimize rect for canvas
  13110. *
  13111. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13112. * `outputShape` and `inputShape` can be the same object.
  13113. * `outputShape` object can be used repeatly, because all of
  13114. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13115. * @param {Object} [inputShape]
  13116. * @param {number} [inputShape.x]
  13117. * @param {number} [inputShape.y]
  13118. * @param {number} [inputShape.width]
  13119. * @param {number} [inputShape.height]
  13120. * @param {Object} [style]
  13121. * @param {number} [style.lineWidth]
  13122. */
  13123. function subPixelOptimizeRect(outputShape, inputShape, style) {
  13124. var lineWidth = style && style.lineWidth;
  13125. if (!inputShape || !lineWidth) {
  13126. return;
  13127. }
  13128. var originX = inputShape.x;
  13129. var originY = inputShape.y;
  13130. var originWidth = inputShape.width;
  13131. var originHeight = inputShape.height;
  13132. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  13133. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  13134. outputShape.width = Math.max(
  13135. subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x,
  13136. originWidth === 0 ? 0 : 1
  13137. );
  13138. outputShape.height = Math.max(
  13139. subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y,
  13140. originHeight === 0 ? 0 : 1
  13141. );
  13142. }
  13143. /**
  13144. * Sub pixel optimize for canvas
  13145. *
  13146. * @param {number} position Coordinate, such as x, y
  13147. * @param {number} lineWidth Should be nonnegative integer.
  13148. * @param {boolean=} positiveOrNegative Default false (negative).
  13149. * @return {number} Optimized position.
  13150. */
  13151. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  13152. // Assure that (position + lineWidth / 2) is near integer edge,
  13153. // otherwise line will be fuzzy in canvas.
  13154. var doubledPosition = round(position * 2);
  13155. return (doubledPosition + round(lineWidth)) % 2 === 0
  13156. ? doubledPosition / 2
  13157. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13158. }
  13159. /**
  13160. * 矩形
  13161. * @module zrender/graphic/shape/Rect
  13162. */
  13163. // Avoid create repeatly.
  13164. var subPixelOptimizeOutputShape = {};
  13165. var Rect = Path.extend({
  13166. type: 'rect',
  13167. shape: {
  13168. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13169. // r缩写为1 相当于 [1, 1, 1, 1]
  13170. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13171. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13172. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13173. r: 0,
  13174. x: 0,
  13175. y: 0,
  13176. width: 0,
  13177. height: 0
  13178. },
  13179. buildPath: function (ctx, shape) {
  13180. var x;
  13181. var y;
  13182. var width;
  13183. var height;
  13184. if (this.subPixelOptimize) {
  13185. subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  13186. x = subPixelOptimizeOutputShape.x;
  13187. y = subPixelOptimizeOutputShape.y;
  13188. width = subPixelOptimizeOutputShape.width;
  13189. height = subPixelOptimizeOutputShape.height;
  13190. subPixelOptimizeOutputShape.r = shape.r;
  13191. shape = subPixelOptimizeOutputShape;
  13192. }
  13193. else {
  13194. x = shape.x;
  13195. y = shape.y;
  13196. width = shape.width;
  13197. height = shape.height;
  13198. }
  13199. if (!shape.r) {
  13200. ctx.rect(x, y, width, height);
  13201. }
  13202. else {
  13203. buildPath(ctx, shape);
  13204. }
  13205. ctx.closePath();
  13206. return;
  13207. }
  13208. });
  13209. /**
  13210. * 椭圆形状
  13211. * @module zrender/graphic/shape/Ellipse
  13212. */
  13213. var Ellipse = Path.extend({
  13214. type: 'ellipse',
  13215. shape: {
  13216. cx: 0, cy: 0,
  13217. rx: 0, ry: 0
  13218. },
  13219. buildPath: function (ctx, shape) {
  13220. var k = 0.5522848;
  13221. var x = shape.cx;
  13222. var y = shape.cy;
  13223. var a = shape.rx;
  13224. var b = shape.ry;
  13225. var ox = a * k; // 水平控制点偏移量
  13226. var oy = b * k; // 垂直控制点偏移量
  13227. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  13228. ctx.moveTo(x - a, y);
  13229. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13230. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13231. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13232. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13233. ctx.closePath();
  13234. }
  13235. });
  13236. /**
  13237. * 直线
  13238. * @module zrender/graphic/shape/Line
  13239. */
  13240. // Avoid create repeatly.
  13241. var subPixelOptimizeOutputShape$1 = {};
  13242. var Line = Path.extend({
  13243. type: 'line',
  13244. shape: {
  13245. // Start point
  13246. x1: 0,
  13247. y1: 0,
  13248. // End point
  13249. x2: 0,
  13250. y2: 0,
  13251. percent: 1
  13252. },
  13253. style: {
  13254. stroke: '#000',
  13255. fill: null
  13256. },
  13257. buildPath: function (ctx, shape) {
  13258. var x1;
  13259. var y1;
  13260. var x2;
  13261. var y2;
  13262. if (this.subPixelOptimize) {
  13263. subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13264. x1 = subPixelOptimizeOutputShape$1.x1;
  13265. y1 = subPixelOptimizeOutputShape$1.y1;
  13266. x2 = subPixelOptimizeOutputShape$1.x2;
  13267. y2 = subPixelOptimizeOutputShape$1.y2;
  13268. }
  13269. else {
  13270. x1 = shape.x1;
  13271. y1 = shape.y1;
  13272. x2 = shape.x2;
  13273. y2 = shape.y2;
  13274. }
  13275. var percent = shape.percent;
  13276. if (percent === 0) {
  13277. return;
  13278. }
  13279. ctx.moveTo(x1, y1);
  13280. if (percent < 1) {
  13281. x2 = x1 * (1 - percent) + x2 * percent;
  13282. y2 = y1 * (1 - percent) + y2 * percent;
  13283. }
  13284. ctx.lineTo(x2, y2);
  13285. },
  13286. /**
  13287. * Get point at percent
  13288. * @param {number} percent
  13289. * @return {Array.<number>}
  13290. */
  13291. pointAt: function (p) {
  13292. var shape = this.shape;
  13293. return [
  13294. shape.x1 * (1 - p) + shape.x2 * p,
  13295. shape.y1 * (1 - p) + shape.y2 * p
  13296. ];
  13297. }
  13298. });
  13299. /**
  13300. * Catmull-Rom spline 插值折线
  13301. * @module zrender/shape/util/smoothSpline
  13302. * @author pissang (https://www.github.com/pissang)
  13303. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13304. * errorrik (errorrik@gmail.com)
  13305. */
  13306. /**
  13307. * @inner
  13308. */
  13309. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13310. var v0 = (p2 - p0) * 0.5;
  13311. var v1 = (p3 - p1) * 0.5;
  13312. return (2 * (p1 - p2) + v0 + v1) * t3
  13313. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13314. + v0 * t + p1;
  13315. }
  13316. /**
  13317. * @alias module:zrender/shape/util/smoothSpline
  13318. * @param {Array} points 线段顶点数组
  13319. * @param {boolean} isLoop
  13320. * @return {Array}
  13321. */
  13322. var smoothSpline = function (points, isLoop) {
  13323. var len$$1 = points.length;
  13324. var ret = [];
  13325. var distance$$1 = 0;
  13326. for (var i = 1; i < len$$1; i++) {
  13327. distance$$1 += distance(points[i - 1], points[i]);
  13328. }
  13329. var segs = distance$$1 / 2;
  13330. segs = segs < len$$1 ? len$$1 : segs;
  13331. for (var i = 0; i < segs; i++) {
  13332. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13333. var idx = Math.floor(pos);
  13334. var w = pos - idx;
  13335. var p0;
  13336. var p1 = points[idx % len$$1];
  13337. var p2;
  13338. var p3;
  13339. if (!isLoop) {
  13340. p0 = points[idx === 0 ? idx : idx - 1];
  13341. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13342. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13343. }
  13344. else {
  13345. p0 = points[(idx - 1 + len$$1) % len$$1];
  13346. p2 = points[(idx + 1) % len$$1];
  13347. p3 = points[(idx + 2) % len$$1];
  13348. }
  13349. var w2 = w * w;
  13350. var w3 = w * w2;
  13351. ret.push([
  13352. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13353. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13354. ]);
  13355. }
  13356. return ret;
  13357. };
  13358. /**
  13359. * 贝塞尔平滑曲线
  13360. * @module zrender/shape/util/smoothBezier
  13361. * @author pissang (https://www.github.com/pissang)
  13362. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13363. * errorrik (errorrik@gmail.com)
  13364. */
  13365. /**
  13366. * 贝塞尔平滑曲线
  13367. * @alias module:zrender/shape/util/smoothBezier
  13368. * @param {Array} points 线段顶点数组
  13369. * @param {number} smooth 平滑等级, 0-1
  13370. * @param {boolean} isLoop
  13371. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13372. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13373. * 整个折线的包围盒做一个并集用来约束控制点。
  13374. * @param {Array} 计算出来的控制点数组
  13375. */
  13376. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13377. var cps = [];
  13378. var v = [];
  13379. var v1 = [];
  13380. var v2 = [];
  13381. var prevPoint;
  13382. var nextPoint;
  13383. var min$$1;
  13384. var max$$1;
  13385. if (constraint) {
  13386. min$$1 = [Infinity, Infinity];
  13387. max$$1 = [-Infinity, -Infinity];
  13388. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13389. min(min$$1, min$$1, points[i]);
  13390. max(max$$1, max$$1, points[i]);
  13391. }
  13392. // 与指定的包围盒做并集
  13393. min(min$$1, min$$1, constraint[0]);
  13394. max(max$$1, max$$1, constraint[1]);
  13395. }
  13396. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13397. var point = points[i];
  13398. if (isLoop) {
  13399. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13400. nextPoint = points[(i + 1) % len$$1];
  13401. }
  13402. else {
  13403. if (i === 0 || i === len$$1 - 1) {
  13404. cps.push(clone$1(points[i]));
  13405. continue;
  13406. }
  13407. else {
  13408. prevPoint = points[i - 1];
  13409. nextPoint = points[i + 1];
  13410. }
  13411. }
  13412. sub(v, nextPoint, prevPoint);
  13413. // use degree to scale the handle length
  13414. scale(v, v, smooth);
  13415. var d0 = distance(point, prevPoint);
  13416. var d1 = distance(point, nextPoint);
  13417. var sum = d0 + d1;
  13418. if (sum !== 0) {
  13419. d0 /= sum;
  13420. d1 /= sum;
  13421. }
  13422. scale(v1, v, -d0);
  13423. scale(v2, v, d1);
  13424. var cp0 = add([], point, v1);
  13425. var cp1 = add([], point, v2);
  13426. if (constraint) {
  13427. max(cp0, cp0, min$$1);
  13428. min(cp0, cp0, max$$1);
  13429. max(cp1, cp1, min$$1);
  13430. min(cp1, cp1, max$$1);
  13431. }
  13432. cps.push(cp0);
  13433. cps.push(cp1);
  13434. }
  13435. if (isLoop) {
  13436. cps.push(cps.shift());
  13437. }
  13438. return cps;
  13439. };
  13440. function buildPath$1(ctx, shape, closePath) {
  13441. var points = shape.points;
  13442. var smooth = shape.smooth;
  13443. if (points && points.length >= 2) {
  13444. if (smooth && smooth !== 'spline') {
  13445. var controlPoints = smoothBezier(
  13446. points, smooth, closePath, shape.smoothConstraint
  13447. );
  13448. ctx.moveTo(points[0][0], points[0][1]);
  13449. var len = points.length;
  13450. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13451. var cp1 = controlPoints[i * 2];
  13452. var cp2 = controlPoints[i * 2 + 1];
  13453. var p = points[(i + 1) % len];
  13454. ctx.bezierCurveTo(
  13455. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13456. );
  13457. }
  13458. }
  13459. else {
  13460. if (smooth === 'spline') {
  13461. points = smoothSpline(points, closePath);
  13462. }
  13463. ctx.moveTo(points[0][0], points[0][1]);
  13464. for (var i = 1, l = points.length; i < l; i++) {
  13465. ctx.lineTo(points[i][0], points[i][1]);
  13466. }
  13467. }
  13468. closePath && ctx.closePath();
  13469. }
  13470. }
  13471. /**
  13472. * 多边形
  13473. * @module zrender/shape/Polygon
  13474. */
  13475. var Polygon = Path.extend({
  13476. type: 'polygon',
  13477. shape: {
  13478. points: null,
  13479. smooth: false,
  13480. smoothConstraint: null
  13481. },
  13482. buildPath: function (ctx, shape) {
  13483. buildPath$1(ctx, shape, true);
  13484. }
  13485. });
  13486. /**
  13487. * @module zrender/graphic/shape/Polyline
  13488. */
  13489. var Polyline = Path.extend({
  13490. type: 'polyline',
  13491. shape: {
  13492. points: null,
  13493. smooth: false,
  13494. smoothConstraint: null
  13495. },
  13496. style: {
  13497. stroke: '#000',
  13498. fill: null
  13499. },
  13500. buildPath: function (ctx, shape) {
  13501. buildPath$1(ctx, shape, false);
  13502. }
  13503. });
  13504. /**
  13505. * @param {Array.<Object>} colorStops
  13506. */
  13507. var Gradient = function (colorStops) {
  13508. this.colorStops = colorStops || [];
  13509. };
  13510. Gradient.prototype = {
  13511. constructor: Gradient,
  13512. addColorStop: function (offset, color) {
  13513. this.colorStops.push({
  13514. offset: offset,
  13515. color: color
  13516. });
  13517. }
  13518. };
  13519. /**
  13520. * x, y, x2, y2 are all percent from 0 to 1
  13521. * @param {number} [x=0]
  13522. * @param {number} [y=0]
  13523. * @param {number} [x2=1]
  13524. * @param {number} [y2=0]
  13525. * @param {Array.<Object>} colorStops
  13526. * @param {boolean} [globalCoord=false]
  13527. */
  13528. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13529. // Should do nothing more in this constructor. Because gradient can be
  13530. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13531. // this constructor will not be called.
  13532. this.x = x == null ? 0 : x;
  13533. this.y = y == null ? 0 : y;
  13534. this.x2 = x2 == null ? 1 : x2;
  13535. this.y2 = y2 == null ? 0 : y2;
  13536. // Can be cloned
  13537. this.type = 'linear';
  13538. // If use global coord
  13539. this.global = globalCoord || false;
  13540. Gradient.call(this, colorStops);
  13541. };
  13542. LinearGradient.prototype = {
  13543. constructor: LinearGradient
  13544. };
  13545. inherits(LinearGradient, Gradient);
  13546. // import RadialGradient from '../graphic/RadialGradient';
  13547. // import Pattern from '../graphic/Pattern';
  13548. // import * as vector from '../core/vector';
  13549. // Most of the values can be separated by comma and/or white space.
  13550. var DILIMITER_REG = /[\s,]+/;
  13551. /**
  13552. * For big svg string, this method might be time consuming.
  13553. *
  13554. * @param {string} svg xml string
  13555. * @return {Object} xml root.
  13556. */
  13557. function parseXML(svg) {
  13558. if (isString(svg)) {
  13559. var parser = new DOMParser();
  13560. svg = parser.parseFromString(svg, 'text/xml');
  13561. }
  13562. // Document node. If using $.get, doc node may be input.
  13563. if (svg.nodeType === 9) {
  13564. svg = svg.firstChild;
  13565. }
  13566. // nodeName of <!DOCTYPE svg> is also 'svg'.
  13567. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  13568. svg = svg.nextSibling;
  13569. }
  13570. return svg;
  13571. }
  13572. function SVGParser() {
  13573. this._defs = {};
  13574. this._root = null;
  13575. this._isDefine = false;
  13576. this._isText = false;
  13577. }
  13578. SVGParser.prototype.parse = function (xml, opt) {
  13579. opt = opt || {};
  13580. var svg = parseXML(xml);
  13581. if (!svg) {
  13582. throw new Error('Illegal svg');
  13583. }
  13584. var root = new Group();
  13585. this._root = root;
  13586. // parse view port
  13587. var viewBox = svg.getAttribute('viewBox') || '';
  13588. // If width/height not specified, means "100%" of `opt.width/height`.
  13589. // TODO: Other percent value not supported yet.
  13590. var width = parseFloat(svg.getAttribute('width') || opt.width);
  13591. var height = parseFloat(svg.getAttribute('height') || opt.height);
  13592. // If width/height not specified, set as null for output.
  13593. isNaN(width) && (width = null);
  13594. isNaN(height) && (height = null);
  13595. // Apply inline style on svg element.
  13596. parseAttributes(svg, root, null, true);
  13597. var child = svg.firstChild;
  13598. while (child) {
  13599. this._parseNode(child, root);
  13600. child = child.nextSibling;
  13601. }
  13602. var viewBoxRect;
  13603. var viewBoxTransform;
  13604. if (viewBox) {
  13605. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  13606. // Some invalid case like viewBox: 'none'.
  13607. if (viewBoxArr.length >= 4) {
  13608. viewBoxRect = {
  13609. x: parseFloat(viewBoxArr[0] || 0),
  13610. y: parseFloat(viewBoxArr[1] || 0),
  13611. width: parseFloat(viewBoxArr[2]),
  13612. height: parseFloat(viewBoxArr[3])
  13613. };
  13614. }
  13615. }
  13616. if (viewBoxRect && width != null && height != null) {
  13617. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  13618. if (!opt.ignoreViewBox) {
  13619. // If set transform on the output group, it probably bring trouble when
  13620. // some users only intend to show the clipped content inside the viewBox,
  13621. // but not intend to transform the output group. So we keep the output
  13622. // group no transform. If the user intend to use the viewBox as a
  13623. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  13624. // manually according to the viewBox info in the output of this method.
  13625. var elRoot = root;
  13626. root = new Group();
  13627. root.add(elRoot);
  13628. elRoot.scale = viewBoxTransform.scale.slice();
  13629. elRoot.position = viewBoxTransform.position.slice();
  13630. }
  13631. }
  13632. // Some shapes might be overflow the viewport, which should be
  13633. // clipped despite whether the viewBox is used, as the SVG does.
  13634. if (!opt.ignoreRootClip && width != null && height != null) {
  13635. root.setClipPath(new Rect({
  13636. shape: {x: 0, y: 0, width: width, height: height}
  13637. }));
  13638. }
  13639. // Set width/height on group just for output the viewport size.
  13640. return {
  13641. root: root,
  13642. width: width,
  13643. height: height,
  13644. viewBoxRect: viewBoxRect,
  13645. viewBoxTransform: viewBoxTransform
  13646. };
  13647. };
  13648. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  13649. var nodeName = xmlNode.nodeName.toLowerCase();
  13650. // TODO
  13651. // support <style>...</style> in svg, where nodeName is 'style',
  13652. // CSS classes is defined globally wherever the style tags are declared.
  13653. if (nodeName === 'defs') {
  13654. // define flag
  13655. this._isDefine = true;
  13656. }
  13657. else if (nodeName === 'text') {
  13658. this._isText = true;
  13659. }
  13660. var el;
  13661. if (this._isDefine) {
  13662. var parser = defineParsers[nodeName];
  13663. if (parser) {
  13664. var def = parser.call(this, xmlNode);
  13665. var id = xmlNode.getAttribute('id');
  13666. if (id) {
  13667. this._defs[id] = def;
  13668. }
  13669. }
  13670. }
  13671. else {
  13672. var parser = nodeParsers[nodeName];
  13673. if (parser) {
  13674. el = parser.call(this, xmlNode, parentGroup);
  13675. parentGroup.add(el);
  13676. }
  13677. }
  13678. var child = xmlNode.firstChild;
  13679. while (child) {
  13680. if (child.nodeType === 1) {
  13681. this._parseNode(child, el);
  13682. }
  13683. // Is text
  13684. if (child.nodeType === 3 && this._isText) {
  13685. this._parseText(child, el);
  13686. }
  13687. child = child.nextSibling;
  13688. }
  13689. // Quit define
  13690. if (nodeName === 'defs') {
  13691. this._isDefine = false;
  13692. }
  13693. else if (nodeName === 'text') {
  13694. this._isText = false;
  13695. }
  13696. };
  13697. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  13698. if (xmlNode.nodeType === 1) {
  13699. var dx = xmlNode.getAttribute('dx') || 0;
  13700. var dy = xmlNode.getAttribute('dy') || 0;
  13701. this._textX += parseFloat(dx);
  13702. this._textY += parseFloat(dy);
  13703. }
  13704. var text = new Text({
  13705. style: {
  13706. text: xmlNode.textContent,
  13707. transformText: true
  13708. },
  13709. position: [this._textX || 0, this._textY || 0]
  13710. });
  13711. inheritStyle(parentGroup, text);
  13712. parseAttributes(xmlNode, text, this._defs);
  13713. var fontSize = text.style.fontSize;
  13714. if (fontSize && fontSize < 9) {
  13715. // PENDING
  13716. text.style.fontSize = 9;
  13717. text.scale = text.scale || [1, 1];
  13718. text.scale[0] *= fontSize / 9;
  13719. text.scale[1] *= fontSize / 9;
  13720. }
  13721. var rect = text.getBoundingRect();
  13722. this._textX += rect.width;
  13723. parentGroup.add(text);
  13724. return text;
  13725. };
  13726. var nodeParsers = {
  13727. 'g': function (xmlNode, parentGroup) {
  13728. var g = new Group();
  13729. inheritStyle(parentGroup, g);
  13730. parseAttributes(xmlNode, g, this._defs);
  13731. return g;
  13732. },
  13733. 'rect': function (xmlNode, parentGroup) {
  13734. var rect = new Rect();
  13735. inheritStyle(parentGroup, rect);
  13736. parseAttributes(xmlNode, rect, this._defs);
  13737. rect.setShape({
  13738. x: parseFloat(xmlNode.getAttribute('x') || 0),
  13739. y: parseFloat(xmlNode.getAttribute('y') || 0),
  13740. width: parseFloat(xmlNode.getAttribute('width') || 0),
  13741. height: parseFloat(xmlNode.getAttribute('height') || 0)
  13742. });
  13743. // console.log(xmlNode.getAttribute('transform'));
  13744. // console.log(rect.transform);
  13745. return rect;
  13746. },
  13747. 'circle': function (xmlNode, parentGroup) {
  13748. var circle = new Circle();
  13749. inheritStyle(parentGroup, circle);
  13750. parseAttributes(xmlNode, circle, this._defs);
  13751. circle.setShape({
  13752. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  13753. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  13754. r: parseFloat(xmlNode.getAttribute('r') || 0)
  13755. });
  13756. return circle;
  13757. },
  13758. 'line': function (xmlNode, parentGroup) {
  13759. var line = new Line();
  13760. inheritStyle(parentGroup, line);
  13761. parseAttributes(xmlNode, line, this._defs);
  13762. line.setShape({
  13763. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  13764. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  13765. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  13766. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  13767. });
  13768. return line;
  13769. },
  13770. 'ellipse': function (xmlNode, parentGroup) {
  13771. var ellipse = new Ellipse();
  13772. inheritStyle(parentGroup, ellipse);
  13773. parseAttributes(xmlNode, ellipse, this._defs);
  13774. ellipse.setShape({
  13775. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  13776. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  13777. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  13778. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  13779. });
  13780. return ellipse;
  13781. },
  13782. 'polygon': function (xmlNode, parentGroup) {
  13783. var points = xmlNode.getAttribute('points');
  13784. if (points) {
  13785. points = parsePoints(points);
  13786. }
  13787. var polygon = new Polygon({
  13788. shape: {
  13789. points: points || []
  13790. }
  13791. });
  13792. inheritStyle(parentGroup, polygon);
  13793. parseAttributes(xmlNode, polygon, this._defs);
  13794. return polygon;
  13795. },
  13796. 'polyline': function (xmlNode, parentGroup) {
  13797. var path = new Path();
  13798. inheritStyle(parentGroup, path);
  13799. parseAttributes(xmlNode, path, this._defs);
  13800. var points = xmlNode.getAttribute('points');
  13801. if (points) {
  13802. points = parsePoints(points);
  13803. }
  13804. var polyline = new Polyline({
  13805. shape: {
  13806. points: points || []
  13807. }
  13808. });
  13809. return polyline;
  13810. },
  13811. 'image': function (xmlNode, parentGroup) {
  13812. var img = new ZImage();
  13813. inheritStyle(parentGroup, img);
  13814. parseAttributes(xmlNode, img, this._defs);
  13815. img.setStyle({
  13816. image: xmlNode.getAttribute('xlink:href'),
  13817. x: xmlNode.getAttribute('x'),
  13818. y: xmlNode.getAttribute('y'),
  13819. width: xmlNode.getAttribute('width'),
  13820. height: xmlNode.getAttribute('height')
  13821. });
  13822. return img;
  13823. },
  13824. 'text': function (xmlNode, parentGroup) {
  13825. var x = xmlNode.getAttribute('x') || 0;
  13826. var y = xmlNode.getAttribute('y') || 0;
  13827. var dx = xmlNode.getAttribute('dx') || 0;
  13828. var dy = xmlNode.getAttribute('dy') || 0;
  13829. this._textX = parseFloat(x) + parseFloat(dx);
  13830. this._textY = parseFloat(y) + parseFloat(dy);
  13831. var g = new Group();
  13832. inheritStyle(parentGroup, g);
  13833. parseAttributes(xmlNode, g, this._defs);
  13834. return g;
  13835. },
  13836. 'tspan': function (xmlNode, parentGroup) {
  13837. var x = xmlNode.getAttribute('x');
  13838. var y = xmlNode.getAttribute('y');
  13839. if (x != null) {
  13840. // new offset x
  13841. this._textX = parseFloat(x);
  13842. }
  13843. if (y != null) {
  13844. // new offset y
  13845. this._textY = parseFloat(y);
  13846. }
  13847. var dx = xmlNode.getAttribute('dx') || 0;
  13848. var dy = xmlNode.getAttribute('dy') || 0;
  13849. var g = new Group();
  13850. inheritStyle(parentGroup, g);
  13851. parseAttributes(xmlNode, g, this._defs);
  13852. this._textX += dx;
  13853. this._textY += dy;
  13854. return g;
  13855. },
  13856. 'path': function (xmlNode, parentGroup) {
  13857. // TODO svg fill rule
  13858. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  13859. // path.style.globalCompositeOperation = 'xor';
  13860. var d = xmlNode.getAttribute('d') || '';
  13861. // Performance sensitive.
  13862. var path = createFromString(d);
  13863. inheritStyle(parentGroup, path);
  13864. parseAttributes(xmlNode, path, this._defs);
  13865. return path;
  13866. }
  13867. };
  13868. var defineParsers = {
  13869. 'lineargradient': function (xmlNode) {
  13870. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  13871. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  13872. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  13873. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  13874. var gradient = new LinearGradient(x1, y1, x2, y2);
  13875. _parseGradientColorStops(xmlNode, gradient);
  13876. return gradient;
  13877. },
  13878. 'radialgradient': function (xmlNode) {
  13879. }
  13880. };
  13881. function _parseGradientColorStops(xmlNode, gradient) {
  13882. var stop = xmlNode.firstChild;
  13883. while (stop) {
  13884. if (stop.nodeType === 1) {
  13885. var offset = stop.getAttribute('offset');
  13886. if (offset.indexOf('%') > 0) { // percentage
  13887. offset = parseInt(offset, 10) / 100;
  13888. }
  13889. else if (offset) { // number from 0 to 1
  13890. offset = parseFloat(offset);
  13891. }
  13892. else {
  13893. offset = 0;
  13894. }
  13895. var stopColor = stop.getAttribute('stop-color') || '#000000';
  13896. gradient.addColorStop(offset, stopColor);
  13897. }
  13898. stop = stop.nextSibling;
  13899. }
  13900. }
  13901. function inheritStyle(parent, child) {
  13902. if (parent && parent.__inheritedStyle) {
  13903. if (!child.__inheritedStyle) {
  13904. child.__inheritedStyle = {};
  13905. }
  13906. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  13907. }
  13908. }
  13909. function parsePoints(pointsString) {
  13910. var list = trim(pointsString).split(DILIMITER_REG);
  13911. var points = [];
  13912. for (var i = 0; i < list.length; i += 2) {
  13913. var x = parseFloat(list[i]);
  13914. var y = parseFloat(list[i + 1]);
  13915. points.push([x, y]);
  13916. }
  13917. return points;
  13918. }
  13919. var attributesMap = {
  13920. 'fill': 'fill',
  13921. 'stroke': 'stroke',
  13922. 'stroke-width': 'lineWidth',
  13923. 'opacity': 'opacity',
  13924. 'fill-opacity': 'fillOpacity',
  13925. 'stroke-opacity': 'strokeOpacity',
  13926. 'stroke-dasharray': 'lineDash',
  13927. 'stroke-dashoffset': 'lineDashOffset',
  13928. 'stroke-linecap': 'lineCap',
  13929. 'stroke-linejoin': 'lineJoin',
  13930. 'stroke-miterlimit': 'miterLimit',
  13931. 'font-family': 'fontFamily',
  13932. 'font-size': 'fontSize',
  13933. 'font-style': 'fontStyle',
  13934. 'font-weight': 'fontWeight',
  13935. 'text-align': 'textAlign',
  13936. 'alignment-baseline': 'textBaseline'
  13937. };
  13938. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  13939. var zrStyle = el.__inheritedStyle || {};
  13940. var isTextEl = el.type === 'text';
  13941. // TODO Shadow
  13942. if (xmlNode.nodeType === 1) {
  13943. parseTransformAttribute(xmlNode, el);
  13944. extend(zrStyle, parseStyleAttribute(xmlNode));
  13945. if (!onlyInlineStyle) {
  13946. for (var svgAttrName in attributesMap) {
  13947. if (attributesMap.hasOwnProperty(svgAttrName)) {
  13948. var attrValue = xmlNode.getAttribute(svgAttrName);
  13949. if (attrValue != null) {
  13950. zrStyle[attributesMap[svgAttrName]] = attrValue;
  13951. }
  13952. }
  13953. }
  13954. }
  13955. }
  13956. var elFillProp = isTextEl ? 'textFill' : 'fill';
  13957. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  13958. el.style = el.style || new Style();
  13959. var elStyle = el.style;
  13960. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  13961. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  13962. each([
  13963. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  13964. ], function (propName) {
  13965. var elPropName = (propName === 'lineWidth' && isTextEl) ? 'textStrokeWidth' : propName;
  13966. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  13967. });
  13968. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  13969. zrStyle.textBaseline = 'alphabetic';
  13970. }
  13971. if (zrStyle.textBaseline === 'alphabetic') {
  13972. zrStyle.textBaseline = 'bottom';
  13973. }
  13974. if (zrStyle.textAlign === 'start') {
  13975. zrStyle.textAlign = 'left';
  13976. }
  13977. if (zrStyle.textAlign === 'end') {
  13978. zrStyle.textAlign = 'right';
  13979. }
  13980. each(['lineDashOffset', 'lineCap', 'lineJoin',
  13981. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  13982. ], function (propName) {
  13983. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  13984. });
  13985. if (zrStyle.lineDash) {
  13986. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  13987. }
  13988. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  13989. // enable stroke
  13990. el[elStrokeProp] = true;
  13991. }
  13992. el.__inheritedStyle = zrStyle;
  13993. }
  13994. var urlRegex = /url\(\s*#(.*?)\)/;
  13995. function getPaint(str, defs) {
  13996. // if (str === 'none') {
  13997. // return;
  13998. // }
  13999. var urlMatch = defs && str && str.match(urlRegex);
  14000. if (urlMatch) {
  14001. var url = trim(urlMatch[1]);
  14002. var def = defs[url];
  14003. return def;
  14004. }
  14005. return str;
  14006. }
  14007. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  14008. function parseTransformAttribute(xmlNode, node) {
  14009. var transform = xmlNode.getAttribute('transform');
  14010. if (transform) {
  14011. transform = transform.replace(/,/g, ' ');
  14012. var m = null;
  14013. var transformOps = [];
  14014. transform.replace(transformRegex, function (str, type, value) {
  14015. transformOps.push(type, value);
  14016. });
  14017. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  14018. var value = transformOps[i];
  14019. var type = transformOps[i - 1];
  14020. m = m || create$1();
  14021. switch (type) {
  14022. case 'translate':
  14023. value = trim(value).split(DILIMITER_REG);
  14024. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  14025. break;
  14026. case 'scale':
  14027. value = trim(value).split(DILIMITER_REG);
  14028. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  14029. break;
  14030. case 'rotate':
  14031. value = trim(value).split(DILIMITER_REG);
  14032. rotate(m, m, parseFloat(value[0]));
  14033. break;
  14034. case 'skew':
  14035. value = trim(value).split(DILIMITER_REG);
  14036. console.warn('Skew transform is not supported yet');
  14037. break;
  14038. case 'matrix':
  14039. var value = trim(value).split(DILIMITER_REG);
  14040. m[0] = parseFloat(value[0]);
  14041. m[1] = parseFloat(value[1]);
  14042. m[2] = parseFloat(value[2]);
  14043. m[3] = parseFloat(value[3]);
  14044. m[4] = parseFloat(value[4]);
  14045. m[5] = parseFloat(value[5]);
  14046. break;
  14047. }
  14048. }
  14049. node.setLocalTransform(m);
  14050. }
  14051. }
  14052. // Value may contain space.
  14053. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  14054. function parseStyleAttribute(xmlNode) {
  14055. var style = xmlNode.getAttribute('style');
  14056. var result = {};
  14057. if (!style) {
  14058. return result;
  14059. }
  14060. var styleList = {};
  14061. styleRegex.lastIndex = 0;
  14062. var styleRegResult;
  14063. while ((styleRegResult = styleRegex.exec(style)) != null) {
  14064. styleList[styleRegResult[1]] = styleRegResult[2];
  14065. }
  14066. for (var svgAttrName in attributesMap) {
  14067. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  14068. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  14069. }
  14070. }
  14071. return result;
  14072. }
  14073. /**
  14074. * @param {Array.<number>} viewBoxRect
  14075. * @param {number} width
  14076. * @param {number} height
  14077. * @return {Object} {scale, position}
  14078. */
  14079. function makeViewBoxTransform(viewBoxRect, width, height) {
  14080. var scaleX = width / viewBoxRect.width;
  14081. var scaleY = height / viewBoxRect.height;
  14082. var scale = Math.min(scaleX, scaleY);
  14083. // preserveAspectRatio 'xMidYMid'
  14084. var viewBoxScale = [scale, scale];
  14085. var viewBoxPosition = [
  14086. -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  14087. -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  14088. ];
  14089. return {
  14090. scale: viewBoxScale,
  14091. position: viewBoxPosition
  14092. };
  14093. }
  14094. /**
  14095. * @param {string|XMLElement} xml
  14096. * @param {Object} [opt]
  14097. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  14098. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  14099. * @param {boolean} [opt.ignoreViewBox]
  14100. * @param {boolean} [opt.ignoreRootClip]
  14101. * @return {Object} result:
  14102. * {
  14103. * root: Group, The root of the the result tree of zrender shapes,
  14104. * width: number, the viewport width of the SVG,
  14105. * height: number, the viewport height of the SVG,
  14106. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  14107. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  14108. * }
  14109. */
  14110. function parseSVG(xml, opt) {
  14111. var parser = new SVGParser();
  14112. return parser.parse(xml, opt);
  14113. }
  14114. // CompoundPath to improve performance
  14115. var CompoundPath = Path.extend({
  14116. type: 'compound',
  14117. shape: {
  14118. paths: null
  14119. },
  14120. _updatePathDirty: function () {
  14121. var dirtyPath = this.__dirtyPath;
  14122. var paths = this.shape.paths;
  14123. for (var i = 0; i < paths.length; i++) {
  14124. // Mark as dirty if any subpath is dirty
  14125. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  14126. }
  14127. this.__dirtyPath = dirtyPath;
  14128. this.__dirty = this.__dirty || dirtyPath;
  14129. },
  14130. beforeBrush: function () {
  14131. this._updatePathDirty();
  14132. var paths = this.shape.paths || [];
  14133. var scale = this.getGlobalScale();
  14134. // Update path scale
  14135. for (var i = 0; i < paths.length; i++) {
  14136. if (!paths[i].path) {
  14137. paths[i].createPathProxy();
  14138. }
  14139. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  14140. }
  14141. },
  14142. buildPath: function (ctx, shape) {
  14143. var paths = shape.paths || [];
  14144. for (var i = 0; i < paths.length; i++) {
  14145. paths[i].buildPath(ctx, paths[i].shape, true);
  14146. }
  14147. },
  14148. afterBrush: function () {
  14149. var paths = this.shape.paths || [];
  14150. for (var i = 0; i < paths.length; i++) {
  14151. paths[i].__dirtyPath = false;
  14152. }
  14153. },
  14154. getBoundingRect: function () {
  14155. this._updatePathDirty();
  14156. return Path.prototype.getBoundingRect.call(this);
  14157. }
  14158. });
  14159. /**
  14160. * Displayable for incremental rendering. It will be rendered in a separate layer
  14161. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  14162. * addDisplayables will render the added displayables incremetally.
  14163. *
  14164. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  14165. */
  14166. // TODO Style override ?
  14167. function IncrementalDisplayble(opts) {
  14168. Displayable.call(this, opts);
  14169. this._displayables = [];
  14170. this._temporaryDisplayables = [];
  14171. this._cursor = 0;
  14172. this.notClear = true;
  14173. }
  14174. IncrementalDisplayble.prototype.incremental = true;
  14175. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  14176. this._displayables = [];
  14177. this._temporaryDisplayables = [];
  14178. this._cursor = 0;
  14179. this.dirty();
  14180. this.notClear = false;
  14181. };
  14182. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  14183. if (notPersistent) {
  14184. this._temporaryDisplayables.push(displayable);
  14185. }
  14186. else {
  14187. this._displayables.push(displayable);
  14188. }
  14189. this.dirty();
  14190. };
  14191. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  14192. notPersistent = notPersistent || false;
  14193. for (var i = 0; i < displayables.length; i++) {
  14194. this.addDisplayable(displayables[i], notPersistent);
  14195. }
  14196. };
  14197. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  14198. for (var i = this._cursor; i < this._displayables.length; i++) {
  14199. cb && cb(this._displayables[i]);
  14200. }
  14201. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14202. cb && cb(this._temporaryDisplayables[i]);
  14203. }
  14204. };
  14205. IncrementalDisplayble.prototype.update = function () {
  14206. this.updateTransform();
  14207. for (var i = this._cursor; i < this._displayables.length; i++) {
  14208. var displayable = this._displayables[i];
  14209. // PENDING
  14210. displayable.parent = this;
  14211. displayable.update();
  14212. displayable.parent = null;
  14213. }
  14214. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14215. var displayable = this._temporaryDisplayables[i];
  14216. // PENDING
  14217. displayable.parent = this;
  14218. displayable.update();
  14219. displayable.parent = null;
  14220. }
  14221. };
  14222. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  14223. // Render persistant displayables.
  14224. for (var i = this._cursor; i < this._displayables.length; i++) {
  14225. var displayable = this._displayables[i];
  14226. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14227. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  14228. displayable.afterBrush && displayable.afterBrush(ctx);
  14229. }
  14230. this._cursor = i;
  14231. // Render temporary displayables.
  14232. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14233. var displayable = this._temporaryDisplayables[i];
  14234. displayable.beforeBrush && displayable.beforeBrush(ctx);
  14235. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  14236. displayable.afterBrush && displayable.afterBrush(ctx);
  14237. }
  14238. this._temporaryDisplayables = [];
  14239. this.notClear = true;
  14240. };
  14241. var m = [];
  14242. IncrementalDisplayble.prototype.getBoundingRect = function () {
  14243. if (!this._rect) {
  14244. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14245. for (var i = 0; i < this._displayables.length; i++) {
  14246. var displayable = this._displayables[i];
  14247. var childRect = displayable.getBoundingRect().clone();
  14248. if (displayable.needLocalTransform()) {
  14249. childRect.applyTransform(displayable.getLocalTransform(m));
  14250. }
  14251. rect.union(childRect);
  14252. }
  14253. this._rect = rect;
  14254. }
  14255. return this._rect;
  14256. };
  14257. IncrementalDisplayble.prototype.contain = function (x, y) {
  14258. var localPos = this.transformCoordToLocal(x, y);
  14259. var rect = this.getBoundingRect();
  14260. if (rect.contain(localPos[0], localPos[1])) {
  14261. for (var i = 0; i < this._displayables.length; i++) {
  14262. var displayable = this._displayables[i];
  14263. if (displayable.contain(x, y)) {
  14264. return true;
  14265. }
  14266. }
  14267. }
  14268. return false;
  14269. };
  14270. inherits(IncrementalDisplayble, Displayable);
  14271. /**
  14272. * 圆弧
  14273. * @module zrender/graphic/shape/Arc
  14274. */
  14275. var Arc = Path.extend({
  14276. type: 'arc',
  14277. shape: {
  14278. cx: 0,
  14279. cy: 0,
  14280. r: 0,
  14281. startAngle: 0,
  14282. endAngle: Math.PI * 2,
  14283. clockwise: true
  14284. },
  14285. style: {
  14286. stroke: '#000',
  14287. fill: null
  14288. },
  14289. buildPath: function (ctx, shape) {
  14290. var x = shape.cx;
  14291. var y = shape.cy;
  14292. var r = Math.max(shape.r, 0);
  14293. var startAngle = shape.startAngle;
  14294. var endAngle = shape.endAngle;
  14295. var clockwise = shape.clockwise;
  14296. var unitX = Math.cos(startAngle);
  14297. var unitY = Math.sin(startAngle);
  14298. ctx.moveTo(unitX * r + x, unitY * r + y);
  14299. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14300. }
  14301. });
  14302. /**
  14303. * 贝塞尔曲线
  14304. * @module zrender/shape/BezierCurve
  14305. */
  14306. var out = [];
  14307. function someVectorAt(shape, t, isTangent) {
  14308. var cpx2 = shape.cpx2;
  14309. var cpy2 = shape.cpy2;
  14310. if (cpx2 === null || cpy2 === null) {
  14311. return [
  14312. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  14313. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  14314. ];
  14315. }
  14316. else {
  14317. return [
  14318. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  14319. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  14320. ];
  14321. }
  14322. }
  14323. var BezierCurve = Path.extend({
  14324. type: 'bezier-curve',
  14325. shape: {
  14326. x1: 0,
  14327. y1: 0,
  14328. x2: 0,
  14329. y2: 0,
  14330. cpx1: 0,
  14331. cpy1: 0,
  14332. // cpx2: 0,
  14333. // cpy2: 0
  14334. // Curve show percent, for animating
  14335. percent: 1
  14336. },
  14337. style: {
  14338. stroke: '#000',
  14339. fill: null
  14340. },
  14341. buildPath: function (ctx, shape) {
  14342. var x1 = shape.x1;
  14343. var y1 = shape.y1;
  14344. var x2 = shape.x2;
  14345. var y2 = shape.y2;
  14346. var cpx1 = shape.cpx1;
  14347. var cpy1 = shape.cpy1;
  14348. var cpx2 = shape.cpx2;
  14349. var cpy2 = shape.cpy2;
  14350. var percent = shape.percent;
  14351. if (percent === 0) {
  14352. return;
  14353. }
  14354. ctx.moveTo(x1, y1);
  14355. if (cpx2 == null || cpy2 == null) {
  14356. if (percent < 1) {
  14357. quadraticSubdivide(
  14358. x1, cpx1, x2, percent, out
  14359. );
  14360. cpx1 = out[1];
  14361. x2 = out[2];
  14362. quadraticSubdivide(
  14363. y1, cpy1, y2, percent, out
  14364. );
  14365. cpy1 = out[1];
  14366. y2 = out[2];
  14367. }
  14368. ctx.quadraticCurveTo(
  14369. cpx1, cpy1,
  14370. x2, y2
  14371. );
  14372. }
  14373. else {
  14374. if (percent < 1) {
  14375. cubicSubdivide(
  14376. x1, cpx1, cpx2, x2, percent, out
  14377. );
  14378. cpx1 = out[1];
  14379. cpx2 = out[2];
  14380. x2 = out[3];
  14381. cubicSubdivide(
  14382. y1, cpy1, cpy2, y2, percent, out
  14383. );
  14384. cpy1 = out[1];
  14385. cpy2 = out[2];
  14386. y2 = out[3];
  14387. }
  14388. ctx.bezierCurveTo(
  14389. cpx1, cpy1,
  14390. cpx2, cpy2,
  14391. x2, y2
  14392. );
  14393. }
  14394. },
  14395. /**
  14396. * Get point at percent
  14397. * @param {number} t
  14398. * @return {Array.<number>}
  14399. */
  14400. pointAt: function (t) {
  14401. return someVectorAt(this.shape, t, false);
  14402. },
  14403. /**
  14404. * Get tangent at percent
  14405. * @param {number} t
  14406. * @return {Array.<number>}
  14407. */
  14408. tangentAt: function (t) {
  14409. var p = someVectorAt(this.shape, t, true);
  14410. return normalize(p, p);
  14411. }
  14412. });
  14413. /**
  14414. * 水滴形状
  14415. * @module zrender/graphic/shape/Droplet
  14416. */
  14417. var Droplet = Path.extend({
  14418. type: 'droplet',
  14419. shape: {
  14420. cx: 0, cy: 0,
  14421. width: 0, height: 0
  14422. },
  14423. buildPath: function (ctx, shape) {
  14424. var x = shape.cx;
  14425. var y = shape.cy;
  14426. var a = shape.width;
  14427. var b = shape.height;
  14428. ctx.moveTo(x, y + a);
  14429. ctx.bezierCurveTo(
  14430. x + a,
  14431. y + a,
  14432. x + a * 3 / 2,
  14433. y - a / 3,
  14434. x,
  14435. y - b
  14436. );
  14437. ctx.bezierCurveTo(
  14438. x - a * 3 / 2,
  14439. y - a / 3,
  14440. x - a,
  14441. y + a,
  14442. x,
  14443. y + a
  14444. );
  14445. ctx.closePath();
  14446. }
  14447. });
  14448. /**
  14449. * 心形
  14450. * @module zrender/graphic/shape/Heart
  14451. */
  14452. var Heart = Path.extend({
  14453. type: 'heart',
  14454. shape: {
  14455. cx: 0,
  14456. cy: 0,
  14457. width: 0,
  14458. height: 0
  14459. },
  14460. buildPath: function (ctx, shape) {
  14461. var x = shape.cx;
  14462. var y = shape.cy;
  14463. var a = shape.width;
  14464. var b = shape.height;
  14465. ctx.moveTo(x, y);
  14466. ctx.bezierCurveTo(
  14467. x + a / 2, y - b * 2 / 3,
  14468. x + a * 2, y + b / 3,
  14469. x, y + b
  14470. );
  14471. ctx.bezierCurveTo(
  14472. x - a * 2, y + b / 3,
  14473. x - a / 2, y - b * 2 / 3,
  14474. x, y
  14475. );
  14476. }
  14477. });
  14478. /**
  14479. * 正多边形
  14480. * @module zrender/shape/Isogon
  14481. */
  14482. var PI$1 = Math.PI;
  14483. var sin = Math.sin;
  14484. var cos = Math.cos;
  14485. var Isogon = Path.extend({
  14486. type: 'isogon',
  14487. shape: {
  14488. x: 0, y: 0,
  14489. r: 0, n: 0
  14490. },
  14491. buildPath: function (ctx, shape) {
  14492. var n = shape.n;
  14493. if (!n || n < 2) {
  14494. return;
  14495. }
  14496. var x = shape.x;
  14497. var y = shape.y;
  14498. var r = shape.r;
  14499. var dStep = 2 * PI$1 / n;
  14500. var deg = -PI$1 / 2;
  14501. ctx.moveTo(x + r * cos(deg), y + r * sin(deg));
  14502. for (var i = 0, end = n - 1; i < end; i++) {
  14503. deg += dStep;
  14504. ctx.lineTo(x + r * cos(deg), y + r * sin(deg));
  14505. }
  14506. ctx.closePath();
  14507. return;
  14508. }
  14509. });
  14510. /**
  14511. * 圆环
  14512. * @module zrender/graphic/shape/Ring
  14513. */
  14514. var Ring = Path.extend({
  14515. type: 'ring',
  14516. shape: {
  14517. cx: 0,
  14518. cy: 0,
  14519. r: 0,
  14520. r0: 0
  14521. },
  14522. buildPath: function (ctx, shape) {
  14523. var x = shape.cx;
  14524. var y = shape.cy;
  14525. var PI2 = Math.PI * 2;
  14526. ctx.moveTo(x + shape.r, y);
  14527. ctx.arc(x, y, shape.r, 0, PI2, false);
  14528. ctx.moveTo(x + shape.r0, y);
  14529. ctx.arc(x, y, shape.r0, 0, PI2, true);
  14530. }
  14531. });
  14532. /**
  14533. * 玫瑰线
  14534. * @module zrender/graphic/shape/Rose
  14535. */
  14536. var sin$1 = Math.sin;
  14537. var cos$1 = Math.cos;
  14538. var radian = Math.PI / 180;
  14539. var Rose = Path.extend({
  14540. type: 'rose',
  14541. shape: {
  14542. cx: 0,
  14543. cy: 0,
  14544. r: [],
  14545. k: 0,
  14546. n: 1
  14547. },
  14548. style: {
  14549. stroke: '#000',
  14550. fill: null
  14551. },
  14552. buildPath: function (ctx, shape) {
  14553. var x;
  14554. var y;
  14555. var R = shape.r;
  14556. var r;
  14557. var k = shape.k;
  14558. var n = shape.n;
  14559. var x0 = shape.cx;
  14560. var y0 = shape.cy;
  14561. ctx.moveTo(x0, y0);
  14562. for (var i = 0, len = R.length; i < len; i++) {
  14563. r = R[i];
  14564. for (var j = 0; j <= 360 * n; j++) {
  14565. x = r
  14566. * sin$1(k / n * j % 360 * radian)
  14567. * cos$1(j * radian)
  14568. + x0;
  14569. y = r
  14570. * sin$1(k / n * j % 360 * radian)
  14571. * sin$1(j * radian)
  14572. + y0;
  14573. ctx.lineTo(x, y);
  14574. }
  14575. }
  14576. }
  14577. });
  14578. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  14579. // where exception "unexpected call to method or property access"
  14580. // might be thrown when calling ctx.fill or ctx.stroke after a path
  14581. // whose area size is zero is drawn and ctx.clip() is called and
  14582. // shadowBlur is set. See #4572, #3112, #5777.
  14583. // (e.g.,
  14584. // ctx.moveTo(10, 10);
  14585. // ctx.lineTo(20, 10);
  14586. // ctx.closePath();
  14587. // ctx.clip();
  14588. // ctx.shadowBlur = 10;
  14589. // ...
  14590. // ctx.fill();
  14591. // )
  14592. var shadowTemp = [
  14593. ['shadowBlur', 0],
  14594. ['shadowColor', '#000'],
  14595. ['shadowOffsetX', 0],
  14596. ['shadowOffsetY', 0]
  14597. ];
  14598. var fixClipWithShadow = function (orignalBrush) {
  14599. // version string can be: '11.0'
  14600. return (env$1.browser.ie && env$1.browser.version >= 11)
  14601. ? function () {
  14602. var clipPaths = this.__clipPaths;
  14603. var style = this.style;
  14604. var modified;
  14605. if (clipPaths) {
  14606. for (var i = 0; i < clipPaths.length; i++) {
  14607. var clipPath = clipPaths[i];
  14608. var shape = clipPath && clipPath.shape;
  14609. var type = clipPath && clipPath.type;
  14610. if (shape && (
  14611. (type === 'sector' && shape.startAngle === shape.endAngle)
  14612. || (type === 'rect' && (!shape.width || !shape.height))
  14613. )) {
  14614. for (var j = 0; j < shadowTemp.length; j++) {
  14615. // It is save to put shadowTemp static, because shadowTemp
  14616. // will be all modified each item brush called.
  14617. shadowTemp[j][2] = style[shadowTemp[j][0]];
  14618. style[shadowTemp[j][0]] = shadowTemp[j][1];
  14619. }
  14620. modified = true;
  14621. break;
  14622. }
  14623. }
  14624. }
  14625. orignalBrush.apply(this, arguments);
  14626. if (modified) {
  14627. for (var j = 0; j < shadowTemp.length; j++) {
  14628. style[shadowTemp[j][0]] = shadowTemp[j][2];
  14629. }
  14630. }
  14631. }
  14632. : orignalBrush;
  14633. };
  14634. /**
  14635. * 扇形
  14636. * @module zrender/graphic/shape/Sector
  14637. */
  14638. var Sector = Path.extend({
  14639. type: 'sector',
  14640. shape: {
  14641. cx: 0,
  14642. cy: 0,
  14643. r0: 0,
  14644. r: 0,
  14645. startAngle: 0,
  14646. endAngle: Math.PI * 2,
  14647. clockwise: true
  14648. },
  14649. brush: fixClipWithShadow(Path.prototype.brush),
  14650. buildPath: function (ctx, shape) {
  14651. var x = shape.cx;
  14652. var y = shape.cy;
  14653. var r0 = Math.max(shape.r0 || 0, 0);
  14654. var r = Math.max(shape.r, 0);
  14655. var startAngle = shape.startAngle;
  14656. var endAngle = shape.endAngle;
  14657. var clockwise = shape.clockwise;
  14658. var unitX = Math.cos(startAngle);
  14659. var unitY = Math.sin(startAngle);
  14660. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  14661. ctx.lineTo(unitX * r + x, unitY * r + y);
  14662. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  14663. ctx.lineTo(
  14664. Math.cos(endAngle) * r0 + x,
  14665. Math.sin(endAngle) * r0 + y
  14666. );
  14667. if (r0 !== 0) {
  14668. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  14669. }
  14670. ctx.closePath();
  14671. }
  14672. });
  14673. /**
  14674. * n角星(n>3)
  14675. * @module zrender/graphic/shape/Star
  14676. */
  14677. var PI$2 = Math.PI;
  14678. var cos$2 = Math.cos;
  14679. var sin$2 = Math.sin;
  14680. var Star = Path.extend({
  14681. type: 'star',
  14682. shape: {
  14683. cx: 0,
  14684. cy: 0,
  14685. n: 3,
  14686. r0: null,
  14687. r: 0
  14688. },
  14689. buildPath: function (ctx, shape) {
  14690. var n = shape.n;
  14691. if (!n || n < 2) {
  14692. return;
  14693. }
  14694. var x = shape.cx;
  14695. var y = shape.cy;
  14696. var r = shape.r;
  14697. var r0 = shape.r0;
  14698. // 如果未指定内部顶点外接圆半径,则自动计算
  14699. if (r0 == null) {
  14700. r0 = n > 4
  14701. // 相隔的外部顶点的连线的交点,
  14702. // 被取为内部交点,以此计算r0
  14703. ? r * cos$2(2 * PI$2 / n) / cos$2(PI$2 / n)
  14704. // 二三四角星的特殊处理
  14705. : r / 3;
  14706. }
  14707. var dStep = PI$2 / n;
  14708. var deg = -PI$2 / 2;
  14709. var xStart = x + r * cos$2(deg);
  14710. var yStart = y + r * sin$2(deg);
  14711. deg += dStep;
  14712. // 记录边界点,用于判断inside
  14713. ctx.moveTo(xStart, yStart);
  14714. for (var i = 0, end = n * 2 - 1, ri; i < end; i++) {
  14715. ri = i % 2 === 0 ? r0 : r;
  14716. ctx.lineTo(x + ri * cos$2(deg), y + ri * sin$2(deg));
  14717. deg += dStep;
  14718. }
  14719. ctx.closePath();
  14720. }
  14721. });
  14722. /**
  14723. * 内外旋轮曲线
  14724. * @module zrender/graphic/shape/Trochold
  14725. */
  14726. var cos$3 = Math.cos;
  14727. var sin$3 = Math.sin;
  14728. var Trochoid = Path.extend({
  14729. type: 'trochoid',
  14730. shape: {
  14731. cx: 0,
  14732. cy: 0,
  14733. r: 0,
  14734. r0: 0,
  14735. d: 0,
  14736. location: 'out'
  14737. },
  14738. style: {
  14739. stroke: '#000',
  14740. fill: null
  14741. },
  14742. buildPath: function (ctx, shape) {
  14743. var x1;
  14744. var y1;
  14745. var x2;
  14746. var y2;
  14747. var R = shape.r;
  14748. var r = shape.r0;
  14749. var d = shape.d;
  14750. var offsetX = shape.cx;
  14751. var offsetY = shape.cy;
  14752. var delta = shape.location === 'out' ? 1 : -1;
  14753. if (shape.location && R <= r) {
  14754. return;
  14755. }
  14756. var num = 0;
  14757. var i = 1;
  14758. var theta;
  14759. x1 = (R + delta * r) * cos$3(0)
  14760. - delta * d * cos$3(0) + offsetX;
  14761. y1 = (R + delta * r) * sin$3(0)
  14762. - d * sin$3(0) + offsetY;
  14763. ctx.moveTo(x1, y1);
  14764. // 计算结束时的i
  14765. do {
  14766. num++;
  14767. }
  14768. while ((r * num) % (R + delta * r) !== 0);
  14769. do {
  14770. theta = Math.PI / 180 * i;
  14771. x2 = (R + delta * r) * cos$3(theta)
  14772. - delta * d * cos$3((R / r + delta) * theta)
  14773. + offsetX;
  14774. y2 = (R + delta * r) * sin$3(theta)
  14775. - d * sin$3((R / r + delta) * theta)
  14776. + offsetY;
  14777. ctx.lineTo(x2, y2);
  14778. i++;
  14779. }
  14780. while (i <= (r * num) / (R + delta * r) * 360);
  14781. }
  14782. });
  14783. /**
  14784. * x, y, r are all percent from 0 to 1
  14785. * @param {number} [x=0.5]
  14786. * @param {number} [y=0.5]
  14787. * @param {number} [r=0.5]
  14788. * @param {Array.<Object>} [colorStops]
  14789. * @param {boolean} [globalCoord=false]
  14790. */
  14791. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  14792. // Should do nothing more in this constructor. Because gradient can be
  14793. // declard by `color: {type: 'radial', colorStops: ...}`, where
  14794. // this constructor will not be called.
  14795. this.x = x == null ? 0.5 : x;
  14796. this.y = y == null ? 0.5 : y;
  14797. this.r = r == null ? 0.5 : r;
  14798. // Can be cloned
  14799. this.type = 'radial';
  14800. // If use global coord
  14801. this.global = globalCoord || false;
  14802. Gradient.call(this, colorStops);
  14803. };
  14804. RadialGradient.prototype = {
  14805. constructor: RadialGradient
  14806. };
  14807. inherits(RadialGradient, Gradient);
  14808. /**
  14809. * Do not mount those modules on 'src/zrender' for better tree shaking.
  14810. */
  14811. var svgURI = 'http://www.w3.org/2000/svg';
  14812. function createElement(name) {
  14813. return document.createElementNS(svgURI, name);
  14814. }
  14815. // TODO
  14816. // 1. shadow
  14817. // 2. Image: sx, sy, sw, sh
  14818. var CMD$3 = PathProxy.CMD;
  14819. var arrayJoin = Array.prototype.join;
  14820. var NONE = 'none';
  14821. var mathRound = Math.round;
  14822. var mathSin$3 = Math.sin;
  14823. var mathCos$3 = Math.cos;
  14824. var PI$3 = Math.PI;
  14825. var PI2$4 = Math.PI * 2;
  14826. var degree = 180 / PI$3;
  14827. var EPSILON$3 = 1e-4;
  14828. function round4(val) {
  14829. return mathRound(val * 1e4) / 1e4;
  14830. }
  14831. function isAroundZero$1(val) {
  14832. return val < EPSILON$3 && val > -EPSILON$3;
  14833. }
  14834. function pathHasFill(style, isText) {
  14835. var fill = isText ? style.textFill : style.fill;
  14836. return fill != null && fill !== NONE;
  14837. }
  14838. function pathHasStroke(style, isText) {
  14839. var stroke = isText ? style.textStroke : style.stroke;
  14840. return stroke != null && stroke !== NONE;
  14841. }
  14842. function setTransform(svgEl, m) {
  14843. if (m) {
  14844. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  14845. }
  14846. }
  14847. function attr(el, key, val) {
  14848. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  14849. // Don't set attribute for gradient, since it need new dom nodes
  14850. el.setAttribute(key, val);
  14851. }
  14852. }
  14853. function attrXLink(el, key, val) {
  14854. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  14855. }
  14856. function bindStyle(svgEl, style, isText, el) {
  14857. if (pathHasFill(style, isText)) {
  14858. var fill = isText ? style.textFill : style.fill;
  14859. fill = fill === 'transparent' ? NONE : fill;
  14860. attr(svgEl, 'fill', fill);
  14861. attr(svgEl, 'fill-opacity', style.fillOpacity != null ? style.fillOpacity * style.opacity : style.opacity);
  14862. }
  14863. else {
  14864. attr(svgEl, 'fill', NONE);
  14865. }
  14866. if (pathHasStroke(style, isText)) {
  14867. var stroke = isText ? style.textStroke : style.stroke;
  14868. stroke = stroke === 'transparent' ? NONE : stroke;
  14869. attr(svgEl, 'stroke', stroke);
  14870. var strokeWidth = isText
  14871. ? style.textStrokeWidth
  14872. : style.lineWidth;
  14873. var strokeScale = !isText && style.strokeNoScale
  14874. ? el.getLineScale()
  14875. : 1;
  14876. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  14877. // stroke then fill for text; fill then stroke for others
  14878. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  14879. attr(svgEl, 'stroke-opacity', style.strokeOpacity != null ? style.strokeOpacity : style.opacity);
  14880. var lineDash = style.lineDash;
  14881. if (lineDash) {
  14882. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  14883. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  14884. }
  14885. else {
  14886. attr(svgEl, 'stroke-dasharray', '');
  14887. }
  14888. // PENDING
  14889. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  14890. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  14891. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  14892. }
  14893. else {
  14894. attr(svgEl, 'stroke', NONE);
  14895. }
  14896. }
  14897. /***************************************************
  14898. * PATH
  14899. **************************************************/
  14900. function pathDataToString(path) {
  14901. var str = [];
  14902. var data = path.data;
  14903. var dataLength = path.len();
  14904. for (var i = 0; i < dataLength;) {
  14905. var cmd = data[i++];
  14906. var cmdStr = '';
  14907. var nData = 0;
  14908. switch (cmd) {
  14909. case CMD$3.M:
  14910. cmdStr = 'M';
  14911. nData = 2;
  14912. break;
  14913. case CMD$3.L:
  14914. cmdStr = 'L';
  14915. nData = 2;
  14916. break;
  14917. case CMD$3.Q:
  14918. cmdStr = 'Q';
  14919. nData = 4;
  14920. break;
  14921. case CMD$3.C:
  14922. cmdStr = 'C';
  14923. nData = 6;
  14924. break;
  14925. case CMD$3.A:
  14926. var cx = data[i++];
  14927. var cy = data[i++];
  14928. var rx = data[i++];
  14929. var ry = data[i++];
  14930. var theta = data[i++];
  14931. var dTheta = data[i++];
  14932. var psi = data[i++];
  14933. var clockwise = data[i++];
  14934. var dThetaPositive = Math.abs(dTheta);
  14935. var isCircle = isAroundZero$1(dThetaPositive - PI2$4)
  14936. || (clockwise ? dTheta >= PI2$4 : -dTheta >= PI2$4);
  14937. // Mapping to 0~2PI
  14938. var unifiedTheta = dTheta > 0 ? dTheta % PI2$4 : (dTheta % PI2$4 + PI2$4);
  14939. var large = false;
  14940. if (isCircle) {
  14941. large = true;
  14942. }
  14943. else if (isAroundZero$1(dThetaPositive)) {
  14944. large = false;
  14945. }
  14946. else {
  14947. large = (unifiedTheta >= PI$3) === !!clockwise;
  14948. }
  14949. var x0 = round4(cx + rx * mathCos$3(theta));
  14950. var y0 = round4(cy + ry * mathSin$3(theta));
  14951. // It will not draw if start point and end point are exactly the same
  14952. // We need to shift the end point with a small value
  14953. // FIXME A better way to draw circle ?
  14954. if (isCircle) {
  14955. if (clockwise) {
  14956. dTheta = PI2$4 - 1e-4;
  14957. }
  14958. else {
  14959. dTheta = -PI2$4 + 1e-4;
  14960. }
  14961. large = true;
  14962. if (i === 9) {
  14963. // Move to (x0, y0) only when CMD.A comes at the
  14964. // first position of a shape.
  14965. // For instance, when drawing a ring, CMD.A comes
  14966. // after CMD.M, so it's unnecessary to move to
  14967. // (x0, y0).
  14968. str.push('M', x0, y0);
  14969. }
  14970. }
  14971. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  14972. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  14973. // FIXME Ellipse
  14974. str.push('A', round4(rx), round4(ry),
  14975. mathRound(psi * degree), +large, +clockwise, x, y);
  14976. break;
  14977. case CMD$3.Z:
  14978. cmdStr = 'Z';
  14979. break;
  14980. case CMD$3.R:
  14981. var x = round4(data[i++]);
  14982. var y = round4(data[i++]);
  14983. var w = round4(data[i++]);
  14984. var h = round4(data[i++]);
  14985. str.push(
  14986. 'M', x, y,
  14987. 'L', x + w, y,
  14988. 'L', x + w, y + h,
  14989. 'L', x, y + h,
  14990. 'L', x, y
  14991. );
  14992. break;
  14993. }
  14994. cmdStr && str.push(cmdStr);
  14995. for (var j = 0; j < nData; j++) {
  14996. // PENDING With scale
  14997. str.push(round4(data[i++]));
  14998. }
  14999. }
  15000. return str.join(' ');
  15001. }
  15002. var svgPath = {};
  15003. svgPath.brush = function (el) {
  15004. var style = el.style;
  15005. var svgEl = el.__svgEl;
  15006. if (!svgEl) {
  15007. svgEl = createElement('path');
  15008. el.__svgEl = svgEl;
  15009. }
  15010. if (!el.path) {
  15011. el.createPathProxy();
  15012. }
  15013. var path = el.path;
  15014. if (el.__dirtyPath) {
  15015. path.beginPath();
  15016. path.subPixelOptimize = false;
  15017. el.buildPath(path, el.shape);
  15018. el.__dirtyPath = false;
  15019. var pathStr = pathDataToString(path);
  15020. if (pathStr.indexOf('NaN') < 0) {
  15021. // Ignore illegal path, which may happen such in out-of-range
  15022. // data in Calendar series.
  15023. attr(svgEl, 'd', pathStr);
  15024. }
  15025. }
  15026. bindStyle(svgEl, style, false, el);
  15027. setTransform(svgEl, el.transform);
  15028. if (style.text != null) {
  15029. svgTextDrawRectText(el, el.getBoundingRect());
  15030. }
  15031. else {
  15032. removeOldTextNode(el);
  15033. }
  15034. };
  15035. /***************************************************
  15036. * IMAGE
  15037. **************************************************/
  15038. var svgImage = {};
  15039. svgImage.brush = function (el) {
  15040. var style = el.style;
  15041. var image = style.image;
  15042. if (image instanceof HTMLImageElement) {
  15043. var src = image.src;
  15044. image = src;
  15045. }
  15046. if (!image) {
  15047. return;
  15048. }
  15049. var x = style.x || 0;
  15050. var y = style.y || 0;
  15051. var dw = style.width;
  15052. var dh = style.height;
  15053. var svgEl = el.__svgEl;
  15054. if (!svgEl) {
  15055. svgEl = createElement('image');
  15056. el.__svgEl = svgEl;
  15057. }
  15058. if (image !== el.__imageSrc) {
  15059. attrXLink(svgEl, 'href', image);
  15060. // Caching image src
  15061. el.__imageSrc = image;
  15062. }
  15063. attr(svgEl, 'width', dw);
  15064. attr(svgEl, 'height', dh);
  15065. attr(svgEl, 'x', x);
  15066. attr(svgEl, 'y', y);
  15067. setTransform(svgEl, el.transform);
  15068. if (style.text != null) {
  15069. svgTextDrawRectText(el, el.getBoundingRect());
  15070. }
  15071. else {
  15072. removeOldTextNode(el);
  15073. }
  15074. };
  15075. /***************************************************
  15076. * TEXT
  15077. **************************************************/
  15078. var svgText = {};
  15079. var _tmpTextHostRect = new BoundingRect();
  15080. var _tmpTextBoxPos = {};
  15081. var _tmpTextTransform = [];
  15082. var TEXT_ALIGN_TO_ANCHRO = {
  15083. left: 'start',
  15084. right: 'end',
  15085. center: 'middle',
  15086. middle: 'middle'
  15087. };
  15088. /**
  15089. * @param {module:zrender/Element} el
  15090. * @param {Object|boolean} [hostRect] {x, y, width, height}
  15091. * If set false, rect text is not used.
  15092. */
  15093. var svgTextDrawRectText = function (el, hostRect) {
  15094. var style = el.style;
  15095. var elTransform = el.transform;
  15096. var needTransformTextByHostEl = el instanceof Text || style.transformText;
  15097. el.__dirty && normalizeTextStyle(style, true);
  15098. var text = style.text;
  15099. // Convert to string
  15100. text != null && (text += '');
  15101. if (!needDrawText(text, style)) {
  15102. return;
  15103. }
  15104. // render empty text for svg if no text but need draw text.
  15105. text == null && (text = '');
  15106. // Follow the setting in the canvas renderer, if not transform the
  15107. // text, transform the hostRect, by which the text is located.
  15108. if (!needTransformTextByHostEl && elTransform) {
  15109. _tmpTextHostRect.copy(hostRect);
  15110. _tmpTextHostRect.applyTransform(elTransform);
  15111. hostRect = _tmpTextHostRect;
  15112. }
  15113. var textSvgEl = el.__textSvgEl;
  15114. if (!textSvgEl) {
  15115. textSvgEl = createElement('text');
  15116. el.__textSvgEl = textSvgEl;
  15117. }
  15118. // style.font has been normalized by `normalizeTextStyle`.
  15119. var textSvgElStyle = textSvgEl.style;
  15120. var font = style.font || DEFAULT_FONT$1;
  15121. var computedFont = textSvgEl.__computedFont;
  15122. if (font !== textSvgEl.__styleFont) {
  15123. textSvgElStyle.font = textSvgEl.__styleFont = font;
  15124. // The computedFont might not be the orginal font if it is illegal font.
  15125. computedFont = textSvgEl.__computedFont = textSvgElStyle.font;
  15126. }
  15127. var textPadding = style.textPadding;
  15128. var textLineHeight = style.textLineHeight;
  15129. var contentBlock = el.__textCotentBlock;
  15130. if (!contentBlock || el.__dirtyText) {
  15131. contentBlock = el.__textCotentBlock = parsePlainText(
  15132. text, computedFont, textPadding, textLineHeight, style.truncate
  15133. );
  15134. }
  15135. var outerHeight = contentBlock.outerHeight;
  15136. var lineHeight = contentBlock.lineHeight;
  15137. getBoxPosition(_tmpTextBoxPos, el, style, hostRect);
  15138. var baseX = _tmpTextBoxPos.baseX;
  15139. var baseY = _tmpTextBoxPos.baseY;
  15140. var textAlign = _tmpTextBoxPos.textAlign || 'left';
  15141. var textVerticalAlign = _tmpTextBoxPos.textVerticalAlign;
  15142. setTextTransform(
  15143. textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY
  15144. );
  15145. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  15146. var textX = baseX;
  15147. var textY = boxY;
  15148. // TODO needDrawBg
  15149. if (textPadding) {
  15150. textX = getTextXForPadding$1(baseX, textAlign, textPadding);
  15151. textY += textPadding[0];
  15152. }
  15153. // `textBaseline` is set as 'middle'.
  15154. textY += lineHeight / 2;
  15155. bindStyle(textSvgEl, style, true, el);
  15156. // FIXME
  15157. // Add a <style> to reset all of the text font as inherit?
  15158. // otherwise the outer <style> may set the unexpected style.
  15159. // Font may affect position of each tspan elements
  15160. var canCacheByTextString = contentBlock.canCacheByTextString;
  15161. var tspanList = el.__tspanList || (el.__tspanList = []);
  15162. var tspanOriginLen = tspanList.length;
  15163. // Optimize for most cases, just compare text string to determine change.
  15164. if (canCacheByTextString && el.__canCacheByTextString && el.__text === text) {
  15165. if (el.__dirtyText && tspanOriginLen) {
  15166. for (var idx = 0; idx < tspanOriginLen; ++idx) {
  15167. updateTextLocation(tspanList[idx], textAlign, textX, textY + idx * lineHeight);
  15168. }
  15169. }
  15170. }
  15171. else {
  15172. el.__text = text;
  15173. el.__canCacheByTextString = canCacheByTextString;
  15174. var textLines = contentBlock.lines;
  15175. var nTextLines = textLines.length;
  15176. var idx = 0;
  15177. for (; idx < nTextLines; idx++) {
  15178. // Using cached tspan elements
  15179. var tspan = tspanList[idx];
  15180. var singleLineText = textLines[idx];
  15181. if (!tspan) {
  15182. tspan = tspanList[idx] = createElement('tspan');
  15183. textSvgEl.appendChild(tspan);
  15184. tspan.appendChild(document.createTextNode(singleLineText));
  15185. }
  15186. else if (tspan.__zrText !== singleLineText) {
  15187. tspan.innerHTML = '';
  15188. tspan.appendChild(document.createTextNode(singleLineText));
  15189. }
  15190. updateTextLocation(tspan, textAlign, textX, textY + idx * lineHeight);
  15191. }
  15192. // Remove unused tspan elements
  15193. if (tspanOriginLen > nTextLines) {
  15194. for (; idx < tspanOriginLen; idx++) {
  15195. textSvgEl.removeChild(tspanList[idx]);
  15196. }
  15197. tspanList.length = nTextLines;
  15198. }
  15199. }
  15200. };
  15201. function setTextTransform(textSvgEl, needTransformTextByHostEl, elTransform, style, hostRect, baseX, baseY) {
  15202. identity(_tmpTextTransform);
  15203. if (needTransformTextByHostEl && elTransform) {
  15204. copy$1(_tmpTextTransform, elTransform);
  15205. }
  15206. // textRotation only apply in RectText.
  15207. var textRotation = style.textRotation;
  15208. if (hostRect && textRotation) {
  15209. var origin = style.textOrigin;
  15210. if (origin === 'center') {
  15211. baseX = hostRect.width / 2 + hostRect.x;
  15212. baseY = hostRect.height / 2 + hostRect.y;
  15213. }
  15214. else if (origin) {
  15215. baseX = origin[0] + hostRect.x;
  15216. baseY = origin[1] + hostRect.y;
  15217. }
  15218. _tmpTextTransform[4] -= baseX;
  15219. _tmpTextTransform[5] -= baseY;
  15220. // Positive: anticlockwise
  15221. rotate(_tmpTextTransform, _tmpTextTransform, textRotation);
  15222. _tmpTextTransform[4] += baseX;
  15223. _tmpTextTransform[5] += baseY;
  15224. }
  15225. // See the definition in `Style.js#textOrigin`, the default
  15226. // origin is from the result of `getBoxPosition`.
  15227. setTransform(textSvgEl, _tmpTextTransform);
  15228. }
  15229. // FIXME merge the same code with `helper/text.js#getTextXForPadding`;
  15230. function getTextXForPadding$1(x, textAlign, textPadding) {
  15231. return textAlign === 'right'
  15232. ? (x - textPadding[1])
  15233. : textAlign === 'center'
  15234. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  15235. : (x + textPadding[3]);
  15236. }
  15237. function updateTextLocation(tspan, textAlign, x, y) {
  15238. // Consider different font display differently in vertial align, we always
  15239. // set vertialAlign as 'middle', and use 'y' to locate text vertically.
  15240. attr(tspan, 'dominant-baseline', 'middle');
  15241. attr(tspan, 'text-anchor', TEXT_ALIGN_TO_ANCHRO[textAlign]);
  15242. attr(tspan, 'x', x);
  15243. attr(tspan, 'y', y);
  15244. }
  15245. function removeOldTextNode(el) {
  15246. if (el && el.__textSvgEl) {
  15247. // textSvgEl may has no parentNode if el has been removed temporary.
  15248. if (el.__textSvgEl.parentNode) {
  15249. el.__textSvgEl.parentNode.removeChild(el.__textSvgEl);
  15250. }
  15251. el.__textSvgEl = null;
  15252. el.__tspanList = [];
  15253. el.__text = null;
  15254. }
  15255. }
  15256. svgText.drawRectText = svgTextDrawRectText;
  15257. svgText.brush = function (el) {
  15258. var style = el.style;
  15259. if (style.text != null) {
  15260. svgTextDrawRectText(el, false);
  15261. }
  15262. else {
  15263. removeOldTextNode(el);
  15264. }
  15265. };
  15266. // Myers' Diff Algorithm
  15267. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  15268. function Diff() {}
  15269. Diff.prototype = {
  15270. diff: function (oldArr, newArr, equals) {
  15271. if (!equals) {
  15272. equals = function (a, b) {
  15273. return a === b;
  15274. };
  15275. }
  15276. this.equals = equals;
  15277. var self = this;
  15278. oldArr = oldArr.slice();
  15279. newArr = newArr.slice();
  15280. // Allow subclasses to massage the input prior to running
  15281. var newLen = newArr.length;
  15282. var oldLen = oldArr.length;
  15283. var editLength = 1;
  15284. var maxEditLength = newLen + oldLen;
  15285. var bestPath = [{ newPos: -1, components: [] }];
  15286. // Seed editLength = 0, i.e. the content starts with the same values
  15287. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  15288. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  15289. var indices = [];
  15290. for (var i = 0; i < newArr.length; i++) {
  15291. indices.push(i);
  15292. }
  15293. // Identity per the equality and tokenizer
  15294. return [{
  15295. indices: indices, count: newArr.length
  15296. }];
  15297. }
  15298. // Main worker method. checks all permutations of a given edit length for acceptance.
  15299. function execEditLength() {
  15300. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  15301. var basePath;
  15302. var addPath = bestPath[diagonalPath - 1];
  15303. var removePath = bestPath[diagonalPath + 1];
  15304. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  15305. if (addPath) {
  15306. // No one else is going to attempt to use this value, clear it
  15307. bestPath[diagonalPath - 1] = undefined;
  15308. }
  15309. var canAdd = addPath && addPath.newPos + 1 < newLen;
  15310. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  15311. if (!canAdd && !canRemove) {
  15312. // If this path is a terminal then prune
  15313. bestPath[diagonalPath] = undefined;
  15314. continue;
  15315. }
  15316. // Select the diagonal that we want to branch from. We select the prior
  15317. // path whose position in the new string is the farthest from the origin
  15318. // and does not pass the bounds of the diff graph
  15319. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  15320. basePath = clonePath(removePath);
  15321. self.pushComponent(basePath.components, undefined, true);
  15322. }
  15323. else {
  15324. basePath = addPath; // No need to clone, we've pulled it from the list
  15325. basePath.newPos++;
  15326. self.pushComponent(basePath.components, true, undefined);
  15327. }
  15328. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  15329. // If we have hit the end of both strings, then we are done
  15330. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  15331. return buildValues(self, basePath.components, newArr, oldArr);
  15332. }
  15333. else {
  15334. // Otherwise track this path as a potential candidate and continue.
  15335. bestPath[diagonalPath] = basePath;
  15336. }
  15337. }
  15338. editLength++;
  15339. }
  15340. while (editLength <= maxEditLength) {
  15341. var ret = execEditLength();
  15342. if (ret) {
  15343. return ret;
  15344. }
  15345. }
  15346. },
  15347. pushComponent: function (components, added, removed) {
  15348. var last = components[components.length - 1];
  15349. if (last && last.added === added && last.removed === removed) {
  15350. // We need to clone here as the component clone operation is just
  15351. // as shallow array clone
  15352. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  15353. }
  15354. else {
  15355. components.push({count: 1, added: added, removed: removed });
  15356. }
  15357. },
  15358. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  15359. var newLen = newArr.length;
  15360. var oldLen = oldArr.length;
  15361. var newPos = basePath.newPos;
  15362. var oldPos = newPos - diagonalPath;
  15363. var commonCount = 0;
  15364. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  15365. newPos++;
  15366. oldPos++;
  15367. commonCount++;
  15368. }
  15369. if (commonCount) {
  15370. basePath.components.push({count: commonCount});
  15371. }
  15372. basePath.newPos = newPos;
  15373. return oldPos;
  15374. },
  15375. tokenize: function (value) {
  15376. return value.slice();
  15377. },
  15378. join: function (value) {
  15379. return value.slice();
  15380. }
  15381. };
  15382. function buildValues(diff, components, newArr, oldArr) {
  15383. var componentPos = 0;
  15384. var componentLen = components.length;
  15385. var newPos = 0;
  15386. var oldPos = 0;
  15387. for (; componentPos < componentLen; componentPos++) {
  15388. var component = components[componentPos];
  15389. if (!component.removed) {
  15390. var indices = [];
  15391. for (var i = newPos; i < newPos + component.count; i++) {
  15392. indices.push(i);
  15393. }
  15394. component.indices = indices;
  15395. newPos += component.count;
  15396. // Common case
  15397. if (!component.added) {
  15398. oldPos += component.count;
  15399. }
  15400. }
  15401. else {
  15402. var indices = [];
  15403. for (var i = oldPos; i < oldPos + component.count; i++) {
  15404. indices.push(i);
  15405. }
  15406. component.indices = indices;
  15407. oldPos += component.count;
  15408. }
  15409. }
  15410. return components;
  15411. }
  15412. function clonePath(path) {
  15413. return { newPos: path.newPos, components: path.components.slice(0) };
  15414. }
  15415. var arrayDiff = new Diff();
  15416. var arrayDiff$1 = function (oldArr, newArr, callback) {
  15417. return arrayDiff.diff(oldArr, newArr, callback);
  15418. };
  15419. /**
  15420. * @file Manages elements that can be defined in <defs> in SVG,
  15421. * e.g., gradients, clip path, etc.
  15422. * @author Zhang Wenli
  15423. */
  15424. var MARK_UNUSED = '0';
  15425. var MARK_USED = '1';
  15426. /**
  15427. * Manages elements that can be defined in <defs> in SVG,
  15428. * e.g., gradients, clip path, etc.
  15429. *
  15430. * @class
  15431. * @param {number} zrId zrender instance id
  15432. * @param {SVGElement} svgRoot root of SVG document
  15433. * @param {string|string[]} tagNames possible tag names
  15434. * @param {string} markLabel label name to make if the element
  15435. * is used
  15436. */
  15437. function Definable(
  15438. zrId,
  15439. svgRoot,
  15440. tagNames,
  15441. markLabel,
  15442. domName
  15443. ) {
  15444. this._zrId = zrId;
  15445. this._svgRoot = svgRoot;
  15446. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  15447. this._markLabel = markLabel;
  15448. this._domName = domName || '_dom';
  15449. this.nextId = 0;
  15450. }
  15451. Definable.prototype.createElement = createElement;
  15452. /**
  15453. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  15454. *
  15455. * @param {boolean} isForceCreating if need to create when not exists
  15456. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  15457. * exist and isForceCreating is false
  15458. */
  15459. Definable.prototype.getDefs = function (isForceCreating) {
  15460. var svgRoot = this._svgRoot;
  15461. var defs = this._svgRoot.getElementsByTagName('defs');
  15462. if (defs.length === 0) {
  15463. // Not exist
  15464. if (isForceCreating) {
  15465. defs = svgRoot.insertBefore(
  15466. this.createElement('defs'), // Create new tag
  15467. svgRoot.firstChild // Insert in the front of svg
  15468. );
  15469. if (!defs.contains) {
  15470. // IE doesn't support contains method
  15471. defs.contains = function (el) {
  15472. var children = defs.children;
  15473. if (!children) {
  15474. return false;
  15475. }
  15476. for (var i = children.length - 1; i >= 0; --i) {
  15477. if (children[i] === el) {
  15478. return true;
  15479. }
  15480. }
  15481. return false;
  15482. };
  15483. }
  15484. return defs;
  15485. }
  15486. else {
  15487. return null;
  15488. }
  15489. }
  15490. else {
  15491. return defs[0];
  15492. }
  15493. };
  15494. /**
  15495. * Update DOM element if necessary.
  15496. *
  15497. * @param {Object|string} element style element. e.g., for gradient,
  15498. * it may be '#ccc' or {type: 'linear', ...}
  15499. * @param {Function|undefined} onUpdate update callback
  15500. */
  15501. Definable.prototype.update = function (element, onUpdate) {
  15502. if (!element) {
  15503. return;
  15504. }
  15505. var defs = this.getDefs(false);
  15506. if (element[this._domName] && defs.contains(element[this._domName])) {
  15507. // Update DOM
  15508. if (typeof onUpdate === 'function') {
  15509. onUpdate(element);
  15510. }
  15511. }
  15512. else {
  15513. // No previous dom, create new
  15514. var dom = this.add(element);
  15515. if (dom) {
  15516. element[this._domName] = dom;
  15517. }
  15518. }
  15519. };
  15520. /**
  15521. * Add gradient dom to defs
  15522. *
  15523. * @param {SVGElement} dom DOM to be added to <defs>
  15524. */
  15525. Definable.prototype.addDom = function (dom) {
  15526. var defs = this.getDefs(true);
  15527. defs.appendChild(dom);
  15528. };
  15529. /**
  15530. * Remove DOM of a given element.
  15531. *
  15532. * @param {SVGElement} element element to remove dom
  15533. */
  15534. Definable.prototype.removeDom = function (element) {
  15535. var defs = this.getDefs(false);
  15536. if (defs && element[this._domName]) {
  15537. defs.removeChild(element[this._domName]);
  15538. element[this._domName] = null;
  15539. }
  15540. };
  15541. /**
  15542. * Get DOMs of this element.
  15543. *
  15544. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  15545. */
  15546. Definable.prototype.getDoms = function () {
  15547. var defs = this.getDefs(false);
  15548. if (!defs) {
  15549. // No dom when defs is not defined
  15550. return [];
  15551. }
  15552. var doms = [];
  15553. each(this._tagNames, function (tagName) {
  15554. var tags = defs.getElementsByTagName(tagName);
  15555. // Note that tags is HTMLCollection, which is array-like
  15556. // rather than real array.
  15557. // So `doms.concat(tags)` add tags as one object.
  15558. doms = doms.concat([].slice.call(tags));
  15559. });
  15560. return doms;
  15561. };
  15562. /**
  15563. * Mark DOMs to be unused before painting, and clear unused ones at the end
  15564. * of the painting.
  15565. */
  15566. Definable.prototype.markAllUnused = function () {
  15567. var doms = this.getDoms();
  15568. var that = this;
  15569. each(doms, function (dom) {
  15570. dom[that._markLabel] = MARK_UNUSED;
  15571. });
  15572. };
  15573. /**
  15574. * Mark a single DOM to be used.
  15575. *
  15576. * @param {SVGElement} dom DOM to mark
  15577. */
  15578. Definable.prototype.markUsed = function (dom) {
  15579. if (dom) {
  15580. dom[this._markLabel] = MARK_USED;
  15581. }
  15582. };
  15583. /**
  15584. * Remove unused DOMs defined in <defs>
  15585. */
  15586. Definable.prototype.removeUnused = function () {
  15587. var defs = this.getDefs(false);
  15588. if (!defs) {
  15589. // Nothing to remove
  15590. return;
  15591. }
  15592. var doms = this.getDoms();
  15593. var that = this;
  15594. each(doms, function (dom) {
  15595. if (dom[that._markLabel] !== MARK_USED) {
  15596. // Remove gradient
  15597. defs.removeChild(dom);
  15598. }
  15599. });
  15600. };
  15601. /**
  15602. * Get SVG proxy.
  15603. *
  15604. * @param {Displayable} displayable displayable element
  15605. * @return {Path|Image|Text} svg proxy of given element
  15606. */
  15607. Definable.prototype.getSvgProxy = function (displayable) {
  15608. if (displayable instanceof Path) {
  15609. return svgPath;
  15610. }
  15611. else if (displayable instanceof ZImage) {
  15612. return svgImage;
  15613. }
  15614. else if (displayable instanceof Text) {
  15615. return svgText;
  15616. }
  15617. else {
  15618. return svgPath;
  15619. }
  15620. };
  15621. /**
  15622. * Get text SVG element.
  15623. *
  15624. * @param {Displayable} displayable displayable element
  15625. * @return {SVGElement} SVG element of text
  15626. */
  15627. Definable.prototype.getTextSvgElement = function (displayable) {
  15628. return displayable.__textSvgEl;
  15629. };
  15630. /**
  15631. * Get SVG element.
  15632. *
  15633. * @param {Displayable} displayable displayable element
  15634. * @return {SVGElement} SVG element
  15635. */
  15636. Definable.prototype.getSvgElement = function (displayable) {
  15637. return displayable.__svgEl;
  15638. };
  15639. /**
  15640. * @file Manages SVG gradient elements.
  15641. * @author Zhang Wenli
  15642. */
  15643. /**
  15644. * Manages SVG gradient elements.
  15645. *
  15646. * @class
  15647. * @extends Definable
  15648. * @param {number} zrId zrender instance id
  15649. * @param {SVGElement} svgRoot root of SVG document
  15650. */
  15651. function GradientManager(zrId, svgRoot) {
  15652. Definable.call(
  15653. this,
  15654. zrId,
  15655. svgRoot,
  15656. ['linearGradient', 'radialGradient'],
  15657. '__gradient_in_use__'
  15658. );
  15659. }
  15660. inherits(GradientManager, Definable);
  15661. /**
  15662. * Create new gradient DOM for fill or stroke if not exist,
  15663. * but will not update gradient if exists.
  15664. *
  15665. * @param {SvgElement} svgElement SVG element to paint
  15666. * @param {Displayable} displayable zrender displayable element
  15667. */
  15668. GradientManager.prototype.addWithoutUpdate = function (
  15669. svgElement,
  15670. displayable
  15671. ) {
  15672. if (displayable && displayable.style) {
  15673. var that = this;
  15674. each(['fill', 'stroke'], function (fillOrStroke) {
  15675. if (displayable.style[fillOrStroke]
  15676. && (displayable.style[fillOrStroke].type === 'linear'
  15677. || displayable.style[fillOrStroke].type === 'radial')
  15678. ) {
  15679. var gradient = displayable.style[fillOrStroke];
  15680. var defs = that.getDefs(true);
  15681. // Create dom in <defs> if not exists
  15682. var dom;
  15683. if (gradient._dom) {
  15684. // Gradient exists
  15685. dom = gradient._dom;
  15686. if (!defs.contains(gradient._dom)) {
  15687. // _dom is no longer in defs, recreate
  15688. that.addDom(dom);
  15689. }
  15690. }
  15691. else {
  15692. // New dom
  15693. dom = that.add(gradient);
  15694. }
  15695. that.markUsed(displayable);
  15696. var id = dom.getAttribute('id');
  15697. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  15698. }
  15699. });
  15700. }
  15701. };
  15702. /**
  15703. * Add a new gradient tag in <defs>
  15704. *
  15705. * @param {Gradient} gradient zr gradient instance
  15706. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  15707. * created DOM
  15708. */
  15709. GradientManager.prototype.add = function (gradient) {
  15710. var dom;
  15711. if (gradient.type === 'linear') {
  15712. dom = this.createElement('linearGradient');
  15713. }
  15714. else if (gradient.type === 'radial') {
  15715. dom = this.createElement('radialGradient');
  15716. }
  15717. else {
  15718. logError$1('Illegal gradient type.');
  15719. return null;
  15720. }
  15721. // Set dom id with gradient id, since each gradient instance
  15722. // will have no more than one dom element.
  15723. // id may exists before for those dirty elements, in which case
  15724. // id should remain the same, and other attributes should be
  15725. // updated.
  15726. gradient.id = gradient.id || this.nextId++;
  15727. dom.setAttribute('id', 'zr' + this._zrId
  15728. + '-gradient-' + gradient.id);
  15729. this.updateDom(gradient, dom);
  15730. this.addDom(dom);
  15731. return dom;
  15732. };
  15733. /**
  15734. * Update gradient.
  15735. *
  15736. * @param {Gradient} gradient zr gradient instance
  15737. */
  15738. GradientManager.prototype.update = function (gradient) {
  15739. var that = this;
  15740. Definable.prototype.update.call(this, gradient, function () {
  15741. var type = gradient.type;
  15742. var tagName = gradient._dom.tagName;
  15743. if (type === 'linear' && tagName === 'linearGradient'
  15744. || type === 'radial' && tagName === 'radialGradient'
  15745. ) {
  15746. // Gradient type is not changed, update gradient
  15747. that.updateDom(gradient, gradient._dom);
  15748. }
  15749. else {
  15750. // Remove and re-create if type is changed
  15751. that.removeDom(gradient);
  15752. that.add(gradient);
  15753. }
  15754. });
  15755. };
  15756. /**
  15757. * Update gradient dom
  15758. *
  15759. * @param {Gradient} gradient zr gradient instance
  15760. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  15761. * DOM to update
  15762. */
  15763. GradientManager.prototype.updateDom = function (gradient, dom) {
  15764. if (gradient.type === 'linear') {
  15765. dom.setAttribute('x1', gradient.x);
  15766. dom.setAttribute('y1', gradient.y);
  15767. dom.setAttribute('x2', gradient.x2);
  15768. dom.setAttribute('y2', gradient.y2);
  15769. }
  15770. else if (gradient.type === 'radial') {
  15771. dom.setAttribute('cx', gradient.x);
  15772. dom.setAttribute('cy', gradient.y);
  15773. dom.setAttribute('r', gradient.r);
  15774. }
  15775. else {
  15776. logError$1('Illegal gradient type.');
  15777. return;
  15778. }
  15779. if (gradient.global) {
  15780. // x1, x2, y1, y2 in range of 0 to canvas width or height
  15781. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  15782. }
  15783. else {
  15784. // x1, x2, y1, y2 in range of 0 to 1
  15785. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  15786. }
  15787. // Remove color stops if exists
  15788. dom.innerHTML = '';
  15789. // Add color stops
  15790. var colors = gradient.colorStops;
  15791. for (var i = 0, len = colors.length; i < len; ++i) {
  15792. var stop = this.createElement('stop');
  15793. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  15794. var color = colors[i].color;
  15795. if (color.indexOf('rgba' > -1)) {
  15796. // Fix Safari bug that stop-color not recognizing alpha #9014
  15797. var opacity = parse(color)[3];
  15798. var hex = toHex(color);
  15799. // stop-color cannot be color, since:
  15800. // The opacity value used for the gradient calculation is the
  15801. // *product* of the value of stop-opacity and the opacity of the
  15802. // value of stop-color.
  15803. // See https://www.w3.org/TR/SVG2/pservers.html#StopOpacityProperty
  15804. stop.setAttribute('stop-color', '#' + hex);
  15805. stop.setAttribute('stop-opacity', opacity);
  15806. }
  15807. else {
  15808. stop.setAttribute('stop-color', colors[i].color);
  15809. }
  15810. dom.appendChild(stop);
  15811. }
  15812. // Store dom element in gradient, to avoid creating multiple
  15813. // dom instances for the same gradient element
  15814. gradient._dom = dom;
  15815. };
  15816. /**
  15817. * Mark a single gradient to be used
  15818. *
  15819. * @param {Displayable} displayable displayable element
  15820. */
  15821. GradientManager.prototype.markUsed = function (displayable) {
  15822. if (displayable.style) {
  15823. var gradient = displayable.style.fill;
  15824. if (gradient && gradient._dom) {
  15825. Definable.prototype.markUsed.call(this, gradient._dom);
  15826. }
  15827. gradient = displayable.style.stroke;
  15828. if (gradient && gradient._dom) {
  15829. Definable.prototype.markUsed.call(this, gradient._dom);
  15830. }
  15831. }
  15832. };
  15833. /**
  15834. * @file Manages SVG clipPath elements.
  15835. * @author Zhang Wenli
  15836. */
  15837. /**
  15838. * Manages SVG clipPath elements.
  15839. *
  15840. * @class
  15841. * @extends Definable
  15842. * @param {number} zrId zrender instance id
  15843. * @param {SVGElement} svgRoot root of SVG document
  15844. */
  15845. function ClippathManager(zrId, svgRoot) {
  15846. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  15847. }
  15848. inherits(ClippathManager, Definable);
  15849. /**
  15850. * Update clipPath.
  15851. *
  15852. * @param {Displayable} displayable displayable element
  15853. */
  15854. ClippathManager.prototype.update = function (displayable) {
  15855. var svgEl = this.getSvgElement(displayable);
  15856. if (svgEl) {
  15857. this.updateDom(svgEl, displayable.__clipPaths, false);
  15858. }
  15859. var textEl = this.getTextSvgElement(displayable);
  15860. if (textEl) {
  15861. // Make another clipPath for text, since it's transform
  15862. // matrix is not the same with svgElement
  15863. this.updateDom(textEl, displayable.__clipPaths, true);
  15864. }
  15865. this.markUsed(displayable);
  15866. };
  15867. /**
  15868. * Create an SVGElement of displayable and create a <clipPath> of its
  15869. * clipPath
  15870. *
  15871. * @param {Displayable} parentEl parent element
  15872. * @param {ClipPath[]} clipPaths clipPaths of parent element
  15873. * @param {boolean} isText if parent element is Text
  15874. */
  15875. ClippathManager.prototype.updateDom = function (
  15876. parentEl,
  15877. clipPaths,
  15878. isText
  15879. ) {
  15880. if (clipPaths && clipPaths.length > 0) {
  15881. // Has clipPath, create <clipPath> with the first clipPath
  15882. var defs = this.getDefs(true);
  15883. var clipPath = clipPaths[0];
  15884. var clipPathEl;
  15885. var id;
  15886. var dom = isText ? '_textDom' : '_dom';
  15887. if (clipPath[dom]) {
  15888. // Use a dom that is already in <defs>
  15889. id = clipPath[dom].getAttribute('id');
  15890. clipPathEl = clipPath[dom];
  15891. // Use a dom that is already in <defs>
  15892. if (!defs.contains(clipPathEl)) {
  15893. // This happens when set old clipPath that has
  15894. // been previously removed
  15895. defs.appendChild(clipPathEl);
  15896. }
  15897. }
  15898. else {
  15899. // New <clipPath>
  15900. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  15901. ++this.nextId;
  15902. clipPathEl = this.createElement('clipPath');
  15903. clipPathEl.setAttribute('id', id);
  15904. defs.appendChild(clipPathEl);
  15905. clipPath[dom] = clipPathEl;
  15906. }
  15907. // Build path and add to <clipPath>
  15908. var svgProxy = this.getSvgProxy(clipPath);
  15909. if (clipPath.transform
  15910. && clipPath.parent.invTransform
  15911. && !isText
  15912. ) {
  15913. /**
  15914. * If a clipPath has a parent with transform, the transform
  15915. * of parent should not be considered when setting transform
  15916. * of clipPath. So we need to transform back from parent's
  15917. * transform, which is done by multiplying parent's inverse
  15918. * transform.
  15919. */
  15920. // Store old transform
  15921. var transform = Array.prototype.slice.call(
  15922. clipPath.transform
  15923. );
  15924. // Transform back from parent, and brush path
  15925. mul$1(
  15926. clipPath.transform,
  15927. clipPath.parent.invTransform,
  15928. clipPath.transform
  15929. );
  15930. svgProxy.brush(clipPath);
  15931. // Set back transform of clipPath
  15932. clipPath.transform = transform;
  15933. }
  15934. else {
  15935. svgProxy.brush(clipPath);
  15936. }
  15937. var pathEl = this.getSvgElement(clipPath);
  15938. clipPathEl.innerHTML = '';
  15939. /**
  15940. * Use `cloneNode()` here to appendChild to multiple parents,
  15941. * which may happend when Text and other shapes are using the same
  15942. * clipPath. Since Text will create an extra clipPath DOM due to
  15943. * different transform rules.
  15944. */
  15945. clipPathEl.appendChild(pathEl.cloneNode());
  15946. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  15947. if (clipPaths.length > 1) {
  15948. // Make the other clipPaths recursively
  15949. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  15950. }
  15951. }
  15952. else {
  15953. // No clipPath
  15954. if (parentEl) {
  15955. parentEl.setAttribute('clip-path', 'none');
  15956. }
  15957. }
  15958. };
  15959. /**
  15960. * Mark a single clipPath to be used
  15961. *
  15962. * @param {Displayable} displayable displayable element
  15963. */
  15964. ClippathManager.prototype.markUsed = function (displayable) {
  15965. var that = this;
  15966. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  15967. if (displayable.__clipPaths) {
  15968. each(displayable.__clipPaths, function (clipPath) {
  15969. if (clipPath._dom) {
  15970. Definable.prototype.markUsed.call(that, clipPath._dom);
  15971. }
  15972. if (clipPath._textDom) {
  15973. Definable.prototype.markUsed.call(that, clipPath._textDom);
  15974. }
  15975. });
  15976. }
  15977. };
  15978. /**
  15979. * @file Manages SVG shadow elements.
  15980. * @author Zhang Wenli
  15981. */
  15982. /**
  15983. * Manages SVG shadow elements.
  15984. *
  15985. * @class
  15986. * @extends Definable
  15987. * @param {number} zrId zrender instance id
  15988. * @param {SVGElement} svgRoot root of SVG document
  15989. */
  15990. function ShadowManager(zrId, svgRoot) {
  15991. Definable.call(
  15992. this,
  15993. zrId,
  15994. svgRoot,
  15995. ['filter'],
  15996. '__filter_in_use__',
  15997. '_shadowDom'
  15998. );
  15999. }
  16000. inherits(ShadowManager, Definable);
  16001. /**
  16002. * Create new shadow DOM for fill or stroke if not exist,
  16003. * but will not update shadow if exists.
  16004. *
  16005. * @param {SvgElement} svgElement SVG element to paint
  16006. * @param {Displayable} displayable zrender displayable element
  16007. */
  16008. ShadowManager.prototype.addWithoutUpdate = function (
  16009. svgElement,
  16010. displayable
  16011. ) {
  16012. if (displayable && hasShadow(displayable.style)) {
  16013. // Create dom in <defs> if not exists
  16014. var dom;
  16015. if (displayable._shadowDom) {
  16016. // Gradient exists
  16017. dom = displayable._shadowDom;
  16018. var defs = this.getDefs(true);
  16019. if (!defs.contains(displayable._shadowDom)) {
  16020. // _shadowDom is no longer in defs, recreate
  16021. this.addDom(dom);
  16022. }
  16023. }
  16024. else {
  16025. // New dom
  16026. dom = this.add(displayable);
  16027. }
  16028. this.markUsed(displayable);
  16029. var id = dom.getAttribute('id');
  16030. svgElement.style.filter = 'url(#' + id + ')';
  16031. }
  16032. };
  16033. /**
  16034. * Add a new shadow tag in <defs>
  16035. *
  16036. * @param {Displayable} displayable zrender displayable element
  16037. * @return {SVGFilterElement} created DOM
  16038. */
  16039. ShadowManager.prototype.add = function (displayable) {
  16040. var dom = this.createElement('filter');
  16041. // Set dom id with shadow id, since each shadow instance
  16042. // will have no more than one dom element.
  16043. // id may exists before for those dirty elements, in which case
  16044. // id should remain the same, and other attributes should be
  16045. // updated.
  16046. displayable._shadowDomId = displayable._shadowDomId || this.nextId++;
  16047. dom.setAttribute('id', 'zr' + this._zrId
  16048. + '-shadow-' + displayable._shadowDomId);
  16049. this.updateDom(displayable, dom);
  16050. this.addDom(dom);
  16051. return dom;
  16052. };
  16053. /**
  16054. * Update shadow.
  16055. *
  16056. * @param {Displayable} displayable zrender displayable element
  16057. */
  16058. ShadowManager.prototype.update = function (svgElement, displayable) {
  16059. var style = displayable.style;
  16060. if (hasShadow(style)) {
  16061. var that = this;
  16062. Definable.prototype.update.call(this, displayable, function () {
  16063. that.updateDom(displayable, displayable._shadowDom);
  16064. });
  16065. }
  16066. else {
  16067. // Remove shadow
  16068. this.remove(svgElement, displayable);
  16069. }
  16070. };
  16071. /**
  16072. * Remove DOM and clear parent filter
  16073. */
  16074. ShadowManager.prototype.remove = function (svgElement, displayable) {
  16075. if (displayable._shadowDomId != null) {
  16076. this.removeDom(svgElement);
  16077. svgElement.style.filter = '';
  16078. }
  16079. };
  16080. /**
  16081. * Update shadow dom
  16082. *
  16083. * @param {Displayable} displayable zrender displayable element
  16084. * @param {SVGFilterElement} dom DOM to update
  16085. */
  16086. ShadowManager.prototype.updateDom = function (displayable, dom) {
  16087. var domChild = dom.getElementsByTagName('feDropShadow');
  16088. if (domChild.length === 0) {
  16089. domChild = this.createElement('feDropShadow');
  16090. }
  16091. else {
  16092. domChild = domChild[0];
  16093. }
  16094. var style = displayable.style;
  16095. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  16096. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  16097. // TODO: textBoxShadowBlur is not supported yet
  16098. var offsetX;
  16099. var offsetY;
  16100. var blur;
  16101. var color;
  16102. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  16103. offsetX = style.shadowOffsetX || 0;
  16104. offsetY = style.shadowOffsetY || 0;
  16105. blur = style.shadowBlur;
  16106. color = style.shadowColor;
  16107. }
  16108. else if (style.textShadowBlur) {
  16109. offsetX = style.textShadowOffsetX || 0;
  16110. offsetY = style.textShadowOffsetY || 0;
  16111. blur = style.textShadowBlur;
  16112. color = style.textShadowColor;
  16113. }
  16114. else {
  16115. // Remove shadow
  16116. this.removeDom(dom, style);
  16117. return;
  16118. }
  16119. domChild.setAttribute('dx', offsetX / scaleX);
  16120. domChild.setAttribute('dy', offsetY / scaleY);
  16121. domChild.setAttribute('flood-color', color);
  16122. // Divide by two here so that it looks the same as in canvas
  16123. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  16124. var stdDx = blur / 2 / scaleX;
  16125. var stdDy = blur / 2 / scaleY;
  16126. var stdDeviation = stdDx + ' ' + stdDy;
  16127. domChild.setAttribute('stdDeviation', stdDeviation);
  16128. // Fix filter clipping problem
  16129. dom.setAttribute('x', '-100%');
  16130. dom.setAttribute('y', '-100%');
  16131. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  16132. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  16133. dom.appendChild(domChild);
  16134. // Store dom element in shadow, to avoid creating multiple
  16135. // dom instances for the same shadow element
  16136. displayable._shadowDom = dom;
  16137. };
  16138. /**
  16139. * Mark a single shadow to be used
  16140. *
  16141. * @param {Displayable} displayable displayable element
  16142. */
  16143. ShadowManager.prototype.markUsed = function (displayable) {
  16144. if (displayable._shadowDom) {
  16145. Definable.prototype.markUsed.call(this, displayable._shadowDom);
  16146. }
  16147. };
  16148. function hasShadow(style) {
  16149. // TODO: textBoxShadowBlur is not supported yet
  16150. return style
  16151. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  16152. || style.textShadowBlur || style.textShadowOffsetX
  16153. || style.textShadowOffsetY);
  16154. }
  16155. /**
  16156. * SVG Painter
  16157. * @module zrender/svg/Painter
  16158. */
  16159. function parseInt10$1(val) {
  16160. return parseInt(val, 10);
  16161. }
  16162. function getSvgProxy(el) {
  16163. if (el instanceof Path) {
  16164. return svgPath;
  16165. }
  16166. else if (el instanceof ZImage) {
  16167. return svgImage;
  16168. }
  16169. else if (el instanceof Text) {
  16170. return svgText;
  16171. }
  16172. else {
  16173. return svgPath;
  16174. }
  16175. }
  16176. function checkParentAvailable(parent, child) {
  16177. return child && parent && child.parentNode !== parent;
  16178. }
  16179. function insertAfter(parent, child, prevSibling) {
  16180. if (checkParentAvailable(parent, child) && prevSibling) {
  16181. var nextSibling = prevSibling.nextSibling;
  16182. nextSibling ? parent.insertBefore(child, nextSibling)
  16183. : parent.appendChild(child);
  16184. }
  16185. }
  16186. function prepend(parent, child) {
  16187. if (checkParentAvailable(parent, child)) {
  16188. var firstChild = parent.firstChild;
  16189. firstChild ? parent.insertBefore(child, firstChild)
  16190. : parent.appendChild(child);
  16191. }
  16192. }
  16193. // function append(parent, child) {
  16194. // if (checkParentAvailable(parent, child)) {
  16195. // parent.appendChild(child);
  16196. // }
  16197. // }
  16198. function remove(parent, child) {
  16199. if (child && parent && child.parentNode === parent) {
  16200. parent.removeChild(child);
  16201. }
  16202. }
  16203. function getTextSvgElement(displayable) {
  16204. return displayable.__textSvgEl;
  16205. }
  16206. function getSvgElement(displayable) {
  16207. return displayable.__svgEl;
  16208. }
  16209. /**
  16210. * @alias module:zrender/svg/Painter
  16211. * @constructor
  16212. * @param {HTMLElement} root 绘图容器
  16213. * @param {module:zrender/Storage} storage
  16214. * @param {Object} opts
  16215. */
  16216. var SVGPainter = function (root, storage, opts, zrId) {
  16217. this.root = root;
  16218. this.storage = storage;
  16219. this._opts = opts = extend({}, opts || {});
  16220. var svgRoot = createElement('svg');
  16221. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  16222. svgRoot.setAttribute('version', '1.1');
  16223. svgRoot.setAttribute('baseProfile', 'full');
  16224. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  16225. this.gradientManager = new GradientManager(zrId, svgRoot);
  16226. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  16227. this.shadowManager = new ShadowManager(zrId, svgRoot);
  16228. var viewport = document.createElement('div');
  16229. viewport.style.cssText = 'overflow:hidden;position:relative';
  16230. this._svgRoot = svgRoot;
  16231. this._viewport = viewport;
  16232. root.appendChild(viewport);
  16233. viewport.appendChild(svgRoot);
  16234. this.resize(opts.width, opts.height);
  16235. this._visibleList = [];
  16236. };
  16237. SVGPainter.prototype = {
  16238. constructor: SVGPainter,
  16239. getType: function () {
  16240. return 'svg';
  16241. },
  16242. getViewportRoot: function () {
  16243. return this._viewport;
  16244. },
  16245. getViewportRootOffset: function () {
  16246. var viewportRoot = this.getViewportRoot();
  16247. if (viewportRoot) {
  16248. return {
  16249. offsetLeft: viewportRoot.offsetLeft || 0,
  16250. offsetTop: viewportRoot.offsetTop || 0
  16251. };
  16252. }
  16253. },
  16254. refresh: function () {
  16255. var list = this.storage.getDisplayList(true);
  16256. this._paintList(list);
  16257. },
  16258. setBackgroundColor: function (backgroundColor) {
  16259. // TODO gradient
  16260. this._viewport.style.background = backgroundColor;
  16261. },
  16262. _paintList: function (list) {
  16263. this.gradientManager.markAllUnused();
  16264. this.clipPathManager.markAllUnused();
  16265. this.shadowManager.markAllUnused();
  16266. var svgRoot = this._svgRoot;
  16267. var visibleList = this._visibleList;
  16268. var listLen = list.length;
  16269. var newVisibleList = [];
  16270. var i;
  16271. for (i = 0; i < listLen; i++) {
  16272. var displayable = list[i];
  16273. var svgProxy = getSvgProxy(displayable);
  16274. var svgElement = getSvgElement(displayable)
  16275. || getTextSvgElement(displayable);
  16276. if (!displayable.invisible) {
  16277. if (displayable.__dirty) {
  16278. svgProxy && svgProxy.brush(displayable);
  16279. // Update clipPath
  16280. this.clipPathManager.update(displayable);
  16281. // Update gradient and shadow
  16282. if (displayable.style) {
  16283. this.gradientManager
  16284. .update(displayable.style.fill);
  16285. this.gradientManager
  16286. .update(displayable.style.stroke);
  16287. this.shadowManager
  16288. .update(svgElement, displayable);
  16289. }
  16290. displayable.__dirty = false;
  16291. }
  16292. newVisibleList.push(displayable);
  16293. }
  16294. }
  16295. var diff = arrayDiff$1(visibleList, newVisibleList);
  16296. var prevSvgElement;
  16297. // First do remove, in case element moved to the head and do remove
  16298. // after add
  16299. for (i = 0; i < diff.length; i++) {
  16300. var item = diff[i];
  16301. if (item.removed) {
  16302. for (var k = 0; k < item.count; k++) {
  16303. var displayable = visibleList[item.indices[k]];
  16304. var svgElement = getSvgElement(displayable);
  16305. var textSvgElement = getTextSvgElement(displayable);
  16306. remove(svgRoot, svgElement);
  16307. remove(svgRoot, textSvgElement);
  16308. }
  16309. }
  16310. }
  16311. for (i = 0; i < diff.length; i++) {
  16312. var item = diff[i];
  16313. if (item.added) {
  16314. for (var k = 0; k < item.count; k++) {
  16315. var displayable = newVisibleList[item.indices[k]];
  16316. var svgElement = getSvgElement(displayable);
  16317. var textSvgElement = getTextSvgElement(displayable);
  16318. prevSvgElement
  16319. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  16320. : prepend(svgRoot, svgElement);
  16321. if (svgElement) {
  16322. insertAfter(svgRoot, textSvgElement, svgElement);
  16323. }
  16324. else if (prevSvgElement) {
  16325. insertAfter(
  16326. svgRoot, textSvgElement, prevSvgElement
  16327. );
  16328. }
  16329. else {
  16330. prepend(svgRoot, textSvgElement);
  16331. }
  16332. // Insert text
  16333. insertAfter(svgRoot, textSvgElement, svgElement);
  16334. prevSvgElement = textSvgElement || svgElement
  16335. || prevSvgElement;
  16336. // zrender.Text only create textSvgElement.
  16337. this.gradientManager
  16338. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  16339. this.shadowManager
  16340. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  16341. this.clipPathManager.markUsed(displayable);
  16342. }
  16343. }
  16344. else if (!item.removed) {
  16345. for (var k = 0; k < item.count; k++) {
  16346. var displayable = newVisibleList[item.indices[k]];
  16347. var svgElement = getSvgElement(displayable);
  16348. var textSvgElement = getTextSvgElement(displayable);
  16349. var svgElement = getSvgElement(displayable);
  16350. var textSvgElement = getTextSvgElement(displayable);
  16351. this.gradientManager.markUsed(displayable);
  16352. this.gradientManager
  16353. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  16354. this.shadowManager.markUsed(displayable);
  16355. this.shadowManager
  16356. .addWithoutUpdate(svgElement || textSvgElement, displayable);
  16357. this.clipPathManager.markUsed(displayable);
  16358. if (textSvgElement) { // Insert text.
  16359. insertAfter(svgRoot, textSvgElement, svgElement);
  16360. }
  16361. prevSvgElement = svgElement
  16362. || textSvgElement || prevSvgElement;
  16363. }
  16364. }
  16365. }
  16366. this.gradientManager.removeUnused();
  16367. this.clipPathManager.removeUnused();
  16368. this.shadowManager.removeUnused();
  16369. this._visibleList = newVisibleList;
  16370. },
  16371. _getDefs: function (isForceCreating) {
  16372. var svgRoot = this._svgRoot;
  16373. var defs = this._svgRoot.getElementsByTagName('defs');
  16374. if (defs.length === 0) {
  16375. // Not exist
  16376. if (isForceCreating) {
  16377. var defs = svgRoot.insertBefore(
  16378. createElement('defs'), // Create new tag
  16379. svgRoot.firstChild // Insert in the front of svg
  16380. );
  16381. if (!defs.contains) {
  16382. // IE doesn't support contains method
  16383. defs.contains = function (el) {
  16384. var children = defs.children;
  16385. if (!children) {
  16386. return false;
  16387. }
  16388. for (var i = children.length - 1; i >= 0; --i) {
  16389. if (children[i] === el) {
  16390. return true;
  16391. }
  16392. }
  16393. return false;
  16394. };
  16395. }
  16396. return defs;
  16397. }
  16398. else {
  16399. return null;
  16400. }
  16401. }
  16402. else {
  16403. return defs[0];
  16404. }
  16405. },
  16406. resize: function (width, height) {
  16407. var viewport = this._viewport;
  16408. // FIXME Why ?
  16409. viewport.style.display = 'none';
  16410. // Save input w/h
  16411. var opts = this._opts;
  16412. width != null && (opts.width = width);
  16413. height != null && (opts.height = height);
  16414. width = this._getSize(0);
  16415. height = this._getSize(1);
  16416. viewport.style.display = '';
  16417. if (this._width !== width || this._height !== height) {
  16418. this._width = width;
  16419. this._height = height;
  16420. var viewportStyle = viewport.style;
  16421. viewportStyle.width = width + 'px';
  16422. viewportStyle.height = height + 'px';
  16423. var svgRoot = this._svgRoot;
  16424. // Set width by 'svgRoot.width = width' is invalid
  16425. svgRoot.setAttribute('width', width);
  16426. svgRoot.setAttribute('height', height);
  16427. }
  16428. },
  16429. /**
  16430. * 获取绘图区域宽度
  16431. */
  16432. getWidth: function () {
  16433. return this._width;
  16434. },
  16435. /**
  16436. * 获取绘图区域高度
  16437. */
  16438. getHeight: function () {
  16439. return this._height;
  16440. },
  16441. _getSize: function (whIdx) {
  16442. var opts = this._opts;
  16443. var wh = ['width', 'height'][whIdx];
  16444. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  16445. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  16446. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  16447. if (opts[wh] != null && opts[wh] !== 'auto') {
  16448. return parseFloat(opts[wh]);
  16449. }
  16450. var root = this.root;
  16451. // IE8 does not support getComputedStyle, but it use VML.
  16452. var stl = document.defaultView.getComputedStyle(root);
  16453. return (
  16454. (root[cwh] || parseInt10$1(stl[wh]) || parseInt10$1(root.style[wh]))
  16455. - (parseInt10$1(stl[plt]) || 0)
  16456. - (parseInt10$1(stl[prb]) || 0)
  16457. ) | 0;
  16458. },
  16459. dispose: function () {
  16460. this.root.innerHTML = '';
  16461. this._svgRoot =
  16462. this._viewport =
  16463. this.storage =
  16464. null;
  16465. },
  16466. clear: function () {
  16467. if (this._viewport) {
  16468. this.root.removeChild(this._viewport);
  16469. }
  16470. },
  16471. pathToDataUrl: function () {
  16472. this.refresh();
  16473. var html = this._svgRoot.outerHTML;
  16474. return 'data:image/svg+xml;charset=UTF-8,' + html;
  16475. }
  16476. };
  16477. // Not supported methods
  16478. function createMethodNotSupport(method) {
  16479. return function () {
  16480. logError$1('In SVG mode painter not support method "' + method + '"');
  16481. };
  16482. }
  16483. // Unsuppoted methods
  16484. each([
  16485. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  16486. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  16487. 'toDataURL', 'pathToImage'
  16488. ], function (name) {
  16489. SVGPainter.prototype[name] = createMethodNotSupport(name);
  16490. });
  16491. registerPainter('svg', SVGPainter);
  16492. var urn = 'urn:schemas-microsoft-com:vml';
  16493. var win = typeof window === 'undefined' ? null : window;
  16494. var vmlInited = false;
  16495. var doc = win && win.document;
  16496. function createNode(tagName) {
  16497. return doCreateNode(tagName);
  16498. }
  16499. // Avoid assign to an exported variable, for transforming to cjs.
  16500. var doCreateNode;
  16501. if (doc && !env$1.canvasSupported) {
  16502. try {
  16503. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  16504. doCreateNode = function (tagName) {
  16505. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  16506. };
  16507. }
  16508. catch (e) {
  16509. doCreateNode = function (tagName) {
  16510. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  16511. };
  16512. }
  16513. }
  16514. // From raphael
  16515. function initVML() {
  16516. if (vmlInited || !doc) {
  16517. return;
  16518. }
  16519. vmlInited = true;
  16520. var styleSheets = doc.styleSheets;
  16521. if (styleSheets.length < 31) {
  16522. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  16523. }
  16524. else {
  16525. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  16526. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  16527. }
  16528. }
  16529. // http://www.w3.org/TR/NOTE-VML
  16530. // TODO Use proxy like svg instead of overwrite brush methods
  16531. var CMD$4 = PathProxy.CMD;
  16532. var round$1 = Math.round;
  16533. var sqrt = Math.sqrt;
  16534. var abs$1 = Math.abs;
  16535. var cos$4 = Math.cos;
  16536. var sin$4 = Math.sin;
  16537. var mathMax$3 = Math.max;
  16538. if (!env$1.canvasSupported) {
  16539. var comma = ',';
  16540. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  16541. var Z = 21600;
  16542. var Z2 = Z / 2;
  16543. var ZLEVEL_BASE = 100000;
  16544. var Z_BASE = 1000;
  16545. var initRootElStyle = function (el) {
  16546. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  16547. el.coordsize = Z + ',' + Z;
  16548. el.coordorigin = '0,0';
  16549. };
  16550. var encodeHtmlAttribute = function (s) {
  16551. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  16552. };
  16553. var rgb2Str = function (r, g, b) {
  16554. return 'rgb(' + [r, g, b].join(',') + ')';
  16555. };
  16556. var append = function (parent, child) {
  16557. if (child && parent && child.parentNode !== parent) {
  16558. parent.appendChild(child);
  16559. }
  16560. };
  16561. var remove$1 = function (parent, child) {
  16562. if (child && parent && child.parentNode === parent) {
  16563. parent.removeChild(child);
  16564. }
  16565. };
  16566. var getZIndex = function (zlevel, z, z2) {
  16567. // z 的取值范围为 [0, 1000]
  16568. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
  16569. };
  16570. var parsePercent$1 = parsePercent;
  16571. /***************************************************
  16572. * PATH
  16573. **************************************************/
  16574. var setColorAndOpacity = function (el, color, opacity) {
  16575. var colorArr = parse(color);
  16576. opacity = +opacity;
  16577. if (isNaN(opacity)) {
  16578. opacity = 1;
  16579. }
  16580. if (colorArr) {
  16581. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  16582. el.opacity = opacity * colorArr[3];
  16583. }
  16584. };
  16585. var getColorAndAlpha = function (color) {
  16586. var colorArr = parse(color);
  16587. return [
  16588. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  16589. colorArr[3]
  16590. ];
  16591. };
  16592. var updateFillNode = function (el, style, zrEl) {
  16593. // TODO pattern
  16594. var fill = style.fill;
  16595. if (fill != null) {
  16596. // Modified from excanvas
  16597. if (fill instanceof Gradient) {
  16598. var gradientType;
  16599. var angle = 0;
  16600. var focus = [0, 0];
  16601. // additional offset
  16602. var shift = 0;
  16603. // scale factor for offset
  16604. var expansion = 1;
  16605. var rect = zrEl.getBoundingRect();
  16606. var rectWidth = rect.width;
  16607. var rectHeight = rect.height;
  16608. if (fill.type === 'linear') {
  16609. gradientType = 'gradient';
  16610. var transform = zrEl.transform;
  16611. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  16612. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  16613. if (transform) {
  16614. applyTransform(p0, p0, transform);
  16615. applyTransform(p1, p1, transform);
  16616. }
  16617. var dx = p1[0] - p0[0];
  16618. var dy = p1[1] - p0[1];
  16619. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  16620. // The angle should be a non-negative number.
  16621. if (angle < 0) {
  16622. angle += 360;
  16623. }
  16624. // Very small angles produce an unexpected result because they are
  16625. // converted to a scientific notation string.
  16626. if (angle < 1e-6) {
  16627. angle = 0;
  16628. }
  16629. }
  16630. else {
  16631. gradientType = 'gradientradial';
  16632. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  16633. var transform = zrEl.transform;
  16634. var scale$$1 = zrEl.scale;
  16635. var width = rectWidth;
  16636. var height = rectHeight;
  16637. focus = [
  16638. // Percent in bounding rect
  16639. (p0[0] - rect.x) / width,
  16640. (p0[1] - rect.y) / height
  16641. ];
  16642. if (transform) {
  16643. applyTransform(p0, p0, transform);
  16644. }
  16645. width /= scale$$1[0] * Z;
  16646. height /= scale$$1[1] * Z;
  16647. var dimension = mathMax$3(width, height);
  16648. shift = 2 * 0 / dimension;
  16649. expansion = 2 * fill.r / dimension - shift;
  16650. }
  16651. // We need to sort the color stops in ascending order by offset,
  16652. // otherwise IE won't interpret it correctly.
  16653. var stops = fill.colorStops.slice();
  16654. stops.sort(function (cs1, cs2) {
  16655. return cs1.offset - cs2.offset;
  16656. });
  16657. var length$$1 = stops.length;
  16658. // Color and alpha list of first and last stop
  16659. var colorAndAlphaList = [];
  16660. var colors = [];
  16661. for (var i = 0; i < length$$1; i++) {
  16662. var stop = stops[i];
  16663. var colorAndAlpha = getColorAndAlpha(stop.color);
  16664. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  16665. if (i === 0 || i === length$$1 - 1) {
  16666. colorAndAlphaList.push(colorAndAlpha);
  16667. }
  16668. }
  16669. if (length$$1 >= 2) {
  16670. var color1 = colorAndAlphaList[0][0];
  16671. var color2 = colorAndAlphaList[1][0];
  16672. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  16673. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  16674. el.type = gradientType;
  16675. el.method = 'none';
  16676. el.focus = '100%';
  16677. el.angle = angle;
  16678. el.color = color1;
  16679. el.color2 = color2;
  16680. el.colors = colors.join(',');
  16681. // When colors attribute is used, the meanings of opacity and o:opacity2
  16682. // are reversed.
  16683. el.opacity = opacity2;
  16684. // FIXME g_o_:opacity ?
  16685. el.opacity2 = opacity1;
  16686. }
  16687. if (gradientType === 'radial') {
  16688. el.focusposition = focus.join(',');
  16689. }
  16690. }
  16691. else {
  16692. // FIXME Change from Gradient fill to color fill
  16693. setColorAndOpacity(el, fill, style.opacity);
  16694. }
  16695. }
  16696. };
  16697. var updateStrokeNode = function (el, style) {
  16698. // if (style.lineJoin != null) {
  16699. // el.joinstyle = style.lineJoin;
  16700. // }
  16701. // if (style.miterLimit != null) {
  16702. // el.miterlimit = style.miterLimit * Z;
  16703. // }
  16704. // if (style.lineCap != null) {
  16705. // el.endcap = style.lineCap;
  16706. // }
  16707. if (style.lineDash) {
  16708. el.dashstyle = style.lineDash.join(' ');
  16709. }
  16710. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  16711. setColorAndOpacity(el, style.stroke, style.opacity);
  16712. }
  16713. };
  16714. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  16715. var isFill = type === 'fill';
  16716. var el = vmlEl.getElementsByTagName(type)[0];
  16717. // Stroke must have lineWidth
  16718. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  16719. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  16720. // FIXME Remove before updating, or set `colors` will throw error
  16721. if (style[type] instanceof Gradient) {
  16722. remove$1(vmlEl, el);
  16723. }
  16724. if (!el) {
  16725. el = createNode(type);
  16726. }
  16727. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  16728. append(vmlEl, el);
  16729. }
  16730. else {
  16731. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  16732. remove$1(vmlEl, el);
  16733. }
  16734. };
  16735. var points$1 = [[], [], []];
  16736. var pathDataToString$1 = function (path, m) {
  16737. var M = CMD$4.M;
  16738. var C = CMD$4.C;
  16739. var L = CMD$4.L;
  16740. var A = CMD$4.A;
  16741. var Q = CMD$4.Q;
  16742. var str = [];
  16743. var nPoint;
  16744. var cmdStr;
  16745. var cmd;
  16746. var i;
  16747. var xi;
  16748. var yi;
  16749. var data = path.data;
  16750. var dataLength = path.len();
  16751. for (i = 0; i < dataLength;) {
  16752. cmd = data[i++];
  16753. cmdStr = '';
  16754. nPoint = 0;
  16755. switch (cmd) {
  16756. case M:
  16757. cmdStr = ' m ';
  16758. nPoint = 1;
  16759. xi = data[i++];
  16760. yi = data[i++];
  16761. points$1[0][0] = xi;
  16762. points$1[0][1] = yi;
  16763. break;
  16764. case L:
  16765. cmdStr = ' l ';
  16766. nPoint = 1;
  16767. xi = data[i++];
  16768. yi = data[i++];
  16769. points$1[0][0] = xi;
  16770. points$1[0][1] = yi;
  16771. break;
  16772. case Q:
  16773. case C:
  16774. cmdStr = ' c ';
  16775. nPoint = 3;
  16776. var x1 = data[i++];
  16777. var y1 = data[i++];
  16778. var x2 = data[i++];
  16779. var y2 = data[i++];
  16780. var x3;
  16781. var y3;
  16782. if (cmd === Q) {
  16783. // Convert quadratic to cubic using degree elevation
  16784. x3 = x2;
  16785. y3 = y2;
  16786. x2 = (x2 + 2 * x1) / 3;
  16787. y2 = (y2 + 2 * y1) / 3;
  16788. x1 = (xi + 2 * x1) / 3;
  16789. y1 = (yi + 2 * y1) / 3;
  16790. }
  16791. else {
  16792. x3 = data[i++];
  16793. y3 = data[i++];
  16794. }
  16795. points$1[0][0] = x1;
  16796. points$1[0][1] = y1;
  16797. points$1[1][0] = x2;
  16798. points$1[1][1] = y2;
  16799. points$1[2][0] = x3;
  16800. points$1[2][1] = y3;
  16801. xi = x3;
  16802. yi = y3;
  16803. break;
  16804. case A:
  16805. var x = 0;
  16806. var y = 0;
  16807. var sx = 1;
  16808. var sy = 1;
  16809. var angle = 0;
  16810. if (m) {
  16811. // Extract SRT from matrix
  16812. x = m[4];
  16813. y = m[5];
  16814. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  16815. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  16816. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  16817. }
  16818. var cx = data[i++];
  16819. var cy = data[i++];
  16820. var rx = data[i++];
  16821. var ry = data[i++];
  16822. var startAngle = data[i++] + angle;
  16823. var endAngle = data[i++] + startAngle + angle;
  16824. // FIXME
  16825. // var psi = data[i++];
  16826. i++;
  16827. var clockwise = data[i++];
  16828. var x0 = cx + cos$4(startAngle) * rx;
  16829. var y0 = cy + sin$4(startAngle) * ry;
  16830. var x1 = cx + cos$4(endAngle) * rx;
  16831. var y1 = cy + sin$4(endAngle) * ry;
  16832. var type = clockwise ? ' wa ' : ' at ';
  16833. if (Math.abs(x0 - x1) < 1e-4) {
  16834. // IE won't render arches drawn counter clockwise if x0 == x1.
  16835. if (Math.abs(endAngle - startAngle) > 1e-2) {
  16836. // Offset x0 by 1/80 of a pixel. Use something
  16837. // that can be represented in binary
  16838. if (clockwise) {
  16839. x0 += 270 / Z;
  16840. }
  16841. }
  16842. else {
  16843. // Avoid case draw full circle
  16844. if (Math.abs(y0 - cy) < 1e-4) {
  16845. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  16846. y1 -= 270 / Z;
  16847. }
  16848. else {
  16849. y1 += 270 / Z;
  16850. }
  16851. }
  16852. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  16853. x1 += 270 / Z;
  16854. }
  16855. else {
  16856. x1 -= 270 / Z;
  16857. }
  16858. }
  16859. }
  16860. str.push(
  16861. type,
  16862. round$1(((cx - rx) * sx + x) * Z - Z2), comma,
  16863. round$1(((cy - ry) * sy + y) * Z - Z2), comma,
  16864. round$1(((cx + rx) * sx + x) * Z - Z2), comma,
  16865. round$1(((cy + ry) * sy + y) * Z - Z2), comma,
  16866. round$1((x0 * sx + x) * Z - Z2), comma,
  16867. round$1((y0 * sy + y) * Z - Z2), comma,
  16868. round$1((x1 * sx + x) * Z - Z2), comma,
  16869. round$1((y1 * sy + y) * Z - Z2)
  16870. );
  16871. xi = x1;
  16872. yi = y1;
  16873. break;
  16874. case CMD$4.R:
  16875. var p0 = points$1[0];
  16876. var p1 = points$1[1];
  16877. // x0, y0
  16878. p0[0] = data[i++];
  16879. p0[1] = data[i++];
  16880. // x1, y1
  16881. p1[0] = p0[0] + data[i++];
  16882. p1[1] = p0[1] + data[i++];
  16883. if (m) {
  16884. applyTransform(p0, p0, m);
  16885. applyTransform(p1, p1, m);
  16886. }
  16887. p0[0] = round$1(p0[0] * Z - Z2);
  16888. p1[0] = round$1(p1[0] * Z - Z2);
  16889. p0[1] = round$1(p0[1] * Z - Z2);
  16890. p1[1] = round$1(p1[1] * Z - Z2);
  16891. str.push(
  16892. // x0, y0
  16893. ' m ', p0[0], comma, p0[1],
  16894. // x1, y0
  16895. ' l ', p1[0], comma, p0[1],
  16896. // x1, y1
  16897. ' l ', p1[0], comma, p1[1],
  16898. // x0, y1
  16899. ' l ', p0[0], comma, p1[1]
  16900. );
  16901. break;
  16902. case CMD$4.Z:
  16903. // FIXME Update xi, yi
  16904. str.push(' x ');
  16905. }
  16906. if (nPoint > 0) {
  16907. str.push(cmdStr);
  16908. for (var k = 0; k < nPoint; k++) {
  16909. var p = points$1[k];
  16910. m && applyTransform(p, p, m);
  16911. // 不 round 会非常慢
  16912. str.push(
  16913. round$1(p[0] * Z - Z2), comma, round$1(p[1] * Z - Z2),
  16914. k < nPoint - 1 ? comma : ''
  16915. );
  16916. }
  16917. }
  16918. }
  16919. return str.join('');
  16920. };
  16921. // Rewrite the original path method
  16922. Path.prototype.brushVML = function (vmlRoot) {
  16923. var style = this.style;
  16924. var vmlEl = this._vmlEl;
  16925. if (!vmlEl) {
  16926. vmlEl = createNode('shape');
  16927. initRootElStyle(vmlEl);
  16928. this._vmlEl = vmlEl;
  16929. }
  16930. updateFillAndStroke(vmlEl, 'fill', style, this);
  16931. updateFillAndStroke(vmlEl, 'stroke', style, this);
  16932. var m = this.transform;
  16933. var needTransform = m != null;
  16934. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  16935. if (strokeEl) {
  16936. var lineWidth = style.lineWidth;
  16937. // Get the line scale.
  16938. // Determinant of this.m_ means how much the area is enlarged by the
  16939. // transformation. So its square root can be used as a scale factor
  16940. // for width.
  16941. if (needTransform && !style.strokeNoScale) {
  16942. var det = m[0] * m[3] - m[1] * m[2];
  16943. lineWidth *= sqrt(abs$1(det));
  16944. }
  16945. strokeEl.weight = lineWidth + 'px';
  16946. }
  16947. var path = this.path || (this.path = new PathProxy());
  16948. if (this.__dirtyPath) {
  16949. path.beginPath();
  16950. path.subPixelOptimize = false;
  16951. this.buildPath(path, this.shape);
  16952. path.toStatic();
  16953. this.__dirtyPath = false;
  16954. }
  16955. vmlEl.path = pathDataToString$1(path, this.transform);
  16956. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  16957. // Append to root
  16958. append(vmlRoot, vmlEl);
  16959. // Text
  16960. if (style.text != null) {
  16961. this.drawRectText(vmlRoot, this.getBoundingRect());
  16962. }
  16963. else {
  16964. this.removeRectText(vmlRoot);
  16965. }
  16966. };
  16967. Path.prototype.onRemove = function (vmlRoot) {
  16968. remove$1(vmlRoot, this._vmlEl);
  16969. this.removeRectText(vmlRoot);
  16970. };
  16971. Path.prototype.onAdd = function (vmlRoot) {
  16972. append(vmlRoot, this._vmlEl);
  16973. this.appendRectText(vmlRoot);
  16974. };
  16975. /***************************************************
  16976. * IMAGE
  16977. **************************************************/
  16978. var isImage = function (img) {
  16979. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  16980. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  16981. // return img instanceof Image;
  16982. };
  16983. // Rewrite the original path method
  16984. ZImage.prototype.brushVML = function (vmlRoot) {
  16985. var style = this.style;
  16986. var image = style.image;
  16987. // Image original width, height
  16988. var ow;
  16989. var oh;
  16990. if (isImage(image)) {
  16991. var src = image.src;
  16992. if (src === this._imageSrc) {
  16993. ow = this._imageWidth;
  16994. oh = this._imageHeight;
  16995. }
  16996. else {
  16997. var imageRuntimeStyle = image.runtimeStyle;
  16998. var oldRuntimeWidth = imageRuntimeStyle.width;
  16999. var oldRuntimeHeight = imageRuntimeStyle.height;
  17000. imageRuntimeStyle.width = 'auto';
  17001. imageRuntimeStyle.height = 'auto';
  17002. // get the original size
  17003. ow = image.width;
  17004. oh = image.height;
  17005. // and remove overides
  17006. imageRuntimeStyle.width = oldRuntimeWidth;
  17007. imageRuntimeStyle.height = oldRuntimeHeight;
  17008. // Caching image original width, height and src
  17009. this._imageSrc = src;
  17010. this._imageWidth = ow;
  17011. this._imageHeight = oh;
  17012. }
  17013. image = src;
  17014. }
  17015. else {
  17016. if (image === this._imageSrc) {
  17017. ow = this._imageWidth;
  17018. oh = this._imageHeight;
  17019. }
  17020. }
  17021. if (!image) {
  17022. return;
  17023. }
  17024. var x = style.x || 0;
  17025. var y = style.y || 0;
  17026. var dw = style.width;
  17027. var dh = style.height;
  17028. var sw = style.sWidth;
  17029. var sh = style.sHeight;
  17030. var sx = style.sx || 0;
  17031. var sy = style.sy || 0;
  17032. var hasCrop = sw && sh;
  17033. var vmlEl = this._vmlEl;
  17034. if (!vmlEl) {
  17035. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  17036. // vmlEl = vmlCore.createNode('group');
  17037. vmlEl = doc.createElement('div');
  17038. initRootElStyle(vmlEl);
  17039. this._vmlEl = vmlEl;
  17040. }
  17041. var vmlElStyle = vmlEl.style;
  17042. var hasRotation = false;
  17043. var m;
  17044. var scaleX = 1;
  17045. var scaleY = 1;
  17046. if (this.transform) {
  17047. m = this.transform;
  17048. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  17049. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  17050. hasRotation = m[1] || m[2];
  17051. }
  17052. if (hasRotation) {
  17053. // If filters are necessary (rotation exists), create them
  17054. // filters are bog-slow, so only create them if abbsolutely necessary
  17055. // The following check doesn't account for skews (which don't exist
  17056. // in the canvas spec (yet) anyway.
  17057. // From excanvas
  17058. var p0 = [x, y];
  17059. var p1 = [x + dw, y];
  17060. var p2 = [x, y + dh];
  17061. var p3 = [x + dw, y + dh];
  17062. applyTransform(p0, p0, m);
  17063. applyTransform(p1, p1, m);
  17064. applyTransform(p2, p2, m);
  17065. applyTransform(p3, p3, m);
  17066. var maxX = mathMax$3(p0[0], p1[0], p2[0], p3[0]);
  17067. var maxY = mathMax$3(p0[1], p1[1], p2[1], p3[1]);
  17068. var transformFilter = [];
  17069. transformFilter.push('M11=', m[0] / scaleX, comma,
  17070. 'M12=', m[2] / scaleY, comma,
  17071. 'M21=', m[1] / scaleX, comma,
  17072. 'M22=', m[3] / scaleY, comma,
  17073. 'Dx=', round$1(x * scaleX + m[4]), comma,
  17074. 'Dy=', round$1(y * scaleY + m[5]));
  17075. vmlElStyle.padding = '0 ' + round$1(maxX) + 'px ' + round$1(maxY) + 'px 0';
  17076. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  17077. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  17078. + transformFilter.join('') + ', SizingMethod=clip)';
  17079. }
  17080. else {
  17081. if (m) {
  17082. x = x * scaleX + m[4];
  17083. y = y * scaleY + m[5];
  17084. }
  17085. vmlElStyle.filter = '';
  17086. vmlElStyle.left = round$1(x) + 'px';
  17087. vmlElStyle.top = round$1(y) + 'px';
  17088. }
  17089. var imageEl = this._imageEl;
  17090. var cropEl = this._cropEl;
  17091. if (!imageEl) {
  17092. imageEl = doc.createElement('div');
  17093. this._imageEl = imageEl;
  17094. }
  17095. var imageELStyle = imageEl.style;
  17096. if (hasCrop) {
  17097. // Needs know image original width and height
  17098. if (!(ow && oh)) {
  17099. var tmpImage = new Image();
  17100. var self = this;
  17101. tmpImage.onload = function () {
  17102. tmpImage.onload = null;
  17103. ow = tmpImage.width;
  17104. oh = tmpImage.height;
  17105. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  17106. imageELStyle.width = round$1(scaleX * ow * dw / sw) + 'px';
  17107. imageELStyle.height = round$1(scaleY * oh * dh / sh) + 'px';
  17108. // Caching image original width, height and src
  17109. self._imageWidth = ow;
  17110. self._imageHeight = oh;
  17111. self._imageSrc = image;
  17112. };
  17113. tmpImage.src = image;
  17114. }
  17115. else {
  17116. imageELStyle.width = round$1(scaleX * ow * dw / sw) + 'px';
  17117. imageELStyle.height = round$1(scaleY * oh * dh / sh) + 'px';
  17118. }
  17119. if (!cropEl) {
  17120. cropEl = doc.createElement('div');
  17121. cropEl.style.overflow = 'hidden';
  17122. this._cropEl = cropEl;
  17123. }
  17124. var cropElStyle = cropEl.style;
  17125. cropElStyle.width = round$1((dw + sx * dw / sw) * scaleX);
  17126. cropElStyle.height = round$1((dh + sy * dh / sh) * scaleY);
  17127. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  17128. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  17129. if (!cropEl.parentNode) {
  17130. vmlEl.appendChild(cropEl);
  17131. }
  17132. if (imageEl.parentNode !== cropEl) {
  17133. cropEl.appendChild(imageEl);
  17134. }
  17135. }
  17136. else {
  17137. imageELStyle.width = round$1(scaleX * dw) + 'px';
  17138. imageELStyle.height = round$1(scaleY * dh) + 'px';
  17139. vmlEl.appendChild(imageEl);
  17140. if (cropEl && cropEl.parentNode) {
  17141. vmlEl.removeChild(cropEl);
  17142. this._cropEl = null;
  17143. }
  17144. }
  17145. var filterStr = '';
  17146. var alpha = style.opacity;
  17147. if (alpha < 1) {
  17148. filterStr += '.Alpha(opacity=' + round$1(alpha * 100) + ') ';
  17149. }
  17150. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  17151. imageELStyle.filter = filterStr;
  17152. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  17153. // Append to root
  17154. append(vmlRoot, vmlEl);
  17155. // Text
  17156. if (style.text != null) {
  17157. this.drawRectText(vmlRoot, this.getBoundingRect());
  17158. }
  17159. };
  17160. ZImage.prototype.onRemove = function (vmlRoot) {
  17161. remove$1(vmlRoot, this._vmlEl);
  17162. this._vmlEl = null;
  17163. this._cropEl = null;
  17164. this._imageEl = null;
  17165. this.removeRectText(vmlRoot);
  17166. };
  17167. ZImage.prototype.onAdd = function (vmlRoot) {
  17168. append(vmlRoot, this._vmlEl);
  17169. this.appendRectText(vmlRoot);
  17170. };
  17171. /***************************************************
  17172. * TEXT
  17173. **************************************************/
  17174. var DEFAULT_STYLE_NORMAL = 'normal';
  17175. var fontStyleCache = {};
  17176. var fontStyleCacheCount = 0;
  17177. var MAX_FONT_CACHE_SIZE = 100;
  17178. var fontEl = document.createElement('div');
  17179. var getFontStyle = function (fontString) {
  17180. var fontStyle = fontStyleCache[fontString];
  17181. if (!fontStyle) {
  17182. // Clear cache
  17183. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  17184. fontStyleCacheCount = 0;
  17185. fontStyleCache = {};
  17186. }
  17187. var style = fontEl.style;
  17188. var fontFamily;
  17189. try {
  17190. style.font = fontString;
  17191. fontFamily = style.fontFamily.split(',')[0];
  17192. }
  17193. catch (e) {
  17194. }
  17195. fontStyle = {
  17196. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  17197. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  17198. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  17199. size: parseFloat(style.fontSize || 12) | 0,
  17200. family: fontFamily || 'Microsoft YaHei'
  17201. };
  17202. fontStyleCache[fontString] = fontStyle;
  17203. fontStyleCacheCount++;
  17204. }
  17205. return fontStyle;
  17206. };
  17207. var textMeasureEl;
  17208. // Overwrite measure text method
  17209. $override$1('measureText', function (text, textFont) {
  17210. var doc$$1 = doc;
  17211. if (!textMeasureEl) {
  17212. textMeasureEl = doc$$1.createElement('div');
  17213. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  17214. + 'padding:0;margin:0;border:none;white-space:pre;';
  17215. doc.body.appendChild(textMeasureEl);
  17216. }
  17217. try {
  17218. textMeasureEl.style.font = textFont;
  17219. }
  17220. catch (ex) {
  17221. // Ignore failures to set to invalid font.
  17222. }
  17223. textMeasureEl.innerHTML = '';
  17224. // Don't use innerHTML or innerText because they allow markup/whitespace.
  17225. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  17226. return {
  17227. width: textMeasureEl.offsetWidth
  17228. };
  17229. });
  17230. var tmpRect$2 = new BoundingRect();
  17231. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  17232. var style = this.style;
  17233. // Optimize, avoid normalize every time.
  17234. this.__dirty && normalizeTextStyle(style, true);
  17235. var text = style.text;
  17236. // Convert to string
  17237. text != null && (text += '');
  17238. if (!text) {
  17239. return;
  17240. }
  17241. // Convert rich text to plain text. Rich text is not supported in
  17242. // IE8-, but tags in rich text template will be removed.
  17243. if (style.rich) {
  17244. var contentBlock = parseRichText(text, style);
  17245. text = [];
  17246. for (var i = 0; i < contentBlock.lines.length; i++) {
  17247. var tokens = contentBlock.lines[i].tokens;
  17248. var textLine = [];
  17249. for (var j = 0; j < tokens.length; j++) {
  17250. textLine.push(tokens[j].text);
  17251. }
  17252. text.push(textLine.join(''));
  17253. }
  17254. text = text.join('\n');
  17255. }
  17256. var x;
  17257. var y;
  17258. var align = style.textAlign;
  17259. var verticalAlign = style.textVerticalAlign;
  17260. var fontStyle = getFontStyle(style.font);
  17261. // FIXME encodeHtmlAttribute ?
  17262. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  17263. + fontStyle.size + 'px "' + fontStyle.family + '"';
  17264. textRect = textRect || getBoundingRect(
  17265. text, font, align, verticalAlign, style.textPadding, style.textLineHeight
  17266. );
  17267. // Transform rect to view space
  17268. var m = this.transform;
  17269. // Ignore transform for text in other element
  17270. if (m && !fromTextEl) {
  17271. tmpRect$2.copy(rect);
  17272. tmpRect$2.applyTransform(m);
  17273. rect = tmpRect$2;
  17274. }
  17275. if (!fromTextEl) {
  17276. var textPosition = style.textPosition;
  17277. // Text position represented by coord
  17278. if (textPosition instanceof Array) {
  17279. x = rect.x + parsePercent$1(textPosition[0], rect.width);
  17280. y = rect.y + parsePercent$1(textPosition[1], rect.height);
  17281. align = align || 'left';
  17282. }
  17283. else {
  17284. var res = this.calculateTextPosition
  17285. ? this.calculateTextPosition({}, style, rect)
  17286. : calculateTextPosition({}, style, rect);
  17287. x = res.x;
  17288. y = res.y;
  17289. // Default align and baseline when has textPosition
  17290. align = align || res.textAlign;
  17291. verticalAlign = verticalAlign || res.textVerticalAlign;
  17292. }
  17293. }
  17294. else {
  17295. x = rect.x;
  17296. y = rect.y;
  17297. }
  17298. x = adjustTextX(x, textRect.width, align);
  17299. y = adjustTextY(y, textRect.height, verticalAlign);
  17300. // Force baseline 'middle'
  17301. y += textRect.height / 2;
  17302. // var fontSize = fontStyle.size;
  17303. // 1.75 is an arbitrary number, as there is no info about the text baseline
  17304. // switch (baseline) {
  17305. // case 'hanging':
  17306. // case 'top':
  17307. // y += fontSize / 1.75;
  17308. // break;
  17309. // case 'middle':
  17310. // break;
  17311. // default:
  17312. // // case null:
  17313. // // case 'alphabetic':
  17314. // // case 'ideographic':
  17315. // // case 'bottom':
  17316. // y -= fontSize / 2.25;
  17317. // break;
  17318. // }
  17319. // switch (align) {
  17320. // case 'left':
  17321. // break;
  17322. // case 'center':
  17323. // x -= textRect.width / 2;
  17324. // break;
  17325. // case 'right':
  17326. // x -= textRect.width;
  17327. // break;
  17328. // case 'end':
  17329. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  17330. // break;
  17331. // case 'start':
  17332. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  17333. // break;
  17334. // default:
  17335. // align = 'left';
  17336. // }
  17337. var createNode$$1 = createNode;
  17338. var textVmlEl = this._textVmlEl;
  17339. var pathEl;
  17340. var textPathEl;
  17341. var skewEl;
  17342. if (!textVmlEl) {
  17343. textVmlEl = createNode$$1('line');
  17344. pathEl = createNode$$1('path');
  17345. textPathEl = createNode$$1('textpath');
  17346. skewEl = createNode$$1('skew');
  17347. // FIXME Why here is not cammel case
  17348. // Align 'center' seems wrong
  17349. textPathEl.style['v-text-align'] = 'left';
  17350. initRootElStyle(textVmlEl);
  17351. pathEl.textpathok = true;
  17352. textPathEl.on = true;
  17353. textVmlEl.from = '0 0';
  17354. textVmlEl.to = '1000 0.05';
  17355. append(textVmlEl, skewEl);
  17356. append(textVmlEl, pathEl);
  17357. append(textVmlEl, textPathEl);
  17358. this._textVmlEl = textVmlEl;
  17359. }
  17360. else {
  17361. // 这里是在前面 appendChild 保证顺序的前提下
  17362. skewEl = textVmlEl.firstChild;
  17363. pathEl = skewEl.nextSibling;
  17364. textPathEl = pathEl.nextSibling;
  17365. }
  17366. var coords = [x, y];
  17367. var textVmlElStyle = textVmlEl.style;
  17368. // Ignore transform for text in other element
  17369. if (m && fromTextEl) {
  17370. applyTransform(coords, coords, m);
  17371. skewEl.on = true;
  17372. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
  17373. + m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  17374. // Text position
  17375. skewEl.offset = (round$1(coords[0]) || 0) + ',' + (round$1(coords[1]) || 0);
  17376. // Left top point as origin
  17377. skewEl.origin = '0 0';
  17378. textVmlElStyle.left = '0px';
  17379. textVmlElStyle.top = '0px';
  17380. }
  17381. else {
  17382. skewEl.on = false;
  17383. textVmlElStyle.left = round$1(x) + 'px';
  17384. textVmlElStyle.top = round$1(y) + 'px';
  17385. }
  17386. textPathEl.string = encodeHtmlAttribute(text);
  17387. // TODO
  17388. try {
  17389. textPathEl.style.font = font;
  17390. }
  17391. // Error font format
  17392. catch (e) {}
  17393. updateFillAndStroke(textVmlEl, 'fill', {
  17394. fill: style.textFill,
  17395. opacity: style.opacity
  17396. }, this);
  17397. updateFillAndStroke(textVmlEl, 'stroke', {
  17398. stroke: style.textStroke,
  17399. opacity: style.opacity,
  17400. lineDash: style.lineDash || null // style.lineDash can be `false`.
  17401. }, this);
  17402. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  17403. // Attached to root
  17404. append(vmlRoot, textVmlEl);
  17405. };
  17406. var removeRectText = function (vmlRoot) {
  17407. remove$1(vmlRoot, this._textVmlEl);
  17408. this._textVmlEl = null;
  17409. };
  17410. var appendRectText = function (vmlRoot) {
  17411. append(vmlRoot, this._textVmlEl);
  17412. };
  17413. var list = [RectText, Displayable, ZImage, Path, Text];
  17414. // In case Displayable has been mixed in RectText
  17415. for (var i$1 = 0; i$1 < list.length; i$1++) {
  17416. var proto = list[i$1].prototype;
  17417. proto.drawRectText = drawRectText;
  17418. proto.removeRectText = removeRectText;
  17419. proto.appendRectText = appendRectText;
  17420. }
  17421. Text.prototype.brushVML = function (vmlRoot) {
  17422. var style = this.style;
  17423. if (style.text != null) {
  17424. this.drawRectText(vmlRoot, {
  17425. x: style.x || 0, y: style.y || 0,
  17426. width: 0, height: 0
  17427. }, this.getBoundingRect(), true);
  17428. }
  17429. else {
  17430. this.removeRectText(vmlRoot);
  17431. }
  17432. };
  17433. Text.prototype.onRemove = function (vmlRoot) {
  17434. this.removeRectText(vmlRoot);
  17435. };
  17436. Text.prototype.onAdd = function (vmlRoot) {
  17437. this.appendRectText(vmlRoot);
  17438. };
  17439. }
  17440. /**
  17441. * VML Painter.
  17442. *
  17443. * @module zrender/vml/Painter
  17444. */
  17445. function parseInt10$2(val) {
  17446. return parseInt(val, 10);
  17447. }
  17448. /**
  17449. * @alias module:zrender/vml/Painter
  17450. */
  17451. function VMLPainter(root, storage) {
  17452. initVML();
  17453. this.root = root;
  17454. this.storage = storage;
  17455. var vmlViewport = document.createElement('div');
  17456. var vmlRoot = document.createElement('div');
  17457. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  17458. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  17459. root.appendChild(vmlViewport);
  17460. this._vmlRoot = vmlRoot;
  17461. this._vmlViewport = vmlViewport;
  17462. this.resize();
  17463. // Modify storage
  17464. var oldDelFromStorage = storage.delFromStorage;
  17465. var oldAddToStorage = storage.addToStorage;
  17466. storage.delFromStorage = function (el) {
  17467. oldDelFromStorage.call(storage, el);
  17468. if (el) {
  17469. el.onRemove && el.onRemove(vmlRoot);
  17470. }
  17471. };
  17472. storage.addToStorage = function (el) {
  17473. // Displayable already has a vml node
  17474. el.onAdd && el.onAdd(vmlRoot);
  17475. oldAddToStorage.call(storage, el);
  17476. };
  17477. this._firstPaint = true;
  17478. }
  17479. VMLPainter.prototype = {
  17480. constructor: VMLPainter,
  17481. getType: function () {
  17482. return 'vml';
  17483. },
  17484. /**
  17485. * @return {HTMLDivElement}
  17486. */
  17487. getViewportRoot: function () {
  17488. return this._vmlViewport;
  17489. },
  17490. getViewportRootOffset: function () {
  17491. var viewportRoot = this.getViewportRoot();
  17492. if (viewportRoot) {
  17493. return {
  17494. offsetLeft: viewportRoot.offsetLeft || 0,
  17495. offsetTop: viewportRoot.offsetTop || 0
  17496. };
  17497. }
  17498. },
  17499. /**
  17500. * 刷新
  17501. */
  17502. refresh: function () {
  17503. var list = this.storage.getDisplayList(true, true);
  17504. this._paintList(list);
  17505. },
  17506. _paintList: function (list) {
  17507. var vmlRoot = this._vmlRoot;
  17508. for (var i = 0; i < list.length; i++) {
  17509. var el = list[i];
  17510. if (el.invisible || el.ignore) {
  17511. if (!el.__alreadyNotVisible) {
  17512. el.onRemove(vmlRoot);
  17513. }
  17514. // Set as already invisible
  17515. el.__alreadyNotVisible = true;
  17516. }
  17517. else {
  17518. if (el.__alreadyNotVisible) {
  17519. el.onAdd(vmlRoot);
  17520. }
  17521. el.__alreadyNotVisible = false;
  17522. if (el.__dirty) {
  17523. el.beforeBrush && el.beforeBrush();
  17524. (el.brushVML || el.brush).call(el, vmlRoot);
  17525. el.afterBrush && el.afterBrush();
  17526. }
  17527. }
  17528. el.__dirty = false;
  17529. }
  17530. if (this._firstPaint) {
  17531. // Detached from document at first time
  17532. // to avoid page refreshing too many times
  17533. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  17534. this._vmlViewport.appendChild(vmlRoot);
  17535. this._firstPaint = false;
  17536. }
  17537. },
  17538. resize: function (width, height) {
  17539. var width = width == null ? this._getWidth() : width;
  17540. var height = height == null ? this._getHeight() : height;
  17541. if (this._width !== width || this._height !== height) {
  17542. this._width = width;
  17543. this._height = height;
  17544. var vmlViewportStyle = this._vmlViewport.style;
  17545. vmlViewportStyle.width = width + 'px';
  17546. vmlViewportStyle.height = height + 'px';
  17547. }
  17548. },
  17549. dispose: function () {
  17550. this.root.innerHTML = '';
  17551. this._vmlRoot =
  17552. this._vmlViewport =
  17553. this.storage = null;
  17554. },
  17555. getWidth: function () {
  17556. return this._width;
  17557. },
  17558. getHeight: function () {
  17559. return this._height;
  17560. },
  17561. clear: function () {
  17562. if (this._vmlViewport) {
  17563. this.root.removeChild(this._vmlViewport);
  17564. }
  17565. },
  17566. _getWidth: function () {
  17567. var root = this.root;
  17568. var stl = root.currentStyle;
  17569. return ((root.clientWidth || parseInt10$2(stl.width))
  17570. - parseInt10$2(stl.paddingLeft)
  17571. - parseInt10$2(stl.paddingRight)) | 0;
  17572. },
  17573. _getHeight: function () {
  17574. var root = this.root;
  17575. var stl = root.currentStyle;
  17576. return ((root.clientHeight || parseInt10$2(stl.height))
  17577. - parseInt10$2(stl.paddingTop)
  17578. - parseInt10$2(stl.paddingBottom)) | 0;
  17579. }
  17580. };
  17581. // Not supported methods
  17582. function createMethodNotSupport$1(method) {
  17583. return function () {
  17584. logError$1('In IE8.0 VML mode painter not support method "' + method + '"');
  17585. };
  17586. }
  17587. // Unsupported methods
  17588. each([
  17589. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  17590. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  17591. ], function (name) {
  17592. VMLPainter.prototype[name] = createMethodNotSupport$1(name);
  17593. });
  17594. registerPainter('vml', VMLPainter);
  17595. exports.version = version;
  17596. exports.init = init;
  17597. exports.dispose = dispose;
  17598. exports.getInstance = getInstance;
  17599. exports.registerPainter = registerPainter;
  17600. exports.matrix = matrix;
  17601. exports.vector = vector;
  17602. exports.color = color;
  17603. exports.path = path;
  17604. exports.util = util;
  17605. exports.parseSVG = parseSVG;
  17606. exports.Group = Group;
  17607. exports.Path = Path;
  17608. exports.Image = ZImage;
  17609. exports.CompoundPath = CompoundPath;
  17610. exports.Text = Text;
  17611. exports.IncrementalDisplayable = IncrementalDisplayble;
  17612. exports.Arc = Arc;
  17613. exports.BezierCurve = BezierCurve;
  17614. exports.Circle = Circle;
  17615. exports.Droplet = Droplet;
  17616. exports.Ellipse = Ellipse;
  17617. exports.Heart = Heart;
  17618. exports.Isogon = Isogon;
  17619. exports.Line = Line;
  17620. exports.Polygon = Polygon;
  17621. exports.Polyline = Polyline;
  17622. exports.Rect = Rect;
  17623. exports.Ring = Ring;
  17624. exports.Rose = Rose;
  17625. exports.Sector = Sector;
  17626. exports.Star = Star;
  17627. exports.Trochoid = Trochoid;
  17628. exports.LinearGradient = LinearGradient;
  17629. exports.RadialGradient = RadialGradient;
  17630. exports.Pattern = Pattern;
  17631. exports.BoundingRect = BoundingRect;
  17632. })));
  17633. //# sourceMappingURL=zrender.js.map