fabric.js 896 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523
  1. /*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */
  2. var fabric = fabric || { version: '2.3.3' };
  3. if (typeof exports !== 'undefined') {
  4. exports.fabric = fabric;
  5. }
  6. /* _AMD_START_ */
  7. else if (typeof define === 'function' && define.amd) {
  8. define([], function() { return fabric; });
  9. }
  10. /* _AMD_END_ */
  11. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  12. fabric.document = document;
  13. fabric.window = window;
  14. }
  15. else {
  16. // assume we're running under node.js when document/window are not present
  17. fabric.document = require('jsdom')
  18. .jsdom(
  19. decodeURIComponent('%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E'),
  20. { features: {
  21. FetchExternalResources: ['img']
  22. }
  23. });
  24. fabric.jsdomImplForWrapper = require('jsdom/lib/jsdom/living/generated/utils').implForWrapper;
  25. fabric.nodeCanvas = require('jsdom/lib/jsdom/utils').Canvas;
  26. fabric.window = fabric.document.defaultView;
  27. DOMParser = require('xmldom').DOMParser;
  28. }
  29. /**
  30. * True when in environment that supports touch events
  31. * @type boolean
  32. */
  33. fabric.isTouchSupported = 'ontouchstart' in fabric.window;
  34. /**
  35. * True when in environment that's probably Node.js
  36. * @type boolean
  37. */
  38. fabric.isLikelyNode = typeof Buffer !== 'undefined' &&
  39. typeof window === 'undefined';
  40. /**
  41. * Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
  42. */
  43. fabric.DPI = 96;
  44. fabric.reNum = '(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)';
  45. fabric.fontPaths = { };
  46. fabric.iMatrix = [1, 0, 0, 1, 0, 0];
  47. fabric.canvasModule = 'canvas';
  48. /**
  49. * Pixel limit for cache canvases. 1Mpx , 4Mpx should be fine.
  50. * @since 1.7.14
  51. * @type Number
  52. * @default
  53. */
  54. fabric.perfLimitSizeTotal = 2097152;
  55. /**
  56. * Pixel limit for cache canvases width or height. IE fixes the maximum at 5000
  57. * @since 1.7.14
  58. * @type Number
  59. * @default
  60. */
  61. fabric.maxCacheSideLimit = 4096;
  62. /**
  63. * Lowest pixel limit for cache canvases, set at 256PX
  64. * @since 1.7.14
  65. * @type Number
  66. * @default
  67. */
  68. fabric.minCacheSideLimit = 256;
  69. /**
  70. * Cache Object for widths of chars in text rendering.
  71. */
  72. fabric.charWidthsCache = { };
  73. /**
  74. * if webgl is enabled and available, textureSize will determine the size
  75. * of the canvas backend
  76. * @since 2.0.0
  77. * @type Number
  78. * @default
  79. */
  80. fabric.textureSize = 2048;
  81. /**
  82. * Enable webgl for filtering picture is available
  83. * A filtering backend will be initialized, this will both take memory and
  84. * time since a default 2048x2048 canvas will be created for the gl context
  85. * @since 2.0.0
  86. * @type Boolean
  87. * @default
  88. */
  89. fabric.enableGLFiltering = true;
  90. /**
  91. * Device Pixel Ratio
  92. * @see https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/SettingUptheCanvas/SettingUptheCanvas.html
  93. */
  94. fabric.devicePixelRatio = fabric.window.devicePixelRatio ||
  95. fabric.window.webkitDevicePixelRatio ||
  96. fabric.window.mozDevicePixelRatio ||
  97. 1;
  98. /**
  99. * Browser-specific constant to adjust CanvasRenderingContext2D.shadowBlur value,
  100. * which is unitless and not rendered equally across browsers.
  101. *
  102. * Values that work quite well (as of October 2017) are:
  103. * - Chrome: 1.5
  104. * - Edge: 1.75
  105. * - Firefox: 0.9
  106. * - Safari: 0.95
  107. *
  108. * @since 2.0.0
  109. * @type Number
  110. * @default 1
  111. */
  112. fabric.browserShadowBlurConstant = 1;
  113. fabric.initFilterBackend = function() {
  114. if (fabric.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(fabric.textureSize)) {
  115. console.log('max texture size: ' + fabric.maxTextureSize);
  116. return (new fabric.WebglFilterBackend({ tileSize: fabric.textureSize }));
  117. }
  118. else if (fabric.Canvas2dFilterBackend) {
  119. return (new fabric.Canvas2dFilterBackend());
  120. }
  121. };
  122. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  123. // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)
  124. window.fabric = fabric;
  125. }
  126. /*:
  127. ----------------------------------------------------
  128. event.js : 1.1.5 : 2014/02/12 : MIT License
  129. ----------------------------------------------------
  130. https://github.com/mudcube/Event.js
  131. ----------------------------------------------------
  132. 1 : click, dblclick, dbltap
  133. 1+ : tap, longpress, drag, swipe
  134. 2+ : pinch, rotate
  135. : mousewheel, devicemotion, shake
  136. ----------------------------------------------------
  137. Ideas for the future
  138. ----------------------------------------------------
  139. * GamePad, and other input abstractions.
  140. * Event batching - i.e. for every x fingers down a new gesture is created.
  141. ----------------------------------------------------
  142. http://www.w3.org/TR/2011/WD-touch-events-20110505/
  143. ----------------------------------------------------
  144. */
  145. if (typeof(eventjs) === "undefined") var eventjs = {};
  146. (function(root) {
  147. // Add custom *EventListener commands to HTMLElements (set false to prevent funkiness).
  148. root.modifyEventListener = false;
  149. // Add bulk *EventListener commands on NodeLists from querySelectorAll and others (set false to prevent funkiness).
  150. root.modifySelectors = false;
  151. root.configure = function(conf) {
  152. if (isFinite(conf.modifyEventListener)) root.modifyEventListener = conf.modifyEventListener;
  153. if (isFinite(conf.modifySelectors)) root.modifySelectors = conf.modifySelectors;
  154. /// Augment event listeners
  155. if (eventListenersAgumented === false && root.modifyEventListener) {
  156. augmentEventListeners();
  157. }
  158. if (selectorsAugmented === false && root.modifySelectors) {
  159. augmentSelectors();
  160. }
  161. };
  162. // Event maintenance.
  163. root.add = function(target, type, listener, configure) {
  164. return eventManager(target, type, listener, configure, "add");
  165. };
  166. root.remove = function(target, type, listener, configure) {
  167. return eventManager(target, type, listener, configure, "remove");
  168. };
  169. root.returnFalse = function(event) {
  170. return false;
  171. };
  172. root.stop = function(event) {
  173. if (!event) return;
  174. if (event.stopPropagation) event.stopPropagation();
  175. event.cancelBubble = true; // <= IE8
  176. event.cancelBubbleCount = 0;
  177. };
  178. root.prevent = function(event) {
  179. if (!event) return;
  180. if (event.preventDefault) {
  181. event.preventDefault();
  182. } else if (event.preventManipulation) {
  183. event.preventManipulation(); // MS
  184. } else {
  185. event.returnValue = false; // <= IE8
  186. }
  187. };
  188. root.cancel = function(event) {
  189. root.stop(event);
  190. root.prevent(event);
  191. };
  192. root.blur = function() { // Blurs the focused element. Useful when using eventjs.cancel as canceling will prevent focused elements from being blurred.
  193. var node = document.activeElement;
  194. if (!node) return;
  195. var nodeName = document.activeElement.nodeName;
  196. if (nodeName === "INPUT" || nodeName === "TEXTAREA" || node.contentEditable === "true") {
  197. if (node.blur) node.blur();
  198. }
  199. };
  200. // Check whether event is natively supported (via @kangax)
  201. root.getEventSupport = function (target, type) {
  202. if (typeof(target) === "string") {
  203. type = target;
  204. target = window;
  205. }
  206. type = "on" + type;
  207. if (type in target) return true;
  208. if (!target.setAttribute) target = document.createElement("div");
  209. if (target.setAttribute && target.removeAttribute) {
  210. target.setAttribute(type, "");
  211. var isSupported = typeof target[type] === "function";
  212. if (typeof target[type] !== "undefined") target[type] = null;
  213. target.removeAttribute(type);
  214. return isSupported;
  215. }
  216. };
  217. var clone = function (obj) {
  218. if (!obj || typeof (obj) !== 'object') return obj;
  219. var temp = new obj.constructor();
  220. for (var key in obj) {
  221. if (!obj[key] || typeof (obj[key]) !== 'object') {
  222. temp[key] = obj[key];
  223. } else { // clone sub-object
  224. temp[key] = clone(obj[key]);
  225. }
  226. }
  227. return temp;
  228. };
  229. /// Handle custom *EventListener commands.
  230. var eventManager = function(target, type, listener, configure, trigger, fromOverwrite) {
  231. configure = configure || {};
  232. // Check whether target is a configuration variable;
  233. if (String(target) === "[object Object]") {
  234. var data = target;
  235. target = data.target; delete data.target;
  236. ///
  237. if (data.type && data.listener) {
  238. type = data.type; delete data.type;
  239. listener = data.listener; delete data.listener;
  240. for (var key in data) {
  241. configure[key] = data[key];
  242. }
  243. } else { // specialness
  244. for (var param in data) {
  245. var value = data[param];
  246. if (typeof(value) === "function") continue;
  247. configure[param] = value;
  248. }
  249. ///
  250. var ret = {};
  251. for (var key in data) {
  252. var param = key.split(",");
  253. var o = data[key];
  254. var conf = {};
  255. for (var k in configure) { // clone base configuration
  256. conf[k] = configure[k];
  257. }
  258. ///
  259. if (typeof(o) === "function") { // without configuration
  260. var listener = o;
  261. } else if (typeof(o.listener) === "function") { // with configuration
  262. var listener = o.listener;
  263. for (var k in o) { // merge configure into base configuration
  264. if (typeof(o[k]) === "function") continue;
  265. conf[k] = o[k];
  266. }
  267. } else { // not a listener
  268. continue;
  269. }
  270. ///
  271. for (var n = 0; n < param.length; n ++) {
  272. ret[key] = eventjs.add(target, param[n], listener, conf, trigger);
  273. }
  274. }
  275. return ret;
  276. }
  277. }
  278. ///
  279. if (!target || !type || !listener) return;
  280. // Check for element to load on interval (before onload).
  281. if (typeof(target) === "string" && type === "ready") {
  282. if (window.eventjs_stallOnReady) { /// force stall for scripts to load
  283. type = "load";
  284. target = window;
  285. } else { //
  286. var time = (new Date()).getTime();
  287. var timeout = configure.timeout;
  288. var ms = configure.interval || 1000 / 60;
  289. var interval = window.setInterval(function() {
  290. if ((new Date()).getTime() - time > timeout) {
  291. window.clearInterval(interval);
  292. }
  293. if (document.querySelector(target)) {
  294. window.clearInterval(interval);
  295. setTimeout(listener, 1);
  296. }
  297. }, ms);
  298. return;
  299. }
  300. }
  301. // Get DOM element from Query Selector.
  302. if (typeof(target) === "string") {
  303. target = document.querySelectorAll(target);
  304. if (target.length === 0) return createError("Missing target on listener!", arguments); // No results.
  305. if (target.length === 1) { // Single target.
  306. target = target[0];
  307. }
  308. }
  309. /// Handle multiple targets.
  310. var event;
  311. var events = {};
  312. if (target.length > 0 && target !== window) {
  313. for (var n0 = 0, length0 = target.length; n0 < length0; n0 ++) {
  314. event = eventManager(target[n0], type, listener, clone(configure), trigger);
  315. if (event) events[n0] = event;
  316. }
  317. return createBatchCommands(events);
  318. }
  319. /// Check for multiple events in one string.
  320. if (typeof(type) === "string") {
  321. type = type.toLowerCase();
  322. if (type.indexOf(" ") !== -1) {
  323. type = type.split(" ");
  324. } else if (type.indexOf(",") !== -1) {
  325. type = type.split(",");
  326. }
  327. }
  328. /// Attach or remove multiple events associated with a target.
  329. if (typeof(type) !== "string") { // Has multiple events.
  330. if (typeof(type.length) === "number") { // Handle multiple listeners glued together.
  331. for (var n1 = 0, length1 = type.length; n1 < length1; n1 ++) { // Array [type]
  332. event = eventManager(target, type[n1], listener, clone(configure), trigger);
  333. if (event) events[type[n1]] = event;
  334. }
  335. } else { // Handle multiple listeners.
  336. for (var key in type) { // Object {type}
  337. if (typeof(type[key]) === "function") { // without configuration.
  338. event = eventManager(target, key, type[key], clone(configure), trigger);
  339. } else { // with configuration.
  340. event = eventManager(target, key, type[key].listener, clone(type[key]), trigger);
  341. }
  342. if (event) events[key] = event;
  343. }
  344. }
  345. return createBatchCommands(events);
  346. } else if (type.indexOf("on") === 0) { // to support things like "onclick" instead of "click"
  347. type = type.substr(2);
  348. }
  349. // Ensure listener is a function.
  350. if (typeof(target) !== "object") return createError("Target is not defined!", arguments);
  351. if (typeof(listener) !== "function") return createError("Listener is not a function!", arguments);
  352. // Generate a unique wrapper identifier.
  353. var useCapture = configure.useCapture || false;
  354. var id = getID(target) + "." + getID(listener) + "." + (useCapture ? 1 : 0);
  355. // Handle the event.
  356. if (root.Gesture && root.Gesture._gestureHandlers[type]) { // Fire custom event.
  357. id = type + id;
  358. if (trigger === "remove") { // Remove event listener.
  359. if (!wrappers[id]) return; // Already removed.
  360. wrappers[id].remove();
  361. delete wrappers[id];
  362. } else if (trigger === "add") { // Attach event listener.
  363. if (wrappers[id]) {
  364. wrappers[id].add();
  365. return wrappers[id]; // Already attached.
  366. }
  367. // Retains "this" orientation.
  368. if (configure.useCall && !root.modifyEventListener) {
  369. var tmp = listener;
  370. listener = function(event, self) {
  371. for (var key in self) event[key] = self[key];
  372. return tmp.call(target, event);
  373. };
  374. }
  375. // Create listener proxy.
  376. configure.gesture = type;
  377. configure.target = target;
  378. configure.listener = listener;
  379. configure.fromOverwrite = fromOverwrite;
  380. // Record wrapper.
  381. wrappers[id] = root.proxy[type](configure);
  382. }
  383. return wrappers[id];
  384. } else { // Fire native event.
  385. var eventList = getEventList(type);
  386. for (var n = 0, eventId; n < eventList.length; n ++) {
  387. type = eventList[n];
  388. eventId = type + "." + id;
  389. if (trigger === "remove") { // Remove event listener.
  390. if (!wrappers[eventId]) continue; // Already removed.
  391. target[remove](type, listener, useCapture);
  392. delete wrappers[eventId];
  393. } else if (trigger === "add") { // Attach event listener.
  394. if (wrappers[eventId]) return wrappers[eventId]; // Already attached.
  395. target[add](type, listener, useCapture);
  396. // Record wrapper.
  397. wrappers[eventId] = {
  398. id: eventId,
  399. type: type,
  400. target: target,
  401. listener: listener,
  402. remove: function() {
  403. for (var n = 0; n < eventList.length; n ++) {
  404. root.remove(target, eventList[n], listener, configure);
  405. }
  406. }
  407. };
  408. }
  409. }
  410. return wrappers[eventId];
  411. }
  412. };
  413. /// Perform batch actions on multiple events.
  414. var createBatchCommands = function(events) {
  415. return {
  416. remove: function() { // Remove multiple events.
  417. for (var key in events) {
  418. events[key].remove();
  419. }
  420. },
  421. add: function() { // Add multiple events.
  422. for (var key in events) {
  423. events[key].add();
  424. }
  425. }
  426. };
  427. };
  428. /// Display error message in console.
  429. var createError = function(message, data) {
  430. if (typeof(console) === "undefined") return;
  431. if (typeof(console.error) === "undefined") return;
  432. console.error(message, data);
  433. };
  434. /// Handle naming discrepancies between platforms.
  435. var pointerDefs = {
  436. "msPointer": [ "MSPointerDown", "MSPointerMove", "MSPointerUp" ],
  437. "touch": [ "touchstart", "touchmove", "touchend" ],
  438. "mouse": [ "mousedown", "mousemove", "mouseup" ]
  439. };
  440. var pointerDetect = {
  441. // MSPointer
  442. "MSPointerDown": 0,
  443. "MSPointerMove": 1,
  444. "MSPointerUp": 2,
  445. // Touch
  446. "touchstart": 0,
  447. "touchmove": 1,
  448. "touchend": 2,
  449. // Mouse
  450. "mousedown": 0,
  451. "mousemove": 1,
  452. "mouseup": 2
  453. };
  454. var getEventSupport = (function() {
  455. root.supports = {};
  456. if (window.navigator.msPointerEnabled) {
  457. root.supports.msPointer = true;
  458. }
  459. if (root.getEventSupport("touchstart")) {
  460. root.supports.touch = true;
  461. }
  462. if (root.getEventSupport("mousedown")) {
  463. root.supports.mouse = true;
  464. }
  465. })();
  466. var getEventList = (function() {
  467. return function(type) {
  468. var prefix = document.addEventListener ? "" : "on"; // IE
  469. var idx = pointerDetect[type];
  470. if (isFinite(idx)) {
  471. var types = [];
  472. for (var key in root.supports) {
  473. types.push(prefix + pointerDefs[key][idx]);
  474. }
  475. return types;
  476. } else {
  477. return [ prefix + type ];
  478. }
  479. };
  480. })();
  481. /// Event wrappers to keep track of all events placed in the window.
  482. var wrappers = {};
  483. var counter = 0;
  484. var getID = function(object) {
  485. if (object === window) return "#window";
  486. if (object === document) return "#document";
  487. if (!object.uniqueID) object.uniqueID = "e" + counter ++;
  488. return object.uniqueID;
  489. };
  490. /// Detect platforms native *EventListener command.
  491. var add = document.addEventListener ? "addEventListener" : "attachEvent";
  492. var remove = document.removeEventListener ? "removeEventListener" : "detachEvent";
  493. /*
  494. Pointer.js
  495. ----------------------------------------
  496. Modified from; https://github.com/borismus/pointer.js
  497. */
  498. root.createPointerEvent = function (event, self, preventRecord) {
  499. var eventName = self.gesture;
  500. var target = self.target;
  501. var pts = event.changedTouches || root.proxy.getCoords(event);
  502. if (pts.length) {
  503. var pt = pts[0];
  504. self.pointers = preventRecord ? [] : pts;
  505. self.pageX = pt.pageX;
  506. self.pageY = pt.pageY;
  507. self.x = self.pageX;
  508. self.y = self.pageY;
  509. }
  510. ///
  511. var newEvent = document.createEvent("Event");
  512. newEvent.initEvent(eventName, true, true);
  513. newEvent.originalEvent = event;
  514. for (var k in self) {
  515. if (k === "target") continue;
  516. newEvent[k] = self[k];
  517. }
  518. ///
  519. var type = newEvent.type;
  520. if (root.Gesture && root.Gesture._gestureHandlers[type]) { // capture custom events.
  521. // target.dispatchEvent(newEvent);
  522. self.oldListener.call(target, newEvent, self, false);
  523. }
  524. };
  525. var eventListenersAgumented = false;
  526. var augmentEventListeners = function() {
  527. /// Allows *EventListener to use custom event proxies.
  528. if (!window.HTMLElement) return;
  529. var augmentEventListener = function(proto) {
  530. var recall = function(trigger) { // overwrite native *EventListener's
  531. var handle = trigger + "EventListener";
  532. var handler = proto[handle];
  533. proto[handle] = function (type, listener, useCapture) {
  534. if (root.Gesture && root.Gesture._gestureHandlers[type]) { // capture custom events.
  535. var configure = useCapture;
  536. if (typeof(useCapture) === "object") {
  537. configure.useCall = true;
  538. } else { // convert to configuration object.
  539. configure = {
  540. useCall: true,
  541. useCapture: useCapture
  542. };
  543. }
  544. eventManager(this, type, listener, configure, trigger, true);
  545. // handler.call(this, type, listener, useCapture);
  546. } else { // use native function.
  547. var types = getEventList(type);
  548. for (var n = 0; n < types.length; n ++) {
  549. handler.call(this, types[n], listener, useCapture);
  550. }
  551. }
  552. };
  553. };
  554. recall("add");
  555. recall("remove");
  556. };
  557. // NOTE: overwriting HTMLElement doesn't do anything in Firefox.
  558. if (navigator.userAgent.match(/Firefox/)) {
  559. // TODO: fix Firefox for the general case.
  560. augmentEventListener(HTMLDivElement.prototype);
  561. augmentEventListener(HTMLCanvasElement.prototype);
  562. } else {
  563. augmentEventListener(HTMLElement.prototype);
  564. }
  565. augmentEventListener(document);
  566. augmentEventListener(window);
  567. };
  568. var selectorsAugmented = false;
  569. var augmentSelectors = function() {
  570. /// Allows querySelectorAll and other NodeLists to perform *EventListener commands in bulk.
  571. var proto = NodeList.prototype;
  572. proto.removeEventListener = function(type, listener, useCapture) {
  573. for (var n = 0, length = this.length; n < length; n ++) {
  574. this[n].removeEventListener(type, listener, useCapture);
  575. }
  576. };
  577. proto.addEventListener = function(type, listener, useCapture) {
  578. for (var n = 0, length = this.length; n < length; n ++) {
  579. this[n].addEventListener(type, listener, useCapture);
  580. }
  581. };
  582. };
  583. return root;
  584. })(eventjs);
  585. /*:
  586. ----------------------------------------------------
  587. eventjs.proxy : 0.4.2 : 2013/07/17 : MIT License
  588. ----------------------------------------------------
  589. https://github.com/mudcube/eventjs.js
  590. ----------------------------------------------------
  591. */
  592. if (typeof(eventjs) === "undefined") var eventjs = {};
  593. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  594. eventjs.proxy = (function(root) { "use strict";
  595. /*
  596. Create a new pointer gesture instance.
  597. */
  598. root.pointerSetup = function(conf, self) {
  599. /// Configure.
  600. conf.target = conf.target || window;
  601. conf.doc = conf.target.ownerDocument || conf.target; // Associated document.
  602. conf.minFingers = conf.minFingers || conf.fingers || 1; // Minimum required fingers.
  603. conf.maxFingers = conf.maxFingers || conf.fingers || Infinity; // Maximum allowed fingers.
  604. conf.position = conf.position || "relative"; // Determines what coordinate system points are returned.
  605. delete conf.fingers; //-
  606. /// Convenience data.
  607. self = self || {};
  608. self.enabled = true;
  609. self.gesture = conf.gesture;
  610. self.target = conf.target;
  611. self.env = conf.env;
  612. ///
  613. if (eventjs.modifyEventListener && conf.fromOverwrite) {
  614. conf.oldListener = conf.listener;
  615. conf.listener = eventjs.createPointerEvent;
  616. }
  617. /// Convenience commands.
  618. var fingers = 0;
  619. var type = self.gesture.indexOf("pointer") === 0 && eventjs.modifyEventListener ? "pointer" : "mouse";
  620. if (conf.oldListener) self.oldListener = conf.oldListener;
  621. ///
  622. self.listener = conf.listener;
  623. self.proxy = function(listener) {
  624. self.defaultListener = conf.listener;
  625. conf.listener = listener;
  626. listener(conf.event, self);
  627. };
  628. self.add = function() {
  629. if (self.enabled === true) return;
  630. if (conf.onPointerDown) eventjs.add(conf.target, type + "down", conf.onPointerDown);
  631. if (conf.onPointerMove) eventjs.add(conf.doc, type + "move", conf.onPointerMove);
  632. if (conf.onPointerUp) eventjs.add(conf.doc, type + "up", conf.onPointerUp);
  633. self.enabled = true;
  634. };
  635. self.remove = function() {
  636. if (self.enabled === false) return;
  637. if (conf.onPointerDown) eventjs.remove(conf.target, type + "down", conf.onPointerDown);
  638. if (conf.onPointerMove) eventjs.remove(conf.doc, type + "move", conf.onPointerMove);
  639. if (conf.onPointerUp) eventjs.remove(conf.doc, type + "up", conf.onPointerUp);
  640. self.reset();
  641. self.enabled = false;
  642. };
  643. self.pause = function(opt) {
  644. if (conf.onPointerMove && (!opt || opt.move)) eventjs.remove(conf.doc, type + "move", conf.onPointerMove);
  645. if (conf.onPointerUp && (!opt || opt.up)) eventjs.remove(conf.doc, type + "up", conf.onPointerUp);
  646. fingers = conf.fingers;
  647. conf.fingers = 0;
  648. };
  649. self.resume = function(opt) {
  650. if (conf.onPointerMove && (!opt || opt.move)) eventjs.add(conf.doc, type + "move", conf.onPointerMove);
  651. if (conf.onPointerUp && (!opt || opt.up)) eventjs.add(conf.doc, type + "up", conf.onPointerUp);
  652. conf.fingers = fingers;
  653. };
  654. self.reset = function() {
  655. conf.tracker = {};
  656. conf.fingers = 0;
  657. };
  658. ///
  659. return self;
  660. };
  661. /*
  662. Begin proxied pointer command.
  663. */
  664. var sp = eventjs.supports; // Default pointerType
  665. ///
  666. eventjs.isMouse = !!sp.mouse;
  667. eventjs.isMSPointer = !!sp.touch;
  668. eventjs.isTouch = !!sp.msPointer;
  669. ///
  670. root.pointerStart = function(event, self, conf) {
  671. /// tracks multiple inputs
  672. var type = (event.type || "mousedown").toUpperCase();
  673. if (type.indexOf("MOUSE") === 0) {
  674. eventjs.isMouse = true;
  675. eventjs.isTouch = false;
  676. eventjs.isMSPointer = false;
  677. } else if (type.indexOf("TOUCH") === 0) {
  678. eventjs.isMouse = false;
  679. eventjs.isTouch = true;
  680. eventjs.isMSPointer = false;
  681. } else if (type.indexOf("MSPOINTER") === 0) {
  682. eventjs.isMouse = false;
  683. eventjs.isTouch = false;
  684. eventjs.isMSPointer = true;
  685. }
  686. ///
  687. var addTouchStart = function(touch, sid) {
  688. var bbox = conf.bbox;
  689. var pt = track[sid] = {};
  690. ///
  691. switch(conf.position) {
  692. case "absolute": // Absolute from within window.
  693. pt.offsetX = 0;
  694. pt.offsetY = 0;
  695. break;
  696. case "differenceFromLast": // Since last coordinate recorded.
  697. pt.offsetX = touch.pageX;
  698. pt.offsetY = touch.pageY;
  699. break;
  700. case "difference": // Relative from origin.
  701. pt.offsetX = touch.pageX;
  702. pt.offsetY = touch.pageY;
  703. break;
  704. case "move": // Move target element.
  705. pt.offsetX = touch.pageX - bbox.x1;
  706. pt.offsetY = touch.pageY - bbox.y1;
  707. break;
  708. default: // Relative from within target.
  709. pt.offsetX = bbox.x1 - bbox.scrollLeft;
  710. pt.offsetY = bbox.y1 - bbox.scrollTop;
  711. break;
  712. }
  713. ///
  714. var x = touch.pageX - pt.offsetX;
  715. var y = touch.pageY - pt.offsetY;
  716. ///
  717. pt.rotation = 0;
  718. pt.scale = 1;
  719. pt.startTime = pt.moveTime = (new Date()).getTime();
  720. pt.move = { x: x, y: y };
  721. pt.start = { x: x, y: y };
  722. ///
  723. conf.fingers ++;
  724. };
  725. ///
  726. conf.event = event;
  727. if (self.defaultListener) {
  728. conf.listener = self.defaultListener;
  729. delete self.defaultListener;
  730. }
  731. ///
  732. var isTouchStart = !conf.fingers;
  733. var track = conf.tracker;
  734. var touches = event.changedTouches || root.getCoords(event);
  735. var length = touches.length;
  736. // Adding touch events to tracking.
  737. for (var i = 0; i < length; i ++) {
  738. var touch = touches[i];
  739. var sid = touch.identifier || Infinity; // Touch ID.
  740. // Track the current state of the touches.
  741. if (conf.fingers) {
  742. if (conf.fingers >= conf.maxFingers) {
  743. var ids = [];
  744. for (var sid in conf.tracker) ids.push(sid);
  745. self.identifier = ids.join(",");
  746. return isTouchStart;
  747. }
  748. var fingers = 0; // Finger ID.
  749. for (var rid in track) {
  750. // Replace removed finger.
  751. if (track[rid].up) {
  752. delete track[rid];
  753. addTouchStart(touch, sid);
  754. conf.cancel = true;
  755. break;
  756. }
  757. fingers ++;
  758. }
  759. // Add additional finger.
  760. if (track[sid]) continue;
  761. addTouchStart(touch, sid);
  762. } else { // Start tracking fingers.
  763. track = conf.tracker = {};
  764. self.bbox = conf.bbox = root.getBoundingBox(conf.target);
  765. conf.fingers = 0;
  766. conf.cancel = false;
  767. addTouchStart(touch, sid);
  768. }
  769. }
  770. ///
  771. var ids = [];
  772. for (var sid in conf.tracker) ids.push(sid);
  773. self.identifier = ids.join(",");
  774. ///
  775. return isTouchStart;
  776. };
  777. /*
  778. End proxied pointer command.
  779. */
  780. root.pointerEnd = function(event, self, conf, onPointerUp) {
  781. // Record changed touches have ended (iOS changedTouches is not reliable).
  782. var touches = event.touches || [];
  783. var length = touches.length;
  784. var exists = {};
  785. for (var i = 0; i < length; i ++) {
  786. var touch = touches[i];
  787. var sid = touch.identifier;
  788. exists[sid || Infinity] = true;
  789. }
  790. for (var sid in conf.tracker) {
  791. var track = conf.tracker[sid];
  792. if (exists[sid] || track.up) continue;
  793. if (onPointerUp) { // add changedTouches to mouse.
  794. onPointerUp({
  795. pageX: track.pageX,
  796. pageY: track.pageY,
  797. changedTouches: [{
  798. pageX: track.pageX,
  799. pageY: track.pageY,
  800. identifier: sid === "Infinity" ? Infinity : sid
  801. }]
  802. }, "up");
  803. }
  804. track.up = true;
  805. conf.fingers --;
  806. }
  807. /* // This should work but fails in Safari on iOS4 so not using it.
  808. var touches = event.changedTouches || root.getCoords(event);
  809. var length = touches.length;
  810. // Record changed touches have ended (this should work).
  811. for (var i = 0; i < length; i ++) {
  812. var touch = touches[i];
  813. var sid = touch.identifier || Infinity;
  814. var track = conf.tracker[sid];
  815. if (track && !track.up) {
  816. if (onPointerUp) { // add changedTouches to mouse.
  817. onPointerUp({
  818. changedTouches: [{
  819. pageX: track.pageX,
  820. pageY: track.pageY,
  821. identifier: sid === "Infinity" ? Infinity : sid
  822. }]
  823. }, "up");
  824. }
  825. track.up = true;
  826. conf.fingers --;
  827. }
  828. } */
  829. // Wait for all fingers to be released.
  830. if (conf.fingers !== 0) return false;
  831. // Record total number of fingers gesture used.
  832. var ids = [];
  833. conf.gestureFingers = 0;
  834. for (var sid in conf.tracker) {
  835. conf.gestureFingers ++;
  836. ids.push(sid);
  837. }
  838. self.identifier = ids.join(",");
  839. // Our pointer gesture has ended.
  840. return true;
  841. };
  842. /*
  843. Returns mouse coords in an array to match event.*Touches
  844. ------------------------------------------------------------
  845. var touch = event.changedTouches || root.getCoords(event);
  846. */
  847. root.getCoords = function(event) {
  848. if (typeof(event.pageX) !== "undefined") { // Desktop browsers.
  849. root.getCoords = function(event) {
  850. return Array({
  851. type: "mouse",
  852. x: event.pageX,
  853. y: event.pageY,
  854. pageX: event.pageX,
  855. pageY: event.pageY,
  856. identifier: event.pointerId || Infinity // pointerId is MS
  857. });
  858. };
  859. } else { // Internet Explorer <= 8.0
  860. root.getCoords = function(event) {
  861. var doc = document.documentElement;
  862. event = event || window.event;
  863. return Array({
  864. type: "mouse",
  865. x: event.clientX + doc.scrollLeft,
  866. y: event.clientY + doc.scrollTop,
  867. pageX: event.clientX + doc.scrollLeft,
  868. pageY: event.clientY + doc.scrollTop,
  869. identifier: Infinity
  870. });
  871. };
  872. }
  873. return root.getCoords(event);
  874. };
  875. /*
  876. Returns single coords in an object.
  877. ------------------------------------------------------------
  878. var mouse = root.getCoord(event);
  879. */
  880. root.getCoord = function(event) {
  881. if ("ontouchstart" in window) { // Mobile browsers.
  882. var pX = 0;
  883. var pY = 0;
  884. root.getCoord = function(event) {
  885. var touches = event.changedTouches;
  886. if (touches && touches.length) { // ontouchstart + ontouchmove
  887. return {
  888. x: pX = touches[0].pageX,
  889. y: pY = touches[0].pageY
  890. };
  891. } else { // ontouchend
  892. return {
  893. x: pX,
  894. y: pY
  895. };
  896. }
  897. };
  898. } else if(typeof(event.pageX) !== "undefined" && typeof(event.pageY) !== "undefined") { // Desktop browsers.
  899. root.getCoord = function(event) {
  900. return {
  901. x: event.pageX,
  902. y: event.pageY
  903. };
  904. };
  905. } else { // Internet Explorer <=8.0
  906. root.getCoord = function(event) {
  907. var doc = document.documentElement;
  908. event = event || window.event;
  909. return {
  910. x: event.clientX + doc.scrollLeft,
  911. y: event.clientY + doc.scrollTop
  912. };
  913. };
  914. }
  915. return root.getCoord(event);
  916. };
  917. /*
  918. Get target scale and position in space.
  919. */
  920. var getPropertyAsFloat = function(o, type) {
  921. var n = parseFloat(o.getPropertyValue(type), 10);
  922. return isFinite(n) ? n : 0;
  923. };
  924. root.getBoundingBox = function(o) {
  925. if (o === window || o === document) o = document.body;
  926. ///
  927. var bbox = {};
  928. var bcr = o.getBoundingClientRect();
  929. bbox.width = bcr.width;
  930. bbox.height = bcr.height;
  931. bbox.x1 = bcr.left;
  932. bbox.y1 = bcr.top;
  933. bbox.scaleX = bcr.width / o.offsetWidth || 1;
  934. bbox.scaleY = bcr.height / o.offsetHeight || 1;
  935. bbox.scrollLeft = 0;
  936. bbox.scrollTop = 0;
  937. ///
  938. var style = window.getComputedStyle(o);
  939. var borderBox = style.getPropertyValue("box-sizing") === "border-box";
  940. ///
  941. if (borderBox === false) {
  942. var left = getPropertyAsFloat(style, "border-left-width");
  943. var right = getPropertyAsFloat(style, "border-right-width");
  944. var bottom = getPropertyAsFloat(style, "border-bottom-width");
  945. var top = getPropertyAsFloat(style, "border-top-width");
  946. bbox.border = [ left, right, top, bottom ];
  947. bbox.x1 += left;
  948. bbox.y1 += top;
  949. bbox.width -= right + left;
  950. bbox.height -= bottom + top;
  951. }
  952. /* var left = getPropertyAsFloat(style, "padding-left");
  953. var right = getPropertyAsFloat(style, "padding-right");
  954. var bottom = getPropertyAsFloat(style, "padding-bottom");
  955. var top = getPropertyAsFloat(style, "padding-top");
  956. bbox.padding = [ left, right, top, bottom ];*/
  957. ///
  958. bbox.x2 = bbox.x1 + bbox.width;
  959. bbox.y2 = bbox.y1 + bbox.height;
  960. /// Get the scroll of container element.
  961. var position = style.getPropertyValue("position");
  962. var tmp = position === "fixed" ? o : o.parentNode;
  963. while (tmp !== null) {
  964. if (tmp === document.body) break;
  965. if (tmp.scrollTop === undefined) break;
  966. var style = window.getComputedStyle(tmp);
  967. var position = style.getPropertyValue("position");
  968. if (position === "absolute") {
  969. } else if (position === "fixed") {
  970. // bbox.scrollTop += document.body.scrollTop;
  971. // bbox.scrollLeft += document.body.scrollLeft;
  972. bbox.scrollTop -= tmp.parentNode.scrollTop;
  973. bbox.scrollLeft -= tmp.parentNode.scrollLeft;
  974. break;
  975. } else {
  976. bbox.scrollLeft += tmp.scrollLeft;
  977. bbox.scrollTop += tmp.scrollTop;
  978. }
  979. ///
  980. tmp = tmp.parentNode;
  981. };
  982. ///
  983. bbox.scrollBodyLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
  984. bbox.scrollBodyTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
  985. ///
  986. bbox.scrollLeft -= bbox.scrollBodyLeft;
  987. bbox.scrollTop -= bbox.scrollBodyTop;
  988. ///
  989. return bbox;
  990. };
  991. /*
  992. Keep track of metaKey, the proper ctrlKey for users platform.
  993. ----------------------------------------------------
  994. http://www.quirksmode.org/js/keys.html
  995. -----------------------------------
  996. http://unixpapa.com/js/key.html
  997. */
  998. (function() {
  999. var agent = navigator.userAgent.toLowerCase();
  1000. var mac = agent.indexOf("macintosh") !== -1;
  1001. var metaKeys;
  1002. if (mac && agent.indexOf("khtml") !== -1) { // chrome, safari.
  1003. metaKeys = { 91: true, 93: true };
  1004. } else if (mac && agent.indexOf("firefox") !== -1) { // mac firefox.
  1005. metaKeys = { 224: true };
  1006. } else { // windows, linux, or mac opera.
  1007. metaKeys = { 17: true };
  1008. }
  1009. (root.metaTrackerReset = function() {
  1010. eventjs.fnKey = root.fnKey = false;
  1011. eventjs.metaKey = root.metaKey = false;
  1012. eventjs.escKey = root.escKey = false;
  1013. eventjs.ctrlKey = root.ctrlKey = false;
  1014. eventjs.shiftKey = root.shiftKey = false;
  1015. eventjs.altKey = root.altKey = false;
  1016. })();
  1017. root.metaTracker = function(event) {
  1018. var isKeyDown = event.type === "keydown";
  1019. if (event.keyCode === 27) eventjs.escKey = root.escKey = isKeyDown;
  1020. if (metaKeys[event.keyCode]) eventjs.metaKey = root.metaKey = isKeyDown;
  1021. eventjs.ctrlKey = root.ctrlKey = event.ctrlKey;
  1022. eventjs.shiftKey = root.shiftKey = event.shiftKey;
  1023. eventjs.altKey = root.altKey = event.altKey;
  1024. };
  1025. })();
  1026. return root;
  1027. })(eventjs.proxy);
  1028. /*:
  1029. ----------------------------------------------------
  1030. "MutationObserver" event proxy.
  1031. ----------------------------------------------------
  1032. author: Selvakumar Arumugam - MIT LICENSE
  1033. src: http://stackoverflow.com/questions/10868104/can-you-have-a-javascript-hook-trigger-after-a-dom-elements-style-object-change
  1034. ----------------------------------------------------
  1035. */
  1036. if (typeof(eventjs) === "undefined") var eventjs = {};
  1037. eventjs.MutationObserver = (function() {
  1038. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  1039. var DOMAttrModifiedSupported = !MutationObserver && (function() {
  1040. var p = document.createElement("p");
  1041. var flag = false;
  1042. var fn = function() { flag = true };
  1043. if (p.addEventListener) {
  1044. p.addEventListener("DOMAttrModified", fn, false);
  1045. } else if (p.attachEvent) {
  1046. p.attachEvent("onDOMAttrModified", fn);
  1047. } else {
  1048. return false;
  1049. }
  1050. ///
  1051. p.setAttribute("id", "target");
  1052. ///
  1053. return flag;
  1054. })();
  1055. ///
  1056. return function(container, callback) {
  1057. if (MutationObserver) {
  1058. var options = {
  1059. subtree: false,
  1060. attributes: true
  1061. };
  1062. var observer = new MutationObserver(function(mutations) {
  1063. mutations.forEach(function(e) {
  1064. callback.call(e.target, e.attributeName);
  1065. });
  1066. });
  1067. observer.observe(container, options)
  1068. } else if (DOMAttrModifiedSupported) {
  1069. eventjs.add(container, "DOMAttrModified", function(e) {
  1070. callback.call(container, e.attrName);
  1071. });
  1072. } else if ("onpropertychange" in document.body) {
  1073. eventjs.add(container, "propertychange", function(e) {
  1074. callback.call(container, window.event.propertyName);
  1075. });
  1076. }
  1077. }
  1078. })();
  1079. /*:
  1080. "Click" event proxy.
  1081. ----------------------------------------------------
  1082. eventjs.add(window, "click", function(event, self) {});
  1083. */
  1084. if (typeof(eventjs) === "undefined") var eventjs = {};
  1085. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1086. eventjs.proxy = (function(root) { "use strict";
  1087. root.click = function(conf) {
  1088. conf.gesture = conf.gesture || "click";
  1089. conf.maxFingers = conf.maxFingers || conf.fingers || 1;
  1090. /// Tracking the events.
  1091. conf.onPointerDown = function (event) {
  1092. if (root.pointerStart(event, self, conf)) {
  1093. eventjs.add(conf.target, "mouseup", conf.onPointerUp);
  1094. }
  1095. };
  1096. conf.onPointerUp = function(event) {
  1097. if (root.pointerEnd(event, self, conf)) {
  1098. eventjs.remove(conf.target, "mouseup", conf.onPointerUp);
  1099. var pointers = event.changedTouches || root.getCoords(event);
  1100. var pointer = pointers[0];
  1101. var bbox = conf.bbox;
  1102. var newbbox = root.getBoundingBox(conf.target);
  1103. var y = pointer.pageY - newbbox.scrollBodyTop;
  1104. var x = pointer.pageX - newbbox.scrollBodyLeft;
  1105. ////
  1106. if (x > bbox.x1 && y > bbox.y1 &&
  1107. x < bbox.x2 && y < bbox.y2 &&
  1108. bbox.scrollTop === newbbox.scrollTop) { // has not been scrolled
  1109. ///
  1110. for (var key in conf.tracker) break; //- should be modularized? in dblclick too
  1111. var point = conf.tracker[key];
  1112. self.x = point.start.x;
  1113. self.y = point.start.y;
  1114. ///
  1115. conf.listener(event, self);
  1116. }
  1117. }
  1118. };
  1119. // Generate maintenance commands, and other configurations.
  1120. var self = root.pointerSetup(conf);
  1121. self.state = "click";
  1122. // Attach events.
  1123. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1124. // Return this object.
  1125. return self;
  1126. };
  1127. eventjs.Gesture = eventjs.Gesture || {};
  1128. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1129. eventjs.Gesture._gestureHandlers.click = root.click;
  1130. return root;
  1131. })(eventjs.proxy);
  1132. /*:
  1133. "Double-Click" aka "Double-Tap" event proxy.
  1134. ----------------------------------------------------
  1135. eventjs.add(window, "dblclick", function(event, self) {});
  1136. ----------------------------------------------------
  1137. Touch an target twice for <= 700ms, with less than 25 pixel drift.
  1138. */
  1139. if (typeof(eventjs) === "undefined") var eventjs = {};
  1140. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1141. eventjs.proxy = (function(root) { "use strict";
  1142. root.dbltap =
  1143. root.dblclick = function(conf) {
  1144. conf.gesture = conf.gesture || "dbltap";
  1145. conf.maxFingers = conf.maxFingers || conf.fingers || 1;
  1146. // Setting up local variables.
  1147. var delay = 700; // in milliseconds
  1148. var time0, time1, timeout;
  1149. var pointer0, pointer1;
  1150. // Tracking the events.
  1151. conf.onPointerDown = function (event) {
  1152. var pointers = event.changedTouches || root.getCoords(event);
  1153. if (time0 && !time1) { // Click #2
  1154. pointer1 = pointers[0];
  1155. time1 = (new Date()).getTime() - time0;
  1156. } else { // Click #1
  1157. pointer0 = pointers[0];
  1158. time0 = (new Date()).getTime();
  1159. time1 = 0;
  1160. clearTimeout(timeout);
  1161. timeout = setTimeout(function() {
  1162. time0 = 0;
  1163. }, delay);
  1164. }
  1165. if (root.pointerStart(event, self, conf)) {
  1166. eventjs.add(conf.target, "mousemove", conf.onPointerMove).listener(event);
  1167. eventjs.add(conf.target, "mouseup", conf.onPointerUp);
  1168. }
  1169. };
  1170. conf.onPointerMove = function (event) {
  1171. if (time0 && !time1) {
  1172. var pointers = event.changedTouches || root.getCoords(event);
  1173. pointer1 = pointers[0];
  1174. }
  1175. var bbox = conf.bbox;
  1176. var ax = (pointer1.pageX - bbox.x1);
  1177. var ay = (pointer1.pageY - bbox.y1);
  1178. if (!(ax > 0 && ax < bbox.width && // Within target coordinates..
  1179. ay > 0 && ay < bbox.height &&
  1180. Math.abs(pointer1.pageX - pointer0.pageX) <= 25 && // Within drift deviance.
  1181. Math.abs(pointer1.pageY - pointer0.pageY) <= 25)) {
  1182. // Cancel out this listener.
  1183. eventjs.remove(conf.target, "mousemove", conf.onPointerMove);
  1184. clearTimeout(timeout);
  1185. time0 = time1 = 0;
  1186. }
  1187. };
  1188. conf.onPointerUp = function(event) {
  1189. if (root.pointerEnd(event, self, conf)) {
  1190. eventjs.remove(conf.target, "mousemove", conf.onPointerMove);
  1191. eventjs.remove(conf.target, "mouseup", conf.onPointerUp);
  1192. }
  1193. if (time0 && time1) {
  1194. if (time1 <= delay) { // && !(event.cancelBubble && ++event.cancelBubbleCount > 1)) {
  1195. self.state = conf.gesture;
  1196. for (var key in conf.tracker) break;
  1197. var point = conf.tracker[key];
  1198. self.x = point.start.x;
  1199. self.y = point.start.y;
  1200. conf.listener(event, self);
  1201. }
  1202. clearTimeout(timeout);
  1203. time0 = time1 = 0;
  1204. }
  1205. };
  1206. // Generate maintenance commands, and other configurations.
  1207. var self = root.pointerSetup(conf);
  1208. self.state = "dblclick";
  1209. // Attach events.
  1210. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1211. // Return this object.
  1212. return self;
  1213. };
  1214. eventjs.Gesture = eventjs.Gesture || {};
  1215. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1216. eventjs.Gesture._gestureHandlers.dbltap = root.dbltap;
  1217. eventjs.Gesture._gestureHandlers.dblclick = root.dblclick;
  1218. return root;
  1219. })(eventjs.proxy);
  1220. /*:
  1221. "Drag" event proxy (1+ fingers).
  1222. ----------------------------------------------------
  1223. CONFIGURE: maxFingers, position.
  1224. ----------------------------------------------------
  1225. eventjs.add(window, "drag", function(event, self) {
  1226. console.log(self.gesture, self.state, self.start, self.x, self.y, self.bbox);
  1227. });
  1228. */
  1229. if (typeof(eventjs) === "undefined") var eventjs = {};
  1230. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1231. eventjs.proxy = (function(root) { "use strict";
  1232. root.dragElement = function(that, event) {
  1233. root.drag({
  1234. event: event,
  1235. target: that,
  1236. position: "move",
  1237. listener: function(event, self) {
  1238. that.style.left = self.x + "px";
  1239. that.style.top = self.y + "px";
  1240. eventjs.prevent(event);
  1241. }
  1242. });
  1243. };
  1244. root.drag = function(conf) {
  1245. conf.gesture = "drag";
  1246. conf.onPointerDown = function (event) {
  1247. if (root.pointerStart(event, self, conf)) {
  1248. if (!conf.monitor) {
  1249. eventjs.add(conf.doc, "mousemove", conf.onPointerMove);
  1250. eventjs.add(conf.doc, "mouseup", conf.onPointerUp);
  1251. }
  1252. }
  1253. // Process event listener.
  1254. conf.onPointerMove(event, "down");
  1255. };
  1256. conf.onPointerMove = function (event, state) {
  1257. if (!conf.tracker) return conf.onPointerDown(event);
  1258. var bbox = conf.bbox;
  1259. var touches = event.changedTouches || root.getCoords(event);
  1260. var length = touches.length;
  1261. for (var i = 0; i < length; i ++) {
  1262. var touch = touches[i];
  1263. var identifier = touch.identifier || Infinity;
  1264. var pt = conf.tracker[identifier];
  1265. // Identifier defined outside of listener.
  1266. if (!pt) continue;
  1267. pt.pageX = touch.pageX;
  1268. pt.pageY = touch.pageY;
  1269. // Record data.
  1270. self.state = state || "move";
  1271. self.identifier = identifier;
  1272. self.start = pt.start;
  1273. self.fingers = conf.fingers;
  1274. if (conf.position === "differenceFromLast") {
  1275. self.x = (pt.pageX - pt.offsetX);
  1276. self.y = (pt.pageY - pt.offsetY);
  1277. pt.offsetX = pt.pageX;
  1278. pt.offsetY = pt.pageY;
  1279. } else {
  1280. self.x = (pt.pageX - pt.offsetX);
  1281. self.y = (pt.pageY - pt.offsetY);
  1282. }
  1283. ///
  1284. conf.listener(event, self);
  1285. }
  1286. };
  1287. conf.onPointerUp = function(event) {
  1288. // Remove tracking for touch.
  1289. if (root.pointerEnd(event, self, conf, conf.onPointerMove)) {
  1290. if (!conf.monitor) {
  1291. eventjs.remove(conf.doc, "mousemove", conf.onPointerMove);
  1292. eventjs.remove(conf.doc, "mouseup", conf.onPointerUp);
  1293. }
  1294. }
  1295. };
  1296. // Generate maintenance commands, and other configurations.
  1297. var self = root.pointerSetup(conf);
  1298. // Attach events.
  1299. if (conf.event) {
  1300. conf.onPointerDown(conf.event);
  1301. } else { //
  1302. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1303. if (conf.monitor) {
  1304. eventjs.add(conf.doc, "mousemove", conf.onPointerMove);
  1305. eventjs.add(conf.doc, "mouseup", conf.onPointerUp);
  1306. }
  1307. }
  1308. // Return this object.
  1309. return self;
  1310. };
  1311. eventjs.Gesture = eventjs.Gesture || {};
  1312. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1313. eventjs.Gesture._gestureHandlers.drag = root.drag;
  1314. return root;
  1315. })(eventjs.proxy);
  1316. /*:
  1317. "Gesture" event proxy (2+ fingers).
  1318. ----------------------------------------------------
  1319. CONFIGURE: minFingers, maxFingers.
  1320. ----------------------------------------------------
  1321. eventjs.add(window, "gesture", function(event, self) {
  1322. console.log(
  1323. self.x, // centroid
  1324. self.y,
  1325. self.rotation,
  1326. self.scale,
  1327. self.fingers,
  1328. self.state
  1329. );
  1330. });
  1331. */
  1332. if (typeof(eventjs) === "undefined") var eventjs = {};
  1333. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1334. eventjs.proxy = (function(root) { "use strict";
  1335. var RAD_DEG = Math.PI / 180;
  1336. var getCentroid = function(self, points) {
  1337. var centroidx = 0;
  1338. var centroidy = 0;
  1339. var length = 0;
  1340. for (var sid in points) {
  1341. var touch = points[sid];
  1342. if (touch.up) continue;
  1343. centroidx += touch.move.x;
  1344. centroidy += touch.move.y;
  1345. length ++;
  1346. }
  1347. self.x = centroidx /= length;
  1348. self.y = centroidy /= length;
  1349. return self;
  1350. };
  1351. root.gesture = function(conf) {
  1352. conf.gesture = conf.gesture || "gesture";
  1353. conf.minFingers = conf.minFingers || conf.fingers || 2;
  1354. // Tracking the events.
  1355. conf.onPointerDown = function (event) {
  1356. var fingers = conf.fingers;
  1357. if (root.pointerStart(event, self, conf)) {
  1358. eventjs.add(conf.doc, "mousemove", conf.onPointerMove);
  1359. eventjs.add(conf.doc, "mouseup", conf.onPointerUp);
  1360. }
  1361. // Record gesture start.
  1362. if (conf.fingers === conf.minFingers && fingers !== conf.fingers) {
  1363. self.fingers = conf.minFingers;
  1364. self.scale = 1;
  1365. self.rotation = 0;
  1366. self.state = "start";
  1367. var sids = ""; //- FIXME(mud): can generate duplicate IDs.
  1368. for (var key in conf.tracker) sids += key;
  1369. self.identifier = parseInt(sids);
  1370. getCentroid(self, conf.tracker);
  1371. conf.listener(event, self);
  1372. }
  1373. };
  1374. ///
  1375. conf.onPointerMove = function (event, state) {
  1376. var bbox = conf.bbox;
  1377. var points = conf.tracker;
  1378. var touches = event.changedTouches || root.getCoords(event);
  1379. var length = touches.length;
  1380. // Update tracker coordinates.
  1381. for (var i = 0; i < length; i ++) {
  1382. var touch = touches[i];
  1383. var sid = touch.identifier || Infinity;
  1384. var pt = points[sid];
  1385. // Check whether "pt" is used by another gesture.
  1386. if (!pt) continue;
  1387. // Find the actual coordinates.
  1388. pt.move.x = (touch.pageX - bbox.x1);
  1389. pt.move.y = (touch.pageY - bbox.y1);
  1390. }
  1391. ///
  1392. if (conf.fingers < conf.minFingers) return;
  1393. ///
  1394. var touches = [];
  1395. var scale = 0;
  1396. var rotation = 0;
  1397. /// Calculate centroid of gesture.
  1398. getCentroid(self, points);
  1399. ///
  1400. for (var sid in points) {
  1401. var touch = points[sid];
  1402. if (touch.up) continue;
  1403. var start = touch.start;
  1404. if (!start.distance) {
  1405. var dx = start.x - self.x;
  1406. var dy = start.y - self.y;
  1407. start.distance = Math.sqrt(dx * dx + dy * dy);
  1408. start.angle = Math.atan2(dx, dy) / RAD_DEG;
  1409. }
  1410. // Calculate scale.
  1411. var dx = touch.move.x - self.x;
  1412. var dy = touch.move.y - self.y;
  1413. var distance = Math.sqrt(dx * dx + dy * dy);
  1414. scale += distance / start.distance;
  1415. // Calculate rotation.
  1416. var angle = Math.atan2(dx, dy) / RAD_DEG;
  1417. var rotate = (start.angle - angle + 360) % 360 - 180;
  1418. touch.DEG2 = touch.DEG1; // Previous degree.
  1419. touch.DEG1 = rotate > 0 ? rotate : -rotate; // Current degree.
  1420. if (typeof(touch.DEG2) !== "undefined") {
  1421. if (rotate > 0) {
  1422. touch.rotation += touch.DEG1 - touch.DEG2;
  1423. } else {
  1424. touch.rotation -= touch.DEG1 - touch.DEG2;
  1425. }
  1426. rotation += touch.rotation;
  1427. }
  1428. // Attach current points to self.
  1429. touches.push(touch.move);
  1430. }
  1431. ///
  1432. self.touches = touches;
  1433. self.fingers = conf.fingers;
  1434. self.scale = scale / conf.fingers;
  1435. self.rotation = rotation / conf.fingers;
  1436. self.state = "change";
  1437. conf.listener(event, self);
  1438. };
  1439. conf.onPointerUp = function(event) {
  1440. // Remove tracking for touch.
  1441. var fingers = conf.fingers;
  1442. if (root.pointerEnd(event, self, conf)) {
  1443. eventjs.remove(conf.doc, "mousemove", conf.onPointerMove);
  1444. eventjs.remove(conf.doc, "mouseup", conf.onPointerUp);
  1445. }
  1446. // Check whether fingers has dropped below minFingers.
  1447. if (fingers === conf.minFingers && conf.fingers < conf.minFingers) {
  1448. self.fingers = conf.fingers;
  1449. self.state = "end";
  1450. conf.listener(event, self);
  1451. }
  1452. };
  1453. // Generate maintenance commands, and other configurations.
  1454. var self = root.pointerSetup(conf);
  1455. // Attach events.
  1456. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1457. // Return this object.
  1458. return self;
  1459. };
  1460. eventjs.Gesture = eventjs.Gesture || {};
  1461. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1462. eventjs.Gesture._gestureHandlers.gesture = root.gesture;
  1463. return root;
  1464. })(eventjs.proxy);
  1465. /*:
  1466. "Pointer" event proxy (1+ fingers).
  1467. ----------------------------------------------------
  1468. CONFIGURE: minFingers, maxFingers.
  1469. ----------------------------------------------------
  1470. eventjs.add(window, "gesture", function(event, self) {
  1471. console.log(self.rotation, self.scale, self.fingers, self.state);
  1472. });
  1473. */
  1474. if (typeof(eventjs) === "undefined") var eventjs = {};
  1475. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1476. eventjs.proxy = (function(root) { "use strict";
  1477. root.pointerdown =
  1478. root.pointermove =
  1479. root.pointerup = function(conf) {
  1480. conf.gesture = conf.gesture || "pointer";
  1481. if (conf.target.isPointerEmitter) return;
  1482. // Tracking the events.
  1483. var isDown = true;
  1484. conf.onPointerDown = function (event) {
  1485. isDown = false;
  1486. self.gesture = "pointerdown";
  1487. conf.listener(event, self);
  1488. };
  1489. conf.onPointerMove = function (event) {
  1490. self.gesture = "pointermove";
  1491. conf.listener(event, self, isDown);
  1492. };
  1493. conf.onPointerUp = function (event) {
  1494. isDown = true;
  1495. self.gesture = "pointerup";
  1496. conf.listener(event, self, true);
  1497. };
  1498. // Generate maintenance commands, and other configurations.
  1499. var self = root.pointerSetup(conf);
  1500. // Attach events.
  1501. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1502. eventjs.add(conf.target, "mousemove", conf.onPointerMove);
  1503. eventjs.add(conf.doc, "mouseup", conf.onPointerUp);
  1504. // Return this object.
  1505. conf.target.isPointerEmitter = true;
  1506. return self;
  1507. };
  1508. eventjs.Gesture = eventjs.Gesture || {};
  1509. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1510. eventjs.Gesture._gestureHandlers.pointerdown = root.pointerdown;
  1511. eventjs.Gesture._gestureHandlers.pointermove = root.pointermove;
  1512. eventjs.Gesture._gestureHandlers.pointerup = root.pointerup;
  1513. return root;
  1514. })(eventjs.proxy);
  1515. /*:
  1516. "Device Motion" and "Shake" event proxy.
  1517. ----------------------------------------------------
  1518. http://developer.android.com/reference/android/hardware/Sensoreventjs.html#values
  1519. ----------------------------------------------------
  1520. eventjs.add(window, "shake", function(event, self) {});
  1521. eventjs.add(window, "devicemotion", function(event, self) {
  1522. console.log(self.acceleration, self.accelerationIncludingGravity);
  1523. });
  1524. */
  1525. if (typeof(eventjs) === "undefined") var eventjs = {};
  1526. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1527. eventjs.proxy = (function(root) { "use strict";
  1528. root.shake = function(conf) {
  1529. // Externally accessible data.
  1530. var self = {
  1531. gesture: "devicemotion",
  1532. acceleration: {},
  1533. accelerationIncludingGravity: {},
  1534. target: conf.target,
  1535. listener: conf.listener,
  1536. remove: function() {
  1537. window.removeEventListener('devicemotion', onDeviceMotion, false);
  1538. }
  1539. };
  1540. // Setting up local variables.
  1541. var threshold = 4; // Gravitational threshold.
  1542. var timeout = 1000; // Timeout between shake events.
  1543. var timeframe = 200; // Time between shakes.
  1544. var shakes = 3; // Minimum shakes to trigger event.
  1545. var lastShake = (new Date()).getTime();
  1546. var gravity = { x: 0, y: 0, z: 0 };
  1547. var delta = {
  1548. x: { count: 0, value: 0 },
  1549. y: { count: 0, value: 0 },
  1550. z: { count: 0, value: 0 }
  1551. };
  1552. // Tracking the events.
  1553. var onDeviceMotion = function(e) {
  1554. var alpha = 0.8; // Low pass filter.
  1555. var o = e.accelerationIncludingGravity;
  1556. gravity.x = alpha * gravity.x + (1 - alpha) * o.x;
  1557. gravity.y = alpha * gravity.y + (1 - alpha) * o.y;
  1558. gravity.z = alpha * gravity.z + (1 - alpha) * o.z;
  1559. self.accelerationIncludingGravity = gravity;
  1560. self.acceleration.x = o.x - gravity.x;
  1561. self.acceleration.y = o.y - gravity.y;
  1562. self.acceleration.z = o.z - gravity.z;
  1563. ///
  1564. if (conf.gesture === "devicemotion") {
  1565. conf.listener(e, self);
  1566. return;
  1567. }
  1568. var data = "xyz";
  1569. var now = (new Date()).getTime();
  1570. for (var n = 0, length = data.length; n < length; n ++) {
  1571. var letter = data[n];
  1572. var ACCELERATION = self.acceleration[letter];
  1573. var DELTA = delta[letter];
  1574. var abs = Math.abs(ACCELERATION);
  1575. /// Check whether another shake event was recently registered.
  1576. if (now - lastShake < timeout) continue;
  1577. /// Check whether delta surpasses threshold.
  1578. if (abs > threshold) {
  1579. var idx = now * ACCELERATION / abs;
  1580. var span = Math.abs(idx + DELTA.value);
  1581. // Check whether last delta was registered within timeframe.
  1582. if (DELTA.value && span < timeframe) {
  1583. DELTA.value = idx;
  1584. DELTA.count ++;
  1585. // Check whether delta count has enough shakes.
  1586. if (DELTA.count === shakes) {
  1587. conf.listener(e, self);
  1588. // Reset tracking.
  1589. lastShake = now;
  1590. DELTA.value = 0;
  1591. DELTA.count = 0;
  1592. }
  1593. } else {
  1594. // Track first shake.
  1595. DELTA.value = idx;
  1596. DELTA.count = 1;
  1597. }
  1598. }
  1599. }
  1600. };
  1601. // Attach events.
  1602. if (!window.addEventListener) return;
  1603. window.addEventListener('devicemotion', onDeviceMotion, false);
  1604. // Return this object.
  1605. return self;
  1606. };
  1607. eventjs.Gesture = eventjs.Gesture || {};
  1608. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1609. eventjs.Gesture._gestureHandlers.shake = root.shake;
  1610. return root;
  1611. })(eventjs.proxy);
  1612. /*:
  1613. "Swipe" event proxy (1+ fingers).
  1614. ----------------------------------------------------
  1615. CONFIGURE: snap, threshold, maxFingers.
  1616. ----------------------------------------------------
  1617. eventjs.add(window, "swipe", function(event, self) {
  1618. console.log(self.velocity, self.angle);
  1619. });
  1620. */
  1621. if (typeof(eventjs) === "undefined") var eventjs = {};
  1622. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1623. eventjs.proxy = (function(root) { "use strict";
  1624. var RAD_DEG = Math.PI / 180;
  1625. root.swipe = function(conf) {
  1626. conf.snap = conf.snap || 90; // angle snap.
  1627. conf.threshold = conf.threshold || 1; // velocity threshold.
  1628. conf.gesture = conf.gesture || "swipe";
  1629. // Tracking the events.
  1630. conf.onPointerDown = function (event) {
  1631. if (root.pointerStart(event, self, conf)) {
  1632. eventjs.add(conf.doc, "mousemove", conf.onPointerMove).listener(event);
  1633. eventjs.add(conf.doc, "mouseup", conf.onPointerUp);
  1634. }
  1635. };
  1636. conf.onPointerMove = function (event) {
  1637. var touches = event.changedTouches || root.getCoords(event);
  1638. var length = touches.length;
  1639. for (var i = 0; i < length; i ++) {
  1640. var touch = touches[i];
  1641. var sid = touch.identifier || Infinity;
  1642. var o = conf.tracker[sid];
  1643. // Identifier defined outside of listener.
  1644. if (!o) continue;
  1645. o.move.x = touch.pageX;
  1646. o.move.y = touch.pageY;
  1647. o.moveTime = (new Date()).getTime();
  1648. }
  1649. };
  1650. conf.onPointerUp = function(event) {
  1651. if (root.pointerEnd(event, self, conf)) {
  1652. eventjs.remove(conf.doc, "mousemove", conf.onPointerMove);
  1653. eventjs.remove(conf.doc, "mouseup", conf.onPointerUp);
  1654. ///
  1655. var velocity1;
  1656. var velocity2
  1657. var degree1;
  1658. var degree2;
  1659. /// Calculate centroid of gesture.
  1660. var start = { x: 0, y: 0 };
  1661. var endx = 0;
  1662. var endy = 0;
  1663. var length = 0;
  1664. ///
  1665. for (var sid in conf.tracker) {
  1666. var touch = conf.tracker[sid];
  1667. var xdist = touch.move.x - touch.start.x;
  1668. var ydist = touch.move.y - touch.start.y;
  1669. ///
  1670. endx += touch.move.x;
  1671. endy += touch.move.y;
  1672. start.x += touch.start.x;
  1673. start.y += touch.start.y;
  1674. length ++;
  1675. ///
  1676. var distance = Math.sqrt(xdist * xdist + ydist * ydist);
  1677. var ms = touch.moveTime - touch.startTime;
  1678. var degree2 = Math.atan2(xdist, ydist) / RAD_DEG + 180;
  1679. var velocity2 = ms ? distance / ms : 0;
  1680. if (typeof(degree1) === "undefined") {
  1681. degree1 = degree2;
  1682. velocity1 = velocity2;
  1683. } else if (Math.abs(degree2 - degree1) <= 20) {
  1684. degree1 = (degree1 + degree2) / 2;
  1685. velocity1 = (velocity1 + velocity2) / 2;
  1686. } else {
  1687. return;
  1688. }
  1689. }
  1690. ///
  1691. var fingers = conf.gestureFingers;
  1692. if (conf.minFingers <= fingers && conf.maxFingers >= fingers) {
  1693. if (velocity1 > conf.threshold) {
  1694. start.x /= length;
  1695. start.y /= length;
  1696. self.start = start;
  1697. self.x = endx / length;
  1698. self.y = endy / length;
  1699. self.angle = -((((degree1 / conf.snap + 0.5) >> 0) * conf.snap || 360) - 360);
  1700. self.velocity = velocity1;
  1701. self.fingers = fingers;
  1702. self.state = "swipe";
  1703. conf.listener(event, self);
  1704. }
  1705. }
  1706. }
  1707. };
  1708. // Generate maintenance commands, and other configurations.
  1709. var self = root.pointerSetup(conf);
  1710. // Attach events.
  1711. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1712. // Return this object.
  1713. return self;
  1714. };
  1715. eventjs.Gesture = eventjs.Gesture || {};
  1716. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1717. eventjs.Gesture._gestureHandlers.swipe = root.swipe;
  1718. return root;
  1719. })(eventjs.proxy);
  1720. /*:
  1721. "Tap" and "Longpress" event proxy.
  1722. ----------------------------------------------------
  1723. CONFIGURE: delay (longpress), timeout (tap).
  1724. ----------------------------------------------------
  1725. eventjs.add(window, "tap", function(event, self) {
  1726. console.log(self.fingers);
  1727. });
  1728. ----------------------------------------------------
  1729. multi-finger tap // touch an target for <= 250ms.
  1730. multi-finger longpress // touch an target for >= 500ms
  1731. */
  1732. if (typeof(eventjs) === "undefined") var eventjs = {};
  1733. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1734. eventjs.proxy = (function(root) { "use strict";
  1735. root.longpress = function(conf) {
  1736. conf.gesture = "longpress";
  1737. return root.tap(conf);
  1738. };
  1739. root.tap = function(conf) {
  1740. conf.delay = conf.delay || 500;
  1741. conf.timeout = conf.timeout || 250;
  1742. conf.driftDeviance = conf.driftDeviance || 10;
  1743. conf.gesture = conf.gesture || "tap";
  1744. // Setting up local variables.
  1745. var timestamp, timeout;
  1746. // Tracking the events.
  1747. conf.onPointerDown = function (event) {
  1748. if (root.pointerStart(event, self, conf)) {
  1749. timestamp = (new Date()).getTime();
  1750. // Initialize event listeners.
  1751. eventjs.add(conf.doc, "mousemove", conf.onPointerMove).listener(event);
  1752. eventjs.add(conf.doc, "mouseup", conf.onPointerUp);
  1753. // Make sure this is a "longpress" event.
  1754. if (conf.gesture !== "longpress") return;
  1755. timeout = setTimeout(function() {
  1756. if (event.cancelBubble && ++event.cancelBubbleCount > 1) return;
  1757. // Make sure no fingers have been changed.
  1758. var fingers = 0;
  1759. for (var key in conf.tracker) {
  1760. var point = conf.tracker[key];
  1761. if (point.end === true) return;
  1762. if (conf.cancel) return;
  1763. fingers ++;
  1764. }
  1765. // Send callback.
  1766. if (conf.minFingers <= fingers && conf.maxFingers >= fingers) {
  1767. self.state = "start";
  1768. self.fingers = fingers;
  1769. self.x = point.start.x;
  1770. self.y = point.start.y;
  1771. conf.listener(event, self);
  1772. }
  1773. }, conf.delay);
  1774. }
  1775. };
  1776. conf.onPointerMove = function (event) {
  1777. var bbox = conf.bbox;
  1778. var touches = event.changedTouches || root.getCoords(event);
  1779. var length = touches.length;
  1780. for (var i = 0; i < length; i ++) {
  1781. var touch = touches[i];
  1782. var identifier = touch.identifier || Infinity;
  1783. var pt = conf.tracker[identifier];
  1784. if (!pt) continue;
  1785. var x = (touch.pageX - bbox.x1);
  1786. var y = (touch.pageY - bbox.y1);
  1787. ///
  1788. var dx = x - pt.start.x;
  1789. var dy = y - pt.start.y;
  1790. var distance = Math.sqrt(dx * dx + dy * dy);
  1791. if (!(x > 0 && x < bbox.width && // Within target coordinates..
  1792. y > 0 && y < bbox.height &&
  1793. distance <= conf.driftDeviance)) { // Within drift deviance.
  1794. // Cancel out this listener.
  1795. eventjs.remove(conf.doc, "mousemove", conf.onPointerMove);
  1796. conf.cancel = true;
  1797. return;
  1798. }
  1799. }
  1800. };
  1801. conf.onPointerUp = function(event) {
  1802. if (root.pointerEnd(event, self, conf)) {
  1803. clearTimeout(timeout);
  1804. eventjs.remove(conf.doc, "mousemove", conf.onPointerMove);
  1805. eventjs.remove(conf.doc, "mouseup", conf.onPointerUp);
  1806. if (event.cancelBubble && ++event.cancelBubbleCount > 1) return;
  1807. // Callback release on longpress.
  1808. if (conf.gesture === "longpress") {
  1809. if (self.state === "start") {
  1810. self.state = "end";
  1811. conf.listener(event, self);
  1812. }
  1813. return;
  1814. }
  1815. // Cancel event due to movement.
  1816. if (conf.cancel) return;
  1817. // Ensure delay is within margins.
  1818. if ((new Date()).getTime() - timestamp > conf.timeout) return;
  1819. // Send callback.
  1820. var fingers = conf.gestureFingers;
  1821. if (conf.minFingers <= fingers && conf.maxFingers >= fingers) {
  1822. self.state = "tap";
  1823. self.fingers = conf.gestureFingers;
  1824. conf.listener(event, self);
  1825. }
  1826. }
  1827. };
  1828. // Generate maintenance commands, and other configurations.
  1829. var self = root.pointerSetup(conf);
  1830. // Attach events.
  1831. eventjs.add(conf.target, "mousedown", conf.onPointerDown);
  1832. // Return this object.
  1833. return self;
  1834. };
  1835. eventjs.Gesture = eventjs.Gesture || {};
  1836. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1837. eventjs.Gesture._gestureHandlers.tap = root.tap;
  1838. eventjs.Gesture._gestureHandlers.longpress = root.longpress;
  1839. return root;
  1840. })(eventjs.proxy);
  1841. /*:
  1842. "Mouse Wheel" event proxy.
  1843. ----------------------------------------------------
  1844. eventjs.add(window, "wheel", function(event, self) {
  1845. console.log(self.state, self.wheelDelta);
  1846. });
  1847. */
  1848. if (typeof(eventjs) === "undefined") var eventjs = {};
  1849. if (typeof(eventjs.proxy) === "undefined") eventjs.proxy = {};
  1850. eventjs.proxy = (function(root) { "use strict";
  1851. root.wheelPreventElasticBounce = function(el) {
  1852. if (!el) return;
  1853. if (typeof(el) === "string") el = document.querySelector(el);
  1854. eventjs.add(el, "wheel", function(event, self) {
  1855. self.preventElasticBounce();
  1856. eventjs.stop(event);
  1857. });
  1858. };
  1859. root.wheel = function(conf) {
  1860. // Configure event listener.
  1861. var interval;
  1862. var timeout = conf.timeout || 150;
  1863. var count = 0;
  1864. // Externally accessible data.
  1865. var self = {
  1866. gesture: "wheel",
  1867. state: "start",
  1868. wheelDelta: 0,
  1869. target: conf.target,
  1870. listener: conf.listener,
  1871. preventElasticBounce: function(event) {
  1872. var target = this.target;
  1873. var scrollTop = target.scrollTop;
  1874. var top = scrollTop + target.offsetHeight;
  1875. var height = target.scrollHeight;
  1876. if (top === height && this.wheelDelta <= 0) eventjs.cancel(event);
  1877. else if (scrollTop === 0 && this.wheelDelta >= 0) eventjs.cancel(event);
  1878. eventjs.stop(event);
  1879. },
  1880. add: function() {
  1881. conf.target[add](type, onMouseWheel, false);
  1882. },
  1883. remove: function() {
  1884. conf.target[remove](type, onMouseWheel, false);
  1885. }
  1886. };
  1887. // Tracking the events.
  1888. var onMouseWheel = function(event) {
  1889. event = event || window.event;
  1890. self.state = count++ ? "change" : "start";
  1891. self.wheelDelta = event.detail ? event.detail * -20 : event.wheelDelta;
  1892. conf.listener(event, self);
  1893. clearTimeout(interval);
  1894. interval = setTimeout(function() {
  1895. count = 0;
  1896. self.state = "end";
  1897. self.wheelDelta = 0;
  1898. conf.listener(event, self);
  1899. }, timeout);
  1900. };
  1901. // Attach events.
  1902. var add = document.addEventListener ? "addEventListener" : "attachEvent";
  1903. var remove = document.removeEventListener ? "removeEventListener" : "detachEvent";
  1904. var type = eventjs.getEventSupport("mousewheel") ? "mousewheel" : "DOMMouseScroll";
  1905. conf.target[add](type, onMouseWheel, false);
  1906. // Return this object.
  1907. return self;
  1908. };
  1909. eventjs.Gesture = eventjs.Gesture || {};
  1910. eventjs.Gesture._gestureHandlers = eventjs.Gesture._gestureHandlers || {};
  1911. eventjs.Gesture._gestureHandlers.wheel = root.wheel;
  1912. return root;
  1913. })(eventjs.proxy);
  1914. /*
  1915. "Orientation Change"
  1916. ----------------------------------------------------
  1917. https://developer.apple.com/library/safari/documentation/SafariDOMAdditions/Reference/DeviceOrientationEventClassRef/DeviceOrientationEvent/DeviceOrientationEvent.html#//apple_ref/doc/uid/TP40010526
  1918. ----------------------------------------------------
  1919. Event.add(window, "deviceorientation", function(event, self) {});
  1920. */
  1921. if (typeof(Event) === "undefined") var Event = {};
  1922. if (typeof(Event.proxy) === "undefined") Event.proxy = {};
  1923. Event.proxy = (function(root) { "use strict";
  1924. root.orientation = function(conf) {
  1925. // Externally accessible data.
  1926. var self = {
  1927. gesture: "orientationchange",
  1928. previous: null, /* Report the previous orientation */
  1929. current: window.orientation,
  1930. target: conf.target,
  1931. listener: conf.listener,
  1932. remove: function() {
  1933. window.removeEventListener('orientationchange', onOrientationChange, false);
  1934. }
  1935. };
  1936. // Tracking the events.
  1937. var onOrientationChange = function(e) {
  1938. self.previous = self.current;
  1939. self.current = window.orientation;
  1940. if(self.previous !== null && self.previous != self.current) {
  1941. conf.listener(e, self);
  1942. return;
  1943. }
  1944. };
  1945. // Attach events.
  1946. if (window.DeviceOrientationEvent) {
  1947. window.addEventListener("orientationchange", onOrientationChange, false);
  1948. }
  1949. // Return this object.
  1950. return self;
  1951. };
  1952. Event.Gesture = Event.Gesture || {};
  1953. Event.Gesture._gestureHandlers = Event.Gesture._gestureHandlers || {};
  1954. Event.Gesture._gestureHandlers.orientation = root.orientation;
  1955. return root;
  1956. })(Event.proxy);
  1957. (function() {
  1958. /**
  1959. * @private
  1960. * @param {String} eventName
  1961. * @param {Function} handler
  1962. */
  1963. function _removeEventListener(eventName, handler) {
  1964. if (!this.__eventListeners[eventName]) {
  1965. return;
  1966. }
  1967. var eventListener = this.__eventListeners[eventName];
  1968. if (handler) {
  1969. eventListener[eventListener.indexOf(handler)] = false;
  1970. }
  1971. else {
  1972. fabric.util.array.fill(eventListener, false);
  1973. }
  1974. }
  1975. /**
  1976. * Observes specified event
  1977. * @deprecated `observe` deprecated since 0.8.34 (use `on` instead)
  1978. * @memberOf fabric.Observable
  1979. * @alias on
  1980. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  1981. * @param {Function} handler Function that receives a notification when an event of the specified type occurs
  1982. * @return {Self} thisArg
  1983. * @chainable
  1984. */
  1985. function observe(eventName, handler) {
  1986. if (!this.__eventListeners) {
  1987. this.__eventListeners = { };
  1988. }
  1989. // one object with key/value pairs was passed
  1990. if (arguments.length === 1) {
  1991. for (var prop in eventName) {
  1992. this.on(prop, eventName[prop]);
  1993. }
  1994. }
  1995. else {
  1996. if (!this.__eventListeners[eventName]) {
  1997. this.__eventListeners[eventName] = [];
  1998. }
  1999. this.__eventListeners[eventName].push(handler);
  2000. }
  2001. return this;
  2002. }
  2003. /**
  2004. * Stops event observing for a particular event handler. Calling this method
  2005. * without arguments removes all handlers for all events
  2006. * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
  2007. * @memberOf fabric.Observable
  2008. * @alias off
  2009. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  2010. * @param {Function} handler Function to be deleted from EventListeners
  2011. * @return {Self} thisArg
  2012. * @chainable
  2013. */
  2014. function stopObserving(eventName, handler) {
  2015. if (!this.__eventListeners) {
  2016. return;
  2017. }
  2018. // remove all key/value pairs (event name -> event handler)
  2019. if (arguments.length === 0) {
  2020. for (eventName in this.__eventListeners) {
  2021. _removeEventListener.call(this, eventName);
  2022. }
  2023. }
  2024. // one object with key/value pairs was passed
  2025. else if (arguments.length === 1 && typeof arguments[0] === 'object') {
  2026. for (var prop in eventName) {
  2027. _removeEventListener.call(this, prop, eventName[prop]);
  2028. }
  2029. }
  2030. else {
  2031. _removeEventListener.call(this, eventName, handler);
  2032. }
  2033. return this;
  2034. }
  2035. /**
  2036. * Fires event with an optional options object
  2037. * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
  2038. * @memberOf fabric.Observable
  2039. * @alias trigger
  2040. * @param {String} eventName Event name to fire
  2041. * @param {Object} [options] Options object
  2042. * @return {Self} thisArg
  2043. * @chainable
  2044. */
  2045. function fire(eventName, options) {
  2046. if (!this.__eventListeners) {
  2047. return;
  2048. }
  2049. var listenersForEvent = this.__eventListeners[eventName];
  2050. if (!listenersForEvent) {
  2051. return;
  2052. }
  2053. for (var i = 0, len = listenersForEvent.length; i < len; i++) {
  2054. listenersForEvent[i] && listenersForEvent[i].call(this, options || { });
  2055. }
  2056. this.__eventListeners[eventName] = listenersForEvent.filter(function(value) {
  2057. return value !== false;
  2058. });
  2059. return this;
  2060. }
  2061. /**
  2062. * @namespace fabric.Observable
  2063. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#events}
  2064. * @see {@link http://fabricjs.com/events|Events demo}
  2065. */
  2066. fabric.Observable = {
  2067. observe: observe,
  2068. stopObserving: stopObserving,
  2069. fire: fire,
  2070. on: observe,
  2071. off: stopObserving,
  2072. trigger: fire
  2073. };
  2074. })();
  2075. /**
  2076. * @namespace fabric.Collection
  2077. */
  2078. fabric.Collection = {
  2079. _objects: [],
  2080. /**
  2081. * Adds objects to collection, Canvas or Group, then renders canvas
  2082. * (if `renderOnAddRemove` is not `false`).
  2083. * in case of Group no changes to bounding box are made.
  2084. * Objects should be instances of (or inherit from) fabric.Object
  2085. * Use of this function is highly discouraged for groups.
  2086. * you can add a bunch of objects with the add method but then you NEED
  2087. * to run a addWithUpdate call for the Group class or position/bbox will be wrong.
  2088. * @param {...fabric.Object} object Zero or more fabric instances
  2089. * @return {Self} thisArg
  2090. * @chainable
  2091. */
  2092. add: function () {
  2093. this._objects.push.apply(this._objects, arguments);
  2094. if (this._onObjectAdded) {
  2095. for (var i = 0, length = arguments.length; i < length; i++) {
  2096. this._onObjectAdded(arguments[i]);
  2097. }
  2098. }
  2099. this.renderOnAddRemove && this.requestRenderAll();
  2100. return this;
  2101. },
  2102. /**
  2103. * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
  2104. * An object should be an instance of (or inherit from) fabric.Object
  2105. * Use of this function is highly discouraged for groups.
  2106. * you can add a bunch of objects with the insertAt method but then you NEED
  2107. * to run a addWithUpdate call for the Group class or position/bbox will be wrong.
  2108. * @param {Object} object Object to insert
  2109. * @param {Number} index Index to insert object at
  2110. * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
  2111. * @return {Self} thisArg
  2112. * @chainable
  2113. */
  2114. insertAt: function (object, index, nonSplicing) {
  2115. var objects = this.getObjects();
  2116. if (nonSplicing) {
  2117. objects[index] = object;
  2118. }
  2119. else {
  2120. objects.splice(index, 0, object);
  2121. }
  2122. this._onObjectAdded && this._onObjectAdded(object);
  2123. this.renderOnAddRemove && this.requestRenderAll();
  2124. return this;
  2125. },
  2126. /**
  2127. * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
  2128. * @param {...fabric.Object} object Zero or more fabric instances
  2129. * @return {Self} thisArg
  2130. * @chainable
  2131. */
  2132. remove: function() {
  2133. var objects = this.getObjects(),
  2134. index, somethingRemoved = false;
  2135. for (var i = 0, length = arguments.length; i < length; i++) {
  2136. index = objects.indexOf(arguments[i]);
  2137. // only call onObjectRemoved if an object was actually removed
  2138. if (index !== -1) {
  2139. somethingRemoved = true;
  2140. objects.splice(index, 1);
  2141. this._onObjectRemoved && this._onObjectRemoved(arguments[i]);
  2142. }
  2143. }
  2144. this.renderOnAddRemove && somethingRemoved && this.requestRenderAll();
  2145. return this;
  2146. },
  2147. /**
  2148. * Executes given function for each object in this group
  2149. * @param {Function} callback
  2150. * Callback invoked with current object as first argument,
  2151. * index - as second and an array of all objects - as third.
  2152. * Callback is invoked in a context of Global Object (e.g. `window`)
  2153. * when no `context` argument is given
  2154. *
  2155. * @param {Object} context Context (aka thisObject)
  2156. * @return {Self} thisArg
  2157. * @chainable
  2158. */
  2159. forEachObject: function(callback, context) {
  2160. var objects = this.getObjects();
  2161. for (var i = 0, len = objects.length; i < len; i++) {
  2162. callback.call(context, objects[i], i, objects);
  2163. }
  2164. return this;
  2165. },
  2166. /**
  2167. * Returns an array of children objects of this instance
  2168. * Type parameter introduced in 1.3.10
  2169. * @param {String} [type] When specified, only objects of this type are returned
  2170. * @return {Array}
  2171. */
  2172. getObjects: function(type) {
  2173. if (typeof type === 'undefined') {
  2174. return this._objects;
  2175. }
  2176. return this._objects.filter(function(o) {
  2177. return o.type === type;
  2178. });
  2179. },
  2180. /**
  2181. * Returns object at specified index
  2182. * @param {Number} index
  2183. * @return {Self} thisArg
  2184. */
  2185. item: function (index) {
  2186. return this.getObjects()[index];
  2187. },
  2188. /**
  2189. * Returns true if collection contains no objects
  2190. * @return {Boolean} true if collection is empty
  2191. */
  2192. isEmpty: function () {
  2193. return this.getObjects().length === 0;
  2194. },
  2195. /**
  2196. * Returns a size of a collection (i.e: length of an array containing its objects)
  2197. * @return {Number} Collection size
  2198. */
  2199. size: function() {
  2200. return this.getObjects().length;
  2201. },
  2202. /**
  2203. * Returns true if collection contains an object
  2204. * @param {Object} object Object to check against
  2205. * @return {Boolean} `true` if collection contains an object
  2206. */
  2207. contains: function(object) {
  2208. return this.getObjects().indexOf(object) > -1;
  2209. },
  2210. /**
  2211. * Returns number representation of a collection complexity
  2212. * @return {Number} complexity
  2213. */
  2214. complexity: function () {
  2215. return this.getObjects().reduce(function (memo, current) {
  2216. memo += current.complexity ? current.complexity() : 0;
  2217. return memo;
  2218. }, 0);
  2219. }
  2220. };
  2221. /**
  2222. * @namespace fabric.CommonMethods
  2223. */
  2224. fabric.CommonMethods = {
  2225. /**
  2226. * Sets object's properties from options
  2227. * @param {Object} [options] Options object
  2228. */
  2229. _setOptions: function(options) {
  2230. for (var prop in options) {
  2231. this.set(prop, options[prop]);
  2232. }
  2233. },
  2234. /**
  2235. * @private
  2236. * @param {Object} [filler] Options object
  2237. * @param {String} [property] property to set the Gradient to
  2238. */
  2239. _initGradient: function(filler, property) {
  2240. if (filler && filler.colorStops && !(filler instanceof fabric.Gradient)) {
  2241. this.set(property, new fabric.Gradient(filler));
  2242. }
  2243. },
  2244. /**
  2245. * @private
  2246. * @param {Object} [filler] Options object
  2247. * @param {String} [property] property to set the Pattern to
  2248. * @param {Function} [callback] callback to invoke after pattern load
  2249. */
  2250. _initPattern: function(filler, property, callback) {
  2251. if (filler && filler.source && !(filler instanceof fabric.Pattern)) {
  2252. this.set(property, new fabric.Pattern(filler, callback));
  2253. }
  2254. else {
  2255. callback && callback();
  2256. }
  2257. },
  2258. /**
  2259. * @private
  2260. * @param {Object} [options] Options object
  2261. */
  2262. _initClipping: function(options) {
  2263. if (!options.clipTo || typeof options.clipTo !== 'string') {
  2264. return;
  2265. }
  2266. var functionBody = fabric.util.getFunctionBody(options.clipTo);
  2267. if (typeof functionBody !== 'undefined') {
  2268. this.clipTo = new Function('ctx', functionBody);
  2269. }
  2270. },
  2271. /**
  2272. * @private
  2273. */
  2274. _setObject: function(obj) {
  2275. for (var prop in obj) {
  2276. this._set(prop, obj[prop]);
  2277. }
  2278. },
  2279. /**
  2280. * Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. If you need to update those, call `setCoords()`.
  2281. * @param {String|Object} key Property name or object (if object, iterate over the object properties)
  2282. * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
  2283. * @return {fabric.Object} thisArg
  2284. * @chainable
  2285. */
  2286. set: function(key, value) {
  2287. if (typeof key === 'object') {
  2288. this._setObject(key);
  2289. }
  2290. else {
  2291. if (typeof value === 'function' && key !== 'clipTo') {
  2292. this._set(key, value(this.get(key)));
  2293. }
  2294. else {
  2295. this._set(key, value);
  2296. }
  2297. }
  2298. return this;
  2299. },
  2300. _set: function(key, value) {
  2301. this[key] = value;
  2302. },
  2303. /**
  2304. * Toggles specified property from `true` to `false` or from `false` to `true`
  2305. * @param {String} property Property to toggle
  2306. * @return {fabric.Object} thisArg
  2307. * @chainable
  2308. */
  2309. toggle: function(property) {
  2310. var value = this.get(property);
  2311. if (typeof value === 'boolean') {
  2312. this.set(property, !value);
  2313. }
  2314. return this;
  2315. },
  2316. /**
  2317. * Basic getter
  2318. * @param {String} property Property name
  2319. * @return {*} value of a property
  2320. */
  2321. get: function(property) {
  2322. return this[property];
  2323. }
  2324. };
  2325. (function(global) {
  2326. var sqrt = Math.sqrt,
  2327. atan2 = Math.atan2,
  2328. pow = Math.pow,
  2329. abs = Math.abs,
  2330. PiBy180 = Math.PI / 180,
  2331. PiBy2 = Math.PI / 2;
  2332. /**
  2333. * @namespace fabric.util
  2334. */
  2335. fabric.util = {
  2336. /**
  2337. * Calculate the cos of an angle, avoiding returning floats for known results
  2338. * @static
  2339. * @memberOf fabric.util
  2340. * @param {Number} angle the angle in radians or in degree
  2341. * @return {Number}
  2342. */
  2343. cos: function(angle) {
  2344. if (angle === 0) { return 1; }
  2345. if (angle < 0) {
  2346. // cos(a) = cos(-a)
  2347. angle = -angle;
  2348. }
  2349. var angleSlice = angle / PiBy2;
  2350. switch (angleSlice) {
  2351. case 1: case 3: return 0;
  2352. case 2: return -1;
  2353. }
  2354. return Math.cos(angle);
  2355. },
  2356. /**
  2357. * Calculate the sin of an angle, avoiding returning floats for known results
  2358. * @static
  2359. * @memberOf fabric.util
  2360. * @param {Number} angle the angle in radians or in degree
  2361. * @return {Number}
  2362. */
  2363. sin: function(angle) {
  2364. if (angle === 0) { return 0; }
  2365. var angleSlice = angle / PiBy2, sign = 1;
  2366. if (angle < 0) {
  2367. // sin(-a) = -sin(a)
  2368. sign = -1;
  2369. }
  2370. switch (angleSlice) {
  2371. case 1: return sign;
  2372. case 2: return 0;
  2373. case 3: return -sign;
  2374. }
  2375. return Math.sin(angle);
  2376. },
  2377. /**
  2378. * Removes value from an array.
  2379. * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
  2380. * @static
  2381. * @memberOf fabric.util
  2382. * @param {Array} array
  2383. * @param {*} value
  2384. * @return {Array} original array
  2385. */
  2386. removeFromArray: function(array, value) {
  2387. var idx = array.indexOf(value);
  2388. if (idx !== -1) {
  2389. array.splice(idx, 1);
  2390. }
  2391. return array;
  2392. },
  2393. /**
  2394. * Returns random number between 2 specified ones.
  2395. * @static
  2396. * @memberOf fabric.util
  2397. * @param {Number} min lower limit
  2398. * @param {Number} max upper limit
  2399. * @return {Number} random value (between min and max)
  2400. */
  2401. getRandomInt: function(min, max) {
  2402. return Math.floor(Math.random() * (max - min + 1)) + min;
  2403. },
  2404. /**
  2405. * Transforms degrees to radians.
  2406. * @static
  2407. * @memberOf fabric.util
  2408. * @param {Number} degrees value in degrees
  2409. * @return {Number} value in radians
  2410. */
  2411. degreesToRadians: function(degrees) {
  2412. return degrees * PiBy180;
  2413. },
  2414. /**
  2415. * Transforms radians to degrees.
  2416. * @static
  2417. * @memberOf fabric.util
  2418. * @param {Number} radians value in radians
  2419. * @return {Number} value in degrees
  2420. */
  2421. radiansToDegrees: function(radians) {
  2422. return radians / PiBy180;
  2423. },
  2424. /**
  2425. * Rotates `point` around `origin` with `radians`
  2426. * @static
  2427. * @memberOf fabric.util
  2428. * @param {fabric.Point} point The point to rotate
  2429. * @param {fabric.Point} origin The origin of the rotation
  2430. * @param {Number} radians The radians of the angle for the rotation
  2431. * @return {fabric.Point} The new rotated point
  2432. */
  2433. rotatePoint: function(point, origin, radians) {
  2434. point.subtractEquals(origin);
  2435. var v = fabric.util.rotateVector(point, radians);
  2436. return new fabric.Point(v.x, v.y).addEquals(origin);
  2437. },
  2438. /**
  2439. * Rotates `vector` with `radians`
  2440. * @static
  2441. * @memberOf fabric.util
  2442. * @param {Object} vector The vector to rotate (x and y)
  2443. * @param {Number} radians The radians of the angle for the rotation
  2444. * @return {Object} The new rotated point
  2445. */
  2446. rotateVector: function(vector, radians) {
  2447. var sin = fabric.util.sin(radians),
  2448. cos = fabric.util.cos(radians),
  2449. rx = vector.x * cos - vector.y * sin,
  2450. ry = vector.x * sin + vector.y * cos;
  2451. return {
  2452. x: rx,
  2453. y: ry
  2454. };
  2455. },
  2456. /**
  2457. * Apply transform t to point p
  2458. * @static
  2459. * @memberOf fabric.util
  2460. * @param {fabric.Point} p The point to transform
  2461. * @param {Array} t The transform
  2462. * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied
  2463. * @return {fabric.Point} The transformed point
  2464. */
  2465. transformPoint: function(p, t, ignoreOffset) {
  2466. if (ignoreOffset) {
  2467. return new fabric.Point(
  2468. t[0] * p.x + t[2] * p.y,
  2469. t[1] * p.x + t[3] * p.y
  2470. );
  2471. }
  2472. return new fabric.Point(
  2473. t[0] * p.x + t[2] * p.y + t[4],
  2474. t[1] * p.x + t[3] * p.y + t[5]
  2475. );
  2476. },
  2477. /**
  2478. * Returns coordinates of points's bounding rectangle (left, top, width, height)
  2479. * @param {Array} points 4 points array
  2480. * @return {Object} Object with left, top, width, height properties
  2481. */
  2482. makeBoundingBoxFromPoints: function(points) {
  2483. var xPoints = [points[0].x, points[1].x, points[2].x, points[3].x],
  2484. minX = fabric.util.array.min(xPoints),
  2485. maxX = fabric.util.array.max(xPoints),
  2486. width = maxX - minX,
  2487. yPoints = [points[0].y, points[1].y, points[2].y, points[3].y],
  2488. minY = fabric.util.array.min(yPoints),
  2489. maxY = fabric.util.array.max(yPoints),
  2490. height = maxY - minY;
  2491. return {
  2492. left: minX,
  2493. top: minY,
  2494. width: width,
  2495. height: height
  2496. };
  2497. },
  2498. /**
  2499. * Invert transformation t
  2500. * @static
  2501. * @memberOf fabric.util
  2502. * @param {Array} t The transform
  2503. * @return {Array} The inverted transform
  2504. */
  2505. invertTransform: function(t) {
  2506. var a = 1 / (t[0] * t[3] - t[1] * t[2]),
  2507. r = [a * t[3], -a * t[1], -a * t[2], a * t[0]],
  2508. o = fabric.util.transformPoint({ x: t[4], y: t[5] }, r, true);
  2509. r[4] = -o.x;
  2510. r[5] = -o.y;
  2511. return r;
  2512. },
  2513. /**
  2514. * A wrapper around Number#toFixed, which contrary to native method returns number, not string.
  2515. * @static
  2516. * @memberOf fabric.util
  2517. * @param {Number|String} number number to operate on
  2518. * @param {Number} fractionDigits number of fraction digits to "leave"
  2519. * @return {Number}
  2520. */
  2521. toFixed: function(number, fractionDigits) {
  2522. return parseFloat(Number(number).toFixed(fractionDigits));
  2523. },
  2524. /**
  2525. * Converts from attribute value to pixel value if applicable.
  2526. * Returns converted pixels or original value not converted.
  2527. * @param {Number|String} value number to operate on
  2528. * @param {Number} fontSize
  2529. * @return {Number|String}
  2530. */
  2531. parseUnit: function(value, fontSize) {
  2532. var unit = /\D{0,2}$/.exec(value),
  2533. number = parseFloat(value);
  2534. if (!fontSize) {
  2535. fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
  2536. }
  2537. switch (unit[0]) {
  2538. case 'mm':
  2539. return number * fabric.DPI / 25.4;
  2540. case 'cm':
  2541. return number * fabric.DPI / 2.54;
  2542. case 'in':
  2543. return number * fabric.DPI;
  2544. case 'pt':
  2545. return number * fabric.DPI / 72; // or * 4 / 3
  2546. case 'pc':
  2547. return number * fabric.DPI / 72 * 12; // or * 16
  2548. case 'em':
  2549. return number * fontSize;
  2550. default:
  2551. return number;
  2552. }
  2553. },
  2554. /**
  2555. * Function which always returns `false`.
  2556. * @static
  2557. * @memberOf fabric.util
  2558. * @return {Boolean}
  2559. */
  2560. falseFunction: function() {
  2561. return false;
  2562. },
  2563. /**
  2564. * Returns klass "Class" object of given namespace
  2565. * @memberOf fabric.util
  2566. * @param {String} type Type of object (eg. 'circle')
  2567. * @param {String} namespace Namespace to get klass "Class" object from
  2568. * @return {Object} klass "Class"
  2569. */
  2570. getKlass: function(type, namespace) {
  2571. // capitalize first letter only
  2572. type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
  2573. return fabric.util.resolveNamespace(namespace)[type];
  2574. },
  2575. /**
  2576. * Returns array of attributes for given svg that fabric parses
  2577. * @memberOf fabric.util
  2578. * @param {String} type Type of svg element (eg. 'circle')
  2579. * @return {Array} string names of supported attributes
  2580. */
  2581. getSvgAttributes: function(type) {
  2582. var attributes = [
  2583. 'instantiated_by_use',
  2584. 'style',
  2585. 'id',
  2586. 'class'
  2587. ];
  2588. switch (type) {
  2589. case 'linearGradient':
  2590. attributes = attributes.concat(['x1', 'y1', 'x2', 'y2', 'gradientUnits', 'gradientTransform']);
  2591. break;
  2592. case 'radialGradient':
  2593. attributes = attributes.concat(['gradientUnits', 'gradientTransform', 'cx', 'cy', 'r', 'fx', 'fy', 'fr']);
  2594. break;
  2595. case 'stop':
  2596. attributes = attributes.concat(['offset', 'stop-color', 'stop-opacity']);
  2597. break;
  2598. }
  2599. return attributes;
  2600. },
  2601. /**
  2602. * Returns object of given namespace
  2603. * @memberOf fabric.util
  2604. * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'
  2605. * @return {Object} Object for given namespace (default fabric)
  2606. */
  2607. resolveNamespace: function(namespace) {
  2608. if (!namespace) {
  2609. return fabric;
  2610. }
  2611. var parts = namespace.split('.'),
  2612. len = parts.length, i,
  2613. obj = global || fabric.window;
  2614. for (i = 0; i < len; ++i) {
  2615. obj = obj[parts[i]];
  2616. }
  2617. return obj;
  2618. },
  2619. /**
  2620. * Loads image element from given url and passes it to a callback
  2621. * @memberOf fabric.util
  2622. * @param {String} url URL representing an image
  2623. * @param {Function} callback Callback; invoked with loaded image
  2624. * @param {*} [context] Context to invoke callback in
  2625. * @param {Object} [crossOrigin] crossOrigin value to set image element to
  2626. */
  2627. loadImage: function(url, callback, context, crossOrigin) {
  2628. if (!url) {
  2629. callback && callback.call(context, url);
  2630. return;
  2631. }
  2632. var img = fabric.util.createImage();
  2633. /** @ignore */
  2634. var onLoadCallback = function () {
  2635. callback && callback.call(context, img);
  2636. img = img.onload = img.onerror = null;
  2637. };
  2638. img.onload = onLoadCallback;
  2639. /** @ignore */
  2640. img.onerror = function() {
  2641. fabric.log('Error loading ' + img.src);
  2642. callback && callback.call(context, null, true);
  2643. img = img.onload = img.onerror = null;
  2644. };
  2645. // data-urls appear to be buggy with crossOrigin
  2646. // https://github.com/kangax/fabric.js/commit/d0abb90f1cd5c5ef9d2a94d3fb21a22330da3e0a#commitcomment-4513767
  2647. // see https://code.google.com/p/chromium/issues/detail?id=315152
  2648. // https://bugzilla.mozilla.org/show_bug.cgi?id=935069
  2649. if (url.indexOf('data') !== 0 && crossOrigin) {
  2650. img.crossOrigin = crossOrigin;
  2651. }
  2652. // IE10 / IE11-Fix: SVG contents from data: URI
  2653. // will only be available if the IMG is present
  2654. // in the DOM (and visible)
  2655. if (url.substring(0,14) === 'data:image/svg') {
  2656. img.onload = null;
  2657. fabric.util.loadImageInDom(img, onLoadCallback);
  2658. }
  2659. img.src = url;
  2660. },
  2661. /**
  2662. * Attaches SVG image with data: URL to the dom
  2663. * @memberOf fabric.util
  2664. * @param {Object} img Image object with data:image/svg src
  2665. * @param {Function} callback Callback; invoked with loaded image
  2666. * @return {Object} DOM element (div containing the SVG image)
  2667. */
  2668. loadImageInDom: function(img, onLoadCallback) {
  2669. var div = fabric.document.createElement('div');
  2670. div.style.width = div.style.height = '1px';
  2671. div.style.left = div.style.top = '-100%';
  2672. div.style.position = 'absolute';
  2673. div.appendChild(img);
  2674. fabric.document.querySelector('body').appendChild(div);
  2675. /**
  2676. * Wrap in function to:
  2677. * 1. Call existing callback
  2678. * 2. Cleanup DOM
  2679. */
  2680. img.onload = function () {
  2681. onLoadCallback();
  2682. div.parentNode.removeChild(div);
  2683. div = null;
  2684. };
  2685. },
  2686. /**
  2687. * Creates corresponding fabric instances from their object representations
  2688. * @static
  2689. * @memberOf fabric.util
  2690. * @param {Array} objects Objects to enliven
  2691. * @param {Function} callback Callback to invoke when all objects are created
  2692. * @param {String} namespace Namespace to get klass "Class" object from
  2693. * @param {Function} reviver Method for further parsing of object elements,
  2694. * called after each fabric object created.
  2695. */
  2696. enlivenObjects: function(objects, callback, namespace, reviver) {
  2697. objects = objects || [];
  2698. function onLoaded() {
  2699. if (++numLoadedObjects === numTotalObjects) {
  2700. callback && callback(enlivenedObjects);
  2701. }
  2702. }
  2703. var enlivenedObjects = [],
  2704. numLoadedObjects = 0,
  2705. numTotalObjects = objects.length;
  2706. if (!numTotalObjects) {
  2707. callback && callback(enlivenedObjects);
  2708. return;
  2709. }
  2710. objects.forEach(function (o, index) {
  2711. // if sparse array
  2712. if (!o || !o.type) {
  2713. onLoaded();
  2714. return;
  2715. }
  2716. var klass = fabric.util.getKlass(o.type, namespace);
  2717. klass.fromObject(o, function (obj, error) {
  2718. error || (enlivenedObjects[index] = obj);
  2719. reviver && reviver(o, obj, error);
  2720. onLoaded();
  2721. });
  2722. });
  2723. },
  2724. /**
  2725. * Create and wait for loading of patterns
  2726. * @static
  2727. * @memberOf fabric.util
  2728. * @param {Array} patterns Objects to enliven
  2729. * @param {Function} callback Callback to invoke when all objects are created
  2730. * called after each fabric object created.
  2731. */
  2732. enlivenPatterns: function(patterns, callback) {
  2733. patterns = patterns || [];
  2734. function onLoaded() {
  2735. if (++numLoadedPatterns === numPatterns) {
  2736. callback && callback(enlivenedPatterns);
  2737. }
  2738. }
  2739. var enlivenedPatterns = [],
  2740. numLoadedPatterns = 0,
  2741. numPatterns = patterns.length;
  2742. if (!numPatterns) {
  2743. callback && callback(enlivenedPatterns);
  2744. return;
  2745. }
  2746. patterns.forEach(function (p, index) {
  2747. if (p && p.source) {
  2748. new fabric.Pattern(p, function(pattern) {
  2749. enlivenedPatterns[index] = pattern;
  2750. onLoaded();
  2751. });
  2752. }
  2753. else {
  2754. enlivenedPatterns[index] = p;
  2755. onLoaded();
  2756. }
  2757. });
  2758. },
  2759. /**
  2760. * Groups SVG elements (usually those retrieved from SVG document)
  2761. * @static
  2762. * @memberOf fabric.util
  2763. * @param {Array} elements SVG elements to group
  2764. * @param {Object} [options] Options object
  2765. * @param {String} path Value to set sourcePath to
  2766. * @return {fabric.Object|fabric.Group}
  2767. */
  2768. groupSVGElements: function(elements, options, path) {
  2769. var object;
  2770. if (elements.length === 1) {
  2771. return elements[0];
  2772. }
  2773. if (options) {
  2774. if (options.width && options.height) {
  2775. options.centerPoint = {
  2776. x: options.width / 2,
  2777. y: options.height / 2
  2778. };
  2779. }
  2780. else {
  2781. delete options.width;
  2782. delete options.height;
  2783. }
  2784. }
  2785. object = new fabric.Group(elements, options);
  2786. if (typeof path !== 'undefined') {
  2787. object.sourcePath = path;
  2788. }
  2789. return object;
  2790. },
  2791. /**
  2792. * Populates an object with properties of another object
  2793. * @static
  2794. * @memberOf fabric.util
  2795. * @param {Object} source Source object
  2796. * @param {Object} destination Destination object
  2797. * @return {Array} properties Properties names to include
  2798. */
  2799. populateWithProperties: function(source, destination, properties) {
  2800. if (properties && Object.prototype.toString.call(properties) === '[object Array]') {
  2801. for (var i = 0, len = properties.length; i < len; i++) {
  2802. if (properties[i] in source) {
  2803. destination[properties[i]] = source[properties[i]];
  2804. }
  2805. }
  2806. }
  2807. },
  2808. /**
  2809. * Draws a dashed line between two points
  2810. *
  2811. * This method is used to draw dashed line around selection area.
  2812. * See <a href="http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas">dotted stroke in canvas</a>
  2813. *
  2814. * @param {CanvasRenderingContext2D} ctx context
  2815. * @param {Number} x start x coordinate
  2816. * @param {Number} y start y coordinate
  2817. * @param {Number} x2 end x coordinate
  2818. * @param {Number} y2 end y coordinate
  2819. * @param {Array} da dash array pattern
  2820. */
  2821. drawDashedLine: function(ctx, x, y, x2, y2, da) {
  2822. var dx = x2 - x,
  2823. dy = y2 - y,
  2824. len = sqrt(dx * dx + dy * dy),
  2825. rot = atan2(dy, dx),
  2826. dc = da.length,
  2827. di = 0,
  2828. draw = true;
  2829. ctx.save();
  2830. ctx.translate(x, y);
  2831. ctx.moveTo(0, 0);
  2832. ctx.rotate(rot);
  2833. x = 0;
  2834. while (len > x) {
  2835. x += da[di++ % dc];
  2836. if (x > len) {
  2837. x = len;
  2838. }
  2839. ctx[draw ? 'lineTo' : 'moveTo'](x, 0);
  2840. draw = !draw;
  2841. }
  2842. ctx.restore();
  2843. },
  2844. /**
  2845. * Creates canvas element
  2846. * @static
  2847. * @memberOf fabric.util
  2848. * @return {CanvasElement} initialized canvas element
  2849. */
  2850. createCanvasElement: function() {
  2851. return fabric.document.createElement('canvas');
  2852. },
  2853. /**
  2854. * Creates a canvas element that is a copy of another and is also painted
  2855. * @static
  2856. * @memberOf fabric.util
  2857. * @return {CanvasElement} initialized canvas element
  2858. */
  2859. copyCanvasElement: function(canvas) {
  2860. var newCanvas = fabric.document.createElement('canvas');
  2861. newCanvas.width = canvas.width;
  2862. newCanvas.height = canvas.height;
  2863. newCanvas.getContext('2d').drawImage(canvas, 0, 0);
  2864. return newCanvas;
  2865. },
  2866. /**
  2867. * Creates image element (works on client and node)
  2868. * @static
  2869. * @memberOf fabric.util
  2870. * @return {HTMLImageElement} HTML image element
  2871. */
  2872. createImage: function() {
  2873. return fabric.document.createElement('img');
  2874. },
  2875. /**
  2876. * @static
  2877. * @memberOf fabric.util
  2878. * @deprecated since 2.0.0
  2879. * @param {fabric.Object} receiver Object implementing `clipTo` method
  2880. * @param {CanvasRenderingContext2D} ctx Context to clip
  2881. */
  2882. clipContext: function(receiver, ctx) {
  2883. ctx.save();
  2884. ctx.beginPath();
  2885. receiver.clipTo(ctx);
  2886. ctx.clip();
  2887. },
  2888. /**
  2889. * Multiply matrix A by matrix B to nest transformations
  2890. * @static
  2891. * @memberOf fabric.util
  2892. * @param {Array} a First transformMatrix
  2893. * @param {Array} b Second transformMatrix
  2894. * @param {Boolean} is2x2 flag to multiply matrices as 2x2 matrices
  2895. * @return {Array} The product of the two transform matrices
  2896. */
  2897. multiplyTransformMatrices: function(a, b, is2x2) {
  2898. // Matrix multiply a * b
  2899. return [
  2900. a[0] * b[0] + a[2] * b[1],
  2901. a[1] * b[0] + a[3] * b[1],
  2902. a[0] * b[2] + a[2] * b[3],
  2903. a[1] * b[2] + a[3] * b[3],
  2904. is2x2 ? 0 : a[0] * b[4] + a[2] * b[5] + a[4],
  2905. is2x2 ? 0 : a[1] * b[4] + a[3] * b[5] + a[5]
  2906. ];
  2907. },
  2908. /**
  2909. * Decomposes standard 2x2 matrix into transform componentes
  2910. * @static
  2911. * @memberOf fabric.util
  2912. * @param {Array} a transformMatrix
  2913. * @return {Object} Components of transform
  2914. */
  2915. qrDecompose: function(a) {
  2916. var angle = atan2(a[1], a[0]),
  2917. denom = pow(a[0], 2) + pow(a[1], 2),
  2918. scaleX = sqrt(denom),
  2919. scaleY = (a[0] * a[3] - a[2] * a [1]) / scaleX,
  2920. skewX = atan2(a[0] * a[2] + a[1] * a [3], denom);
  2921. return {
  2922. angle: angle / PiBy180,
  2923. scaleX: scaleX,
  2924. scaleY: scaleY,
  2925. skewX: skewX / PiBy180,
  2926. skewY: 0,
  2927. translateX: a[4],
  2928. translateY: a[5]
  2929. };
  2930. },
  2931. customTransformMatrix: function(scaleX, scaleY, skewX) {
  2932. var skewMatrixX = [1, 0, abs(Math.tan(skewX * PiBy180)), 1],
  2933. scaleMatrix = [abs(scaleX), 0, 0, abs(scaleY)];
  2934. return fabric.util.multiplyTransformMatrices(scaleMatrix, skewMatrixX, true);
  2935. },
  2936. resetObjectTransform: function (target) {
  2937. target.scaleX = 1;
  2938. target.scaleY = 1;
  2939. target.skewX = 0;
  2940. target.skewY = 0;
  2941. target.flipX = false;
  2942. target.flipY = false;
  2943. target.rotate(0);
  2944. },
  2945. /**
  2946. * Returns string representation of function body
  2947. * @param {Function} fn Function to get body of
  2948. * @return {String} Function body
  2949. */
  2950. getFunctionBody: function(fn) {
  2951. return (String(fn).match(/function[^{]*\{([\s\S]*)\}/) || {})[1];
  2952. },
  2953. /**
  2954. * Returns true if context has transparent pixel
  2955. * at specified location (taking tolerance into account)
  2956. * @param {CanvasRenderingContext2D} ctx context
  2957. * @param {Number} x x coordinate
  2958. * @param {Number} y y coordinate
  2959. * @param {Number} tolerance Tolerance
  2960. */
  2961. isTransparent: function(ctx, x, y, tolerance) {
  2962. // If tolerance is > 0 adjust start coords to take into account.
  2963. // If moves off Canvas fix to 0
  2964. if (tolerance > 0) {
  2965. if (x > tolerance) {
  2966. x -= tolerance;
  2967. }
  2968. else {
  2969. x = 0;
  2970. }
  2971. if (y > tolerance) {
  2972. y -= tolerance;
  2973. }
  2974. else {
  2975. y = 0;
  2976. }
  2977. }
  2978. var _isTransparent = true, i, temp,
  2979. imageData = ctx.getImageData(x, y, (tolerance * 2) || 1, (tolerance * 2) || 1),
  2980. l = imageData.data.length;
  2981. // Split image data - for tolerance > 1, pixelDataSize = 4;
  2982. for (i = 3; i < l; i += 4) {
  2983. temp = imageData.data[i];
  2984. _isTransparent = temp <= 0;
  2985. if (_isTransparent === false) {
  2986. break; // Stop if colour found
  2987. }
  2988. }
  2989. imageData = null;
  2990. return _isTransparent;
  2991. },
  2992. /**
  2993. * Parse preserveAspectRatio attribute from element
  2994. * @param {string} attribute to be parsed
  2995. * @return {Object} an object containing align and meetOrSlice attribute
  2996. */
  2997. parsePreserveAspectRatioAttribute: function(attribute) {
  2998. var meetOrSlice = 'meet', alignX = 'Mid', alignY = 'Mid',
  2999. aspectRatioAttrs = attribute.split(' '), align;
  3000. if (aspectRatioAttrs && aspectRatioAttrs.length) {
  3001. meetOrSlice = aspectRatioAttrs.pop();
  3002. if (meetOrSlice !== 'meet' && meetOrSlice !== 'slice') {
  3003. align = meetOrSlice;
  3004. meetOrSlice = 'meet';
  3005. }
  3006. else if (aspectRatioAttrs.length) {
  3007. align = aspectRatioAttrs.pop();
  3008. }
  3009. }
  3010. //divide align in alignX and alignY
  3011. alignX = align !== 'none' ? align.slice(1, 4) : 'none';
  3012. alignY = align !== 'none' ? align.slice(5, 8) : 'none';
  3013. return {
  3014. meetOrSlice: meetOrSlice,
  3015. alignX: alignX,
  3016. alignY: alignY
  3017. };
  3018. },
  3019. /**
  3020. * Clear char widths cache for the given font family or all the cache if no
  3021. * fontFamily is specified.
  3022. * Use it if you know you are loading fonts in a lazy way and you are not waiting
  3023. * for custom fonts to load properly when adding text objects to the canvas.
  3024. * If a text object is added when its own font is not loaded yet, you will get wrong
  3025. * measurement and so wrong bounding boxes.
  3026. * After the font cache is cleared, either change the textObject text content or call
  3027. * initDimensions() to trigger a recalculation
  3028. * @memberOf fabric.util
  3029. * @param {String} [fontFamily] font family to clear
  3030. */
  3031. clearFabricFontCache: function(fontFamily) {
  3032. fontFamily = (fontFamily || '').toLowerCase();
  3033. if (!fontFamily) {
  3034. fabric.charWidthsCache = { };
  3035. }
  3036. else if (fabric.charWidthsCache[fontFamily]) {
  3037. delete fabric.charWidthsCache[fontFamily];
  3038. }
  3039. },
  3040. /**
  3041. * Given current aspect ratio, determines the max width and height that can
  3042. * respect the total allowed area for the cache.
  3043. * @memberOf fabric.util
  3044. * @param {Number} ar aspect ratio
  3045. * @param {Number} maximumArea Maximum area you want to achieve
  3046. * @return {Object.x} Limited dimensions by X
  3047. * @return {Object.y} Limited dimensions by Y
  3048. */
  3049. limitDimsByArea: function(ar, maximumArea) {
  3050. var roughWidth = Math.sqrt(maximumArea * ar),
  3051. perfLimitSizeY = Math.floor(maximumArea / roughWidth);
  3052. return { x: Math.floor(roughWidth), y: perfLimitSizeY };
  3053. },
  3054. capValue: function(min, value, max) {
  3055. return Math.max(min, Math.min(value, max));
  3056. },
  3057. findScaleToFit: function(source, destination) {
  3058. return Math.min(destination.width / source.width, destination.height / source.height);
  3059. },
  3060. findScaleToCover: function(source, destination) {
  3061. return Math.max(destination.width / source.width, destination.height / source.height);
  3062. }
  3063. };
  3064. })(typeof exports !== 'undefined' ? exports : this);
  3065. (function() {
  3066. /**
  3067. * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array
  3068. * @static
  3069. * @memberOf fabric.util
  3070. * @param {Object} klass "Class" to create accessors for
  3071. */
  3072. fabric.util.createAccessors = function(klass) {
  3073. var proto = klass.prototype, i, propName,
  3074. capitalizedPropName, setterName, getterName;
  3075. for (i = proto.stateProperties.length; i--; ) {
  3076. propName = proto.stateProperties[i];
  3077. capitalizedPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  3078. setterName = 'set' + capitalizedPropName;
  3079. getterName = 'get' + capitalizedPropName;
  3080. // using `new Function` for better introspection
  3081. if (!proto[getterName]) {
  3082. proto[getterName] = (function(property) {
  3083. return new Function('return this.get("' + property + '")');
  3084. })(propName);
  3085. }
  3086. if (!proto[setterName]) {
  3087. proto[setterName] = (function(property) {
  3088. return new Function('value', 'return this.set("' + property + '", value)');
  3089. })(propName);
  3090. }
  3091. }
  3092. };
  3093. /** @lends fabric.Text.Prototype */
  3094. /**
  3095. * Retrieves object's fontSize
  3096. * @method getFontSize
  3097. * @memberOf fabric.Text.prototype
  3098. * @return {String} Font size (in pixels)
  3099. */
  3100. /**
  3101. * Sets object's fontSize
  3102. * Does not update the object .width and .height,
  3103. * call .initDimensions() to update the values.
  3104. * @method setFontSize
  3105. * @memberOf fabric.Text.prototype
  3106. * @param {Number} fontSize Font size (in pixels)
  3107. * @return {fabric.Text}
  3108. * @chainable
  3109. */
  3110. /**
  3111. * Retrieves object's fontWeight
  3112. * @method getFontWeight
  3113. * @memberOf fabric.Text.prototype
  3114. * @return {(String|Number)} Font weight
  3115. */
  3116. /**
  3117. * Sets object's fontWeight
  3118. * Does not update the object .width and .height,
  3119. * call .initDimensions() to update the values.
  3120. * @method setFontWeight
  3121. * @memberOf fabric.Text.prototype
  3122. * @param {(Number|String)} fontWeight Font weight
  3123. * @return {fabric.Text}
  3124. * @chainable
  3125. */
  3126. /**
  3127. * Retrieves object's fontFamily
  3128. * @method getFontFamily
  3129. * @memberOf fabric.Text.prototype
  3130. * @return {String} Font family
  3131. */
  3132. /**
  3133. * Sets object's fontFamily
  3134. * Does not update the object .width and .height,
  3135. * call .initDimensions() to update the values.
  3136. * @method setFontFamily
  3137. * @memberOf fabric.Text.prototype
  3138. * @param {String} fontFamily Font family
  3139. * @return {fabric.Text}
  3140. * @chainable
  3141. */
  3142. /**
  3143. * Retrieves object's text
  3144. * @method getText
  3145. * @memberOf fabric.Text.prototype
  3146. * @return {String} text
  3147. */
  3148. /**
  3149. * Sets object's text
  3150. * Does not update the object .width and .height,
  3151. * call .initDimensions() to update the values.
  3152. * @method setText
  3153. * @memberOf fabric.Text.prototype
  3154. * @param {String} text Text
  3155. * @return {fabric.Text}
  3156. * @chainable
  3157. */
  3158. /**
  3159. * Retrieves object's underline
  3160. * @method getUnderline
  3161. * @memberOf fabric.Text.prototype
  3162. * @return {Boolean} underline enabled or disabled
  3163. */
  3164. /**
  3165. * Sets object's underline
  3166. * @method setUnderline
  3167. * @memberOf fabric.Text.prototype
  3168. * @param {Boolean} underline Text decoration
  3169. * @return {fabric.Text}
  3170. * @chainable
  3171. */
  3172. /**
  3173. * Retrieves object's fontStyle
  3174. * @method getFontStyle
  3175. * @memberOf fabric.Text.prototype
  3176. * @return {String} Font style
  3177. */
  3178. /**
  3179. * Sets object's fontStyle
  3180. * Does not update the object .width and .height,
  3181. * call .initDimensions() to update the values.
  3182. * @method setFontStyle
  3183. * @memberOf fabric.Text.prototype
  3184. * @param {String} fontStyle Font style
  3185. * @return {fabric.Text}
  3186. * @chainable
  3187. */
  3188. /**
  3189. * Retrieves object's lineHeight
  3190. * @method getLineHeight
  3191. * @memberOf fabric.Text.prototype
  3192. * @return {Number} Line height
  3193. */
  3194. /**
  3195. * Sets object's lineHeight
  3196. * @method setLineHeight
  3197. * @memberOf fabric.Text.prototype
  3198. * @param {Number} lineHeight Line height
  3199. * @return {fabric.Text}
  3200. * @chainable
  3201. */
  3202. /**
  3203. * Retrieves object's textAlign
  3204. * @method getTextAlign
  3205. * @memberOf fabric.Text.prototype
  3206. * @return {String} Text alignment
  3207. */
  3208. /**
  3209. * Sets object's textAlign
  3210. * @method setTextAlign
  3211. * @memberOf fabric.Text.prototype
  3212. * @param {String} textAlign Text alignment
  3213. * @return {fabric.Text}
  3214. * @chainable
  3215. */
  3216. /**
  3217. * Retrieves object's textBackgroundColor
  3218. * @method getTextBackgroundColor
  3219. * @memberOf fabric.Text.prototype
  3220. * @return {String} Text background color
  3221. */
  3222. /**
  3223. * Sets object's textBackgroundColor
  3224. * @method setTextBackgroundColor
  3225. * @memberOf fabric.Text.prototype
  3226. * @param {String} textBackgroundColor Text background color
  3227. * @return {fabric.Text}
  3228. * @chainable
  3229. */
  3230. /** @lends fabric.Object.Prototype */
  3231. /**
  3232. * Retrieves object's {@link fabric.Object#clipTo|clipping function}
  3233. * @method getClipTo
  3234. * @memberOf fabric.Object.prototype
  3235. * @return {Function}
  3236. */
  3237. /**
  3238. * Sets object's {@link fabric.Object#clipTo|clipping function}
  3239. * @method setClipTo
  3240. * @memberOf fabric.Object.prototype
  3241. * @param {Function} clipTo Clipping function
  3242. * @return {fabric.Object} thisArg
  3243. * @chainable
  3244. */
  3245. /**
  3246. * Retrieves object's {@link fabric.Object#transformMatrix|transformMatrix}
  3247. * @method getTransformMatrix
  3248. * @memberOf fabric.Object.prototype
  3249. * @return {Array} transformMatrix
  3250. */
  3251. /**
  3252. * Sets object's {@link fabric.Object#transformMatrix|transformMatrix}
  3253. * @method setTransformMatrix
  3254. * @memberOf fabric.Object.prototype
  3255. * @param {Array} transformMatrix
  3256. * @return {fabric.Object} thisArg
  3257. * @chainable
  3258. */
  3259. /**
  3260. * Retrieves object's {@link fabric.Object#visible|visible} state
  3261. * @method getVisible
  3262. * @memberOf fabric.Object.prototype
  3263. * @return {Boolean} True if visible
  3264. */
  3265. /**
  3266. * Sets object's {@link fabric.Object#visible|visible} state
  3267. * @method setVisible
  3268. * @memberOf fabric.Object.prototype
  3269. * @param {Boolean} value visible value
  3270. * @return {fabric.Object} thisArg
  3271. * @chainable
  3272. */
  3273. /**
  3274. * Retrieves object's {@link fabric.Object#shadow|shadow}
  3275. * @method getShadow
  3276. * @memberOf fabric.Object.prototype
  3277. * @return {Object} Shadow instance
  3278. */
  3279. /**
  3280. * Retrieves object's {@link fabric.Object#stroke|stroke}
  3281. * @method getStroke
  3282. * @memberOf fabric.Object.prototype
  3283. * @return {String} stroke value
  3284. */
  3285. /**
  3286. * Sets object's {@link fabric.Object#stroke|stroke}
  3287. * @method setStroke
  3288. * @memberOf fabric.Object.prototype
  3289. * @param {String} value stroke value
  3290. * @return {fabric.Object} thisArg
  3291. * @chainable
  3292. */
  3293. /**
  3294. * Retrieves object's {@link fabric.Object#strokeWidth|strokeWidth}
  3295. * @method getStrokeWidth
  3296. * @memberOf fabric.Object.prototype
  3297. * @return {Number} strokeWidth value
  3298. */
  3299. /**
  3300. * Sets object's {@link fabric.Object#strokeWidth|strokeWidth}
  3301. * @method setStrokeWidth
  3302. * @memberOf fabric.Object.prototype
  3303. * @param {Number} value strokeWidth value
  3304. * @return {fabric.Object} thisArg
  3305. * @chainable
  3306. */
  3307. /**
  3308. * Retrieves object's {@link fabric.Object#originX|originX}
  3309. * @method getOriginX
  3310. * @memberOf fabric.Object.prototype
  3311. * @return {String} originX value
  3312. */
  3313. /**
  3314. * Sets object's {@link fabric.Object#originX|originX}
  3315. * @method setOriginX
  3316. * @memberOf fabric.Object.prototype
  3317. * @param {String} value originX value
  3318. * @return {fabric.Object} thisArg
  3319. * @chainable
  3320. */
  3321. /**
  3322. * Retrieves object's {@link fabric.Object#originY|originY}
  3323. * @method getOriginY
  3324. * @memberOf fabric.Object.prototype
  3325. * @return {String} originY value
  3326. */
  3327. /**
  3328. * Sets object's {@link fabric.Object#originY|originY}
  3329. * @method setOriginY
  3330. * @memberOf fabric.Object.prototype
  3331. * @param {String} value originY value
  3332. * @return {fabric.Object} thisArg
  3333. * @chainable
  3334. */
  3335. /**
  3336. * Retrieves object's {@link fabric.Object#fill|fill}
  3337. * @method getFill
  3338. * @memberOf fabric.Object.prototype
  3339. * @return {String} Fill value
  3340. */
  3341. /**
  3342. * Sets object's {@link fabric.Object#fill|fill}
  3343. * @method setFill
  3344. * @memberOf fabric.Object.prototype
  3345. * @param {String} value Fill value
  3346. * @return {fabric.Object} thisArg
  3347. * @chainable
  3348. */
  3349. /**
  3350. * Retrieves object's {@link fabric.Object#opacity|opacity}
  3351. * @method getOpacity
  3352. * @memberOf fabric.Object.prototype
  3353. * @return {Number} Opacity value (0-1)
  3354. */
  3355. /**
  3356. * Sets object's {@link fabric.Object#opacity|opacity}
  3357. * @method setOpacity
  3358. * @memberOf fabric.Object.prototype
  3359. * @param {Number} value Opacity value (0-1)
  3360. * @return {fabric.Object} thisArg
  3361. * @chainable
  3362. */
  3363. /**
  3364. * Retrieves object's {@link fabric.Object#angle|angle} (in degrees)
  3365. * @method getAngle
  3366. * @memberOf fabric.Object.prototype
  3367. * @return {Number}
  3368. */
  3369. /**
  3370. * Retrieves object's {@link fabric.Object#top|top position}
  3371. * @method getTop
  3372. * @memberOf fabric.Object.prototype
  3373. * @return {Number} Top value (in pixels)
  3374. */
  3375. /**
  3376. * Sets object's {@link fabric.Object#top|top position}
  3377. * @method setTop
  3378. * @memberOf fabric.Object.prototype
  3379. * @param {Number} value Top value (in pixels)
  3380. * @return {fabric.Object} thisArg
  3381. * @chainable
  3382. */
  3383. /**
  3384. * Retrieves object's {@link fabric.Object#left|left position}
  3385. * @method getLeft
  3386. * @memberOf fabric.Object.prototype
  3387. * @return {Number} Left value (in pixels)
  3388. */
  3389. /**
  3390. * Sets object's {@link fabric.Object#left|left position}
  3391. * @method setLeft
  3392. * @memberOf fabric.Object.prototype
  3393. * @param {Number} value Left value (in pixels)
  3394. * @return {fabric.Object} thisArg
  3395. * @chainable
  3396. */
  3397. /**
  3398. * Retrieves object's {@link fabric.Object#scaleX|scaleX} value
  3399. * @method getScaleX
  3400. * @memberOf fabric.Object.prototype
  3401. * @return {Number} scaleX value
  3402. */
  3403. /**
  3404. * Sets object's {@link fabric.Object#scaleX|scaleX} value
  3405. * @method setScaleX
  3406. * @memberOf fabric.Object.prototype
  3407. * @param {Number} value scaleX value
  3408. * @return {fabric.Object} thisArg
  3409. * @chainable
  3410. */
  3411. /**
  3412. * Retrieves object's {@link fabric.Object#scaleY|scaleY} value
  3413. * @method getScaleY
  3414. * @memberOf fabric.Object.prototype
  3415. * @return {Number} scaleY value
  3416. */
  3417. /**
  3418. * Sets object's {@link fabric.Object#scaleY|scaleY} value
  3419. * @method setScaleY
  3420. * @memberOf fabric.Object.prototype
  3421. * @param {Number} value scaleY value
  3422. * @return {fabric.Object} thisArg
  3423. * @chainable
  3424. */
  3425. /**
  3426. * Retrieves object's {@link fabric.Object#flipX|flipX} value
  3427. * @method getFlipX
  3428. * @memberOf fabric.Object.prototype
  3429. * @return {Boolean} flipX value
  3430. */
  3431. /**
  3432. * Sets object's {@link fabric.Object#flipX|flipX} value
  3433. * @method setFlipX
  3434. * @memberOf fabric.Object.prototype
  3435. * @param {Boolean} value flipX value
  3436. * @return {fabric.Object} thisArg
  3437. * @chainable
  3438. */
  3439. /**
  3440. * Retrieves object's {@link fabric.Object#flipY|flipY} value
  3441. * @method getFlipY
  3442. * @memberOf fabric.Object.prototype
  3443. * @return {Boolean} flipY value
  3444. */
  3445. /**
  3446. * Sets object's {@link fabric.Object#flipY|flipY} value
  3447. * @method setFlipY
  3448. * @memberOf fabric.Object.prototype
  3449. * @param {Boolean} value flipY value
  3450. * @return {fabric.Object} thisArg
  3451. * @chainable
  3452. */
  3453. })(typeof exports !== 'undefined' ? exports : this);
  3454. (function() {
  3455. var arcToSegmentsCache = { },
  3456. segmentToBezierCache = { },
  3457. boundsOfCurveCache = { },
  3458. _join = Array.prototype.join;
  3459. /* Adapted from http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp
  3460. * by Andrea Bogazzi code is under MPL. if you don't have a copy of the license you can take it here
  3461. * http://mozilla.org/MPL/2.0/
  3462. */
  3463. function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {
  3464. var argsString = _join.call(arguments);
  3465. if (arcToSegmentsCache[argsString]) {
  3466. return arcToSegmentsCache[argsString];
  3467. }
  3468. var PI = Math.PI, th = rotateX * PI / 180,
  3469. sinTh = fabric.util.sin(th),
  3470. cosTh = fabric.util.cos(th),
  3471. fromX = 0, fromY = 0;
  3472. rx = Math.abs(rx);
  3473. ry = Math.abs(ry);
  3474. var px = -cosTh * toX * 0.5 - sinTh * toY * 0.5,
  3475. py = -cosTh * toY * 0.5 + sinTh * toX * 0.5,
  3476. rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px,
  3477. pl = rx2 * ry2 - rx2 * py2 - ry2 * px2,
  3478. root = 0;
  3479. if (pl < 0) {
  3480. var s = Math.sqrt(1 - pl / (rx2 * ry2));
  3481. rx *= s;
  3482. ry *= s;
  3483. }
  3484. else {
  3485. root = (large === sweep ? -1.0 : 1.0) *
  3486. Math.sqrt( pl / (rx2 * py2 + ry2 * px2));
  3487. }
  3488. var cx = root * rx * py / ry,
  3489. cy = -root * ry * px / rx,
  3490. cx1 = cosTh * cx - sinTh * cy + toX * 0.5,
  3491. cy1 = sinTh * cx + cosTh * cy + toY * 0.5,
  3492. mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry),
  3493. dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry);
  3494. if (sweep === 0 && dtheta > 0) {
  3495. dtheta -= 2 * PI;
  3496. }
  3497. else if (sweep === 1 && dtheta < 0) {
  3498. dtheta += 2 * PI;
  3499. }
  3500. // Convert into cubic bezier segments <= 90deg
  3501. var segments = Math.ceil(Math.abs(dtheta / PI * 2)),
  3502. result = [], mDelta = dtheta / segments,
  3503. mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2),
  3504. th3 = mTheta + mDelta;
  3505. for (var i = 0; i < segments; i++) {
  3506. result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);
  3507. fromX = result[i][4];
  3508. fromY = result[i][5];
  3509. mTheta = th3;
  3510. th3 += mDelta;
  3511. }
  3512. arcToSegmentsCache[argsString] = result;
  3513. return result;
  3514. }
  3515. function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {
  3516. var argsString2 = _join.call(arguments);
  3517. if (segmentToBezierCache[argsString2]) {
  3518. return segmentToBezierCache[argsString2];
  3519. }
  3520. var costh2 = fabric.util.cos(th2),
  3521. sinth2 = fabric.util.sin(th2),
  3522. costh3 = fabric.util.cos(th3),
  3523. sinth3 = fabric.util.sin(th3),
  3524. toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1,
  3525. toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1,
  3526. cp1X = fromX + mT * ( -cosTh * rx * sinth2 - sinTh * ry * costh2),
  3527. cp1Y = fromY + mT * ( -sinTh * rx * sinth2 + cosTh * ry * costh2),
  3528. cp2X = toX + mT * ( cosTh * rx * sinth3 + sinTh * ry * costh3),
  3529. cp2Y = toY + mT * ( sinTh * rx * sinth3 - cosTh * ry * costh3);
  3530. segmentToBezierCache[argsString2] = [
  3531. cp1X, cp1Y,
  3532. cp2X, cp2Y,
  3533. toX, toY
  3534. ];
  3535. return segmentToBezierCache[argsString2];
  3536. }
  3537. /*
  3538. * Private
  3539. */
  3540. function calcVectorAngle(ux, uy, vx, vy) {
  3541. var ta = Math.atan2(uy, ux),
  3542. tb = Math.atan2(vy, vx);
  3543. if (tb >= ta) {
  3544. return tb - ta;
  3545. }
  3546. else {
  3547. return 2 * Math.PI - (ta - tb);
  3548. }
  3549. }
  3550. /**
  3551. * Draws arc
  3552. * @param {CanvasRenderingContext2D} ctx
  3553. * @param {Number} fx
  3554. * @param {Number} fy
  3555. * @param {Array} coords
  3556. */
  3557. fabric.util.drawArc = function(ctx, fx, fy, coords) {
  3558. var rx = coords[0],
  3559. ry = coords[1],
  3560. rot = coords[2],
  3561. large = coords[3],
  3562. sweep = coords[4],
  3563. tx = coords[5],
  3564. ty = coords[6],
  3565. segs = [[], [], [], []],
  3566. segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
  3567. for (var i = 0, len = segsNorm.length; i < len; i++) {
  3568. segs[i][0] = segsNorm[i][0] + fx;
  3569. segs[i][1] = segsNorm[i][1] + fy;
  3570. segs[i][2] = segsNorm[i][2] + fx;
  3571. segs[i][3] = segsNorm[i][3] + fy;
  3572. segs[i][4] = segsNorm[i][4] + fx;
  3573. segs[i][5] = segsNorm[i][5] + fy;
  3574. ctx.bezierCurveTo.apply(ctx, segs[i]);
  3575. }
  3576. };
  3577. /**
  3578. * Calculate bounding box of a elliptic-arc
  3579. * @param {Number} fx start point of arc
  3580. * @param {Number} fy
  3581. * @param {Number} rx horizontal radius
  3582. * @param {Number} ry vertical radius
  3583. * @param {Number} rot angle of horizontal axe
  3584. * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points
  3585. * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction
  3586. * @param {Number} tx end point of arc
  3587. * @param {Number} ty
  3588. */
  3589. fabric.util.getBoundsOfArc = function(fx, fy, rx, ry, rot, large, sweep, tx, ty) {
  3590. var fromX = 0, fromY = 0, bound, bounds = [],
  3591. segs = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
  3592. for (var i = 0, len = segs.length; i < len; i++) {
  3593. bound = getBoundsOfCurve(fromX, fromY, segs[i][0], segs[i][1], segs[i][2], segs[i][3], segs[i][4], segs[i][5]);
  3594. bounds.push({ x: bound[0].x + fx, y: bound[0].y + fy });
  3595. bounds.push({ x: bound[1].x + fx, y: bound[1].y + fy });
  3596. fromX = segs[i][4];
  3597. fromY = segs[i][5];
  3598. }
  3599. return bounds;
  3600. };
  3601. /**
  3602. * Calculate bounding box of a beziercurve
  3603. * @param {Number} x0 starting point
  3604. * @param {Number} y0
  3605. * @param {Number} x1 first control point
  3606. * @param {Number} y1
  3607. * @param {Number} x2 secondo control point
  3608. * @param {Number} y2
  3609. * @param {Number} x3 end of beizer
  3610. * @param {Number} y3
  3611. */
  3612. // taken from http://jsbin.com/ivomiq/56/edit no credits available for that.
  3613. function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {
  3614. var argsString = _join.call(arguments);
  3615. if (boundsOfCurveCache[argsString]) {
  3616. return boundsOfCurveCache[argsString];
  3617. }
  3618. var sqrt = Math.sqrt,
  3619. min = Math.min, max = Math.max,
  3620. abs = Math.abs, tvalues = [],
  3621. bounds = [[], []],
  3622. a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  3623. b = 6 * x0 - 12 * x1 + 6 * x2;
  3624. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  3625. c = 3 * x1 - 3 * x0;
  3626. for (var i = 0; i < 2; ++i) {
  3627. if (i > 0) {
  3628. b = 6 * y0 - 12 * y1 + 6 * y2;
  3629. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  3630. c = 3 * y1 - 3 * y0;
  3631. }
  3632. if (abs(a) < 1e-12) {
  3633. if (abs(b) < 1e-12) {
  3634. continue;
  3635. }
  3636. t = -c / b;
  3637. if (0 < t && t < 1) {
  3638. tvalues.push(t);
  3639. }
  3640. continue;
  3641. }
  3642. b2ac = b * b - 4 * c * a;
  3643. if (b2ac < 0) {
  3644. continue;
  3645. }
  3646. sqrtb2ac = sqrt(b2ac);
  3647. t1 = (-b + sqrtb2ac) / (2 * a);
  3648. if (0 < t1 && t1 < 1) {
  3649. tvalues.push(t1);
  3650. }
  3651. t2 = (-b - sqrtb2ac) / (2 * a);
  3652. if (0 < t2 && t2 < 1) {
  3653. tvalues.push(t2);
  3654. }
  3655. }
  3656. var x, y, j = tvalues.length, jlen = j, mt;
  3657. while (j--) {
  3658. t = tvalues[j];
  3659. mt = 1 - t;
  3660. x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
  3661. bounds[0][j] = x;
  3662. y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
  3663. bounds[1][j] = y;
  3664. }
  3665. bounds[0][jlen] = x0;
  3666. bounds[1][jlen] = y0;
  3667. bounds[0][jlen + 1] = x3;
  3668. bounds[1][jlen + 1] = y3;
  3669. var result = [
  3670. {
  3671. x: min.apply(null, bounds[0]),
  3672. y: min.apply(null, bounds[1])
  3673. },
  3674. {
  3675. x: max.apply(null, bounds[0]),
  3676. y: max.apply(null, bounds[1])
  3677. }
  3678. ];
  3679. boundsOfCurveCache[argsString] = result;
  3680. return result;
  3681. }
  3682. fabric.util.getBoundsOfCurve = getBoundsOfCurve;
  3683. })();
  3684. (function() {
  3685. var slice = Array.prototype.slice;
  3686. /**
  3687. * Invokes method on all items in a given array
  3688. * @memberOf fabric.util.array
  3689. * @param {Array} array Array to iterate over
  3690. * @param {String} method Name of a method to invoke
  3691. * @return {Array}
  3692. */
  3693. function invoke(array, method) {
  3694. var args = slice.call(arguments, 2), result = [];
  3695. for (var i = 0, len = array.length; i < len; i++) {
  3696. result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
  3697. }
  3698. return result;
  3699. }
  3700. /**
  3701. * Finds maximum value in array (not necessarily "first" one)
  3702. * @memberOf fabric.util.array
  3703. * @param {Array} array Array to iterate over
  3704. * @param {String} byProperty
  3705. * @return {*}
  3706. */
  3707. function max(array, byProperty) {
  3708. return find(array, byProperty, function(value1, value2) {
  3709. return value1 >= value2;
  3710. });
  3711. }
  3712. /**
  3713. * Finds minimum value in array (not necessarily "first" one)
  3714. * @memberOf fabric.util.array
  3715. * @param {Array} array Array to iterate over
  3716. * @param {String} byProperty
  3717. * @return {*}
  3718. */
  3719. function min(array, byProperty) {
  3720. return find(array, byProperty, function(value1, value2) {
  3721. return value1 < value2;
  3722. });
  3723. }
  3724. /**
  3725. * @private
  3726. */
  3727. function fill(array, value) {
  3728. var k = array.length;
  3729. while (k--) {
  3730. array[k] = value;
  3731. }
  3732. return array;
  3733. }
  3734. /**
  3735. * @private
  3736. */
  3737. function find(array, byProperty, condition) {
  3738. if (!array || array.length === 0) {
  3739. return;
  3740. }
  3741. var i = array.length - 1,
  3742. result = byProperty ? array[i][byProperty] : array[i];
  3743. if (byProperty) {
  3744. while (i--) {
  3745. if (condition(array[i][byProperty], result)) {
  3746. result = array[i][byProperty];
  3747. }
  3748. }
  3749. }
  3750. else {
  3751. while (i--) {
  3752. if (condition(array[i], result)) {
  3753. result = array[i];
  3754. }
  3755. }
  3756. }
  3757. return result;
  3758. }
  3759. /**
  3760. * @namespace fabric.util.array
  3761. */
  3762. fabric.util.array = {
  3763. fill: fill,
  3764. invoke: invoke,
  3765. min: min,
  3766. max: max
  3767. };
  3768. })();
  3769. (function() {
  3770. /**
  3771. * Copies all enumerable properties of one js object to another
  3772. * Does not clone or extend fabric.Object subclasses.
  3773. * @memberOf fabric.util.object
  3774. * @param {Object} destination Where to copy to
  3775. * @param {Object} source Where to copy from
  3776. * @return {Object}
  3777. */
  3778. function extend(destination, source, deep) {
  3779. // JScript DontEnum bug is not taken care of
  3780. // the deep clone is for internal use, is not meant to avoid
  3781. // javascript traps or cloning html element or self referenced objects.
  3782. if (deep) {
  3783. if (!fabric.isLikelyNode && source instanceof Element) {
  3784. // avoid cloning deep images, canvases,
  3785. destination = source;
  3786. }
  3787. else if (source instanceof Array) {
  3788. destination = [];
  3789. for (var i = 0, len = source.length; i < len; i++) {
  3790. destination[i] = extend({ }, source[i], deep);
  3791. }
  3792. }
  3793. else if (source && typeof source === 'object') {
  3794. for (var property in source) {
  3795. if (source.hasOwnProperty(property)) {
  3796. destination[property] = extend({ }, source[property], deep);
  3797. }
  3798. }
  3799. }
  3800. else {
  3801. // this sounds odd for an extend but is ok for recursive use
  3802. destination = source;
  3803. }
  3804. }
  3805. else {
  3806. for (var property in source) {
  3807. destination[property] = source[property];
  3808. }
  3809. }
  3810. return destination;
  3811. }
  3812. /**
  3813. * Creates an empty object and copies all enumerable properties of another object to it
  3814. * @memberOf fabric.util.object
  3815. * TODO: this function return an empty object if you try to clone null
  3816. * @param {Object} object Object to clone
  3817. * @return {Object}
  3818. */
  3819. function clone(object, deep) {
  3820. return extend({ }, object, deep);
  3821. }
  3822. /** @namespace fabric.util.object */
  3823. fabric.util.object = {
  3824. extend: extend,
  3825. clone: clone
  3826. };
  3827. fabric.util.object.extend(fabric.util, fabric.Observable);
  3828. })();
  3829. (function() {
  3830. /**
  3831. * Camelizes a string
  3832. * @memberOf fabric.util.string
  3833. * @param {String} string String to camelize
  3834. * @return {String} Camelized version of a string
  3835. */
  3836. function camelize(string) {
  3837. return string.replace(/-+(.)?/g, function(match, character) {
  3838. return character ? character.toUpperCase() : '';
  3839. });
  3840. }
  3841. /**
  3842. * Capitalizes a string
  3843. * @memberOf fabric.util.string
  3844. * @param {String} string String to capitalize
  3845. * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized
  3846. * and other letters stay untouched, if false first letter is capitalized
  3847. * and other letters are converted to lowercase.
  3848. * @return {String} Capitalized version of a string
  3849. */
  3850. function capitalize(string, firstLetterOnly) {
  3851. return string.charAt(0).toUpperCase() +
  3852. (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());
  3853. }
  3854. /**
  3855. * Escapes XML in a string
  3856. * @memberOf fabric.util.string
  3857. * @param {String} string String to escape
  3858. * @return {String} Escaped version of a string
  3859. */
  3860. function escapeXml(string) {
  3861. return string.replace(/&/g, '&amp;')
  3862. .replace(/"/g, '&quot;')
  3863. .replace(/'/g, '&apos;')
  3864. .replace(/</g, '&lt;')
  3865. .replace(/>/g, '&gt;');
  3866. }
  3867. /**
  3868. * Divide a string in the user perceived single units
  3869. * @memberOf fabric.util.string
  3870. * @param {String} textstring String to escape
  3871. * @return {Array} array containing the graphemes
  3872. */
  3873. function graphemeSplit(textstring) {
  3874. var i = 0, chr, graphemes = [];
  3875. for (i = 0, chr; i < textstring.length; i++) {
  3876. if ((chr = getWholeChar(textstring, i)) === false) {
  3877. continue;
  3878. }
  3879. graphemes.push(chr);
  3880. }
  3881. return graphemes;
  3882. }
  3883. // taken from mdn in the charAt doc page.
  3884. function getWholeChar(str, i) {
  3885. var code = str.charCodeAt(i);
  3886. if (isNaN(code)) {
  3887. return ''; // Position not found
  3888. }
  3889. if (code < 0xD800 || code > 0xDFFF) {
  3890. return str.charAt(i);
  3891. }
  3892. // High surrogate (could change last hex to 0xDB7F to treat high private
  3893. // surrogates as single characters)
  3894. if (0xD800 <= code && code <= 0xDBFF) {
  3895. if (str.length <= (i + 1)) {
  3896. throw 'High surrogate without following low surrogate';
  3897. }
  3898. var next = str.charCodeAt(i + 1);
  3899. if (0xDC00 > next || next > 0xDFFF) {
  3900. throw 'High surrogate without following low surrogate';
  3901. }
  3902. return str.charAt(i) + str.charAt(i + 1);
  3903. }
  3904. // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  3905. if (i === 0) {
  3906. throw 'Low surrogate without preceding high surrogate';
  3907. }
  3908. var prev = str.charCodeAt(i - 1);
  3909. // (could change last hex to 0xDB7F to treat high private
  3910. // surrogates as single characters)
  3911. if (0xD800 > prev || prev > 0xDBFF) {
  3912. throw 'Low surrogate without preceding high surrogate';
  3913. }
  3914. // We can pass over low surrogates now as the second component
  3915. // in a pair which we have already processed
  3916. return false;
  3917. }
  3918. /**
  3919. * String utilities
  3920. * @namespace fabric.util.string
  3921. */
  3922. fabric.util.string = {
  3923. camelize: camelize,
  3924. capitalize: capitalize,
  3925. escapeXml: escapeXml,
  3926. graphemeSplit: graphemeSplit
  3927. };
  3928. })();
  3929. (function() {
  3930. var slice = Array.prototype.slice, emptyFunction = function() { },
  3931. IS_DONTENUM_BUGGY = (function() {
  3932. for (var p in { toString: 1 }) {
  3933. if (p === 'toString') {
  3934. return false;
  3935. }
  3936. }
  3937. return true;
  3938. })(),
  3939. /** @ignore */
  3940. addMethods = function(klass, source, parent) {
  3941. for (var property in source) {
  3942. if (property in klass.prototype &&
  3943. typeof klass.prototype[property] === 'function' &&
  3944. (source[property] + '').indexOf('callSuper') > -1) {
  3945. klass.prototype[property] = (function(property) {
  3946. return function() {
  3947. var superclass = this.constructor.superclass;
  3948. this.constructor.superclass = parent;
  3949. var returnValue = source[property].apply(this, arguments);
  3950. this.constructor.superclass = superclass;
  3951. if (property !== 'initialize') {
  3952. return returnValue;
  3953. }
  3954. };
  3955. })(property);
  3956. }
  3957. else {
  3958. klass.prototype[property] = source[property];
  3959. }
  3960. if (IS_DONTENUM_BUGGY) {
  3961. if (source.toString !== Object.prototype.toString) {
  3962. klass.prototype.toString = source.toString;
  3963. }
  3964. if (source.valueOf !== Object.prototype.valueOf) {
  3965. klass.prototype.valueOf = source.valueOf;
  3966. }
  3967. }
  3968. }
  3969. };
  3970. function Subclass() { }
  3971. function callSuper(methodName) {
  3972. var parentMethod = null,
  3973. _this = this;
  3974. // climb prototype chain to find method not equal to callee's method
  3975. while (_this.constructor.superclass) {
  3976. var superClassMethod = _this.constructor.superclass.prototype[methodName];
  3977. if (_this[methodName] !== superClassMethod) {
  3978. parentMethod = superClassMethod;
  3979. break;
  3980. }
  3981. // eslint-disable-next-line
  3982. _this = _this.constructor.superclass.prototype;
  3983. }
  3984. if (!parentMethod) {
  3985. return console.log('tried to callSuper ' + methodName + ', method not found in prototype chain', this);
  3986. }
  3987. return (arguments.length > 1)
  3988. ? parentMethod.apply(this, slice.call(arguments, 1))
  3989. : parentMethod.call(this);
  3990. }
  3991. /**
  3992. * Helper for creation of "classes".
  3993. * @memberOf fabric.util
  3994. * @param {Function} [parent] optional "Class" to inherit from
  3995. * @param {Object} [properties] Properties shared by all instances of this class
  3996. * (be careful modifying objects defined here as this would affect all instances)
  3997. */
  3998. function createClass() {
  3999. var parent = null,
  4000. properties = slice.call(arguments, 0);
  4001. if (typeof properties[0] === 'function') {
  4002. parent = properties.shift();
  4003. }
  4004. function klass() {
  4005. this.initialize.apply(this, arguments);
  4006. }
  4007. klass.superclass = parent;
  4008. klass.subclasses = [];
  4009. if (parent) {
  4010. Subclass.prototype = parent.prototype;
  4011. klass.prototype = new Subclass();
  4012. parent.subclasses.push(klass);
  4013. }
  4014. for (var i = 0, length = properties.length; i < length; i++) {
  4015. addMethods(klass, properties[i], parent);
  4016. }
  4017. if (!klass.prototype.initialize) {
  4018. klass.prototype.initialize = emptyFunction;
  4019. }
  4020. klass.prototype.constructor = klass;
  4021. klass.prototype.callSuper = callSuper;
  4022. return klass;
  4023. }
  4024. fabric.util.createClass = createClass;
  4025. })();
  4026. (function () {
  4027. var unknown = 'unknown';
  4028. /* EVENT HANDLING */
  4029. function areHostMethods(object) {
  4030. var methodNames = Array.prototype.slice.call(arguments, 1),
  4031. t, i, len = methodNames.length;
  4032. for (i = 0; i < len; i++) {
  4033. t = typeof object[methodNames[i]];
  4034. if (!(/^(?:function|object|unknown)$/).test(t)) {
  4035. return false;
  4036. }
  4037. }
  4038. return true;
  4039. }
  4040. /** @ignore */
  4041. var getElement,
  4042. setElement,
  4043. getUniqueId = (function () {
  4044. var uid = 0;
  4045. return function (element) {
  4046. return element.__uniqueID || (element.__uniqueID = 'uniqueID__' + uid++);
  4047. };
  4048. })();
  4049. (function () {
  4050. var elements = { };
  4051. /** @ignore */
  4052. getElement = function (uid) {
  4053. return elements[uid];
  4054. };
  4055. /** @ignore */
  4056. setElement = function (uid, element) {
  4057. elements[uid] = element;
  4058. };
  4059. })();
  4060. function createListener(uid, handler) {
  4061. return {
  4062. handler: handler,
  4063. wrappedHandler: createWrappedHandler(uid, handler)
  4064. };
  4065. }
  4066. function createWrappedHandler(uid, handler) {
  4067. return function (e) {
  4068. handler.call(getElement(uid), e || fabric.window.event);
  4069. };
  4070. }
  4071. function createDispatcher(uid, eventName) {
  4072. return function (e) {
  4073. if (handlers[uid] && handlers[uid][eventName]) {
  4074. var handlersForEvent = handlers[uid][eventName];
  4075. for (var i = 0, len = handlersForEvent.length; i < len; i++) {
  4076. handlersForEvent[i].call(this, e || fabric.window.event);
  4077. }
  4078. }
  4079. };
  4080. }
  4081. var shouldUseAddListenerRemoveListener = (
  4082. areHostMethods(fabric.document.documentElement, 'addEventListener', 'removeEventListener') &&
  4083. areHostMethods(fabric.window, 'addEventListener', 'removeEventListener')),
  4084. shouldUseAttachEventDetachEvent = (
  4085. areHostMethods(fabric.document.documentElement, 'attachEvent', 'detachEvent') &&
  4086. areHostMethods(fabric.window, 'attachEvent', 'detachEvent')),
  4087. // IE branch
  4088. listeners = { },
  4089. // DOM L0 branch
  4090. handlers = { },
  4091. addListener, removeListener;
  4092. if (shouldUseAddListenerRemoveListener) {
  4093. /** @ignore */
  4094. addListener = function (element, eventName, handler, options) {
  4095. // since ie10 or ie9 can use addEventListener but they do not support options, i need to check
  4096. element && element.addEventListener(eventName, handler, shouldUseAttachEventDetachEvent ? false : options);
  4097. };
  4098. /** @ignore */
  4099. removeListener = function (element, eventName, handler, options) {
  4100. element && element.removeEventListener(eventName, handler, shouldUseAttachEventDetachEvent ? false : options);
  4101. };
  4102. }
  4103. else if (shouldUseAttachEventDetachEvent) {
  4104. /** @ignore */
  4105. addListener = function (element, eventName, handler) {
  4106. if (!element) {
  4107. return;
  4108. }
  4109. var uid = getUniqueId(element);
  4110. setElement(uid, element);
  4111. if (!listeners[uid]) {
  4112. listeners[uid] = { };
  4113. }
  4114. if (!listeners[uid][eventName]) {
  4115. listeners[uid][eventName] = [];
  4116. }
  4117. var listener = createListener(uid, handler);
  4118. listeners[uid][eventName].push(listener);
  4119. element.attachEvent('on' + eventName, listener.wrappedHandler);
  4120. };
  4121. /** @ignore */
  4122. removeListener = function (element, eventName, handler) {
  4123. if (!element) {
  4124. return;
  4125. }
  4126. var uid = getUniqueId(element), listener;
  4127. if (listeners[uid] && listeners[uid][eventName]) {
  4128. for (var i = 0, len = listeners[uid][eventName].length; i < len; i++) {
  4129. listener = listeners[uid][eventName][i];
  4130. if (listener && listener.handler === handler) {
  4131. element.detachEvent('on' + eventName, listener.wrappedHandler);
  4132. listeners[uid][eventName][i] = null;
  4133. }
  4134. }
  4135. }
  4136. };
  4137. }
  4138. else {
  4139. /** @ignore */
  4140. addListener = function (element, eventName, handler) {
  4141. if (!element) {
  4142. return;
  4143. }
  4144. var uid = getUniqueId(element);
  4145. if (!handlers[uid]) {
  4146. handlers[uid] = { };
  4147. }
  4148. if (!handlers[uid][eventName]) {
  4149. handlers[uid][eventName] = [];
  4150. var existingHandler = element['on' + eventName];
  4151. if (existingHandler) {
  4152. handlers[uid][eventName].push(existingHandler);
  4153. }
  4154. element['on' + eventName] = createDispatcher(uid, eventName);
  4155. }
  4156. handlers[uid][eventName].push(handler);
  4157. };
  4158. /** @ignore */
  4159. removeListener = function (element, eventName, handler) {
  4160. if (!element) {
  4161. return;
  4162. }
  4163. var uid = getUniqueId(element);
  4164. if (handlers[uid] && handlers[uid][eventName]) {
  4165. var handlersForEvent = handlers[uid][eventName];
  4166. for (var i = 0, len = handlersForEvent.length; i < len; i++) {
  4167. if (handlersForEvent[i] === handler) {
  4168. handlersForEvent.splice(i, 1);
  4169. }
  4170. }
  4171. }
  4172. };
  4173. }
  4174. /**
  4175. * Adds an event listener to an element
  4176. * @function
  4177. * @memberOf fabric.util
  4178. * @param {HTMLElement} element
  4179. * @param {String} eventName
  4180. * @param {Function} handler
  4181. */
  4182. fabric.util.addListener = addListener;
  4183. /**
  4184. * Removes an event listener from an element
  4185. * @function
  4186. * @memberOf fabric.util
  4187. * @param {HTMLElement} element
  4188. * @param {String} eventName
  4189. * @param {Function} handler
  4190. */
  4191. fabric.util.removeListener = removeListener;
  4192. /**
  4193. * Cross-browser wrapper for getting event's coordinates
  4194. * @memberOf fabric.util
  4195. * @param {Event} event Event object
  4196. */
  4197. function getPointer(event) {
  4198. event || (event = fabric.window.event);
  4199. var element = event.target ||
  4200. (typeof event.srcElement !== unknown ? event.srcElement : null),
  4201. scroll = fabric.util.getScrollLeftTop(element);
  4202. return {
  4203. x: pointerX(event) + scroll.left,
  4204. y: pointerY(event) + scroll.top
  4205. };
  4206. }
  4207. var pointerX = function(event) {
  4208. return event.clientX;
  4209. },
  4210. pointerY = function(event) {
  4211. return event.clientY;
  4212. };
  4213. function _getPointer(event, pageProp, clientProp) {
  4214. var touchProp = event.type === 'touchend' ? 'changedTouches' : 'touches';
  4215. var pointer, eventTouchProp = event[touchProp];
  4216. if (eventTouchProp && eventTouchProp[0]) {
  4217. pointer = eventTouchProp[0][clientProp];
  4218. }
  4219. if (typeof pointer === 'undefined') {
  4220. pointer = event[clientProp];
  4221. }
  4222. return pointer;
  4223. }
  4224. if (fabric.isTouchSupported) {
  4225. pointerX = function(event) {
  4226. return _getPointer(event, 'pageX', 'clientX');
  4227. };
  4228. pointerY = function(event) {
  4229. return _getPointer(event, 'pageY', 'clientY');
  4230. };
  4231. }
  4232. fabric.util.getPointer = getPointer;
  4233. })();
  4234. (function () {
  4235. /**
  4236. * Cross-browser wrapper for setting element's style
  4237. * @memberOf fabric.util
  4238. * @param {HTMLElement} element
  4239. * @param {Object} styles
  4240. * @return {HTMLElement} Element that was passed as a first argument
  4241. */
  4242. function setStyle(element, styles) {
  4243. var elementStyle = element.style;
  4244. if (!elementStyle) {
  4245. return element;
  4246. }
  4247. if (typeof styles === 'string') {
  4248. element.style.cssText += ';' + styles;
  4249. return styles.indexOf('opacity') > -1
  4250. ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1])
  4251. : element;
  4252. }
  4253. for (var property in styles) {
  4254. if (property === 'opacity') {
  4255. setOpacity(element, styles[property]);
  4256. }
  4257. else {
  4258. var normalizedProperty = (property === 'float' || property === 'cssFloat')
  4259. ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')
  4260. : property;
  4261. elementStyle[normalizedProperty] = styles[property];
  4262. }
  4263. }
  4264. return element;
  4265. }
  4266. var parseEl = fabric.document.createElement('div'),
  4267. supportsOpacity = typeof parseEl.style.opacity === 'string',
  4268. supportsFilters = typeof parseEl.style.filter === 'string',
  4269. reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
  4270. /** @ignore */
  4271. setOpacity = function (element) { return element; };
  4272. if (supportsOpacity) {
  4273. /** @ignore */
  4274. setOpacity = function(element, value) {
  4275. element.style.opacity = value;
  4276. return element;
  4277. };
  4278. }
  4279. else if (supportsFilters) {
  4280. /** @ignore */
  4281. setOpacity = function(element, value) {
  4282. var es = element.style;
  4283. if (element.currentStyle && !element.currentStyle.hasLayout) {
  4284. es.zoom = 1;
  4285. }
  4286. if (reOpacity.test(es.filter)) {
  4287. value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
  4288. es.filter = es.filter.replace(reOpacity, value);
  4289. }
  4290. else {
  4291. es.filter += ' alpha(opacity=' + (value * 100) + ')';
  4292. }
  4293. return element;
  4294. };
  4295. }
  4296. fabric.util.setStyle = setStyle;
  4297. })();
  4298. (function() {
  4299. var _slice = Array.prototype.slice;
  4300. /**
  4301. * Takes id and returns an element with that id (if one exists in a document)
  4302. * @memberOf fabric.util
  4303. * @param {String|HTMLElement} id
  4304. * @return {HTMLElement|null}
  4305. */
  4306. function getById(id) {
  4307. return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  4308. }
  4309. var sliceCanConvertNodelists,
  4310. /**
  4311. * Converts an array-like object (e.g. arguments or NodeList) to an array
  4312. * @memberOf fabric.util
  4313. * @param {Object} arrayLike
  4314. * @return {Array}
  4315. */
  4316. toArray = function(arrayLike) {
  4317. return _slice.call(arrayLike, 0);
  4318. };
  4319. try {
  4320. sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  4321. }
  4322. catch (err) { }
  4323. if (!sliceCanConvertNodelists) {
  4324. toArray = function(arrayLike) {
  4325. var arr = new Array(arrayLike.length), i = arrayLike.length;
  4326. while (i--) {
  4327. arr[i] = arrayLike[i];
  4328. }
  4329. return arr;
  4330. };
  4331. }
  4332. /**
  4333. * Creates specified element with specified attributes
  4334. * @memberOf fabric.util
  4335. * @param {String} tagName Type of an element to create
  4336. * @param {Object} [attributes] Attributes to set on an element
  4337. * @return {HTMLElement} Newly created element
  4338. */
  4339. function makeElement(tagName, attributes) {
  4340. var el = fabric.document.createElement(tagName);
  4341. for (var prop in attributes) {
  4342. if (prop === 'class') {
  4343. el.className = attributes[prop];
  4344. }
  4345. else if (prop === 'for') {
  4346. el.htmlFor = attributes[prop];
  4347. }
  4348. else {
  4349. el.setAttribute(prop, attributes[prop]);
  4350. }
  4351. }
  4352. return el;
  4353. }
  4354. /**
  4355. * Adds class to an element
  4356. * @memberOf fabric.util
  4357. * @param {HTMLElement} element Element to add class to
  4358. * @param {String} className Class to add to an element
  4359. */
  4360. function addClass(element, className) {
  4361. if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
  4362. element.className += (element.className ? ' ' : '') + className;
  4363. }
  4364. }
  4365. /**
  4366. * Wraps element with another element
  4367. * @memberOf fabric.util
  4368. * @param {HTMLElement} element Element to wrap
  4369. * @param {HTMLElement|String} wrapper Element to wrap with
  4370. * @param {Object} [attributes] Attributes to set on a wrapper
  4371. * @return {HTMLElement} wrapper
  4372. */
  4373. function wrapElement(element, wrapper, attributes) {
  4374. if (typeof wrapper === 'string') {
  4375. wrapper = makeElement(wrapper, attributes);
  4376. }
  4377. if (element.parentNode) {
  4378. element.parentNode.replaceChild(wrapper, element);
  4379. }
  4380. wrapper.appendChild(element);
  4381. return wrapper;
  4382. }
  4383. /**
  4384. * Returns element scroll offsets
  4385. * @memberOf fabric.util
  4386. * @param {HTMLElement} element Element to operate on
  4387. * @return {Object} Object with left/top values
  4388. */
  4389. function getScrollLeftTop(element) {
  4390. var left = 0,
  4391. top = 0,
  4392. docElement = fabric.document.documentElement,
  4393. body = fabric.document.body || {
  4394. scrollLeft: 0, scrollTop: 0
  4395. };
  4396. // While loop checks (and then sets element to) .parentNode OR .host
  4397. // to account for ShadowDOM. We still want to traverse up out of ShadowDOM,
  4398. // but the .parentNode of a root ShadowDOM node will always be null, instead
  4399. // it should be accessed through .host. See http://stackoverflow.com/a/24765528/4383938
  4400. while (element && (element.parentNode || element.host)) {
  4401. // Set element to element parent, or 'host' in case of ShadowDOM
  4402. element = element.parentNode || element.host;
  4403. if (element === fabric.document) {
  4404. left = body.scrollLeft || docElement.scrollLeft || 0;
  4405. top = body.scrollTop || docElement.scrollTop || 0;
  4406. }
  4407. else {
  4408. left += element.scrollLeft || 0;
  4409. top += element.scrollTop || 0;
  4410. }
  4411. if (element.nodeType === 1 && element.style.position === 'fixed') {
  4412. break;
  4413. }
  4414. }
  4415. return { left: left, top: top };
  4416. }
  4417. /**
  4418. * Returns offset for a given element
  4419. * @function
  4420. * @memberOf fabric.util
  4421. * @param {HTMLElement} element Element to get offset for
  4422. * @return {Object} Object with "left" and "top" properties
  4423. */
  4424. function getElementOffset(element) {
  4425. var docElem,
  4426. doc = element && element.ownerDocument,
  4427. box = { left: 0, top: 0 },
  4428. offset = { left: 0, top: 0 },
  4429. scrollLeftTop,
  4430. offsetAttributes = {
  4431. borderLeftWidth: 'left',
  4432. borderTopWidth: 'top',
  4433. paddingLeft: 'left',
  4434. paddingTop: 'top'
  4435. };
  4436. if (!doc) {
  4437. return offset;
  4438. }
  4439. for (var attr in offsetAttributes) {
  4440. offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
  4441. }
  4442. docElem = doc.documentElement;
  4443. if ( typeof element.getBoundingClientRect !== 'undefined' ) {
  4444. box = element.getBoundingClientRect();
  4445. }
  4446. scrollLeftTop = getScrollLeftTop(element);
  4447. return {
  4448. left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
  4449. top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top
  4450. };
  4451. }
  4452. /**
  4453. * Returns style attribute value of a given element
  4454. * @memberOf fabric.util
  4455. * @param {HTMLElement} element Element to get style attribute for
  4456. * @param {String} attr Style attribute to get for element
  4457. * @return {String} Style attribute value of the given element.
  4458. */
  4459. var getElementStyle;
  4460. if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
  4461. getElementStyle = function(element, attr) {
  4462. var style = fabric.document.defaultView.getComputedStyle(element, null);
  4463. return style ? style[attr] : undefined;
  4464. };
  4465. }
  4466. else {
  4467. getElementStyle = function(element, attr) {
  4468. var value = element.style[attr];
  4469. if (!value && element.currentStyle) {
  4470. value = element.currentStyle[attr];
  4471. }
  4472. return value;
  4473. };
  4474. }
  4475. (function () {
  4476. var style = fabric.document.documentElement.style,
  4477. selectProp = 'userSelect' in style
  4478. ? 'userSelect'
  4479. : 'MozUserSelect' in style
  4480. ? 'MozUserSelect'
  4481. : 'WebkitUserSelect' in style
  4482. ? 'WebkitUserSelect'
  4483. : 'KhtmlUserSelect' in style
  4484. ? 'KhtmlUserSelect'
  4485. : '';
  4486. /**
  4487. * Makes element unselectable
  4488. * @memberOf fabric.util
  4489. * @param {HTMLElement} element Element to make unselectable
  4490. * @return {HTMLElement} Element that was passed in
  4491. */
  4492. function makeElementUnselectable(element) {
  4493. if (typeof element.onselectstart !== 'undefined') {
  4494. element.onselectstart = fabric.util.falseFunction;
  4495. }
  4496. if (selectProp) {
  4497. element.style[selectProp] = 'none';
  4498. }
  4499. else if (typeof element.unselectable === 'string') {
  4500. element.unselectable = 'on';
  4501. }
  4502. return element;
  4503. }
  4504. /**
  4505. * Makes element selectable
  4506. * @memberOf fabric.util
  4507. * @param {HTMLElement} element Element to make selectable
  4508. * @return {HTMLElement} Element that was passed in
  4509. */
  4510. function makeElementSelectable(element) {
  4511. if (typeof element.onselectstart !== 'undefined') {
  4512. element.onselectstart = null;
  4513. }
  4514. if (selectProp) {
  4515. element.style[selectProp] = '';
  4516. }
  4517. else if (typeof element.unselectable === 'string') {
  4518. element.unselectable = '';
  4519. }
  4520. return element;
  4521. }
  4522. fabric.util.makeElementUnselectable = makeElementUnselectable;
  4523. fabric.util.makeElementSelectable = makeElementSelectable;
  4524. })();
  4525. (function() {
  4526. /**
  4527. * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
  4528. * @memberOf fabric.util
  4529. * @param {String} url URL of a script to load
  4530. * @param {Function} callback Callback to execute when script is finished loading
  4531. */
  4532. function getScript(url, callback) {
  4533. var headEl = fabric.document.getElementsByTagName('head')[0],
  4534. scriptEl = fabric.document.createElement('script'),
  4535. loading = true;
  4536. /** @ignore */
  4537. scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
  4538. if (loading) {
  4539. if (typeof this.readyState === 'string' &&
  4540. this.readyState !== 'loaded' &&
  4541. this.readyState !== 'complete') {
  4542. return;
  4543. }
  4544. loading = false;
  4545. callback(e || fabric.window.event);
  4546. scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
  4547. }
  4548. };
  4549. scriptEl.src = url;
  4550. headEl.appendChild(scriptEl);
  4551. // causes issue in Opera
  4552. // headEl.removeChild(scriptEl);
  4553. }
  4554. fabric.util.getScript = getScript;
  4555. })();
  4556. function getNodeCanvas(element) {
  4557. var impl = fabric.jsdomImplForWrapper(element);
  4558. return impl._canvas || impl._image;
  4559. };
  4560. fabric.util.getById = getById;
  4561. fabric.util.toArray = toArray;
  4562. fabric.util.makeElement = makeElement;
  4563. fabric.util.addClass = addClass;
  4564. fabric.util.wrapElement = wrapElement;
  4565. fabric.util.getScrollLeftTop = getScrollLeftTop;
  4566. fabric.util.getElementOffset = getElementOffset;
  4567. fabric.util.getElementStyle = getElementStyle;
  4568. fabric.util.getNodeCanvas = getNodeCanvas;
  4569. })();
  4570. (function() {
  4571. function addParamToUrl(url, param) {
  4572. return url + (/\?/.test(url) ? '&' : '?') + param;
  4573. }
  4574. var makeXHR = (function() {
  4575. var factories = [
  4576. function() { return new ActiveXObject('Microsoft.XMLHTTP'); },
  4577. function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
  4578. function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
  4579. function() { return new XMLHttpRequest(); }
  4580. ];
  4581. for (var i = factories.length; i--; ) {
  4582. try {
  4583. var req = factories[i]();
  4584. if (req) {
  4585. return factories[i];
  4586. }
  4587. }
  4588. catch (err) { }
  4589. }
  4590. })();
  4591. function emptyFn() { }
  4592. /**
  4593. * Cross-browser abstraction for sending XMLHttpRequest
  4594. * @memberOf fabric.util
  4595. * @param {String} url URL to send XMLHttpRequest to
  4596. * @param {Object} [options] Options object
  4597. * @param {String} [options.method="GET"]
  4598. * @param {String} [options.parameters] parameters to append to url in GET or in body
  4599. * @param {String} [options.body] body to send with POST or PUT request
  4600. * @param {Function} options.onComplete Callback to invoke when request is completed
  4601. * @return {XMLHttpRequest} request
  4602. */
  4603. function request(url, options) {
  4604. options || (options = { });
  4605. var method = options.method ? options.method.toUpperCase() : 'GET',
  4606. onComplete = options.onComplete || function() { },
  4607. xhr = makeXHR(),
  4608. body = options.body || options.parameters;
  4609. /** @ignore */
  4610. xhr.onreadystatechange = function() {
  4611. if (xhr.readyState === 4) {
  4612. onComplete(xhr);
  4613. xhr.onreadystatechange = emptyFn;
  4614. }
  4615. };
  4616. if (method === 'GET') {
  4617. body = null;
  4618. if (typeof options.parameters === 'string') {
  4619. url = addParamToUrl(url, options.parameters);
  4620. }
  4621. }
  4622. xhr.open(method, url, true);
  4623. if (method === 'POST' || method === 'PUT') {
  4624. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4625. }
  4626. xhr.send(body);
  4627. return xhr;
  4628. }
  4629. fabric.util.request = request;
  4630. })();
  4631. /**
  4632. * Wrapper around `console.log` (when available)
  4633. * @param {*} [values] Values to log
  4634. */
  4635. fabric.log = function() { };
  4636. /**
  4637. * Wrapper around `console.warn` (when available)
  4638. * @param {*} [values] Values to log as a warning
  4639. */
  4640. fabric.warn = function() { };
  4641. /* eslint-disable */
  4642. if (typeof console !== 'undefined') {
  4643. ['log', 'warn'].forEach(function(methodName) {
  4644. if (typeof console[methodName] !== 'undefined' &&
  4645. typeof console[methodName].apply === 'function') {
  4646. fabric[methodName] = function() {
  4647. return console[methodName].apply(console, arguments);
  4648. };
  4649. }
  4650. });
  4651. }
  4652. /* eslint-enable */
  4653. (function() {
  4654. function noop() {
  4655. return false;
  4656. }
  4657. /**
  4658. * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
  4659. * @memberOf fabric.util
  4660. * @param {Object} [options] Animation options
  4661. * @param {Function} [options.onChange] Callback; invoked on every value change
  4662. * @param {Function} [options.onComplete] Callback; invoked when value change is completed
  4663. * @param {Number} [options.startValue=0] Starting value
  4664. * @param {Number} [options.endValue=100] Ending value
  4665. * @param {Number} [options.byValue=100] Value to modify the property by
  4666. * @param {Function} [options.easing] Easing function
  4667. * @param {Number} [options.duration=500] Duration of change (in ms)
  4668. */
  4669. function animate(options) {
  4670. requestAnimFrame(function(timestamp) {
  4671. options || (options = { });
  4672. var start = timestamp || +new Date(),
  4673. duration = options.duration || 500,
  4674. finish = start + duration, time,
  4675. onChange = options.onChange || noop,
  4676. abort = options.abort || noop,
  4677. onComplete = options.onComplete || noop,
  4678. easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;},
  4679. startValue = 'startValue' in options ? options.startValue : 0,
  4680. endValue = 'endValue' in options ? options.endValue : 100,
  4681. byValue = options.byValue || endValue - startValue;
  4682. options.onStart && options.onStart();
  4683. (function tick(ticktime) {
  4684. if (abort()) {
  4685. onComplete(endValue, 1, 1);
  4686. return;
  4687. }
  4688. time = ticktime || +new Date();
  4689. var currentTime = time > finish ? duration : (time - start),
  4690. timePerc = currentTime / duration,
  4691. current = easing(currentTime, startValue, byValue, duration),
  4692. valuePerc = Math.abs((current - startValue) / byValue);
  4693. onChange(current, valuePerc, timePerc);
  4694. if (time > finish) {
  4695. options.onComplete && options.onComplete();
  4696. return;
  4697. }
  4698. requestAnimFrame(tick);
  4699. })(start);
  4700. });
  4701. }
  4702. var _requestAnimFrame = fabric.window.requestAnimationFrame ||
  4703. fabric.window.webkitRequestAnimationFrame ||
  4704. fabric.window.mozRequestAnimationFrame ||
  4705. fabric.window.oRequestAnimationFrame ||
  4706. fabric.window.msRequestAnimationFrame ||
  4707. function(callback) {
  4708. return fabric.window.setTimeout(callback, 1000 / 60);
  4709. };
  4710. var _cancelAnimFrame = fabric.window.cancelAnimationFrame || fabric.window.clearTimeout;
  4711. /**
  4712. * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  4713. * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method
  4714. * @memberOf fabric.util
  4715. * @param {Function} callback Callback to invoke
  4716. * @param {DOMElement} element optional Element to associate with animation
  4717. */
  4718. function requestAnimFrame() {
  4719. return _requestAnimFrame.apply(fabric.window, arguments);
  4720. }
  4721. function cancelAnimFrame() {
  4722. return _cancelAnimFrame.apply(fabric.window, arguments);
  4723. }
  4724. fabric.util.animate = animate;
  4725. fabric.util.requestAnimFrame = requestAnimFrame;
  4726. fabric.util.cancelAnimFrame = cancelAnimFrame;
  4727. })();
  4728. (function() {
  4729. // Calculate an in-between color. Returns a "rgba()" string.
  4730. // Credit: Edwin Martin <edwin@bitstorm.org>
  4731. // http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors.js
  4732. function calculateColor(begin, end, pos) {
  4733. var color = 'rgba('
  4734. + parseInt((begin[0] + pos * (end[0] - begin[0])), 10) + ','
  4735. + parseInt((begin[1] + pos * (end[1] - begin[1])), 10) + ','
  4736. + parseInt((begin[2] + pos * (end[2] - begin[2])), 10);
  4737. color += ',' + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);
  4738. color += ')';
  4739. return color;
  4740. }
  4741. /**
  4742. * Changes the color from one to another within certain period of time, invoking callbacks as value is being changed.
  4743. * @memberOf fabric.util
  4744. * @param {String} fromColor The starting color in hex or rgb(a) format.
  4745. * @param {String} toColor The starting color in hex or rgb(a) format.
  4746. * @param {Number} [duration] Duration of change (in ms).
  4747. * @param {Object} [options] Animation options
  4748. * @param {Function} [options.onChange] Callback; invoked on every value change
  4749. * @param {Function} [options.onComplete] Callback; invoked when value change is completed
  4750. * @param {Function} [options.colorEasing] Easing function. Note that this function only take two arguments (currentTime, duration). Thus the regular animation easing functions cannot be used.
  4751. */
  4752. function animateColor(fromColor, toColor, duration, options) {
  4753. var startColor = new fabric.Color(fromColor).getSource(),
  4754. endColor = new fabric.Color(toColor).getSource();
  4755. options = options || {};
  4756. fabric.util.animate(fabric.util.object.extend(options, {
  4757. duration: duration || 500,
  4758. startValue: startColor,
  4759. endValue: endColor,
  4760. byValue: endColor,
  4761. easing: function (currentTime, startValue, byValue, duration) {
  4762. var posValue = options.colorEasing
  4763. ? options.colorEasing(currentTime, duration)
  4764. : 1 - Math.cos(currentTime / duration * (Math.PI / 2));
  4765. return calculateColor(startValue, byValue, posValue);
  4766. }
  4767. }));
  4768. }
  4769. fabric.util.animateColor = animateColor;
  4770. })();
  4771. (function() {
  4772. function normalize(a, c, p, s) {
  4773. if (a < Math.abs(c)) {
  4774. a = c;
  4775. s = p / 4;
  4776. }
  4777. else {
  4778. //handle the 0/0 case:
  4779. if (c === 0 && a === 0) {
  4780. s = p / (2 * Math.PI) * Math.asin(1);
  4781. }
  4782. else {
  4783. s = p / (2 * Math.PI) * Math.asin(c / a);
  4784. }
  4785. }
  4786. return { a: a, c: c, p: p, s: s };
  4787. }
  4788. function elastic(opts, t, d) {
  4789. return opts.a *
  4790. Math.pow(2, 10 * (t -= 1)) *
  4791. Math.sin( (t * d - opts.s) * (2 * Math.PI) / opts.p );
  4792. }
  4793. /**
  4794. * Cubic easing out
  4795. * @memberOf fabric.util.ease
  4796. */
  4797. function easeOutCubic(t, b, c, d) {
  4798. return c * ((t = t / d - 1) * t * t + 1) + b;
  4799. }
  4800. /**
  4801. * Cubic easing in and out
  4802. * @memberOf fabric.util.ease
  4803. */
  4804. function easeInOutCubic(t, b, c, d) {
  4805. t /= d / 2;
  4806. if (t < 1) {
  4807. return c / 2 * t * t * t + b;
  4808. }
  4809. return c / 2 * ((t -= 2) * t * t + 2) + b;
  4810. }
  4811. /**
  4812. * Quartic easing in
  4813. * @memberOf fabric.util.ease
  4814. */
  4815. function easeInQuart(t, b, c, d) {
  4816. return c * (t /= d) * t * t * t + b;
  4817. }
  4818. /**
  4819. * Quartic easing out
  4820. * @memberOf fabric.util.ease
  4821. */
  4822. function easeOutQuart(t, b, c, d) {
  4823. return -c * ((t = t / d - 1) * t * t * t - 1) + b;
  4824. }
  4825. /**
  4826. * Quartic easing in and out
  4827. * @memberOf fabric.util.ease
  4828. */
  4829. function easeInOutQuart(t, b, c, d) {
  4830. t /= d / 2;
  4831. if (t < 1) {
  4832. return c / 2 * t * t * t * t + b;
  4833. }
  4834. return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
  4835. }
  4836. /**
  4837. * Quintic easing in
  4838. * @memberOf fabric.util.ease
  4839. */
  4840. function easeInQuint(t, b, c, d) {
  4841. return c * (t /= d) * t * t * t * t + b;
  4842. }
  4843. /**
  4844. * Quintic easing out
  4845. * @memberOf fabric.util.ease
  4846. */
  4847. function easeOutQuint(t, b, c, d) {
  4848. return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  4849. }
  4850. /**
  4851. * Quintic easing in and out
  4852. * @memberOf fabric.util.ease
  4853. */
  4854. function easeInOutQuint(t, b, c, d) {
  4855. t /= d / 2;
  4856. if (t < 1) {
  4857. return c / 2 * t * t * t * t * t + b;
  4858. }
  4859. return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
  4860. }
  4861. /**
  4862. * Sinusoidal easing in
  4863. * @memberOf fabric.util.ease
  4864. */
  4865. function easeInSine(t, b, c, d) {
  4866. return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
  4867. }
  4868. /**
  4869. * Sinusoidal easing out
  4870. * @memberOf fabric.util.ease
  4871. */
  4872. function easeOutSine(t, b, c, d) {
  4873. return c * Math.sin(t / d * (Math.PI / 2)) + b;
  4874. }
  4875. /**
  4876. * Sinusoidal easing in and out
  4877. * @memberOf fabric.util.ease
  4878. */
  4879. function easeInOutSine(t, b, c, d) {
  4880. return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
  4881. }
  4882. /**
  4883. * Exponential easing in
  4884. * @memberOf fabric.util.ease
  4885. */
  4886. function easeInExpo(t, b, c, d) {
  4887. return (t === 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
  4888. }
  4889. /**
  4890. * Exponential easing out
  4891. * @memberOf fabric.util.ease
  4892. */
  4893. function easeOutExpo(t, b, c, d) {
  4894. return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
  4895. }
  4896. /**
  4897. * Exponential easing in and out
  4898. * @memberOf fabric.util.ease
  4899. */
  4900. function easeInOutExpo(t, b, c, d) {
  4901. if (t === 0) {
  4902. return b;
  4903. }
  4904. if (t === d) {
  4905. return b + c;
  4906. }
  4907. t /= d / 2;
  4908. if (t < 1) {
  4909. return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
  4910. }
  4911. return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
  4912. }
  4913. /**
  4914. * Circular easing in
  4915. * @memberOf fabric.util.ease
  4916. */
  4917. function easeInCirc(t, b, c, d) {
  4918. return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
  4919. }
  4920. /**
  4921. * Circular easing out
  4922. * @memberOf fabric.util.ease
  4923. */
  4924. function easeOutCirc(t, b, c, d) {
  4925. return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
  4926. }
  4927. /**
  4928. * Circular easing in and out
  4929. * @memberOf fabric.util.ease
  4930. */
  4931. function easeInOutCirc(t, b, c, d) {
  4932. t /= d / 2;
  4933. if (t < 1) {
  4934. return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
  4935. }
  4936. return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
  4937. }
  4938. /**
  4939. * Elastic easing in
  4940. * @memberOf fabric.util.ease
  4941. */
  4942. function easeInElastic(t, b, c, d) {
  4943. var s = 1.70158, p = 0, a = c;
  4944. if (t === 0) {
  4945. return b;
  4946. }
  4947. t /= d;
  4948. if (t === 1) {
  4949. return b + c;
  4950. }
  4951. if (!p) {
  4952. p = d * 0.3;
  4953. }
  4954. var opts = normalize(a, c, p, s);
  4955. return -elastic(opts, t, d) + b;
  4956. }
  4957. /**
  4958. * Elastic easing out
  4959. * @memberOf fabric.util.ease
  4960. */
  4961. function easeOutElastic(t, b, c, d) {
  4962. var s = 1.70158, p = 0, a = c;
  4963. if (t === 0) {
  4964. return b;
  4965. }
  4966. t /= d;
  4967. if (t === 1) {
  4968. return b + c;
  4969. }
  4970. if (!p) {
  4971. p = d * 0.3;
  4972. }
  4973. var opts = normalize(a, c, p, s);
  4974. return opts.a * Math.pow(2, -10 * t) * Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) + opts.c + b;
  4975. }
  4976. /**
  4977. * Elastic easing in and out
  4978. * @memberOf fabric.util.ease
  4979. */
  4980. function easeInOutElastic(t, b, c, d) {
  4981. var s = 1.70158, p = 0, a = c;
  4982. if (t === 0) {
  4983. return b;
  4984. }
  4985. t /= d / 2;
  4986. if (t === 2) {
  4987. return b + c;
  4988. }
  4989. if (!p) {
  4990. p = d * (0.3 * 1.5);
  4991. }
  4992. var opts = normalize(a, c, p, s);
  4993. if (t < 1) {
  4994. return -0.5 * elastic(opts, t, d) + b;
  4995. }
  4996. return opts.a * Math.pow(2, -10 * (t -= 1)) *
  4997. Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) * 0.5 + opts.c + b;
  4998. }
  4999. /**
  5000. * Backwards easing in
  5001. * @memberOf fabric.util.ease
  5002. */
  5003. function easeInBack(t, b, c, d, s) {
  5004. if (s === undefined) {
  5005. s = 1.70158;
  5006. }
  5007. return c * (t /= d) * t * ((s + 1) * t - s) + b;
  5008. }
  5009. /**
  5010. * Backwards easing out
  5011. * @memberOf fabric.util.ease
  5012. */
  5013. function easeOutBack(t, b, c, d, s) {
  5014. if (s === undefined) {
  5015. s = 1.70158;
  5016. }
  5017. return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
  5018. }
  5019. /**
  5020. * Backwards easing in and out
  5021. * @memberOf fabric.util.ease
  5022. */
  5023. function easeInOutBack(t, b, c, d, s) {
  5024. if (s === undefined) {
  5025. s = 1.70158;
  5026. }
  5027. t /= d / 2;
  5028. if (t < 1) {
  5029. return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
  5030. }
  5031. return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
  5032. }
  5033. /**
  5034. * Bouncing easing in
  5035. * @memberOf fabric.util.ease
  5036. */
  5037. function easeInBounce(t, b, c, d) {
  5038. return c - easeOutBounce (d - t, 0, c, d) + b;
  5039. }
  5040. /**
  5041. * Bouncing easing out
  5042. * @memberOf fabric.util.ease
  5043. */
  5044. function easeOutBounce(t, b, c, d) {
  5045. if ((t /= d) < (1 / 2.75)) {
  5046. return c * (7.5625 * t * t) + b;
  5047. }
  5048. else if (t < (2 / 2.75)) {
  5049. return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
  5050. }
  5051. else if (t < (2.5 / 2.75)) {
  5052. return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
  5053. }
  5054. else {
  5055. return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
  5056. }
  5057. }
  5058. /**
  5059. * Bouncing easing in and out
  5060. * @memberOf fabric.util.ease
  5061. */
  5062. function easeInOutBounce(t, b, c, d) {
  5063. if (t < d / 2) {
  5064. return easeInBounce (t * 2, 0, c, d) * 0.5 + b;
  5065. }
  5066. return easeOutBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
  5067. }
  5068. /**
  5069. * Easing functions
  5070. * See <a href="http://gizma.com/easing/">Easing Equations by Robert Penner</a>
  5071. * @namespace fabric.util.ease
  5072. */
  5073. fabric.util.ease = {
  5074. /**
  5075. * Quadratic easing in
  5076. * @memberOf fabric.util.ease
  5077. */
  5078. easeInQuad: function(t, b, c, d) {
  5079. return c * (t /= d) * t + b;
  5080. },
  5081. /**
  5082. * Quadratic easing out
  5083. * @memberOf fabric.util.ease
  5084. */
  5085. easeOutQuad: function(t, b, c, d) {
  5086. return -c * (t /= d) * (t - 2) + b;
  5087. },
  5088. /**
  5089. * Quadratic easing in and out
  5090. * @memberOf fabric.util.ease
  5091. */
  5092. easeInOutQuad: function(t, b, c, d) {
  5093. t /= (d / 2);
  5094. if (t < 1) {
  5095. return c / 2 * t * t + b;
  5096. }
  5097. return -c / 2 * ((--t) * (t - 2) - 1) + b;
  5098. },
  5099. /**
  5100. * Cubic easing in
  5101. * @memberOf fabric.util.ease
  5102. */
  5103. easeInCubic: function(t, b, c, d) {
  5104. return c * (t /= d) * t * t + b;
  5105. },
  5106. easeOutCubic: easeOutCubic,
  5107. easeInOutCubic: easeInOutCubic,
  5108. easeInQuart: easeInQuart,
  5109. easeOutQuart: easeOutQuart,
  5110. easeInOutQuart: easeInOutQuart,
  5111. easeInQuint: easeInQuint,
  5112. easeOutQuint: easeOutQuint,
  5113. easeInOutQuint: easeInOutQuint,
  5114. easeInSine: easeInSine,
  5115. easeOutSine: easeOutSine,
  5116. easeInOutSine: easeInOutSine,
  5117. easeInExpo: easeInExpo,
  5118. easeOutExpo: easeOutExpo,
  5119. easeInOutExpo: easeInOutExpo,
  5120. easeInCirc: easeInCirc,
  5121. easeOutCirc: easeOutCirc,
  5122. easeInOutCirc: easeInOutCirc,
  5123. easeInElastic: easeInElastic,
  5124. easeOutElastic: easeOutElastic,
  5125. easeInOutElastic: easeInOutElastic,
  5126. easeInBack: easeInBack,
  5127. easeOutBack: easeOutBack,
  5128. easeInOutBack: easeInOutBack,
  5129. easeInBounce: easeInBounce,
  5130. easeOutBounce: easeOutBounce,
  5131. easeInOutBounce: easeInOutBounce
  5132. };
  5133. })();
  5134. (function(global) {
  5135. 'use strict';
  5136. /**
  5137. * @name fabric
  5138. * @namespace
  5139. */
  5140. var fabric = global.fabric || (global.fabric = { }),
  5141. extend = fabric.util.object.extend,
  5142. clone = fabric.util.object.clone,
  5143. toFixed = fabric.util.toFixed,
  5144. parseUnit = fabric.util.parseUnit,
  5145. multiplyTransformMatrices = fabric.util.multiplyTransformMatrices,
  5146. svgValidTagNames = ['path', 'circle', 'polygon', 'polyline', 'ellipse', 'rect', 'line',
  5147. 'image', 'text'],
  5148. svgViewBoxElements = ['symbol', 'image', 'marker', 'pattern', 'view', 'svg'],
  5149. svgInvalidAncestors = ['pattern', 'defs', 'symbol', 'metadata', 'clipPath', 'mask', 'desc'],
  5150. svgValidParents = ['symbol', 'g', 'a', 'svg', 'clipPath', 'defs'],
  5151. attributesMap = {
  5152. cx: 'left',
  5153. x: 'left',
  5154. r: 'radius',
  5155. cy: 'top',
  5156. y: 'top',
  5157. display: 'visible',
  5158. visibility: 'visible',
  5159. transform: 'transformMatrix',
  5160. 'fill-opacity': 'fillOpacity',
  5161. 'fill-rule': 'fillRule',
  5162. 'font-family': 'fontFamily',
  5163. 'font-size': 'fontSize',
  5164. 'font-style': 'fontStyle',
  5165. 'font-weight': 'fontWeight',
  5166. 'letter-spacing': 'charSpacing',
  5167. 'paint-order': 'paintFirst',
  5168. 'stroke-dasharray': 'strokeDashArray',
  5169. 'stroke-linecap': 'strokeLineCap',
  5170. 'stroke-linejoin': 'strokeLineJoin',
  5171. 'stroke-miterlimit': 'strokeMiterLimit',
  5172. 'stroke-opacity': 'strokeOpacity',
  5173. 'stroke-width': 'strokeWidth',
  5174. 'text-decoration': 'textDecoration',
  5175. 'text-anchor': 'textAnchor',
  5176. opacity: 'opacity',
  5177. 'clip-path': 'clipPath',
  5178. 'clip-rule': 'clipRule',
  5179. },
  5180. colorAttributes = {
  5181. stroke: 'strokeOpacity',
  5182. fill: 'fillOpacity'
  5183. };
  5184. fabric.svgValidTagNamesRegEx = getSvgRegex(svgValidTagNames);
  5185. fabric.svgViewBoxElementsRegEx = getSvgRegex(svgViewBoxElements);
  5186. fabric.svgInvalidAncestorsRegEx = getSvgRegex(svgInvalidAncestors);
  5187. fabric.svgValidParentsRegEx = getSvgRegex(svgValidParents);
  5188. fabric.cssRules = { };
  5189. fabric.gradientDefs = { };
  5190. fabric.clipPaths = { };
  5191. function normalizeAttr(attr) {
  5192. // transform attribute names
  5193. if (attr in attributesMap) {
  5194. return attributesMap[attr];
  5195. }
  5196. return attr;
  5197. }
  5198. function normalizeValue(attr, value, parentAttributes, fontSize) {
  5199. var isArray = Object.prototype.toString.call(value) === '[object Array]',
  5200. parsed;
  5201. if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
  5202. value = '';
  5203. }
  5204. else if (attr === 'strokeDashArray') {
  5205. if (value === 'none') {
  5206. value = null;
  5207. }
  5208. else {
  5209. value = value.replace(/,/g, ' ').split(/\s+/).map(function(n) {
  5210. return parseFloat(n);
  5211. });
  5212. }
  5213. }
  5214. else if (attr === 'transformMatrix') {
  5215. if (parentAttributes && parentAttributes.transformMatrix) {
  5216. value = multiplyTransformMatrices(
  5217. parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));
  5218. }
  5219. else {
  5220. value = fabric.parseTransformAttribute(value);
  5221. }
  5222. }
  5223. else if (attr === 'visible') {
  5224. value = value !== 'none' && value !== 'hidden';
  5225. // display=none on parent element always takes precedence over child element
  5226. if (parentAttributes && parentAttributes.visible === false) {
  5227. value = false;
  5228. }
  5229. }
  5230. else if (attr === 'opacity') {
  5231. value = parseFloat(value);
  5232. if (parentAttributes && typeof parentAttributes.opacity !== 'undefined') {
  5233. value *= parentAttributes.opacity;
  5234. }
  5235. }
  5236. else if (attr === 'textAnchor' /* text-anchor */) {
  5237. value = value === 'start' ? 'left' : value === 'end' ? 'right' : 'center';
  5238. }
  5239. else if (attr === 'charSpacing') {
  5240. // parseUnit returns px and we convert it to em
  5241. parsed = parseUnit(value, fontSize) / fontSize * 1000;
  5242. }
  5243. else if (attr === 'paintFirst') {
  5244. var fillIndex = value.indexOf('fill');
  5245. var strokeIndex = value.indexOf('stroke');
  5246. var value = 'fill';
  5247. if (fillIndex > -1 && strokeIndex > -1 && strokeIndex < fillIndex) {
  5248. value = 'stroke';
  5249. }
  5250. else if (fillIndex === -1 && strokeIndex > -1) {
  5251. value = 'stroke';
  5252. }
  5253. }
  5254. else {
  5255. parsed = isArray ? value.map(parseUnit) : parseUnit(value, fontSize);
  5256. }
  5257. return (!isArray && isNaN(parsed) ? value : parsed);
  5258. }
  5259. /**
  5260. * @private
  5261. */
  5262. function getSvgRegex(arr) {
  5263. return new RegExp('^(' + arr.join('|') + ')\\b', 'i');
  5264. }
  5265. /**
  5266. * @private
  5267. * @param {Object} attributes Array of attributes to parse
  5268. */
  5269. function _setStrokeFillOpacity(attributes) {
  5270. for (var attr in colorAttributes) {
  5271. if (typeof attributes[colorAttributes[attr]] === 'undefined' || attributes[attr] === '') {
  5272. continue;
  5273. }
  5274. if (typeof attributes[attr] === 'undefined') {
  5275. if (!fabric.Object.prototype[attr]) {
  5276. continue;
  5277. }
  5278. attributes[attr] = fabric.Object.prototype[attr];
  5279. }
  5280. if (attributes[attr].indexOf('url(') === 0) {
  5281. continue;
  5282. }
  5283. var color = new fabric.Color(attributes[attr]);
  5284. attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
  5285. }
  5286. return attributes;
  5287. }
  5288. /**
  5289. * @private
  5290. */
  5291. function _getMultipleNodes(doc, nodeNames) {
  5292. var nodeName, nodeArray = [], nodeList, i, len;
  5293. for (i = 0, len = nodeNames.length; i < len; i++) {
  5294. nodeName = nodeNames[i];
  5295. nodeList = doc.getElementsByTagName(nodeName);
  5296. nodeArray = nodeArray.concat(Array.prototype.slice.call(nodeList));
  5297. }
  5298. return nodeArray;
  5299. }
  5300. /**
  5301. * Parses "transform" attribute, returning an array of values
  5302. * @static
  5303. * @function
  5304. * @memberOf fabric
  5305. * @param {String} attributeValue String containing attribute value
  5306. * @return {Array} Array of 6 elements representing transformation matrix
  5307. */
  5308. fabric.parseTransformAttribute = (function() {
  5309. function rotateMatrix(matrix, args) {
  5310. var cos = fabric.util.cos(args[0]), sin = fabric.util.sin(args[0]),
  5311. x = 0, y = 0;
  5312. if (args.length === 3) {
  5313. x = args[1];
  5314. y = args[2];
  5315. }
  5316. matrix[0] = cos;
  5317. matrix[1] = sin;
  5318. matrix[2] = -sin;
  5319. matrix[3] = cos;
  5320. matrix[4] = x - (cos * x - sin * y);
  5321. matrix[5] = y - (sin * x + cos * y);
  5322. }
  5323. function scaleMatrix(matrix, args) {
  5324. var multiplierX = args[0],
  5325. multiplierY = (args.length === 2) ? args[1] : args[0];
  5326. matrix[0] = multiplierX;
  5327. matrix[3] = multiplierY;
  5328. }
  5329. function skewMatrix(matrix, args, pos) {
  5330. matrix[pos] = Math.tan(fabric.util.degreesToRadians(args[0]));
  5331. }
  5332. function translateMatrix(matrix, args) {
  5333. matrix[4] = args[0];
  5334. if (args.length === 2) {
  5335. matrix[5] = args[1];
  5336. }
  5337. }
  5338. // identity matrix
  5339. var iMatrix = [
  5340. 1, // a
  5341. 0, // b
  5342. 0, // c
  5343. 1, // d
  5344. 0, // e
  5345. 0 // f
  5346. ],
  5347. // == begin transform regexp
  5348. number = fabric.reNum,
  5349. commaWsp = '(?:\\s+,?\\s*|,\\s*)',
  5350. skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
  5351. skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
  5352. rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' +
  5353. commaWsp + '(' + number + ')' +
  5354. commaWsp + '(' + number + '))?\\s*\\))',
  5355. scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' +
  5356. commaWsp + '(' + number + '))?\\s*\\))',
  5357. translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' +
  5358. commaWsp + '(' + number + '))?\\s*\\))',
  5359. matrix = '(?:(matrix)\\s*\\(\\s*' +
  5360. '(' + number + ')' + commaWsp +
  5361. '(' + number + ')' + commaWsp +
  5362. '(' + number + ')' + commaWsp +
  5363. '(' + number + ')' + commaWsp +
  5364. '(' + number + ')' + commaWsp +
  5365. '(' + number + ')' +
  5366. '\\s*\\))',
  5367. transform = '(?:' +
  5368. matrix + '|' +
  5369. translate + '|' +
  5370. scale + '|' +
  5371. rotate + '|' +
  5372. skewX + '|' +
  5373. skewY +
  5374. ')',
  5375. transforms = '(?:' + transform + '(?:' + commaWsp + '*' + transform + ')*' + ')',
  5376. transformList = '^\\s*(?:' + transforms + '?)\\s*$',
  5377. // http://www.w3.org/TR/SVG/coords.html#TransformAttribute
  5378. reTransformList = new RegExp(transformList),
  5379. // == end transform regexp
  5380. reTransform = new RegExp(transform, 'g');
  5381. return function(attributeValue) {
  5382. // start with identity matrix
  5383. var matrix = iMatrix.concat(),
  5384. matrices = [];
  5385. // return if no argument was given or
  5386. // an argument does not match transform attribute regexp
  5387. if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
  5388. return matrix;
  5389. }
  5390. attributeValue.replace(reTransform, function(match) {
  5391. var m = new RegExp(transform).exec(match).filter(function (match) {
  5392. // match !== '' && match != null
  5393. return (!!match);
  5394. }),
  5395. operation = m[1],
  5396. args = m.slice(2).map(parseFloat);
  5397. switch (operation) {
  5398. case 'translate':
  5399. translateMatrix(matrix, args);
  5400. break;
  5401. case 'rotate':
  5402. args[0] = fabric.util.degreesToRadians(args[0]);
  5403. rotateMatrix(matrix, args);
  5404. break;
  5405. case 'scale':
  5406. scaleMatrix(matrix, args);
  5407. break;
  5408. case 'skewX':
  5409. skewMatrix(matrix, args, 2);
  5410. break;
  5411. case 'skewY':
  5412. skewMatrix(matrix, args, 1);
  5413. break;
  5414. case 'matrix':
  5415. matrix = args;
  5416. break;
  5417. }
  5418. // snapshot current matrix into matrices array
  5419. matrices.push(matrix.concat());
  5420. // reset
  5421. matrix = iMatrix.concat();
  5422. });
  5423. var combinedMatrix = matrices[0];
  5424. while (matrices.length > 1) {
  5425. matrices.shift();
  5426. combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
  5427. }
  5428. return combinedMatrix;
  5429. };
  5430. })();
  5431. /**
  5432. * @private
  5433. */
  5434. function parseStyleString(style, oStyle) {
  5435. var attr, value;
  5436. style.replace(/;\s*$/, '').split(';').forEach(function (chunk) {
  5437. var pair = chunk.split(':');
  5438. attr = pair[0].trim().toLowerCase();
  5439. value = pair[1].trim();
  5440. oStyle[attr] = value;
  5441. });
  5442. }
  5443. /**
  5444. * @private
  5445. */
  5446. function parseStyleObject(style, oStyle) {
  5447. var attr, value;
  5448. for (var prop in style) {
  5449. if (typeof style[prop] === 'undefined') {
  5450. continue;
  5451. }
  5452. attr = prop.toLowerCase();
  5453. value = style[prop];
  5454. oStyle[attr] = value;
  5455. }
  5456. }
  5457. /**
  5458. * @private
  5459. */
  5460. function getGlobalStylesForElement(element, svgUid) {
  5461. var styles = { };
  5462. for (var rule in fabric.cssRules[svgUid]) {
  5463. if (elementMatchesRule(element, rule.split(' '))) {
  5464. for (var property in fabric.cssRules[svgUid][rule]) {
  5465. styles[property] = fabric.cssRules[svgUid][rule][property];
  5466. }
  5467. }
  5468. }
  5469. return styles;
  5470. }
  5471. /**
  5472. * @private
  5473. */
  5474. function elementMatchesRule(element, selectors) {
  5475. var firstMatching, parentMatching = true;
  5476. //start from rightmost selector.
  5477. firstMatching = selectorMatches(element, selectors.pop());
  5478. if (firstMatching && selectors.length) {
  5479. parentMatching = doesSomeParentMatch(element, selectors);
  5480. }
  5481. return firstMatching && parentMatching && (selectors.length === 0);
  5482. }
  5483. function doesSomeParentMatch(element, selectors) {
  5484. var selector, parentMatching = true;
  5485. while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {
  5486. if (parentMatching) {
  5487. selector = selectors.pop();
  5488. }
  5489. element = element.parentNode;
  5490. parentMatching = selectorMatches(element, selector);
  5491. }
  5492. return selectors.length === 0;
  5493. }
  5494. /**
  5495. * @private
  5496. */
  5497. function selectorMatches(element, selector) {
  5498. var nodeName = element.nodeName,
  5499. classNames = element.getAttribute('class'),
  5500. id = element.getAttribute('id'), matcher, i;
  5501. // i check if a selector matches slicing away part from it.
  5502. // if i get empty string i should match
  5503. matcher = new RegExp('^' + nodeName, 'i');
  5504. selector = selector.replace(matcher, '');
  5505. if (id && selector.length) {
  5506. matcher = new RegExp('#' + id + '(?![a-zA-Z\\-]+)', 'i');
  5507. selector = selector.replace(matcher, '');
  5508. }
  5509. if (classNames && selector.length) {
  5510. classNames = classNames.split(' ');
  5511. for (i = classNames.length; i--;) {
  5512. matcher = new RegExp('\\.' + classNames[i] + '(?![a-zA-Z\\-]+)', 'i');
  5513. selector = selector.replace(matcher, '');
  5514. }
  5515. }
  5516. return selector.length === 0;
  5517. }
  5518. /**
  5519. * @private
  5520. * to support IE8 missing getElementById on SVGdocument
  5521. */
  5522. function elementById(doc, id) {
  5523. var el;
  5524. doc.getElementById && (el = doc.getElementById(id));
  5525. if (el) {
  5526. return el;
  5527. }
  5528. var node, i, len, nodelist = doc.getElementsByTagName('*');
  5529. for (i = 0, len = nodelist.length; i < len; i++) {
  5530. node = nodelist[i];
  5531. if (id === node.getAttribute('id')) {
  5532. return node;
  5533. }
  5534. }
  5535. }
  5536. /**
  5537. * @private
  5538. */
  5539. function parseUseDirectives(doc) {
  5540. var nodelist = _getMultipleNodes(doc, ['use', 'svg:use']), i = 0;
  5541. while (nodelist.length && i < nodelist.length) {
  5542. var el = nodelist[i],
  5543. xlink = el.getAttribute('xlink:href').substr(1),
  5544. x = el.getAttribute('x') || 0,
  5545. y = el.getAttribute('y') || 0,
  5546. el2 = elementById(doc, xlink).cloneNode(true),
  5547. currentTrans = (el2.getAttribute('transform') || '') + ' translate(' + x + ', ' + y + ')',
  5548. parentNode, oldLength = nodelist.length, attr, j, attrs, len;
  5549. applyViewboxTransform(el2);
  5550. if (/^svg$/i.test(el2.nodeName)) {
  5551. var el3 = el2.ownerDocument.createElement('g');
  5552. for (j = 0, attrs = el2.attributes, len = attrs.length; j < len; j++) {
  5553. attr = attrs.item(j);
  5554. el3.setAttribute(attr.nodeName, attr.nodeValue);
  5555. }
  5556. // el2.firstChild != null
  5557. while (el2.firstChild) {
  5558. el3.appendChild(el2.firstChild);
  5559. }
  5560. el2 = el3;
  5561. }
  5562. for (j = 0, attrs = el.attributes, len = attrs.length; j < len; j++) {
  5563. attr = attrs.item(j);
  5564. if (attr.nodeName === 'x' || attr.nodeName === 'y' || attr.nodeName === 'xlink:href') {
  5565. continue;
  5566. }
  5567. if (attr.nodeName === 'transform') {
  5568. currentTrans = attr.nodeValue + ' ' + currentTrans;
  5569. }
  5570. else {
  5571. el2.setAttribute(attr.nodeName, attr.nodeValue);
  5572. }
  5573. }
  5574. el2.setAttribute('transform', currentTrans);
  5575. el2.setAttribute('instantiated_by_use', '1');
  5576. el2.removeAttribute('id');
  5577. parentNode = el.parentNode;
  5578. parentNode.replaceChild(el2, el);
  5579. // some browsers do not shorten nodelist after replaceChild (IE8)
  5580. if (nodelist.length === oldLength) {
  5581. i++;
  5582. }
  5583. }
  5584. }
  5585. // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
  5586. // matches, e.g.: +14.56e-12, etc.
  5587. var reViewBoxAttrValue = new RegExp(
  5588. '^' +
  5589. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  5590. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  5591. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  5592. '\\s*(' + fabric.reNum + '+)\\s*' +
  5593. '$'
  5594. );
  5595. /**
  5596. * Add a <g> element that envelop all child elements and makes the viewbox transformMatrix descend on all elements
  5597. */
  5598. function applyViewboxTransform(element) {
  5599. var viewBoxAttr = element.getAttribute('viewBox'),
  5600. scaleX = 1,
  5601. scaleY = 1,
  5602. minX = 0,
  5603. minY = 0,
  5604. viewBoxWidth, viewBoxHeight, matrix, el,
  5605. widthAttr = element.getAttribute('width'),
  5606. heightAttr = element.getAttribute('height'),
  5607. x = element.getAttribute('x') || 0,
  5608. y = element.getAttribute('y') || 0,
  5609. preserveAspectRatio = element.getAttribute('preserveAspectRatio') || '',
  5610. missingViewBox = (!viewBoxAttr || !fabric.svgViewBoxElementsRegEx.test(element.nodeName)
  5611. || !(viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))),
  5612. missingDimAttr = (!widthAttr || !heightAttr || widthAttr === '100%' || heightAttr === '100%'),
  5613. toBeParsed = missingViewBox && missingDimAttr,
  5614. parsedDim = { }, translateMatrix = '', widthDiff = 0, heightDiff = 0;
  5615. parsedDim.width = 0;
  5616. parsedDim.height = 0;
  5617. parsedDim.toBeParsed = toBeParsed;
  5618. if (toBeParsed) {
  5619. return parsedDim;
  5620. }
  5621. if (missingViewBox) {
  5622. parsedDim.width = parseUnit(widthAttr);
  5623. parsedDim.height = parseUnit(heightAttr);
  5624. return parsedDim;
  5625. }
  5626. minX = -parseFloat(viewBoxAttr[1]);
  5627. minY = -parseFloat(viewBoxAttr[2]);
  5628. viewBoxWidth = parseFloat(viewBoxAttr[3]);
  5629. viewBoxHeight = parseFloat(viewBoxAttr[4]);
  5630. if (!missingDimAttr) {
  5631. parsedDim.width = parseUnit(widthAttr);
  5632. parsedDim.height = parseUnit(heightAttr);
  5633. scaleX = parsedDim.width / viewBoxWidth;
  5634. scaleY = parsedDim.height / viewBoxHeight;
  5635. }
  5636. else {
  5637. parsedDim.width = viewBoxWidth;
  5638. parsedDim.height = viewBoxHeight;
  5639. }
  5640. // default is to preserve aspect ratio
  5641. preserveAspectRatio = fabric.util.parsePreserveAspectRatioAttribute(preserveAspectRatio);
  5642. if (preserveAspectRatio.alignX !== 'none') {
  5643. //translate all container for the effect of Mid, Min, Max
  5644. if (preserveAspectRatio.meetOrSlice === 'meet') {
  5645. scaleY = scaleX = (scaleX > scaleY ? scaleY : scaleX);
  5646. // calculate additional translation to move the viewbox
  5647. }
  5648. if (preserveAspectRatio.meetOrSlice === 'slice') {
  5649. scaleY = scaleX = (scaleX > scaleY ? scaleX : scaleY);
  5650. // calculate additional translation to move the viewbox
  5651. }
  5652. widthDiff = parsedDim.width - viewBoxWidth * scaleX;
  5653. heightDiff = parsedDim.height - viewBoxHeight * scaleX;
  5654. if (preserveAspectRatio.alignX === 'Mid') {
  5655. widthDiff /= 2;
  5656. }
  5657. if (preserveAspectRatio.alignY === 'Mid') {
  5658. heightDiff /= 2;
  5659. }
  5660. if (preserveAspectRatio.alignX === 'Min') {
  5661. widthDiff = 0;
  5662. }
  5663. if (preserveAspectRatio.alignY === 'Min') {
  5664. heightDiff = 0;
  5665. }
  5666. }
  5667. if (scaleX === 1 && scaleY === 1 && minX === 0 && minY === 0 && x === 0 && y === 0) {
  5668. return parsedDim;
  5669. }
  5670. if (x || y) {
  5671. translateMatrix = ' translate(' + parseUnit(x) + ' ' + parseUnit(y) + ') ';
  5672. }
  5673. matrix = translateMatrix + ' matrix(' + scaleX +
  5674. ' 0' +
  5675. ' 0 ' +
  5676. scaleY + ' ' +
  5677. (minX * scaleX + widthDiff) + ' ' +
  5678. (minY * scaleY + heightDiff) + ') ';
  5679. parsedDim.viewboxTransform = fabric.parseTransformAttribute(matrix);
  5680. if (element.nodeName === 'svg') {
  5681. el = element.ownerDocument.createElement('g');
  5682. // element.firstChild != null
  5683. while (element.firstChild) {
  5684. el.appendChild(element.firstChild);
  5685. }
  5686. element.appendChild(el);
  5687. }
  5688. else {
  5689. el = element;
  5690. matrix = el.getAttribute('transform') + matrix;
  5691. }
  5692. el.setAttribute('transform', matrix);
  5693. return parsedDim;
  5694. }
  5695. function hasAncestorWithNodeName(element, nodeName) {
  5696. while (element && (element = element.parentNode)) {
  5697. if (element.nodeName && nodeName.test(element.nodeName.replace('svg:', ''))
  5698. && !element.getAttribute('instantiated_by_use')) {
  5699. return true;
  5700. }
  5701. }
  5702. return false;
  5703. }
  5704. /**
  5705. * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
  5706. * @static
  5707. * @function
  5708. * @memberOf fabric
  5709. * @param {SVGDocument} doc SVG document to parse
  5710. * @param {Function} callback Callback to call when parsing is finished;
  5711. * It's being passed an array of elements (parsed from a document).
  5712. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  5713. * @param {Object} [parsingOptions] options for parsing document
  5714. * @param {String} [parsingOptions.crossOrigin] crossOrigin settings
  5715. */
  5716. fabric.parseSVGDocument = function(doc, callback, reviver, parsingOptions) {
  5717. if (!doc) {
  5718. return;
  5719. }
  5720. parseUseDirectives(doc);
  5721. var svgUid = fabric.Object.__uid++, i, len,
  5722. options = applyViewboxTransform(doc),
  5723. descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
  5724. options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;
  5725. options.svgUid = svgUid;
  5726. if (descendants.length === 0 && fabric.isLikelyNode) {
  5727. // we're likely in node, where "o3-xml" library fails to gEBTN("*")
  5728. // https://github.com/ajaxorg/node-o3-xml/issues/21
  5729. descendants = doc.selectNodes('//*[name(.)!="svg"]');
  5730. var arr = [];
  5731. for (i = 0, len = descendants.length; i < len; i++) {
  5732. arr[i] = descendants[i];
  5733. }
  5734. descendants = arr;
  5735. }
  5736. var elements = descendants.filter(function(el) {
  5737. applyViewboxTransform(el);
  5738. return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', '')) &&
  5739. !hasAncestorWithNodeName(el, fabric.svgInvalidAncestorsRegEx); // http://www.w3.org/TR/SVG/struct.html#DefsElement
  5740. });
  5741. if (!elements || (elements && !elements.length)) {
  5742. callback && callback([], {});
  5743. return;
  5744. }
  5745. var clipPaths = { };
  5746. descendants.filter(function(el) {
  5747. return el.nodeName.replace('svg:', '') === 'clipPath';
  5748. }).forEach(function(el) {
  5749. clipPaths[el.id] = fabric.util.toArray(el.getElementsByTagName('*')).filter(function(el) {
  5750. return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', ''));
  5751. });
  5752. });
  5753. fabric.gradientDefs[svgUid] = fabric.getGradientDefs(doc);
  5754. fabric.cssRules[svgUid] = fabric.getCSSRules(doc);
  5755. fabric.clipPaths[svgUid] = clipPaths;
  5756. // Precedence of rules: style > class > attribute
  5757. fabric.parseElements(elements, function(instances, elements) {
  5758. if (callback) {
  5759. callback(instances, options, elements, descendants);
  5760. delete fabric.gradientDefs[svgUid];
  5761. delete fabric.cssRules[svgUid];
  5762. delete fabric.clipPaths[svgUid];
  5763. }
  5764. }, clone(options), reviver, parsingOptions);
  5765. };
  5766. var reFontDeclaration = new RegExp(
  5767. '(normal|italic)?\\s*(normal|small-caps)?\\s*' +
  5768. '(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(' +
  5769. fabric.reNum +
  5770. '(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|' + fabric.reNum + '))?\\s+(.*)');
  5771. extend(fabric, {
  5772. /**
  5773. * Parses a short font declaration, building adding its properties to a style object
  5774. * @static
  5775. * @function
  5776. * @memberOf fabric
  5777. * @param {String} value font declaration
  5778. * @param {Object} oStyle definition
  5779. */
  5780. parseFontDeclaration: function(value, oStyle) {
  5781. var match = value.match(reFontDeclaration);
  5782. if (!match) {
  5783. return;
  5784. }
  5785. var fontStyle = match[1],
  5786. // font variant is not used
  5787. // fontVariant = match[2],
  5788. fontWeight = match[3],
  5789. fontSize = match[4],
  5790. lineHeight = match[5],
  5791. fontFamily = match[6];
  5792. if (fontStyle) {
  5793. oStyle.fontStyle = fontStyle;
  5794. }
  5795. if (fontWeight) {
  5796. oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
  5797. }
  5798. if (fontSize) {
  5799. oStyle.fontSize = parseUnit(fontSize);
  5800. }
  5801. if (fontFamily) {
  5802. oStyle.fontFamily = fontFamily;
  5803. }
  5804. if (lineHeight) {
  5805. oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;
  5806. }
  5807. },
  5808. /**
  5809. * Parses an SVG document, returning all of the gradient declarations found in it
  5810. * @static
  5811. * @function
  5812. * @memberOf fabric
  5813. * @param {SVGDocument} doc SVG document to parse
  5814. * @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
  5815. */
  5816. getGradientDefs: function(doc) {
  5817. var tagArray = [
  5818. 'linearGradient',
  5819. 'radialGradient',
  5820. 'svg:linearGradient',
  5821. 'svg:radialGradient'],
  5822. elList = _getMultipleNodes(doc, tagArray),
  5823. el, j = 0, id, xlink,
  5824. gradientDefs = { }, idsToXlinkMap = { };
  5825. j = elList.length;
  5826. while (j--) {
  5827. el = elList[j];
  5828. xlink = el.getAttribute('xlink:href');
  5829. id = el.getAttribute('id');
  5830. if (xlink) {
  5831. idsToXlinkMap[id] = xlink.substr(1);
  5832. }
  5833. gradientDefs[id] = el;
  5834. }
  5835. for (id in idsToXlinkMap) {
  5836. var el2 = gradientDefs[idsToXlinkMap[id]].cloneNode(true);
  5837. el = gradientDefs[id];
  5838. while (el2.firstChild) {
  5839. el.appendChild(el2.firstChild);
  5840. }
  5841. }
  5842. return gradientDefs;
  5843. },
  5844. /**
  5845. * Returns an object of attributes' name/value, given element and an array of attribute names;
  5846. * Parses parent "g" nodes recursively upwards.
  5847. * @static
  5848. * @memberOf fabric
  5849. * @param {DOMElement} element Element to parse
  5850. * @param {Array} attributes Array of attributes to parse
  5851. * @return {Object} object containing parsed attributes' names/values
  5852. */
  5853. parseAttributes: function(element, attributes, svgUid) {
  5854. if (!element) {
  5855. return;
  5856. }
  5857. var value,
  5858. parentAttributes = { },
  5859. fontSize;
  5860. if (typeof svgUid === 'undefined') {
  5861. svgUid = element.getAttribute('svgUid');
  5862. }
  5863. // if there's a parent container (`g` or `a` or `symbol` node), parse its attributes recursively upwards
  5864. if (element.parentNode && fabric.svgValidParentsRegEx.test(element.parentNode.nodeName)) {
  5865. parentAttributes = fabric.parseAttributes(element.parentNode, attributes, svgUid);
  5866. }
  5867. fontSize = (parentAttributes && parentAttributes.fontSize ) ||
  5868. element.getAttribute('font-size') || fabric.Text.DEFAULT_SVG_FONT_SIZE;
  5869. var ownAttributes = attributes.reduce(function(memo, attr) {
  5870. value = element.getAttribute(attr);
  5871. if (value) { // eslint-disable-line
  5872. memo[attr] = value;
  5873. }
  5874. return memo;
  5875. }, { });
  5876. // add values parsed from style, which take precedence over attributes
  5877. // (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
  5878. ownAttributes = extend(ownAttributes,
  5879. extend(getGlobalStylesForElement(element, svgUid), fabric.parseStyleAttribute(element)));
  5880. var normalizedAttr, normalizedValue, normalizedStyle = {};
  5881. for (var attr in ownAttributes) {
  5882. normalizedAttr = normalizeAttr(attr);
  5883. normalizedValue = normalizeValue(normalizedAttr, ownAttributes[attr], parentAttributes, fontSize);
  5884. normalizedStyle[normalizedAttr] = normalizedValue;
  5885. }
  5886. if (normalizedStyle && normalizedStyle.font) {
  5887. fabric.parseFontDeclaration(normalizedStyle.font, normalizedStyle);
  5888. }
  5889. var mergedAttrs = extend(parentAttributes, normalizedStyle);
  5890. return fabric.svgValidParentsRegEx.test(element.nodeName) ? mergedAttrs : _setStrokeFillOpacity(mergedAttrs);
  5891. },
  5892. /**
  5893. * Transforms an array of svg elements to corresponding fabric.* instances
  5894. * @static
  5895. * @memberOf fabric
  5896. * @param {Array} elements Array of elements to parse
  5897. * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
  5898. * @param {Object} [options] Options object
  5899. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  5900. */
  5901. parseElements: function(elements, callback, options, reviver, parsingOptions) {
  5902. new fabric.ElementsParser(elements, callback, options, reviver, parsingOptions).parse();
  5903. },
  5904. /**
  5905. * Parses "style" attribute, retuning an object with values
  5906. * @static
  5907. * @memberOf fabric
  5908. * @param {SVGElement} element Element to parse
  5909. * @return {Object} Objects with values parsed from style attribute of an element
  5910. */
  5911. parseStyleAttribute: function(element) {
  5912. var oStyle = { },
  5913. style = element.getAttribute('style');
  5914. if (!style) {
  5915. return oStyle;
  5916. }
  5917. if (typeof style === 'string') {
  5918. parseStyleString(style, oStyle);
  5919. }
  5920. else {
  5921. parseStyleObject(style, oStyle);
  5922. }
  5923. return oStyle;
  5924. },
  5925. /**
  5926. * Parses "points" attribute, returning an array of values
  5927. * @static
  5928. * @memberOf fabric
  5929. * @param {String} points points attribute string
  5930. * @return {Array} array of points
  5931. */
  5932. parsePointsAttribute: function(points) {
  5933. // points attribute is required and must not be empty
  5934. if (!points) {
  5935. return null;
  5936. }
  5937. // replace commas with whitespace and remove bookending whitespace
  5938. points = points.replace(/,/g, ' ').trim();
  5939. points = points.split(/\s+/);
  5940. var parsedPoints = [], i, len;
  5941. for (i = 0, len = points.length; i < len; i += 2) {
  5942. parsedPoints.push({
  5943. x: parseFloat(points[i]),
  5944. y: parseFloat(points[i + 1])
  5945. });
  5946. }
  5947. // odd number of points is an error
  5948. // if (parsedPoints.length % 2 !== 0) {
  5949. // return null;
  5950. // }
  5951. return parsedPoints;
  5952. },
  5953. /**
  5954. * Returns CSS rules for a given SVG document
  5955. * @static
  5956. * @function
  5957. * @memberOf fabric
  5958. * @param {SVGDocument} doc SVG document to parse
  5959. * @return {Object} CSS rules of this document
  5960. */
  5961. getCSSRules: function(doc) {
  5962. var styles = doc.getElementsByTagName('style'), i, len,
  5963. allRules = { }, rules;
  5964. // very crude parsing of style contents
  5965. for (i = 0, len = styles.length; i < len; i++) {
  5966. // IE9 doesn't support textContent, but provides text instead.
  5967. var styleContents = styles[i].textContent || styles[i].text;
  5968. // remove comments
  5969. styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');
  5970. if (styleContents.trim() === '') {
  5971. continue;
  5972. }
  5973. rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
  5974. rules = rules.map(function(rule) { return rule.trim(); });
  5975. // eslint-disable-next-line no-loop-func
  5976. rules.forEach(function(rule) {
  5977. var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/),
  5978. ruleObj = { }, declaration = match[2].trim(),
  5979. propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/);
  5980. for (i = 0, len = propertyValuePairs.length; i < len; i++) {
  5981. var pair = propertyValuePairs[i].split(/\s*:\s*/),
  5982. property = pair[0],
  5983. value = pair[1];
  5984. ruleObj[property] = value;
  5985. }
  5986. rule = match[1];
  5987. rule.split(',').forEach(function(_rule) {
  5988. _rule = _rule.replace(/^svg/i, '').trim();
  5989. if (_rule === '') {
  5990. return;
  5991. }
  5992. if (allRules[_rule]) {
  5993. fabric.util.object.extend(allRules[_rule], ruleObj);
  5994. }
  5995. else {
  5996. allRules[_rule] = fabric.util.object.clone(ruleObj);
  5997. }
  5998. });
  5999. });
  6000. }
  6001. return allRules;
  6002. },
  6003. /**
  6004. * Takes url corresponding to an SVG document, and parses it into a set of fabric objects.
  6005. * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
  6006. * @memberOf fabric
  6007. * @param {String} url
  6008. * @param {Function} callback
  6009. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  6010. * @param {Object} [options] Object containing options for parsing
  6011. * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
  6012. */
  6013. loadSVGFromURL: function(url, callback, reviver, options) {
  6014. url = url.replace(/^\n\s*/, '').trim();
  6015. new fabric.util.request(url, {
  6016. method: 'get',
  6017. onComplete: onComplete
  6018. });
  6019. function onComplete(r) {
  6020. var xml = r.responseXML;
  6021. if (xml && !xml.documentElement && fabric.window.ActiveXObject && r.responseText) {
  6022. xml = new ActiveXObject('Microsoft.XMLDOM');
  6023. xml.async = 'false';
  6024. //IE chokes on DOCTYPE
  6025. xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
  6026. }
  6027. if (!xml || !xml.documentElement) {
  6028. callback && callback(null);
  6029. }
  6030. fabric.parseSVGDocument(xml.documentElement, function (results, _options, elements, allElements) {
  6031. callback && callback(results, _options, elements, allElements);
  6032. }, reviver, options);
  6033. }
  6034. },
  6035. /**
  6036. * Takes string corresponding to an SVG document, and parses it into a set of fabric objects
  6037. * @memberOf fabric
  6038. * @param {String} string
  6039. * @param {Function} callback
  6040. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  6041. * @param {Object} [options] Object containing options for parsing
  6042. * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
  6043. */
  6044. loadSVGFromString: function(string, callback, reviver, options) {
  6045. string = string.trim();
  6046. var doc;
  6047. if (typeof DOMParser !== 'undefined') {
  6048. var parser = new DOMParser();
  6049. if (parser && parser.parseFromString) {
  6050. doc = parser.parseFromString(string, 'text/xml');
  6051. }
  6052. }
  6053. else if (fabric.window.ActiveXObject) {
  6054. doc = new ActiveXObject('Microsoft.XMLDOM');
  6055. doc.async = 'false';
  6056. // IE chokes on DOCTYPE
  6057. doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
  6058. }
  6059. fabric.parseSVGDocument(doc.documentElement, function (results, _options, elements, allElements) {
  6060. callback(results, _options, elements, allElements);
  6061. }, reviver, options);
  6062. }
  6063. });
  6064. })(typeof exports !== 'undefined' ? exports : this);
  6065. fabric.ElementsParser = function(elements, callback, options, reviver, parsingOptions) {
  6066. this.elements = elements;
  6067. this.callback = callback;
  6068. this.options = options;
  6069. this.reviver = reviver;
  6070. this.svgUid = (options && options.svgUid) || 0;
  6071. this.parsingOptions = parsingOptions;
  6072. this.regexUrl = /^url\(['"]?#([^'"]+)['"]?\)/g;
  6073. };
  6074. (function(proto) {
  6075. proto.parse = function() {
  6076. this.instances = new Array(this.elements.length);
  6077. this.numElements = this.elements.length;
  6078. this.createObjects();
  6079. };
  6080. proto.createObjects = function() {
  6081. var _this = this;
  6082. this.elements.forEach(function(element, i) {
  6083. element.setAttribute('svgUid', _this.svgUid);
  6084. _this.createObject(element, i);
  6085. });
  6086. };
  6087. proto.findTag = function(el) {
  6088. return fabric[fabric.util.string.capitalize(el.tagName.replace('svg:', ''))];
  6089. };
  6090. proto.createObject = function(el, index) {
  6091. var klass = this.findTag(el);
  6092. if (klass && klass.fromElement) {
  6093. try {
  6094. klass.fromElement(el, this.createCallback(index, el), this.options);
  6095. }
  6096. catch (err) {
  6097. fabric.log(err);
  6098. }
  6099. }
  6100. else {
  6101. this.checkIfDone();
  6102. }
  6103. };
  6104. proto.createCallback = function(index, el) {
  6105. var _this = this;
  6106. return function(obj) {
  6107. var _options;
  6108. _this.resolveGradient(obj, 'fill');
  6109. _this.resolveGradient(obj, 'stroke');
  6110. if (obj instanceof fabric.Image) {
  6111. _options = obj.parsePreserveAspectRatioAttribute(el);
  6112. }
  6113. obj._removeTransformMatrix(_options);
  6114. _this.resolveClipPath(obj);
  6115. _this.reviver && _this.reviver(el, obj);
  6116. _this.instances[index] = obj;
  6117. _this.checkIfDone();
  6118. };
  6119. };
  6120. proto.extractPropertyDefinition = function(obj, property, storage) {
  6121. var value = obj[property];
  6122. if (!(/^url\(/).test(value)) {
  6123. return;
  6124. }
  6125. var id = this.regexUrl.exec(value)[1];
  6126. this.regexUrl.lastIndex = 0;
  6127. return fabric[storage][this.svgUid][id];
  6128. };
  6129. proto.resolveGradient = function(obj, property) {
  6130. var gradientDef = this.extractPropertyDefinition(obj, property, 'gradientDefs');
  6131. if (gradientDef) {
  6132. obj.set(property, fabric.Gradient.fromElement(gradientDef, obj));
  6133. }
  6134. };
  6135. proto.createClipPathCallback = function(obj, container) {
  6136. return function(_newObj) {
  6137. _newObj._removeTransformMatrix();
  6138. _newObj.fillRule = _newObj.clipRule;
  6139. container.push(_newObj);
  6140. };
  6141. };
  6142. proto.resolveClipPath = function(obj) {
  6143. var clipPath = this.extractPropertyDefinition(obj, 'clipPath', 'clipPaths'),
  6144. element, klass, objTransformInv, container, gTransform, options;
  6145. if (clipPath) {
  6146. container = [];
  6147. objTransformInv = fabric.util.invertTransform(obj.calcTransformMatrix());
  6148. for (var i = 0; i < clipPath.length; i++) {
  6149. element = clipPath[i];
  6150. klass = this.findTag(element);
  6151. klass.fromElement(
  6152. element,
  6153. this.createClipPathCallback(obj, container),
  6154. this.options
  6155. );
  6156. }
  6157. clipPath = new fabric.Group(container);
  6158. gTransform = fabric.util.multiplyTransformMatrices(
  6159. objTransformInv,
  6160. clipPath.calcTransformMatrix()
  6161. );
  6162. var options = fabric.util.qrDecompose(gTransform);
  6163. clipPath.flipX = false;
  6164. clipPath.flipY = false;
  6165. clipPath.set('scaleX', options.scaleX);
  6166. clipPath.set('scaleY', options.scaleY);
  6167. clipPath.angle = options.angle;
  6168. clipPath.skewX = options.skewX;
  6169. clipPath.skewY = 0;
  6170. clipPath.setPositionByOrigin({ x: options.translateX, y: options.translateY }, 'center', 'center');
  6171. obj.clipPath = clipPath;
  6172. }
  6173. };
  6174. proto.checkIfDone = function() {
  6175. if (--this.numElements === 0) {
  6176. this.instances = this.instances.filter(function(el) {
  6177. // eslint-disable-next-line no-eq-null, eqeqeq
  6178. return el != null;
  6179. });
  6180. this.callback(this.instances, this.elements);
  6181. }
  6182. };
  6183. })(fabric.ElementsParser.prototype);
  6184. (function(global) {
  6185. 'use strict';
  6186. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  6187. var fabric = global.fabric || (global.fabric = { });
  6188. if (fabric.Point) {
  6189. fabric.warn('fabric.Point is already defined');
  6190. return;
  6191. }
  6192. fabric.Point = Point;
  6193. /**
  6194. * Point class
  6195. * @class fabric.Point
  6196. * @memberOf fabric
  6197. * @constructor
  6198. * @param {Number} x
  6199. * @param {Number} y
  6200. * @return {fabric.Point} thisArg
  6201. */
  6202. function Point(x, y) {
  6203. this.x = x;
  6204. this.y = y;
  6205. }
  6206. Point.prototype = /** @lends fabric.Point.prototype */ {
  6207. type: 'point',
  6208. constructor: Point,
  6209. /**
  6210. * Adds another point to this one and returns another one
  6211. * @param {fabric.Point} that
  6212. * @return {fabric.Point} new Point instance with added values
  6213. */
  6214. add: function (that) {
  6215. return new Point(this.x + that.x, this.y + that.y);
  6216. },
  6217. /**
  6218. * Adds another point to this one
  6219. * @param {fabric.Point} that
  6220. * @return {fabric.Point} thisArg
  6221. * @chainable
  6222. */
  6223. addEquals: function (that) {
  6224. this.x += that.x;
  6225. this.y += that.y;
  6226. return this;
  6227. },
  6228. /**
  6229. * Adds value to this point and returns a new one
  6230. * @param {Number} scalar
  6231. * @return {fabric.Point} new Point with added value
  6232. */
  6233. scalarAdd: function (scalar) {
  6234. return new Point(this.x + scalar, this.y + scalar);
  6235. },
  6236. /**
  6237. * Adds value to this point
  6238. * @param {Number} scalar
  6239. * @return {fabric.Point} thisArg
  6240. * @chainable
  6241. */
  6242. scalarAddEquals: function (scalar) {
  6243. this.x += scalar;
  6244. this.y += scalar;
  6245. return this;
  6246. },
  6247. /**
  6248. * Subtracts another point from this point and returns a new one
  6249. * @param {fabric.Point} that
  6250. * @return {fabric.Point} new Point object with subtracted values
  6251. */
  6252. subtract: function (that) {
  6253. return new Point(this.x - that.x, this.y - that.y);
  6254. },
  6255. /**
  6256. * Subtracts another point from this point
  6257. * @param {fabric.Point} that
  6258. * @return {fabric.Point} thisArg
  6259. * @chainable
  6260. */
  6261. subtractEquals: function (that) {
  6262. this.x -= that.x;
  6263. this.y -= that.y;
  6264. return this;
  6265. },
  6266. /**
  6267. * Subtracts value from this point and returns a new one
  6268. * @param {Number} scalar
  6269. * @return {fabric.Point}
  6270. */
  6271. scalarSubtract: function (scalar) {
  6272. return new Point(this.x - scalar, this.y - scalar);
  6273. },
  6274. /**
  6275. * Subtracts value from this point
  6276. * @param {Number} scalar
  6277. * @return {fabric.Point} thisArg
  6278. * @chainable
  6279. */
  6280. scalarSubtractEquals: function (scalar) {
  6281. this.x -= scalar;
  6282. this.y -= scalar;
  6283. return this;
  6284. },
  6285. /**
  6286. * Multiplies this point by a value and returns a new one
  6287. * TODO: rename in scalarMultiply in 2.0
  6288. * @param {Number} scalar
  6289. * @return {fabric.Point}
  6290. */
  6291. multiply: function (scalar) {
  6292. return new Point(this.x * scalar, this.y * scalar);
  6293. },
  6294. /**
  6295. * Multiplies this point by a value
  6296. * TODO: rename in scalarMultiplyEquals in 2.0
  6297. * @param {Number} scalar
  6298. * @return {fabric.Point} thisArg
  6299. * @chainable
  6300. */
  6301. multiplyEquals: function (scalar) {
  6302. this.x *= scalar;
  6303. this.y *= scalar;
  6304. return this;
  6305. },
  6306. /**
  6307. * Divides this point by a value and returns a new one
  6308. * TODO: rename in scalarDivide in 2.0
  6309. * @param {Number} scalar
  6310. * @return {fabric.Point}
  6311. */
  6312. divide: function (scalar) {
  6313. return new Point(this.x / scalar, this.y / scalar);
  6314. },
  6315. /**
  6316. * Divides this point by a value
  6317. * TODO: rename in scalarDivideEquals in 2.0
  6318. * @param {Number} scalar
  6319. * @return {fabric.Point} thisArg
  6320. * @chainable
  6321. */
  6322. divideEquals: function (scalar) {
  6323. this.x /= scalar;
  6324. this.y /= scalar;
  6325. return this;
  6326. },
  6327. /**
  6328. * Returns true if this point is equal to another one
  6329. * @param {fabric.Point} that
  6330. * @return {Boolean}
  6331. */
  6332. eq: function (that) {
  6333. return (this.x === that.x && this.y === that.y);
  6334. },
  6335. /**
  6336. * Returns true if this point is less than another one
  6337. * @param {fabric.Point} that
  6338. * @return {Boolean}
  6339. */
  6340. lt: function (that) {
  6341. return (this.x < that.x && this.y < that.y);
  6342. },
  6343. /**
  6344. * Returns true if this point is less than or equal to another one
  6345. * @param {fabric.Point} that
  6346. * @return {Boolean}
  6347. */
  6348. lte: function (that) {
  6349. return (this.x <= that.x && this.y <= that.y);
  6350. },
  6351. /**
  6352. * Returns true if this point is greater another one
  6353. * @param {fabric.Point} that
  6354. * @return {Boolean}
  6355. */
  6356. gt: function (that) {
  6357. return (this.x > that.x && this.y > that.y);
  6358. },
  6359. /**
  6360. * Returns true if this point is greater than or equal to another one
  6361. * @param {fabric.Point} that
  6362. * @return {Boolean}
  6363. */
  6364. gte: function (that) {
  6365. return (this.x >= that.x && this.y >= that.y);
  6366. },
  6367. /**
  6368. * Returns new point which is the result of linear interpolation with this one and another one
  6369. * @param {fabric.Point} that
  6370. * @param {Number} t , position of interpolation, between 0 and 1 default 0.5
  6371. * @return {fabric.Point}
  6372. */
  6373. lerp: function (that, t) {
  6374. if (typeof t === 'undefined') {
  6375. t = 0.5;
  6376. }
  6377. t = Math.max(Math.min(1, t), 0);
  6378. return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
  6379. },
  6380. /**
  6381. * Returns distance from this point and another one
  6382. * @param {fabric.Point} that
  6383. * @return {Number}
  6384. */
  6385. distanceFrom: function (that) {
  6386. var dx = this.x - that.x,
  6387. dy = this.y - that.y;
  6388. return Math.sqrt(dx * dx + dy * dy);
  6389. },
  6390. /**
  6391. * Returns the point between this point and another one
  6392. * @param {fabric.Point} that
  6393. * @return {fabric.Point}
  6394. */
  6395. midPointFrom: function (that) {
  6396. return this.lerp(that);
  6397. },
  6398. /**
  6399. * Returns a new point which is the min of this and another one
  6400. * @param {fabric.Point} that
  6401. * @return {fabric.Point}
  6402. */
  6403. min: function (that) {
  6404. return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
  6405. },
  6406. /**
  6407. * Returns a new point which is the max of this and another one
  6408. * @param {fabric.Point} that
  6409. * @return {fabric.Point}
  6410. */
  6411. max: function (that) {
  6412. return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
  6413. },
  6414. /**
  6415. * Returns string representation of this point
  6416. * @return {String}
  6417. */
  6418. toString: function () {
  6419. return this.x + ',' + this.y;
  6420. },
  6421. /**
  6422. * Sets x/y of this point
  6423. * @param {Number} x
  6424. * @param {Number} y
  6425. * @chainable
  6426. */
  6427. setXY: function (x, y) {
  6428. this.x = x;
  6429. this.y = y;
  6430. return this;
  6431. },
  6432. /**
  6433. * Sets x of this point
  6434. * @param {Number} x
  6435. * @chainable
  6436. */
  6437. setX: function (x) {
  6438. this.x = x;
  6439. return this;
  6440. },
  6441. /**
  6442. * Sets y of this point
  6443. * @param {Number} y
  6444. * @chainable
  6445. */
  6446. setY: function (y) {
  6447. this.y = y;
  6448. return this;
  6449. },
  6450. /**
  6451. * Sets x/y of this point from another point
  6452. * @param {fabric.Point} that
  6453. * @chainable
  6454. */
  6455. setFromPoint: function (that) {
  6456. this.x = that.x;
  6457. this.y = that.y;
  6458. return this;
  6459. },
  6460. /**
  6461. * Swaps x/y of this point and another point
  6462. * @param {fabric.Point} that
  6463. */
  6464. swap: function (that) {
  6465. var x = this.x,
  6466. y = this.y;
  6467. this.x = that.x;
  6468. this.y = that.y;
  6469. that.x = x;
  6470. that.y = y;
  6471. },
  6472. /**
  6473. * return a cloned instance of the point
  6474. * @return {fabric.Point}
  6475. */
  6476. clone: function () {
  6477. return new Point(this.x, this.y);
  6478. }
  6479. };
  6480. })(typeof exports !== 'undefined' ? exports : this);
  6481. (function(global) {
  6482. 'use strict';
  6483. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  6484. var fabric = global.fabric || (global.fabric = { });
  6485. if (fabric.Intersection) {
  6486. fabric.warn('fabric.Intersection is already defined');
  6487. return;
  6488. }
  6489. /**
  6490. * Intersection class
  6491. * @class fabric.Intersection
  6492. * @memberOf fabric
  6493. * @constructor
  6494. */
  6495. function Intersection(status) {
  6496. this.status = status;
  6497. this.points = [];
  6498. }
  6499. fabric.Intersection = Intersection;
  6500. fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {
  6501. constructor: Intersection,
  6502. /**
  6503. * Appends a point to intersection
  6504. * @param {fabric.Point} point
  6505. * @return {fabric.Intersection} thisArg
  6506. * @chainable
  6507. */
  6508. appendPoint: function (point) {
  6509. this.points.push(point);
  6510. return this;
  6511. },
  6512. /**
  6513. * Appends points to intersection
  6514. * @param {Array} points
  6515. * @return {fabric.Intersection} thisArg
  6516. * @chainable
  6517. */
  6518. appendPoints: function (points) {
  6519. this.points = this.points.concat(points);
  6520. return this;
  6521. }
  6522. };
  6523. /**
  6524. * Checks if one line intersects another
  6525. * TODO: rename in intersectSegmentSegment
  6526. * @static
  6527. * @param {fabric.Point} a1
  6528. * @param {fabric.Point} a2
  6529. * @param {fabric.Point} b1
  6530. * @param {fabric.Point} b2
  6531. * @return {fabric.Intersection}
  6532. */
  6533. fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {
  6534. var result,
  6535. uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
  6536. ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
  6537. uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
  6538. if (uB !== 0) {
  6539. var ua = uaT / uB,
  6540. ub = ubT / uB;
  6541. if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
  6542. result = new Intersection('Intersection');
  6543. result.appendPoint(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
  6544. }
  6545. else {
  6546. result = new Intersection();
  6547. }
  6548. }
  6549. else {
  6550. if (uaT === 0 || ubT === 0) {
  6551. result = new Intersection('Coincident');
  6552. }
  6553. else {
  6554. result = new Intersection('Parallel');
  6555. }
  6556. }
  6557. return result;
  6558. };
  6559. /**
  6560. * Checks if line intersects polygon
  6561. * TODO: rename in intersectSegmentPolygon
  6562. * fix detection of coincident
  6563. * @static
  6564. * @param {fabric.Point} a1
  6565. * @param {fabric.Point} a2
  6566. * @param {Array} points
  6567. * @return {fabric.Intersection}
  6568. */
  6569. fabric.Intersection.intersectLinePolygon = function(a1, a2, points) {
  6570. var result = new Intersection(),
  6571. length = points.length,
  6572. b1, b2, inter, i;
  6573. for (i = 0; i < length; i++) {
  6574. b1 = points[i];
  6575. b2 = points[(i + 1) % length];
  6576. inter = Intersection.intersectLineLine(a1, a2, b1, b2);
  6577. result.appendPoints(inter.points);
  6578. }
  6579. if (result.points.length > 0) {
  6580. result.status = 'Intersection';
  6581. }
  6582. return result;
  6583. };
  6584. /**
  6585. * Checks if polygon intersects another polygon
  6586. * @static
  6587. * @param {Array} points1
  6588. * @param {Array} points2
  6589. * @return {fabric.Intersection}
  6590. */
  6591. fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {
  6592. var result = new Intersection(),
  6593. length = points1.length, i;
  6594. for (i = 0; i < length; i++) {
  6595. var a1 = points1[i],
  6596. a2 = points1[(i + 1) % length],
  6597. inter = Intersection.intersectLinePolygon(a1, a2, points2);
  6598. result.appendPoints(inter.points);
  6599. }
  6600. if (result.points.length > 0) {
  6601. result.status = 'Intersection';
  6602. }
  6603. return result;
  6604. };
  6605. /**
  6606. * Checks if polygon intersects rectangle
  6607. * @static
  6608. * @param {Array} points
  6609. * @param {fabric.Point} r1
  6610. * @param {fabric.Point} r2
  6611. * @return {fabric.Intersection}
  6612. */
  6613. fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {
  6614. var min = r1.min(r2),
  6615. max = r1.max(r2),
  6616. topRight = new fabric.Point(max.x, min.y),
  6617. bottomLeft = new fabric.Point(min.x, max.y),
  6618. inter1 = Intersection.intersectLinePolygon(min, topRight, points),
  6619. inter2 = Intersection.intersectLinePolygon(topRight, max, points),
  6620. inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),
  6621. inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),
  6622. result = new Intersection();
  6623. result.appendPoints(inter1.points);
  6624. result.appendPoints(inter2.points);
  6625. result.appendPoints(inter3.points);
  6626. result.appendPoints(inter4.points);
  6627. if (result.points.length > 0) {
  6628. result.status = 'Intersection';
  6629. }
  6630. return result;
  6631. };
  6632. })(typeof exports !== 'undefined' ? exports : this);
  6633. (function(global) {
  6634. 'use strict';
  6635. var fabric = global.fabric || (global.fabric = { });
  6636. if (fabric.Color) {
  6637. fabric.warn('fabric.Color is already defined.');
  6638. return;
  6639. }
  6640. /**
  6641. * Color class
  6642. * The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;
  6643. * {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.
  6644. *
  6645. * @class fabric.Color
  6646. * @param {String} color optional in hex or rgb(a) or hsl format or from known color list
  6647. * @return {fabric.Color} thisArg
  6648. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}
  6649. */
  6650. function Color(color) {
  6651. if (!color) {
  6652. this.setSource([0, 0, 0, 1]);
  6653. }
  6654. else {
  6655. this._tryParsingColor(color);
  6656. }
  6657. }
  6658. fabric.Color = Color;
  6659. fabric.Color.prototype = /** @lends fabric.Color.prototype */ {
  6660. /**
  6661. * @private
  6662. * @param {String|Array} color Color value to parse
  6663. */
  6664. _tryParsingColor: function(color) {
  6665. var source;
  6666. if (color in Color.colorNameMap) {
  6667. color = Color.colorNameMap[color];
  6668. }
  6669. if (color === 'transparent') {
  6670. source = [255, 255, 255, 0];
  6671. }
  6672. if (!source) {
  6673. source = Color.sourceFromHex(color);
  6674. }
  6675. if (!source) {
  6676. source = Color.sourceFromRgb(color);
  6677. }
  6678. if (!source) {
  6679. source = Color.sourceFromHsl(color);
  6680. }
  6681. if (!source) {
  6682. //if color is not recognize let's make black as canvas does
  6683. source = [0, 0, 0, 1];
  6684. }
  6685. if (source) {
  6686. this.setSource(source);
  6687. }
  6688. },
  6689. /**
  6690. * Adapted from <a href="https://rawgithub.com/mjijackson/mjijackson.github.com/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.html">https://github.com/mjijackson</a>
  6691. * @private
  6692. * @param {Number} r Red color value
  6693. * @param {Number} g Green color value
  6694. * @param {Number} b Blue color value
  6695. * @return {Array} Hsl color
  6696. */
  6697. _rgbToHsl: function(r, g, b) {
  6698. r /= 255; g /= 255; b /= 255;
  6699. var h, s, l,
  6700. max = fabric.util.array.max([r, g, b]),
  6701. min = fabric.util.array.min([r, g, b]);
  6702. l = (max + min) / 2;
  6703. if (max === min) {
  6704. h = s = 0; // achromatic
  6705. }
  6706. else {
  6707. var d = max - min;
  6708. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  6709. switch (max) {
  6710. case r:
  6711. h = (g - b) / d + (g < b ? 6 : 0);
  6712. break;
  6713. case g:
  6714. h = (b - r) / d + 2;
  6715. break;
  6716. case b:
  6717. h = (r - g) / d + 4;
  6718. break;
  6719. }
  6720. h /= 6;
  6721. }
  6722. return [
  6723. Math.round(h * 360),
  6724. Math.round(s * 100),
  6725. Math.round(l * 100)
  6726. ];
  6727. },
  6728. /**
  6729. * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  6730. * @return {Array}
  6731. */
  6732. getSource: function() {
  6733. return this._source;
  6734. },
  6735. /**
  6736. * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  6737. * @param {Array} source
  6738. */
  6739. setSource: function(source) {
  6740. this._source = source;
  6741. },
  6742. /**
  6743. * Returns color representation in RGB format
  6744. * @return {String} ex: rgb(0-255,0-255,0-255)
  6745. */
  6746. toRgb: function() {
  6747. var source = this.getSource();
  6748. return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';
  6749. },
  6750. /**
  6751. * Returns color representation in RGBA format
  6752. * @return {String} ex: rgba(0-255,0-255,0-255,0-1)
  6753. */
  6754. toRgba: function() {
  6755. var source = this.getSource();
  6756. return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';
  6757. },
  6758. /**
  6759. * Returns color representation in HSL format
  6760. * @return {String} ex: hsl(0-360,0%-100%,0%-100%)
  6761. */
  6762. toHsl: function() {
  6763. var source = this.getSource(),
  6764. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  6765. return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';
  6766. },
  6767. /**
  6768. * Returns color representation in HSLA format
  6769. * @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)
  6770. */
  6771. toHsla: function() {
  6772. var source = this.getSource(),
  6773. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  6774. return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';
  6775. },
  6776. /**
  6777. * Returns color representation in HEX format
  6778. * @return {String} ex: FF5555
  6779. */
  6780. toHex: function() {
  6781. var source = this.getSource(), r, g, b;
  6782. r = source[0].toString(16);
  6783. r = (r.length === 1) ? ('0' + r) : r;
  6784. g = source[1].toString(16);
  6785. g = (g.length === 1) ? ('0' + g) : g;
  6786. b = source[2].toString(16);
  6787. b = (b.length === 1) ? ('0' + b) : b;
  6788. return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();
  6789. },
  6790. /**
  6791. * Returns color representation in HEXA format
  6792. * @return {String} ex: FF5555CC
  6793. */
  6794. toHexa: function() {
  6795. var source = this.getSource(), a;
  6796. a = Math.round(source[3] * 255);
  6797. a = a.toString(16);
  6798. a = (a.length === 1) ? ('0' + a) : a;
  6799. return this.toHex() + a.toUpperCase();
  6800. },
  6801. /**
  6802. * Gets value of alpha channel for this color
  6803. * @return {Number} 0-1
  6804. */
  6805. getAlpha: function() {
  6806. return this.getSource()[3];
  6807. },
  6808. /**
  6809. * Sets value of alpha channel for this color
  6810. * @param {Number} alpha Alpha value 0-1
  6811. * @return {fabric.Color} thisArg
  6812. */
  6813. setAlpha: function(alpha) {
  6814. var source = this.getSource();
  6815. source[3] = alpha;
  6816. this.setSource(source);
  6817. return this;
  6818. },
  6819. /**
  6820. * Transforms color to its grayscale representation
  6821. * @return {fabric.Color} thisArg
  6822. */
  6823. toGrayscale: function() {
  6824. var source = this.getSource(),
  6825. average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),
  6826. currentAlpha = source[3];
  6827. this.setSource([average, average, average, currentAlpha]);
  6828. return this;
  6829. },
  6830. /**
  6831. * Transforms color to its black and white representation
  6832. * @param {Number} threshold
  6833. * @return {fabric.Color} thisArg
  6834. */
  6835. toBlackWhite: function(threshold) {
  6836. var source = this.getSource(),
  6837. average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),
  6838. currentAlpha = source[3];
  6839. threshold = threshold || 127;
  6840. average = (Number(average) < Number(threshold)) ? 0 : 255;
  6841. this.setSource([average, average, average, currentAlpha]);
  6842. return this;
  6843. },
  6844. /**
  6845. * Overlays color with another color
  6846. * @param {String|fabric.Color} otherColor
  6847. * @return {fabric.Color} thisArg
  6848. */
  6849. overlayWith: function(otherColor) {
  6850. if (!(otherColor instanceof Color)) {
  6851. otherColor = new Color(otherColor);
  6852. }
  6853. var result = [],
  6854. alpha = this.getAlpha(),
  6855. otherAlpha = 0.5,
  6856. source = this.getSource(),
  6857. otherSource = otherColor.getSource(), i;
  6858. for (i = 0; i < 3; i++) {
  6859. result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));
  6860. }
  6861. result[3] = alpha;
  6862. this.setSource(result);
  6863. return this;
  6864. }
  6865. };
  6866. /**
  6867. * Regex matching color in RGB or RGBA formats (ex: rgb(0, 0, 0), rgba(255, 100, 10, 0.5), rgba( 255 , 100 , 10 , 0.5 ), rgb(1,1,1), rgba(100%, 60%, 10%, 0.5))
  6868. * @static
  6869. * @field
  6870. * @memberOf fabric.Color
  6871. */
  6872. // eslint-disable-next-line max-len
  6873. fabric.Color.reRGBa = /^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/i;
  6874. /**
  6875. * Regex matching color in HSL or HSLA formats (ex: hsl(200, 80%, 10%), hsla(300, 50%, 80%, 0.5), hsla( 300 , 50% , 80% , 0.5 ))
  6876. * @static
  6877. * @field
  6878. * @memberOf fabric.Color
  6879. */
  6880. fabric.Color.reHSLa = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/i;
  6881. /**
  6882. * Regex matching color in HEX format (ex: #FF5544CC, #FF5555, 010155, aff)
  6883. * @static
  6884. * @field
  6885. * @memberOf fabric.Color
  6886. */
  6887. fabric.Color.reHex = /^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i;
  6888. /**
  6889. * Map of the 148 color names with HEX code
  6890. * @static
  6891. * @field
  6892. * @memberOf fabric.Color
  6893. * @see: https://www.w3.org/TR/css3-color/#svg-color
  6894. */
  6895. fabric.Color.colorNameMap = {
  6896. aliceblue: '#F0F8FF',
  6897. antiquewhite: '#FAEBD7',
  6898. aqua: '#00FFFF',
  6899. aquamarine: '#7FFFD4',
  6900. azure: '#F0FFFF',
  6901. beige: '#F5F5DC',
  6902. bisque: '#FFE4C4',
  6903. black: '#000000',
  6904. blanchedalmond: '#FFEBCD',
  6905. blue: '#0000FF',
  6906. blueviolet: '#8A2BE2',
  6907. brown: '#A52A2A',
  6908. burlywood: '#DEB887',
  6909. cadetblue: '#5F9EA0',
  6910. chartreuse: '#7FFF00',
  6911. chocolate: '#D2691E',
  6912. coral: '#FF7F50',
  6913. cornflowerblue: '#6495ED',
  6914. cornsilk: '#FFF8DC',
  6915. crimson: '#DC143C',
  6916. cyan: '#00FFFF',
  6917. darkblue: '#00008B',
  6918. darkcyan: '#008B8B',
  6919. darkgoldenrod: '#B8860B',
  6920. darkgray: '#A9A9A9',
  6921. darkgrey: '#A9A9A9',
  6922. darkgreen: '#006400',
  6923. darkkhaki: '#BDB76B',
  6924. darkmagenta: '#8B008B',
  6925. darkolivegreen: '#556B2F',
  6926. darkorange: '#FF8C00',
  6927. darkorchid: '#9932CC',
  6928. darkred: '#8B0000',
  6929. darksalmon: '#E9967A',
  6930. darkseagreen: '#8FBC8F',
  6931. darkslateblue: '#483D8B',
  6932. darkslategray: '#2F4F4F',
  6933. darkslategrey: '#2F4F4F',
  6934. darkturquoise: '#00CED1',
  6935. darkviolet: '#9400D3',
  6936. deeppink: '#FF1493',
  6937. deepskyblue: '#00BFFF',
  6938. dimgray: '#696969',
  6939. dimgrey: '#696969',
  6940. dodgerblue: '#1E90FF',
  6941. firebrick: '#B22222',
  6942. floralwhite: '#FFFAF0',
  6943. forestgreen: '#228B22',
  6944. fuchsia: '#FF00FF',
  6945. gainsboro: '#DCDCDC',
  6946. ghostwhite: '#F8F8FF',
  6947. gold: '#FFD700',
  6948. goldenrod: '#DAA520',
  6949. gray: '#808080',
  6950. grey: '#808080',
  6951. green: '#008000',
  6952. greenyellow: '#ADFF2F',
  6953. honeydew: '#F0FFF0',
  6954. hotpink: '#FF69B4',
  6955. indianred: '#CD5C5C',
  6956. indigo: '#4B0082',
  6957. ivory: '#FFFFF0',
  6958. khaki: '#F0E68C',
  6959. lavender: '#E6E6FA',
  6960. lavenderblush: '#FFF0F5',
  6961. lawngreen: '#7CFC00',
  6962. lemonchiffon: '#FFFACD',
  6963. lightblue: '#ADD8E6',
  6964. lightcoral: '#F08080',
  6965. lightcyan: '#E0FFFF',
  6966. lightgoldenrodyellow: '#FAFAD2',
  6967. lightgray: '#D3D3D3',
  6968. lightgrey: '#D3D3D3',
  6969. lightgreen: '#90EE90',
  6970. lightpink: '#FFB6C1',
  6971. lightsalmon: '#FFA07A',
  6972. lightseagreen: '#20B2AA',
  6973. lightskyblue: '#87CEFA',
  6974. lightslategray: '#778899',
  6975. lightslategrey: '#778899',
  6976. lightsteelblue: '#B0C4DE',
  6977. lightyellow: '#FFFFE0',
  6978. lime: '#00FF00',
  6979. limegreen: '#32CD32',
  6980. linen: '#FAF0E6',
  6981. magenta: '#FF00FF',
  6982. maroon: '#800000',
  6983. mediumaquamarine: '#66CDAA',
  6984. mediumblue: '#0000CD',
  6985. mediumorchid: '#BA55D3',
  6986. mediumpurple: '#9370DB',
  6987. mediumseagreen: '#3CB371',
  6988. mediumslateblue: '#7B68EE',
  6989. mediumspringgreen: '#00FA9A',
  6990. mediumturquoise: '#48D1CC',
  6991. mediumvioletred: '#C71585',
  6992. midnightblue: '#191970',
  6993. mintcream: '#F5FFFA',
  6994. mistyrose: '#FFE4E1',
  6995. moccasin: '#FFE4B5',
  6996. navajowhite: '#FFDEAD',
  6997. navy: '#000080',
  6998. oldlace: '#FDF5E6',
  6999. olive: '#808000',
  7000. olivedrab: '#6B8E23',
  7001. orange: '#FFA500',
  7002. orangered: '#FF4500',
  7003. orchid: '#DA70D6',
  7004. palegoldenrod: '#EEE8AA',
  7005. palegreen: '#98FB98',
  7006. paleturquoise: '#AFEEEE',
  7007. palevioletred: '#DB7093',
  7008. papayawhip: '#FFEFD5',
  7009. peachpuff: '#FFDAB9',
  7010. peru: '#CD853F',
  7011. pink: '#FFC0CB',
  7012. plum: '#DDA0DD',
  7013. powderblue: '#B0E0E6',
  7014. purple: '#800080',
  7015. rebeccapurple: '#663399',
  7016. red: '#FF0000',
  7017. rosybrown: '#BC8F8F',
  7018. royalblue: '#4169E1',
  7019. saddlebrown: '#8B4513',
  7020. salmon: '#FA8072',
  7021. sandybrown: '#F4A460',
  7022. seagreen: '#2E8B57',
  7023. seashell: '#FFF5EE',
  7024. sienna: '#A0522D',
  7025. silver: '#C0C0C0',
  7026. skyblue: '#87CEEB',
  7027. slateblue: '#6A5ACD',
  7028. slategray: '#708090',
  7029. slategrey: '#708090',
  7030. snow: '#FFFAFA',
  7031. springgreen: '#00FF7F',
  7032. steelblue: '#4682B4',
  7033. tan: '#D2B48C',
  7034. teal: '#008080',
  7035. thistle: '#D8BFD8',
  7036. tomato: '#FF6347',
  7037. turquoise: '#40E0D0',
  7038. violet: '#EE82EE',
  7039. wheat: '#F5DEB3',
  7040. white: '#FFFFFF',
  7041. whitesmoke: '#F5F5F5',
  7042. yellow: '#FFFF00',
  7043. yellowgreen: '#9ACD32'
  7044. };
  7045. /**
  7046. * @private
  7047. * @param {Number} p
  7048. * @param {Number} q
  7049. * @param {Number} t
  7050. * @return {Number}
  7051. */
  7052. function hue2rgb(p, q, t) {
  7053. if (t < 0) {
  7054. t += 1;
  7055. }
  7056. if (t > 1) {
  7057. t -= 1;
  7058. }
  7059. if (t < 1 / 6) {
  7060. return p + (q - p) * 6 * t;
  7061. }
  7062. if (t < 1 / 2) {
  7063. return q;
  7064. }
  7065. if (t < 2 / 3) {
  7066. return p + (q - p) * (2 / 3 - t) * 6;
  7067. }
  7068. return p;
  7069. }
  7070. /**
  7071. * Returns new color object, when given a color in RGB format
  7072. * @memberOf fabric.Color
  7073. * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
  7074. * @return {fabric.Color}
  7075. */
  7076. fabric.Color.fromRgb = function(color) {
  7077. return Color.fromSource(Color.sourceFromRgb(color));
  7078. };
  7079. /**
  7080. * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
  7081. * @memberOf fabric.Color
  7082. * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
  7083. * @return {Array} source
  7084. */
  7085. fabric.Color.sourceFromRgb = function(color) {
  7086. var match = color.match(Color.reRGBa);
  7087. if (match) {
  7088. var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),
  7089. g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),
  7090. b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
  7091. return [
  7092. parseInt(r, 10),
  7093. parseInt(g, 10),
  7094. parseInt(b, 10),
  7095. match[4] ? parseFloat(match[4]) : 1
  7096. ];
  7097. }
  7098. };
  7099. /**
  7100. * Returns new color object, when given a color in RGBA format
  7101. * @static
  7102. * @function
  7103. * @memberOf fabric.Color
  7104. * @param {String} color
  7105. * @return {fabric.Color}
  7106. */
  7107. fabric.Color.fromRgba = Color.fromRgb;
  7108. /**
  7109. * Returns new color object, when given a color in HSL format
  7110. * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
  7111. * @memberOf fabric.Color
  7112. * @return {fabric.Color}
  7113. */
  7114. fabric.Color.fromHsl = function(color) {
  7115. return Color.fromSource(Color.sourceFromHsl(color));
  7116. };
  7117. /**
  7118. * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
  7119. * Adapted from <a href="https://rawgithub.com/mjijackson/mjijackson.github.com/master/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript.html">https://github.com/mjijackson</a>
  7120. * @memberOf fabric.Color
  7121. * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
  7122. * @return {Array} source
  7123. * @see http://http://www.w3.org/TR/css3-color/#hsl-color
  7124. */
  7125. fabric.Color.sourceFromHsl = function(color) {
  7126. var match = color.match(Color.reHSLa);
  7127. if (!match) {
  7128. return;
  7129. }
  7130. var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,
  7131. s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),
  7132. l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),
  7133. r, g, b;
  7134. if (s === 0) {
  7135. r = g = b = l;
  7136. }
  7137. else {
  7138. var q = l <= 0.5 ? l * (s + 1) : l + s - l * s,
  7139. p = l * 2 - q;
  7140. r = hue2rgb(p, q, h + 1 / 3);
  7141. g = hue2rgb(p, q, h);
  7142. b = hue2rgb(p, q, h - 1 / 3);
  7143. }
  7144. return [
  7145. Math.round(r * 255),
  7146. Math.round(g * 255),
  7147. Math.round(b * 255),
  7148. match[4] ? parseFloat(match[4]) : 1
  7149. ];
  7150. };
  7151. /**
  7152. * Returns new color object, when given a color in HSLA format
  7153. * @static
  7154. * @function
  7155. * @memberOf fabric.Color
  7156. * @param {String} color
  7157. * @return {fabric.Color}
  7158. */
  7159. fabric.Color.fromHsla = Color.fromHsl;
  7160. /**
  7161. * Returns new color object, when given a color in HEX format
  7162. * @static
  7163. * @memberOf fabric.Color
  7164. * @param {String} color Color value ex: FF5555
  7165. * @return {fabric.Color}
  7166. */
  7167. fabric.Color.fromHex = function(color) {
  7168. return Color.fromSource(Color.sourceFromHex(color));
  7169. };
  7170. /**
  7171. * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HEX format
  7172. * @static
  7173. * @memberOf fabric.Color
  7174. * @param {String} color ex: FF5555 or FF5544CC (RGBa)
  7175. * @return {Array} source
  7176. */
  7177. fabric.Color.sourceFromHex = function(color) {
  7178. if (color.match(Color.reHex)) {
  7179. var value = color.slice(color.indexOf('#') + 1),
  7180. isShortNotation = (value.length === 3 || value.length === 4),
  7181. isRGBa = (value.length === 8 || value.length === 4),
  7182. r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),
  7183. g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),
  7184. b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6),
  7185. a = isRGBa ? (isShortNotation ? (value.charAt(3) + value.charAt(3)) : value.substring(6, 8)) : 'FF';
  7186. return [
  7187. parseInt(r, 16),
  7188. parseInt(g, 16),
  7189. parseInt(b, 16),
  7190. parseFloat((parseInt(a, 16) / 255).toFixed(2))
  7191. ];
  7192. }
  7193. };
  7194. /**
  7195. * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
  7196. * @static
  7197. * @memberOf fabric.Color
  7198. * @param {Array} source
  7199. * @return {fabric.Color}
  7200. */
  7201. fabric.Color.fromSource = function(source) {
  7202. var oColor = new Color();
  7203. oColor.setSource(source);
  7204. return oColor;
  7205. };
  7206. })(typeof exports !== 'undefined' ? exports : this);
  7207. (function() {
  7208. var clone = fabric.util.object.clone;
  7209. /**
  7210. * Gradient class
  7211. * @class fabric.Gradient
  7212. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#gradients}
  7213. * @see {@link fabric.Gradient#initialize} for constructor definition
  7214. */
  7215. fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {
  7216. /**
  7217. * Horizontal offset for aligning gradients coming from SVG when outside pathgroups
  7218. * @type Number
  7219. * @default 0
  7220. */
  7221. offsetX: 0,
  7222. /**
  7223. * Vertical offset for aligning gradients coming from SVG when outside pathgroups
  7224. * @type Number
  7225. * @default 0
  7226. */
  7227. offsetY: 0,
  7228. /**
  7229. * Constructor
  7230. * @param {Object} [options] Options object with type, coords, gradientUnits and colorStops
  7231. * @return {fabric.Gradient} thisArg
  7232. */
  7233. initialize: function(options) {
  7234. options || (options = { });
  7235. var coords = { };
  7236. this.id = fabric.Object.__uid++;
  7237. this.type = options.type || 'linear';
  7238. coords = {
  7239. x1: options.coords.x1 || 0,
  7240. y1: options.coords.y1 || 0,
  7241. x2: options.coords.x2 || 0,
  7242. y2: options.coords.y2 || 0
  7243. };
  7244. if (this.type === 'radial') {
  7245. coords.r1 = options.coords.r1 || 0;
  7246. coords.r2 = options.coords.r2 || 0;
  7247. }
  7248. this.coords = coords;
  7249. this.colorStops = options.colorStops.slice();
  7250. if (options.gradientTransform) {
  7251. this.gradientTransform = options.gradientTransform;
  7252. }
  7253. this.offsetX = options.offsetX || this.offsetX;
  7254. this.offsetY = options.offsetY || this.offsetY;
  7255. },
  7256. /**
  7257. * Adds another colorStop
  7258. * @param {Object} colorStop Object with offset and color
  7259. * @return {fabric.Gradient} thisArg
  7260. */
  7261. addColorStop: function(colorStops) {
  7262. for (var position in colorStops) {
  7263. var color = new fabric.Color(colorStops[position]);
  7264. this.colorStops.push({
  7265. offset: parseFloat(position),
  7266. color: color.toRgb(),
  7267. opacity: color.getAlpha()
  7268. });
  7269. }
  7270. return this;
  7271. },
  7272. /**
  7273. * Returns object representation of a gradient
  7274. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  7275. * @return {Object}
  7276. */
  7277. toObject: function(propertiesToInclude) {
  7278. var object = {
  7279. type: this.type,
  7280. coords: this.coords,
  7281. colorStops: this.colorStops,
  7282. offsetX: this.offsetX,
  7283. offsetY: this.offsetY,
  7284. gradientTransform: this.gradientTransform ? this.gradientTransform.concat() : this.gradientTransform
  7285. };
  7286. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  7287. return object;
  7288. },
  7289. /**
  7290. * Returns an instance of CanvasGradient
  7291. * @param {CanvasRenderingContext2D} ctx Context to render on
  7292. * @return {CanvasGradient}
  7293. */
  7294. toLive: function(ctx) {
  7295. var gradient, coords = fabric.util.object.clone(this.coords), i, len;
  7296. if (!this.type) {
  7297. return;
  7298. }
  7299. if (this.type === 'linear') {
  7300. gradient = ctx.createLinearGradient(
  7301. coords.x1, coords.y1, coords.x2, coords.y2);
  7302. }
  7303. else if (this.type === 'radial') {
  7304. gradient = ctx.createRadialGradient(
  7305. coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);
  7306. }
  7307. for (i = 0, len = this.colorStops.length; i < len; i++) {
  7308. var color = this.colorStops[i].color,
  7309. opacity = this.colorStops[i].opacity,
  7310. offset = this.colorStops[i].offset;
  7311. if (typeof opacity !== 'undefined') {
  7312. color = new fabric.Color(color).setAlpha(opacity).toRgba();
  7313. }
  7314. gradient.addColorStop(offset, color);
  7315. }
  7316. return gradient;
  7317. }
  7318. });
  7319. fabric.util.object.extend(fabric.Gradient, {
  7320. /**
  7321. * Returns {@link fabric.Gradient} instance from its object representation
  7322. * @static
  7323. * @memberOf fabric.Gradient
  7324. * @param {Object} obj
  7325. * @param {Object} [options] Options object
  7326. */
  7327. forObject: function(obj, options) {
  7328. options || (options = { });
  7329. _convertPercentUnitsToValues(obj, options.coords, 'userSpaceOnUse');
  7330. return new fabric.Gradient(options);
  7331. }
  7332. });
  7333. /**
  7334. * @private
  7335. */
  7336. function _convertPercentUnitsToValues(object, options, gradientUnits) {
  7337. var propValue, addFactor = 0, multFactor = 1, ellipseMatrix = '';
  7338. for (var prop in options) {
  7339. if (options[prop] === 'Infinity') {
  7340. options[prop] = 1;
  7341. }
  7342. else if (options[prop] === '-Infinity') {
  7343. options[prop] = 0;
  7344. }
  7345. propValue = parseFloat(options[prop], 10);
  7346. if (typeof options[prop] === 'string' && /^(\d+\.\d+)%|(\d+)%$/.test(options[prop])) {
  7347. multFactor = 0.01;
  7348. }
  7349. else {
  7350. multFactor = 1;
  7351. }
  7352. if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
  7353. multFactor *= gradientUnits === 'objectBoundingBox' ? object.width : 1;
  7354. addFactor = gradientUnits === 'objectBoundingBox' ? object.left || 0 : 0;
  7355. }
  7356. else if (prop === 'y1' || prop === 'y2') {
  7357. multFactor *= gradientUnits === 'objectBoundingBox' ? object.height : 1;
  7358. addFactor = gradientUnits === 'objectBoundingBox' ? object.top || 0 : 0;
  7359. }
  7360. options[prop] = propValue * multFactor + addFactor;
  7361. }
  7362. if (object.type === 'ellipse' &&
  7363. options.r2 !== null &&
  7364. gradientUnits === 'objectBoundingBox' &&
  7365. object.rx !== object.ry) {
  7366. var scaleFactor = object.ry / object.rx;
  7367. ellipseMatrix = ' scale(1, ' + scaleFactor + ')';
  7368. if (options.y1) {
  7369. options.y1 /= scaleFactor;
  7370. }
  7371. if (options.y2) {
  7372. options.y2 /= scaleFactor;
  7373. }
  7374. }
  7375. return ellipseMatrix;
  7376. }
  7377. })();
  7378. (function() {
  7379. 'use strict';
  7380. var toFixed = fabric.util.toFixed;
  7381. /**
  7382. * Pattern class
  7383. * @class fabric.Pattern
  7384. * @see {@link http://fabricjs.com/patterns|Pattern demo}
  7385. * @see {@link http://fabricjs.com/dynamic-patterns|DynamicPattern demo}
  7386. * @see {@link fabric.Pattern#initialize} for constructor definition
  7387. */
  7388. fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {
  7389. /**
  7390. * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  7391. * @type String
  7392. * @default
  7393. */
  7394. repeat: 'repeat',
  7395. /**
  7396. * Pattern horizontal offset from object's left/top corner
  7397. * @type Number
  7398. * @default
  7399. */
  7400. offsetX: 0,
  7401. /**
  7402. * Pattern vertical offset from object's left/top corner
  7403. * @type Number
  7404. * @default
  7405. */
  7406. offsetY: 0,
  7407. /**
  7408. * crossOrigin value (one of "", "anonymous", "use-credentials")
  7409. * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
  7410. * @type String
  7411. * @default
  7412. */
  7413. crossOrigin: '',
  7414. /**
  7415. * transform matrix to change the pattern, imported from svgs.
  7416. * @type Array
  7417. * @default
  7418. */
  7419. patternTransform: null,
  7420. /**
  7421. * Constructor
  7422. * @param {Object} [options] Options object
  7423. * @param {Function} [callback] function to invoke after callback init.
  7424. * @return {fabric.Pattern} thisArg
  7425. */
  7426. initialize: function(options, callback) {
  7427. options || (options = { });
  7428. this.id = fabric.Object.__uid++;
  7429. this.setOptions(options);
  7430. if (!options.source || (options.source && typeof options.source !== 'string')) {
  7431. callback && callback(this);
  7432. return;
  7433. }
  7434. // function string
  7435. if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
  7436. this.source = new Function(fabric.util.getFunctionBody(options.source));
  7437. callback && callback(this);
  7438. }
  7439. else {
  7440. // img src string
  7441. var _this = this;
  7442. this.source = fabric.util.createImage();
  7443. fabric.util.loadImage(options.source, function(img) {
  7444. _this.source = img;
  7445. callback && callback(_this);
  7446. }, null, this.crossOrigin);
  7447. }
  7448. },
  7449. /**
  7450. * Returns object representation of a pattern
  7451. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  7452. * @return {Object} Object representation of a pattern instance
  7453. */
  7454. toObject: function(propertiesToInclude) {
  7455. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  7456. source, object;
  7457. // callback
  7458. if (typeof this.source === 'function') {
  7459. source = String(this.source);
  7460. }
  7461. // <img> element
  7462. else if (typeof this.source.src === 'string') {
  7463. source = this.source.src;
  7464. }
  7465. // <canvas> element
  7466. else if (typeof this.source === 'object' && this.source.toDataURL) {
  7467. source = this.source.toDataURL();
  7468. }
  7469. object = {
  7470. type: 'pattern',
  7471. source: source,
  7472. repeat: this.repeat,
  7473. crossOrigin: this.crossOrigin,
  7474. offsetX: toFixed(this.offsetX, NUM_FRACTION_DIGITS),
  7475. offsetY: toFixed(this.offsetY, NUM_FRACTION_DIGITS),
  7476. patternTransform: this.patternTransform ? this.patternTransform.concat() : null
  7477. };
  7478. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  7479. return object;
  7480. },
  7481. setOptions: function(options) {
  7482. for (var prop in options) {
  7483. this[prop] = options[prop];
  7484. }
  7485. },
  7486. /**
  7487. * Returns an instance of CanvasPattern
  7488. * @param {CanvasRenderingContext2D} ctx Context to create pattern
  7489. * @return {CanvasPattern}
  7490. */
  7491. toLive: function(ctx) {
  7492. var source = typeof this.source === 'function' ? this.source() : this.source;
  7493. // if the image failed to load, return, and allow rest to continue loading
  7494. if (!source) {
  7495. return '';
  7496. }
  7497. // if an image
  7498. if (typeof source.src !== 'undefined') {
  7499. if (!source.complete) {
  7500. return '';
  7501. }
  7502. if (source.naturalWidth === 0 || source.naturalHeight === 0) {
  7503. return '';
  7504. }
  7505. }
  7506. return ctx.createPattern(source, this.repeat);
  7507. }
  7508. });
  7509. })();
  7510. (function(global) {
  7511. 'use strict';
  7512. var fabric = global.fabric || (global.fabric = { }),
  7513. toFixed = fabric.util.toFixed;
  7514. if (fabric.Shadow) {
  7515. fabric.warn('fabric.Shadow is already defined.');
  7516. return;
  7517. }
  7518. /**
  7519. * Shadow class
  7520. * @class fabric.Shadow
  7521. * @see {@link http://fabricjs.com/shadows|Shadow demo}
  7522. * @see {@link fabric.Shadow#initialize} for constructor definition
  7523. */
  7524. fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {
  7525. /**
  7526. * Shadow color
  7527. * @type String
  7528. * @default
  7529. */
  7530. color: 'rgb(0,0,0)',
  7531. /**
  7532. * Shadow blur
  7533. * @type Number
  7534. */
  7535. blur: 0,
  7536. /**
  7537. * Shadow horizontal offset
  7538. * @type Number
  7539. * @default
  7540. */
  7541. offsetX: 0,
  7542. /**
  7543. * Shadow vertical offset
  7544. * @type Number
  7545. * @default
  7546. */
  7547. offsetY: 0,
  7548. /**
  7549. * Whether the shadow should affect stroke operations
  7550. * @type Boolean
  7551. * @default
  7552. */
  7553. affectStroke: false,
  7554. /**
  7555. * Indicates whether toObject should include default values
  7556. * @type Boolean
  7557. * @default
  7558. */
  7559. includeDefaultValues: true,
  7560. /**
  7561. * Constructor
  7562. * @param {Object|String} [options] Options object with any of color, blur, offsetX, offsetY properties or string (e.g. "rgba(0,0,0,0.2) 2px 2px 10px")
  7563. * @return {fabric.Shadow} thisArg
  7564. */
  7565. initialize: function(options) {
  7566. if (typeof options === 'string') {
  7567. options = this._parseShadow(options);
  7568. }
  7569. for (var prop in options) {
  7570. this[prop] = options[prop];
  7571. }
  7572. this.id = fabric.Object.__uid++;
  7573. },
  7574. /**
  7575. * @private
  7576. * @param {String} shadow Shadow value to parse
  7577. * @return {Object} Shadow object with color, offsetX, offsetY and blur
  7578. */
  7579. _parseShadow: function(shadow) {
  7580. var shadowStr = shadow.trim(),
  7581. offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [],
  7582. color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';
  7583. return {
  7584. color: color.trim(),
  7585. offsetX: parseInt(offsetsAndBlur[1], 10) || 0,
  7586. offsetY: parseInt(offsetsAndBlur[2], 10) || 0,
  7587. blur: parseInt(offsetsAndBlur[3], 10) || 0
  7588. };
  7589. },
  7590. /**
  7591. * Returns a string representation of an instance
  7592. * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
  7593. * @return {String} Returns CSS3 text-shadow declaration
  7594. */
  7595. toString: function() {
  7596. return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');
  7597. },
  7598. /**
  7599. * Returns object representation of a shadow
  7600. * @return {Object} Object representation of a shadow instance
  7601. */
  7602. toObject: function() {
  7603. if (this.includeDefaultValues) {
  7604. return {
  7605. color: this.color,
  7606. blur: this.blur,
  7607. offsetX: this.offsetX,
  7608. offsetY: this.offsetY,
  7609. affectStroke: this.affectStroke
  7610. };
  7611. }
  7612. var obj = { }, proto = fabric.Shadow.prototype;
  7613. ['color', 'blur', 'offsetX', 'offsetY', 'affectStroke'].forEach(function(prop) {
  7614. if (this[prop] !== proto[prop]) {
  7615. obj[prop] = this[prop];
  7616. }
  7617. }, this);
  7618. return obj;
  7619. }
  7620. });
  7621. /**
  7622. * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
  7623. * @static
  7624. * @field
  7625. * @memberOf fabric.Shadow
  7626. */
  7627. // eslint-disable-next-line max-len
  7628. fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/;
  7629. })(typeof exports !== 'undefined' ? exports : this);
  7630. (function () {
  7631. 'use strict';
  7632. if (fabric.StaticCanvas) {
  7633. fabric.warn('fabric.StaticCanvas is already defined.');
  7634. return;
  7635. }
  7636. // aliases for faster resolution
  7637. var extend = fabric.util.object.extend,
  7638. getElementOffset = fabric.util.getElementOffset,
  7639. removeFromArray = fabric.util.removeFromArray,
  7640. toFixed = fabric.util.toFixed,
  7641. transformPoint = fabric.util.transformPoint,
  7642. invertTransform = fabric.util.invertTransform,
  7643. CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');
  7644. /**
  7645. * Static canvas class
  7646. * @class fabric.StaticCanvas
  7647. * @mixes fabric.Collection
  7648. * @mixes fabric.Observable
  7649. * @see {@link http://fabricjs.com/static_canvas|StaticCanvas demo}
  7650. * @see {@link fabric.StaticCanvas#initialize} for constructor definition
  7651. * @fires before:render
  7652. * @fires after:render
  7653. * @fires canvas:cleared
  7654. * @fires object:added
  7655. * @fires object:removed
  7656. */
  7657. fabric.StaticCanvas = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.StaticCanvas.prototype */ {
  7658. /**
  7659. * Constructor
  7660. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  7661. * @param {Object} [options] Options object
  7662. * @return {Object} thisArg
  7663. */
  7664. initialize: function(el, options) {
  7665. options || (options = { });
  7666. this.renderAndResetBound = this.renderAndReset.bind(this);
  7667. this.requestRenderAllBound = this.requestRenderAll.bind(this);
  7668. this._initStatic(el, options);
  7669. },
  7670. /**
  7671. * Background color of canvas instance.
  7672. * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.
  7673. * @type {(String|fabric.Pattern)}
  7674. * @default
  7675. */
  7676. backgroundColor: '',
  7677. /**
  7678. * Background image of canvas instance.
  7679. * Should be set via {@link fabric.StaticCanvas#setBackgroundImage}.
  7680. * <b>Backwards incompatibility note:</b> The "backgroundImageOpacity"
  7681. * and "backgroundImageStretch" properties are deprecated since 1.3.9.
  7682. * Use {@link fabric.Image#opacity}, {@link fabric.Image#width} and {@link fabric.Image#height}.
  7683. * @type fabric.Image
  7684. * @default
  7685. */
  7686. backgroundImage: null,
  7687. /**
  7688. * Overlay color of canvas instance.
  7689. * Should be set via {@link fabric.StaticCanvas#setOverlayColor}
  7690. * @since 1.3.9
  7691. * @type {(String|fabric.Pattern)}
  7692. * @default
  7693. */
  7694. overlayColor: '',
  7695. /**
  7696. * Overlay image of canvas instance.
  7697. * Should be set via {@link fabric.StaticCanvas#setOverlayImage}.
  7698. * <b>Backwards incompatibility note:</b> The "overlayImageLeft"
  7699. * and "overlayImageTop" properties are deprecated since 1.3.9.
  7700. * Use {@link fabric.Image#left} and {@link fabric.Image#top}.
  7701. * @type fabric.Image
  7702. * @default
  7703. */
  7704. overlayImage: null,
  7705. /**
  7706. * Indicates whether toObject/toDatalessObject should include default values
  7707. * @type Boolean
  7708. * @default
  7709. */
  7710. includeDefaultValues: true,
  7711. /**
  7712. * Indicates whether objects' state should be saved
  7713. * @type Boolean
  7714. * @default
  7715. */
  7716. stateful: false,
  7717. /**
  7718. * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove},
  7719. * {@link fabric.StaticCanvas.moveTo}, {@link fabric.StaticCanvas.clear} and many more, should also re-render canvas.
  7720. * Disabling this option will not give a performance boost when adding/removing a lot of objects to/from canvas at once
  7721. * since the renders are quequed and executed one per frame.
  7722. * Disabling is suggested anyway and managing the renders of the app manually is not a big effort ( canvas.requestRenderAll() )
  7723. * Left default to true to do not break documentation and old app, fiddles.
  7724. * @type Boolean
  7725. * @default
  7726. */
  7727. renderOnAddRemove: true,
  7728. /**
  7729. * Function that determines clipping of entire canvas area
  7730. * Being passed context as first argument. See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ}
  7731. * @deprecated since 2.0.0
  7732. * @type Function
  7733. * @default
  7734. */
  7735. clipTo: null,
  7736. /**
  7737. * Indicates whether object controls (borders/controls) are rendered above overlay image
  7738. * @type Boolean
  7739. * @default
  7740. */
  7741. controlsAboveOverlay: false,
  7742. /**
  7743. * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
  7744. * @type Boolean
  7745. * @default
  7746. */
  7747. allowTouchScrolling: false,
  7748. /**
  7749. * Indicates whether this canvas will use image smoothing, this is on by default in browsers
  7750. * @type Boolean
  7751. * @default
  7752. */
  7753. imageSmoothingEnabled: true,
  7754. /**
  7755. * The transformation (in the format of Canvas transform) which focuses the viewport
  7756. * @type Array
  7757. * @default
  7758. */
  7759. viewportTransform: fabric.iMatrix.concat(),
  7760. /**
  7761. * if set to false background image is not affected by viewport transform
  7762. * @since 1.6.3
  7763. * @type Boolean
  7764. * @default
  7765. */
  7766. backgroundVpt: true,
  7767. /**
  7768. * if set to false overlya image is not affected by viewport transform
  7769. * @since 1.6.3
  7770. * @type Boolean
  7771. * @default
  7772. */
  7773. overlayVpt: true,
  7774. /**
  7775. * Callback; invoked right before object is about to be scaled/rotated
  7776. * @deprecated since 2.3.0
  7777. * Use before:transform event
  7778. */
  7779. onBeforeScaleRotate: function () {
  7780. /* NOOP */
  7781. },
  7782. /**
  7783. * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens
  7784. * @type Boolean
  7785. * @default
  7786. */
  7787. enableRetinaScaling: true,
  7788. /**
  7789. * Describe canvas element extension over design
  7790. * properties are tl,tr,bl,br.
  7791. * if canvas is not zoomed/panned those points are the four corner of canvas
  7792. * if canvas is viewportTransformed you those points indicate the extension
  7793. * of canvas element in plain untrasformed coordinates
  7794. * The coordinates get updated with @method calcViewportBoundaries.
  7795. * @memberOf fabric.StaticCanvas.prototype
  7796. */
  7797. vptCoords: { },
  7798. /**
  7799. * Based on vptCoords and object.aCoords, skip rendering of objects that
  7800. * are not included in current viewport.
  7801. * May greatly help in applications with crowded canvas and use of zoom/pan
  7802. * If One of the corner of the bounding box of the object is on the canvas
  7803. * the objects get rendered.
  7804. * @memberOf fabric.StaticCanvas.prototype
  7805. * @type Boolean
  7806. * @default
  7807. */
  7808. skipOffscreen: true,
  7809. /**
  7810. * @private
  7811. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  7812. * @param {Object} [options] Options object
  7813. */
  7814. _initStatic: function(el, options) {
  7815. var cb = this.requestRenderAllBound;
  7816. this._objects = [];
  7817. this._createLowerCanvas(el);
  7818. this._initOptions(options);
  7819. this._setImageSmoothing();
  7820. // only initialize retina scaling once
  7821. if (!this.interactive) {
  7822. this._initRetinaScaling();
  7823. }
  7824. if (options.overlayImage) {
  7825. this.setOverlayImage(options.overlayImage, cb);
  7826. }
  7827. if (options.backgroundImage) {
  7828. this.setBackgroundImage(options.backgroundImage, cb);
  7829. }
  7830. if (options.backgroundColor) {
  7831. this.setBackgroundColor(options.backgroundColor, cb);
  7832. }
  7833. if (options.overlayColor) {
  7834. this.setOverlayColor(options.overlayColor, cb);
  7835. }
  7836. this.calcOffset();
  7837. },
  7838. /**
  7839. * @private
  7840. */
  7841. _isRetinaScaling: function() {
  7842. return (fabric.devicePixelRatio !== 1 && this.enableRetinaScaling);
  7843. },
  7844. /**
  7845. * @private
  7846. * @return {Number} retinaScaling if applied, otherwise 1;
  7847. */
  7848. getRetinaScaling: function() {
  7849. return this._isRetinaScaling() ? fabric.devicePixelRatio : 1;
  7850. },
  7851. /**
  7852. * @private
  7853. */
  7854. _initRetinaScaling: function() {
  7855. if (!this._isRetinaScaling()) {
  7856. return;
  7857. }
  7858. this.lowerCanvasEl.setAttribute('width', this.width * fabric.devicePixelRatio);
  7859. this.lowerCanvasEl.setAttribute('height', this.height * fabric.devicePixelRatio);
  7860. this.contextContainer.scale(fabric.devicePixelRatio, fabric.devicePixelRatio);
  7861. },
  7862. /**
  7863. * Calculates canvas element offset relative to the document
  7864. * This method is also attached as "resize" event handler of window
  7865. * @return {fabric.Canvas} instance
  7866. * @chainable
  7867. */
  7868. calcOffset: function () {
  7869. this._offset = getElementOffset(this.lowerCanvasEl);
  7870. return this;
  7871. },
  7872. /**
  7873. * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
  7874. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to
  7875. * @param {Function} callback callback to invoke when image is loaded and set as an overlay
  7876. * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.
  7877. * @return {fabric.Canvas} thisArg
  7878. * @chainable
  7879. * @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}
  7880. * @example <caption>Normal overlayImage with left/top = 0</caption>
  7881. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  7882. * // Needed to position overlayImage at 0/0
  7883. * originX: 'left',
  7884. * originY: 'top'
  7885. * });
  7886. * @example <caption>overlayImage with different properties</caption>
  7887. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  7888. * opacity: 0.5,
  7889. * angle: 45,
  7890. * left: 400,
  7891. * top: 400,
  7892. * originX: 'left',
  7893. * originY: 'top'
  7894. * });
  7895. * @example <caption>Stretched overlayImage #1 - width/height correspond to canvas width/height</caption>
  7896. * fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img) {
  7897. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  7898. * canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));
  7899. * });
  7900. * @example <caption>Stretched overlayImage #2 - width/height correspond to canvas width/height</caption>
  7901. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  7902. * width: canvas.width,
  7903. * height: canvas.height,
  7904. * // Needed to position overlayImage at 0/0
  7905. * originX: 'left',
  7906. * originY: 'top'
  7907. * });
  7908. * @example <caption>overlayImage loaded from cross-origin</caption>
  7909. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  7910. * opacity: 0.5,
  7911. * angle: 45,
  7912. * left: 400,
  7913. * top: 400,
  7914. * originX: 'left',
  7915. * originY: 'top',
  7916. * crossOrigin: 'anonymous'
  7917. * });
  7918. */
  7919. setOverlayImage: function (image, callback, options) {
  7920. return this.__setBgOverlayImage('overlayImage', image, callback, options);
  7921. },
  7922. /**
  7923. * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
  7924. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to
  7925. * @param {Function} callback Callback to invoke when image is loaded and set as background
  7926. * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.
  7927. * @return {fabric.Canvas} thisArg
  7928. * @chainable
  7929. * @see {@link http://jsfiddle.net/djnr8o7a/28/|jsFiddle demo}
  7930. * @example <caption>Normal backgroundImage with left/top = 0</caption>
  7931. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  7932. * // Needed to position backgroundImage at 0/0
  7933. * originX: 'left',
  7934. * originY: 'top'
  7935. * });
  7936. * @example <caption>backgroundImage with different properties</caption>
  7937. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  7938. * opacity: 0.5,
  7939. * angle: 45,
  7940. * left: 400,
  7941. * top: 400,
  7942. * originX: 'left',
  7943. * originY: 'top'
  7944. * });
  7945. * @example <caption>Stretched backgroundImage #1 - width/height correspond to canvas width/height</caption>
  7946. * fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img) {
  7947. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  7948. * canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
  7949. * });
  7950. * @example <caption>Stretched backgroundImage #2 - width/height correspond to canvas width/height</caption>
  7951. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  7952. * width: canvas.width,
  7953. * height: canvas.height,
  7954. * // Needed to position backgroundImage at 0/0
  7955. * originX: 'left',
  7956. * originY: 'top'
  7957. * });
  7958. * @example <caption>backgroundImage loaded from cross-origin</caption>
  7959. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  7960. * opacity: 0.5,
  7961. * angle: 45,
  7962. * left: 400,
  7963. * top: 400,
  7964. * originX: 'left',
  7965. * originY: 'top',
  7966. * crossOrigin: 'anonymous'
  7967. * });
  7968. */
  7969. setBackgroundImage: function (image, callback, options) {
  7970. return this.__setBgOverlayImage('backgroundImage', image, callback, options);
  7971. },
  7972. /**
  7973. * Sets {@link fabric.StaticCanvas#overlayColor|foreground color} for this canvas
  7974. * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set foreground color to
  7975. * @param {Function} callback Callback to invoke when foreground color is set
  7976. * @return {fabric.Canvas} thisArg
  7977. * @chainable
  7978. * @see {@link http://jsfiddle.net/fabricjs/pB55h/|jsFiddle demo}
  7979. * @example <caption>Normal overlayColor - color value</caption>
  7980. * canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  7981. * @example <caption>fabric.Pattern used as overlayColor</caption>
  7982. * canvas.setOverlayColor({
  7983. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  7984. * }, canvas.renderAll.bind(canvas));
  7985. * @example <caption>fabric.Pattern used as overlayColor with repeat and offset</caption>
  7986. * canvas.setOverlayColor({
  7987. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  7988. * repeat: 'repeat',
  7989. * offsetX: 200,
  7990. * offsetY: 100
  7991. * }, canvas.renderAll.bind(canvas));
  7992. */
  7993. setOverlayColor: function(overlayColor, callback) {
  7994. return this.__setBgOverlayColor('overlayColor', overlayColor, callback);
  7995. },
  7996. /**
  7997. * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas
  7998. * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to
  7999. * @param {Function} callback Callback to invoke when background color is set
  8000. * @return {fabric.Canvas} thisArg
  8001. * @chainable
  8002. * @see {@link http://jsfiddle.net/fabricjs/hXzvk/|jsFiddle demo}
  8003. * @example <caption>Normal backgroundColor - color value</caption>
  8004. * canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  8005. * @example <caption>fabric.Pattern used as backgroundColor</caption>
  8006. * canvas.setBackgroundColor({
  8007. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  8008. * }, canvas.renderAll.bind(canvas));
  8009. * @example <caption>fabric.Pattern used as backgroundColor with repeat and offset</caption>
  8010. * canvas.setBackgroundColor({
  8011. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  8012. * repeat: 'repeat',
  8013. * offsetX: 200,
  8014. * offsetY: 100
  8015. * }, canvas.renderAll.bind(canvas));
  8016. */
  8017. setBackgroundColor: function(backgroundColor, callback) {
  8018. return this.__setBgOverlayColor('backgroundColor', backgroundColor, callback);
  8019. },
  8020. /**
  8021. * @private
  8022. * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled|WhatWG Canvas Standard}
  8023. */
  8024. _setImageSmoothing: function() {
  8025. var ctx = this.getContext();
  8026. ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled || ctx.webkitImageSmoothingEnabled
  8027. || ctx.mozImageSmoothingEnabled || ctx.msImageSmoothingEnabled || ctx.oImageSmoothingEnabled;
  8028. ctx.imageSmoothingEnabled = this.imageSmoothingEnabled;
  8029. },
  8030. /**
  8031. * @private
  8032. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundImage|backgroundImage}
  8033. * or {@link fabric.StaticCanvas#overlayImage|overlayImage})
  8034. * @param {(fabric.Image|String|null)} image fabric.Image instance, URL of an image or null to set background or overlay to
  8035. * @param {Function} callback Callback to invoke when image is loaded and set as background or overlay
  8036. * @param {Object} [options] Optional options to set for the {@link fabric.Image|image}.
  8037. */
  8038. __setBgOverlayImage: function(property, image, callback, options) {
  8039. if (typeof image === 'string') {
  8040. fabric.util.loadImage(image, function(img) {
  8041. img && (this[property] = new fabric.Image(img, options));
  8042. callback && callback(img);
  8043. }, this, options && options.crossOrigin);
  8044. }
  8045. else {
  8046. options && image.setOptions(options);
  8047. this[property] = image;
  8048. callback && callback(image);
  8049. }
  8050. return this;
  8051. },
  8052. /**
  8053. * @private
  8054. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundColor|backgroundColor}
  8055. * or {@link fabric.StaticCanvas#overlayColor|overlayColor})
  8056. * @param {(Object|String|null)} color Object with pattern information, color value or null
  8057. * @param {Function} [callback] Callback is invoked when color is set
  8058. */
  8059. __setBgOverlayColor: function(property, color, callback) {
  8060. this[property] = color;
  8061. this._initGradient(color, property);
  8062. this._initPattern(color, property, callback);
  8063. return this;
  8064. },
  8065. /**
  8066. * @private
  8067. */
  8068. _createCanvasElement: function() {
  8069. var element = fabric.util.createCanvasElement();
  8070. if (!element) {
  8071. throw CANVAS_INIT_ERROR;
  8072. }
  8073. if (!element.style) {
  8074. element.style = { };
  8075. }
  8076. if (typeof element.getContext === 'undefined') {
  8077. throw CANVAS_INIT_ERROR;
  8078. }
  8079. return element;
  8080. },
  8081. /**
  8082. * @private
  8083. * @param {Object} [options] Options object
  8084. */
  8085. _initOptions: function (options) {
  8086. this._setOptions(options);
  8087. this.width = this.width || parseInt(this.lowerCanvasEl.width, 10) || 0;
  8088. this.height = this.height || parseInt(this.lowerCanvasEl.height, 10) || 0;
  8089. if (!this.lowerCanvasEl.style) {
  8090. return;
  8091. }
  8092. this.lowerCanvasEl.width = this.width;
  8093. this.lowerCanvasEl.height = this.height;
  8094. this.lowerCanvasEl.style.width = this.width + 'px';
  8095. this.lowerCanvasEl.style.height = this.height + 'px';
  8096. this.viewportTransform = this.viewportTransform.slice();
  8097. },
  8098. /**
  8099. * Creates a bottom canvas
  8100. * @private
  8101. * @param {HTMLElement} [canvasEl]
  8102. */
  8103. _createLowerCanvas: function (canvasEl) {
  8104. // canvasEl === 'HTMLCanvasElement' does not work on jsdom/node
  8105. if (canvasEl && canvasEl.getContext) {
  8106. this.lowerCanvasEl = canvasEl;
  8107. }
  8108. else {
  8109. this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();
  8110. }
  8111. fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');
  8112. if (this.interactive) {
  8113. this._applyCanvasStyle(this.lowerCanvasEl);
  8114. }
  8115. this.contextContainer = this.lowerCanvasEl.getContext('2d');
  8116. },
  8117. /**
  8118. * Returns canvas width (in px)
  8119. * @return {Number}
  8120. */
  8121. getWidth: function () {
  8122. return this.width;
  8123. },
  8124. /**
  8125. * Returns canvas height (in px)
  8126. * @return {Number}
  8127. */
  8128. getHeight: function () {
  8129. return this.height;
  8130. },
  8131. /**
  8132. * Sets width of this canvas instance
  8133. * @param {Number|String} value Value to set width to
  8134. * @param {Object} [options] Options object
  8135. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  8136. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  8137. * @return {fabric.Canvas} instance
  8138. * @chainable true
  8139. */
  8140. setWidth: function (value, options) {
  8141. return this.setDimensions({ width: value }, options);
  8142. },
  8143. /**
  8144. * Sets height of this canvas instance
  8145. * @param {Number|String} value Value to set height to
  8146. * @param {Object} [options] Options object
  8147. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  8148. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  8149. * @return {fabric.Canvas} instance
  8150. * @chainable true
  8151. */
  8152. setHeight: function (value, options) {
  8153. return this.setDimensions({ height: value }, options);
  8154. },
  8155. /**
  8156. * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
  8157. * @param {Object} dimensions Object with width/height properties
  8158. * @param {Number|String} [dimensions.width] Width of canvas element
  8159. * @param {Number|String} [dimensions.height] Height of canvas element
  8160. * @param {Object} [options] Options object
  8161. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  8162. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  8163. * @return {fabric.Canvas} thisArg
  8164. * @chainable
  8165. */
  8166. setDimensions: function (dimensions, options) {
  8167. var cssValue;
  8168. options = options || {};
  8169. for (var prop in dimensions) {
  8170. cssValue = dimensions[prop];
  8171. if (!options.cssOnly) {
  8172. this._setBackstoreDimension(prop, dimensions[prop]);
  8173. cssValue += 'px';
  8174. this.hasLostContext = true;
  8175. }
  8176. if (!options.backstoreOnly) {
  8177. this._setCssDimension(prop, cssValue);
  8178. }
  8179. }
  8180. if (this._isCurrentlyDrawing) {
  8181. this.freeDrawingBrush && this.freeDrawingBrush._setBrushStyles();
  8182. }
  8183. this._initRetinaScaling();
  8184. this._setImageSmoothing();
  8185. this.calcOffset();
  8186. if (!options.cssOnly) {
  8187. this.requestRenderAll();
  8188. }
  8189. return this;
  8190. },
  8191. /**
  8192. * Helper for setting width/height
  8193. * @private
  8194. * @param {String} prop property (width|height)
  8195. * @param {Number} value value to set property to
  8196. * @return {fabric.Canvas} instance
  8197. * @chainable true
  8198. */
  8199. _setBackstoreDimension: function (prop, value) {
  8200. this.lowerCanvasEl[prop] = value;
  8201. if (this.upperCanvasEl) {
  8202. this.upperCanvasEl[prop] = value;
  8203. }
  8204. if (this.cacheCanvasEl) {
  8205. this.cacheCanvasEl[prop] = value;
  8206. }
  8207. this[prop] = value;
  8208. return this;
  8209. },
  8210. /**
  8211. * Helper for setting css width/height
  8212. * @private
  8213. * @param {String} prop property (width|height)
  8214. * @param {String} value value to set property to
  8215. * @return {fabric.Canvas} instance
  8216. * @chainable true
  8217. */
  8218. _setCssDimension: function (prop, value) {
  8219. this.lowerCanvasEl.style[prop] = value;
  8220. if (this.upperCanvasEl) {
  8221. this.upperCanvasEl.style[prop] = value;
  8222. }
  8223. if (this.wrapperEl) {
  8224. this.wrapperEl.style[prop] = value;
  8225. }
  8226. return this;
  8227. },
  8228. /**
  8229. * Returns canvas zoom level
  8230. * @return {Number}
  8231. */
  8232. getZoom: function () {
  8233. return this.viewportTransform[0];
  8234. },
  8235. /**
  8236. * Sets viewport transform of this canvas instance
  8237. * @param {Array} vpt the transform in the form of context.transform
  8238. * @return {fabric.Canvas} instance
  8239. * @chainable true
  8240. */
  8241. setViewportTransform: function (vpt) {
  8242. var activeObject = this._activeObject, object, ignoreVpt = false, skipAbsolute = true, i, len;
  8243. this.viewportTransform = vpt;
  8244. for (i = 0, len = this._objects.length; i < len; i++) {
  8245. object = this._objects[i];
  8246. object.group || object.setCoords(ignoreVpt, skipAbsolute);
  8247. }
  8248. if (activeObject && activeObject.type === 'activeSelection') {
  8249. activeObject.setCoords(ignoreVpt, skipAbsolute);
  8250. }
  8251. this.calcViewportBoundaries();
  8252. this.renderOnAddRemove && this.requestRenderAll();
  8253. return this;
  8254. },
  8255. /**
  8256. * Sets zoom level of this canvas instance, zoom centered around point
  8257. * @param {fabric.Point} point to zoom with respect to
  8258. * @param {Number} value to set zoom to, less than 1 zooms out
  8259. * @return {fabric.Canvas} instance
  8260. * @chainable true
  8261. */
  8262. zoomToPoint: function (point, value) {
  8263. // TODO: just change the scale, preserve other transformations
  8264. var before = point, vpt = this.viewportTransform.slice(0);
  8265. point = transformPoint(point, invertTransform(this.viewportTransform));
  8266. vpt[0] = value;
  8267. vpt[3] = value;
  8268. var after = transformPoint(point, vpt);
  8269. vpt[4] += before.x - after.x;
  8270. vpt[5] += before.y - after.y;
  8271. return this.setViewportTransform(vpt);
  8272. },
  8273. /**
  8274. * Sets zoom level of this canvas instance
  8275. * @param {Number} value to set zoom to, less than 1 zooms out
  8276. * @return {fabric.Canvas} instance
  8277. * @chainable true
  8278. */
  8279. setZoom: function (value) {
  8280. this.zoomToPoint(new fabric.Point(0, 0), value);
  8281. return this;
  8282. },
  8283. /**
  8284. * Pan viewport so as to place point at top left corner of canvas
  8285. * @param {fabric.Point} point to move to
  8286. * @return {fabric.Canvas} instance
  8287. * @chainable true
  8288. */
  8289. absolutePan: function (point) {
  8290. var vpt = this.viewportTransform.slice(0);
  8291. vpt[4] = -point.x;
  8292. vpt[5] = -point.y;
  8293. return this.setViewportTransform(vpt);
  8294. },
  8295. /**
  8296. * Pans viewpoint relatively
  8297. * @param {fabric.Point} point (position vector) to move by
  8298. * @return {fabric.Canvas} instance
  8299. * @chainable true
  8300. */
  8301. relativePan: function (point) {
  8302. return this.absolutePan(new fabric.Point(
  8303. -point.x - this.viewportTransform[4],
  8304. -point.y - this.viewportTransform[5]
  8305. ));
  8306. },
  8307. /**
  8308. * Returns &lt;canvas> element corresponding to this instance
  8309. * @return {HTMLCanvasElement}
  8310. */
  8311. getElement: function () {
  8312. return this.lowerCanvasEl;
  8313. },
  8314. /**
  8315. * @private
  8316. * @param {fabric.Object} obj Object that was added
  8317. */
  8318. _onObjectAdded: function(obj) {
  8319. this.stateful && obj.setupState();
  8320. obj._set('canvas', this);
  8321. obj.setCoords();
  8322. this.fire('object:added', { target: obj });
  8323. obj.fire('added');
  8324. },
  8325. /**
  8326. * @private
  8327. * @param {fabric.Object} obj Object that was removed
  8328. */
  8329. _onObjectRemoved: function(obj) {
  8330. this.fire('object:removed', { target: obj });
  8331. obj.fire('removed');
  8332. delete obj.canvas;
  8333. },
  8334. /**
  8335. * Clears specified context of canvas element
  8336. * @param {CanvasRenderingContext2D} ctx Context to clear
  8337. * @return {fabric.Canvas} thisArg
  8338. * @chainable
  8339. */
  8340. clearContext: function(ctx) {
  8341. ctx.clearRect(0, 0, this.width, this.height);
  8342. return this;
  8343. },
  8344. /**
  8345. * Returns context of canvas where objects are drawn
  8346. * @return {CanvasRenderingContext2D}
  8347. */
  8348. getContext: function () {
  8349. return this.contextContainer;
  8350. },
  8351. /**
  8352. * Clears all contexts (background, main, top) of an instance
  8353. * @return {fabric.Canvas} thisArg
  8354. * @chainable
  8355. */
  8356. clear: function () {
  8357. this._objects.length = 0;
  8358. this.backgroundImage = null;
  8359. this.overlayImage = null;
  8360. this.backgroundColor = '';
  8361. this.overlayColor = '';
  8362. if (this._hasITextHandlers) {
  8363. this.off('mouse:up', this._mouseUpITextHandler);
  8364. this._iTextInstances = null;
  8365. this._hasITextHandlers = false;
  8366. }
  8367. this.clearContext(this.contextContainer);
  8368. this.fire('canvas:cleared');
  8369. this.renderOnAddRemove && this.requestRenderAll();
  8370. return this;
  8371. },
  8372. /**
  8373. * Renders the canvas
  8374. * @return {fabric.Canvas} instance
  8375. * @chainable
  8376. */
  8377. renderAll: function () {
  8378. var canvasToDrawOn = this.contextContainer;
  8379. this.renderCanvas(canvasToDrawOn, this._objects);
  8380. return this;
  8381. },
  8382. /**
  8383. * Function created to be instance bound at initialization
  8384. * used in requestAnimationFrame rendering
  8385. * @return {fabric.Canvas} instance
  8386. * @chainable
  8387. */
  8388. renderAndReset: function() {
  8389. this.isRendering = 0;
  8390. this.renderAll();
  8391. },
  8392. /**
  8393. * Append a renderAll request to next animation frame.
  8394. * a boolean flag will avoid appending more.
  8395. * @return {fabric.Canvas} instance
  8396. * @chainable
  8397. */
  8398. requestRenderAll: function () {
  8399. if (!this.isRendering) {
  8400. this.isRendering = fabric.util.requestAnimFrame(this.renderAndResetBound);
  8401. }
  8402. return this;
  8403. },
  8404. /**
  8405. * Calculate the position of the 4 corner of canvas with current viewportTransform.
  8406. * helps to determinate when an object is in the current rendering viewport using
  8407. * object absolute coordinates ( aCoords )
  8408. * @return {Object} points.tl
  8409. * @chainable
  8410. */
  8411. calcViewportBoundaries: function() {
  8412. var points = { }, width = this.width, height = this.height,
  8413. iVpt = invertTransform(this.viewportTransform);
  8414. points.tl = transformPoint({ x: 0, y: 0 }, iVpt);
  8415. points.br = transformPoint({ x: width, y: height }, iVpt);
  8416. points.tr = new fabric.Point(points.br.x, points.tl.y);
  8417. points.bl = new fabric.Point(points.tl.x, points.br.y);
  8418. this.vptCoords = points;
  8419. return points;
  8420. },
  8421. /**
  8422. * Renders background, objects, overlay and controls.
  8423. * @param {CanvasRenderingContext2D} ctx
  8424. * @param {Array} objects to render
  8425. * @return {fabric.Canvas} instance
  8426. * @chainable
  8427. */
  8428. renderCanvas: function(ctx, objects) {
  8429. var v = this.viewportTransform;
  8430. if (this.isRendering) {
  8431. fabric.util.cancelAnimFrame(this.isRendering);
  8432. this.isRendering = 0;
  8433. }
  8434. this.calcViewportBoundaries();
  8435. this.clearContext(ctx);
  8436. this.fire('before:render');
  8437. if (this.clipTo) {
  8438. fabric.util.clipContext(this, ctx);
  8439. }
  8440. this._renderBackground(ctx);
  8441. ctx.save();
  8442. //apply viewport transform once for all rendering process
  8443. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  8444. this._renderObjects(ctx, objects);
  8445. ctx.restore();
  8446. if (!this.controlsAboveOverlay && this.interactive) {
  8447. this.drawControls(ctx);
  8448. }
  8449. if (this.clipTo) {
  8450. ctx.restore();
  8451. }
  8452. this._renderOverlay(ctx);
  8453. if (this.controlsAboveOverlay && this.interactive) {
  8454. this.drawControls(ctx);
  8455. }
  8456. this.fire('after:render');
  8457. },
  8458. /**
  8459. * @private
  8460. * @param {CanvasRenderingContext2D} ctx Context to render on
  8461. * @param {Array} objects to render
  8462. */
  8463. _renderObjects: function(ctx, objects) {
  8464. var i, len;
  8465. for (i = 0, len = objects.length; i < len; ++i) {
  8466. objects[i] && objects[i].render(ctx);
  8467. }
  8468. },
  8469. /**
  8470. * @private
  8471. * @param {CanvasRenderingContext2D} ctx Context to render on
  8472. * @param {string} property 'background' or 'overlay'
  8473. */
  8474. _renderBackgroundOrOverlay: function(ctx, property) {
  8475. var object = this[property + 'Color'], v;
  8476. if (object) {
  8477. ctx.fillStyle = object.toLive
  8478. ? object.toLive(ctx, this)
  8479. : object;
  8480. ctx.fillRect(
  8481. object.offsetX || 0,
  8482. object.offsetY || 0,
  8483. this.width,
  8484. this.height);
  8485. }
  8486. object = this[property + 'Image'];
  8487. if (object) {
  8488. if (this[property + 'Vpt']) {
  8489. v = this.viewportTransform;
  8490. ctx.save();
  8491. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  8492. }
  8493. object.render(ctx);
  8494. this[property + 'Vpt'] && ctx.restore();
  8495. }
  8496. },
  8497. /**
  8498. * @private
  8499. * @param {CanvasRenderingContext2D} ctx Context to render on
  8500. */
  8501. _renderBackground: function(ctx) {
  8502. this._renderBackgroundOrOverlay(ctx, 'background');
  8503. },
  8504. /**
  8505. * @private
  8506. * @param {CanvasRenderingContext2D} ctx Context to render on
  8507. */
  8508. _renderOverlay: function(ctx) {
  8509. this._renderBackgroundOrOverlay(ctx, 'overlay');
  8510. },
  8511. /**
  8512. * Returns coordinates of a center of canvas.
  8513. * Returned value is an object with top and left properties
  8514. * @return {Object} object with "top" and "left" number values
  8515. */
  8516. getCenter: function () {
  8517. return {
  8518. top: this.height / 2,
  8519. left: this.width / 2
  8520. };
  8521. },
  8522. /**
  8523. * Centers object horizontally in the canvas
  8524. * @param {fabric.Object} object Object to center horizontally
  8525. * @return {fabric.Canvas} thisArg
  8526. */
  8527. centerObjectH: function (object) {
  8528. return this._centerObject(object, new fabric.Point(this.getCenter().left, object.getCenterPoint().y));
  8529. },
  8530. /**
  8531. * Centers object vertically in the canvas
  8532. * @param {fabric.Object} object Object to center vertically
  8533. * @return {fabric.Canvas} thisArg
  8534. * @chainable
  8535. */
  8536. centerObjectV: function (object) {
  8537. return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, this.getCenter().top));
  8538. },
  8539. /**
  8540. * Centers object vertically and horizontally in the canvas
  8541. * @param {fabric.Object} object Object to center vertically and horizontally
  8542. * @return {fabric.Canvas} thisArg
  8543. * @chainable
  8544. */
  8545. centerObject: function(object) {
  8546. var center = this.getCenter();
  8547. return this._centerObject(object, new fabric.Point(center.left, center.top));
  8548. },
  8549. /**
  8550. * Centers object vertically and horizontally in the viewport
  8551. * @param {fabric.Object} object Object to center vertically and horizontally
  8552. * @return {fabric.Canvas} thisArg
  8553. * @chainable
  8554. */
  8555. viewportCenterObject: function(object) {
  8556. var vpCenter = this.getVpCenter();
  8557. return this._centerObject(object, vpCenter);
  8558. },
  8559. /**
  8560. * Centers object horizontally in the viewport, object.top is unchanged
  8561. * @param {fabric.Object} object Object to center vertically and horizontally
  8562. * @return {fabric.Canvas} thisArg
  8563. * @chainable
  8564. */
  8565. viewportCenterObjectH: function(object) {
  8566. var vpCenter = this.getVpCenter();
  8567. this._centerObject(object, new fabric.Point(vpCenter.x, object.getCenterPoint().y));
  8568. return this;
  8569. },
  8570. /**
  8571. * Centers object Vertically in the viewport, object.top is unchanged
  8572. * @param {fabric.Object} object Object to center vertically and horizontally
  8573. * @return {fabric.Canvas} thisArg
  8574. * @chainable
  8575. */
  8576. viewportCenterObjectV: function(object) {
  8577. var vpCenter = this.getVpCenter();
  8578. return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, vpCenter.y));
  8579. },
  8580. /**
  8581. * Calculate the point in canvas that correspond to the center of actual viewport.
  8582. * @return {fabric.Point} vpCenter, viewport center
  8583. * @chainable
  8584. */
  8585. getVpCenter: function() {
  8586. var center = this.getCenter(),
  8587. iVpt = invertTransform(this.viewportTransform);
  8588. return transformPoint({ x: center.left, y: center.top }, iVpt);
  8589. },
  8590. /**
  8591. * @private
  8592. * @param {fabric.Object} object Object to center
  8593. * @param {fabric.Point} center Center point
  8594. * @return {fabric.Canvas} thisArg
  8595. * @chainable
  8596. */
  8597. _centerObject: function(object, center) {
  8598. object.setPositionByOrigin(center, 'center', 'center');
  8599. object.setCoords();
  8600. this.renderOnAddRemove && this.requestRenderAll();
  8601. return this;
  8602. },
  8603. /**
  8604. * Returs dataless JSON representation of canvas
  8605. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  8606. * @return {String} json string
  8607. */
  8608. toDatalessJSON: function (propertiesToInclude) {
  8609. return this.toDatalessObject(propertiesToInclude);
  8610. },
  8611. /**
  8612. * Returns object representation of canvas
  8613. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  8614. * @return {Object} object representation of an instance
  8615. */
  8616. toObject: function (propertiesToInclude) {
  8617. return this._toObjectMethod('toObject', propertiesToInclude);
  8618. },
  8619. /**
  8620. * Returns dataless object representation of canvas
  8621. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  8622. * @return {Object} object representation of an instance
  8623. */
  8624. toDatalessObject: function (propertiesToInclude) {
  8625. return this._toObjectMethod('toDatalessObject', propertiesToInclude);
  8626. },
  8627. /**
  8628. * @private
  8629. */
  8630. _toObjectMethod: function (methodName, propertiesToInclude) {
  8631. var data = {
  8632. version: fabric.version,
  8633. objects: this._toObjects(methodName, propertiesToInclude)
  8634. };
  8635. extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));
  8636. fabric.util.populateWithProperties(this, data, propertiesToInclude);
  8637. return data;
  8638. },
  8639. /**
  8640. * @private
  8641. */
  8642. _toObjects: function(methodName, propertiesToInclude) {
  8643. return this.getObjects().filter(function(object) {
  8644. return !object.excludeFromExport;
  8645. }).map(function(instance) {
  8646. return this._toObject(instance, methodName, propertiesToInclude);
  8647. }, this);
  8648. },
  8649. /**
  8650. * @private
  8651. */
  8652. _toObject: function(instance, methodName, propertiesToInclude) {
  8653. var originalValue;
  8654. if (!this.includeDefaultValues) {
  8655. originalValue = instance.includeDefaultValues;
  8656. instance.includeDefaultValues = false;
  8657. }
  8658. var object = instance[methodName](propertiesToInclude);
  8659. if (!this.includeDefaultValues) {
  8660. instance.includeDefaultValues = originalValue;
  8661. }
  8662. return object;
  8663. },
  8664. /**
  8665. * @private
  8666. */
  8667. __serializeBgOverlay: function(methodName, propertiesToInclude) {
  8668. var data = { }, bgImage = this.backgroundImage, overlay = this.overlayImage;
  8669. if (this.backgroundColor) {
  8670. data.background = this.backgroundColor.toObject
  8671. ? this.backgroundColor.toObject(propertiesToInclude)
  8672. : this.backgroundColor;
  8673. }
  8674. if (this.overlayColor) {
  8675. data.overlay = this.overlayColor.toObject
  8676. ? this.overlayColor.toObject(propertiesToInclude)
  8677. : this.overlayColor;
  8678. }
  8679. if (bgImage && !bgImage.excludeFromExport) {
  8680. data.backgroundImage = this._toObject(bgImage, methodName, propertiesToInclude);
  8681. }
  8682. if (overlay && !overlay.excludeFromExport) {
  8683. data.overlayImage = this._toObject(overlay, methodName, propertiesToInclude);
  8684. }
  8685. return data;
  8686. },
  8687. /**
  8688. * Moves an object or the objects of a multiple selection
  8689. * to the bottom of the stack of drawn objects
  8690. * @param {fabric.Object} object Object to send to back
  8691. * @return {fabric.Canvas} thisArg
  8692. * @chainable
  8693. */
  8694. sendToBack: function (object) {
  8695. if (!object) {
  8696. return this;
  8697. }
  8698. var activeSelection = this._activeObject,
  8699. i, obj, objs;
  8700. if (object === activeSelection && object.type === 'activeSelection') {
  8701. objs = activeSelection._objects;
  8702. for (i = objs.length; i--;) {
  8703. obj = objs[i];
  8704. removeFromArray(this._objects, obj);
  8705. this._objects.unshift(obj);
  8706. }
  8707. }
  8708. else {
  8709. removeFromArray(this._objects, object);
  8710. this._objects.unshift(object);
  8711. }
  8712. this.renderOnAddRemove && this.requestRenderAll();
  8713. return this;
  8714. },
  8715. /**
  8716. * Moves an object or the objects of a multiple selection
  8717. * to the top of the stack of drawn objects
  8718. * @param {fabric.Object} object Object to send
  8719. * @return {fabric.Canvas} thisArg
  8720. * @chainable
  8721. */
  8722. bringToFront: function (object) {
  8723. if (!object) {
  8724. return this;
  8725. }
  8726. var activeSelection = this._activeObject,
  8727. i, obj, objs;
  8728. if (object === activeSelection && object.type === 'activeSelection') {
  8729. objs = activeSelection._objects;
  8730. for (i = 0; i < objs.length; i++) {
  8731. obj = objs[i];
  8732. removeFromArray(this._objects, obj);
  8733. this._objects.push(obj);
  8734. }
  8735. }
  8736. else {
  8737. removeFromArray(this._objects, object);
  8738. this._objects.push(object);
  8739. }
  8740. this.renderOnAddRemove && this.requestRenderAll();
  8741. return this;
  8742. },
  8743. /**
  8744. * Moves an object or a selection down in stack of drawn objects
  8745. * An optional paramter, intersecting allowes to move the object in behind
  8746. * the first intersecting object. Where intersection is calculated with
  8747. * bounding box. If no intersection is found, there will not be change in the
  8748. * stack.
  8749. * @param {fabric.Object} object Object to send
  8750. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  8751. * @return {fabric.Canvas} thisArg
  8752. * @chainable
  8753. */
  8754. sendBackwards: function (object, intersecting) {
  8755. if (!object) {
  8756. return this;
  8757. }
  8758. var activeSelection = this._activeObject,
  8759. i, obj, idx, newIdx, objs, objsMoved = 0;
  8760. if (object === activeSelection && object.type === 'activeSelection') {
  8761. objs = activeSelection._objects;
  8762. for (i = 0; i < objs.length; i++) {
  8763. obj = objs[i];
  8764. idx = this._objects.indexOf(obj);
  8765. if (idx > 0 + objsMoved) {
  8766. newIdx = idx - 1;
  8767. removeFromArray(this._objects, obj);
  8768. this._objects.splice(newIdx, 0, obj);
  8769. }
  8770. objsMoved++;
  8771. }
  8772. }
  8773. else {
  8774. idx = this._objects.indexOf(object);
  8775. if (idx !== 0) {
  8776. // if object is not on the bottom of stack
  8777. newIdx = this._findNewLowerIndex(object, idx, intersecting);
  8778. removeFromArray(this._objects, object);
  8779. this._objects.splice(newIdx, 0, object);
  8780. }
  8781. }
  8782. this.renderOnAddRemove && this.requestRenderAll();
  8783. return this;
  8784. },
  8785. /**
  8786. * @private
  8787. */
  8788. _findNewLowerIndex: function(object, idx, intersecting) {
  8789. var newIdx, i;
  8790. if (intersecting) {
  8791. newIdx = idx;
  8792. // traverse down the stack looking for the nearest intersecting object
  8793. for (i = idx - 1; i >= 0; --i) {
  8794. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  8795. object.isContainedWithinObject(this._objects[i]) ||
  8796. this._objects[i].isContainedWithinObject(object);
  8797. if (isIntersecting) {
  8798. newIdx = i;
  8799. break;
  8800. }
  8801. }
  8802. }
  8803. else {
  8804. newIdx = idx - 1;
  8805. }
  8806. return newIdx;
  8807. },
  8808. /**
  8809. * Moves an object or a selection up in stack of drawn objects
  8810. * An optional paramter, intersecting allowes to move the object in front
  8811. * of the first intersecting object. Where intersection is calculated with
  8812. * bounding box. If no intersection is found, there will not be change in the
  8813. * stack.
  8814. * @param {fabric.Object} object Object to send
  8815. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  8816. * @return {fabric.Canvas} thisArg
  8817. * @chainable
  8818. */
  8819. bringForward: function (object, intersecting) {
  8820. if (!object) {
  8821. return this;
  8822. }
  8823. var activeSelection = this._activeObject,
  8824. i, obj, idx, newIdx, objs, objsMoved = 0;
  8825. if (object === activeSelection && object.type === 'activeSelection') {
  8826. objs = activeSelection._objects;
  8827. for (i = objs.length; i--;) {
  8828. obj = objs[i];
  8829. idx = this._objects.indexOf(obj);
  8830. if (idx < this._objects.length - 1 - objsMoved) {
  8831. newIdx = idx + 1;
  8832. removeFromArray(this._objects, obj);
  8833. this._objects.splice(newIdx, 0, obj);
  8834. }
  8835. objsMoved++;
  8836. }
  8837. }
  8838. else {
  8839. idx = this._objects.indexOf(object);
  8840. if (idx !== this._objects.length - 1) {
  8841. // if object is not on top of stack (last item in an array)
  8842. newIdx = this._findNewUpperIndex(object, idx, intersecting);
  8843. removeFromArray(this._objects, object);
  8844. this._objects.splice(newIdx, 0, object);
  8845. }
  8846. }
  8847. this.renderOnAddRemove && this.requestRenderAll();
  8848. return this;
  8849. },
  8850. /**
  8851. * @private
  8852. */
  8853. _findNewUpperIndex: function(object, idx, intersecting) {
  8854. var newIdx, i, len;
  8855. if (intersecting) {
  8856. newIdx = idx;
  8857. // traverse up the stack looking for the nearest intersecting object
  8858. for (i = idx + 1, len = this._objects.length; i < len; ++i) {
  8859. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  8860. object.isContainedWithinObject(this._objects[i]) ||
  8861. this._objects[i].isContainedWithinObject(object);
  8862. if (isIntersecting) {
  8863. newIdx = i;
  8864. break;
  8865. }
  8866. }
  8867. }
  8868. else {
  8869. newIdx = idx + 1;
  8870. }
  8871. return newIdx;
  8872. },
  8873. /**
  8874. * Moves an object to specified level in stack of drawn objects
  8875. * @param {fabric.Object} object Object to send
  8876. * @param {Number} index Position to move to
  8877. * @return {fabric.Canvas} thisArg
  8878. * @chainable
  8879. */
  8880. moveTo: function (object, index) {
  8881. removeFromArray(this._objects, object);
  8882. this._objects.splice(index, 0, object);
  8883. return this.renderOnAddRemove && this.requestRenderAll();
  8884. },
  8885. /**
  8886. * Clears a canvas element and dispose objects
  8887. * @return {fabric.Canvas} thisArg
  8888. * @chainable
  8889. */
  8890. dispose: function () {
  8891. // cancel eventually ongoing renders
  8892. if (this.isRendering) {
  8893. fabric.util.cancelAnimFrame(this.isRendering);
  8894. this.isRendering = 0;
  8895. }
  8896. this.forEachObject(function(object) {
  8897. object.dispose && object.dispose();
  8898. });
  8899. this._objects = [];
  8900. this.backgroundImage = null;
  8901. this.overlayImage = null;
  8902. this._iTextInstances = null;
  8903. this.lowerCanvasEl = null;
  8904. this.contextContainer = null;
  8905. return this;
  8906. },
  8907. /**
  8908. * Returns a string representation of an instance
  8909. * @return {String} string representation of an instance
  8910. */
  8911. toString: function () {
  8912. return '#<fabric.Canvas (' + this.complexity() + '): ' +
  8913. '{ objects: ' + this.getObjects().length + ' }>';
  8914. }
  8915. });
  8916. extend(fabric.StaticCanvas.prototype, fabric.Observable);
  8917. extend(fabric.StaticCanvas.prototype, fabric.Collection);
  8918. extend(fabric.StaticCanvas.prototype, fabric.DataURLExporter);
  8919. extend(fabric.StaticCanvas, /** @lends fabric.StaticCanvas */ {
  8920. /**
  8921. * @static
  8922. * @type String
  8923. * @default
  8924. */
  8925. EMPTY_JSON: '{"objects": [], "background": "white"}',
  8926. /**
  8927. * Provides a way to check support of some of the canvas methods
  8928. * (either those of HTMLCanvasElement itself, or rendering context)
  8929. *
  8930. * @param {String} methodName Method to check support for;
  8931. * Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash"
  8932. * @return {Boolean | null} `true` if method is supported (or at least exists),
  8933. * `null` if canvas element or context can not be initialized
  8934. */
  8935. supports: function (methodName) {
  8936. var el = fabric.util.createCanvasElement();
  8937. if (!el || !el.getContext) {
  8938. return null;
  8939. }
  8940. var ctx = el.getContext('2d');
  8941. if (!ctx) {
  8942. return null;
  8943. }
  8944. switch (methodName) {
  8945. case 'getImageData':
  8946. return typeof ctx.getImageData !== 'undefined';
  8947. case 'setLineDash':
  8948. return typeof ctx.setLineDash !== 'undefined';
  8949. case 'toDataURL':
  8950. return typeof el.toDataURL !== 'undefined';
  8951. case 'toDataURLWithQuality':
  8952. try {
  8953. el.toDataURL('image/jpeg', 0);
  8954. return true;
  8955. }
  8956. catch (e) { }
  8957. return false;
  8958. default:
  8959. return null;
  8960. }
  8961. }
  8962. });
  8963. /**
  8964. * Returns JSON representation of canvas
  8965. * @function
  8966. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  8967. * @return {String} JSON string
  8968. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}
  8969. * @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}
  8970. * @example <caption>JSON without additional properties</caption>
  8971. * var json = canvas.toJSON();
  8972. * @example <caption>JSON with additional properties included</caption>
  8973. * var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY', 'lockUniScaling']);
  8974. * @example <caption>JSON without default values</caption>
  8975. * canvas.includeDefaultValues = false;
  8976. * var json = canvas.toJSON();
  8977. */
  8978. fabric.StaticCanvas.prototype.toJSON = fabric.StaticCanvas.prototype.toObject;
  8979. if (fabric.isLikelyNode) {
  8980. fabric.StaticCanvas.prototype.createPNGStream = function() {
  8981. var impl = fabric.util.getNodeCanvas(this.lowerCanvasEl);
  8982. return impl && impl.createPNGStream();
  8983. };
  8984. fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
  8985. var impl = fabric.util.getNodeCanvas(this.lowerCanvasEl);
  8986. return impl && impl.createJPEGStream(opts);
  8987. };
  8988. }
  8989. })();
  8990. /**
  8991. * BaseBrush class
  8992. * @class fabric.BaseBrush
  8993. * @see {@link http://fabricjs.com/freedrawing|Freedrawing demo}
  8994. */
  8995. fabric.BaseBrush = fabric.util.createClass(/** @lends fabric.BaseBrush.prototype */ {
  8996. /**
  8997. * Color of a brush
  8998. * @type String
  8999. * @default
  9000. */
  9001. color: 'rgb(0, 0, 0)',
  9002. /**
  9003. * Width of a brush, has to be a Number, no string literals
  9004. * @type Number
  9005. * @default
  9006. */
  9007. width: 1,
  9008. /**
  9009. * Shadow object representing shadow of this shape.
  9010. * <b>Backwards incompatibility note:</b> This property replaces "shadowColor" (String), "shadowOffsetX" (Number),
  9011. * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12
  9012. * @type fabric.Shadow
  9013. * @default
  9014. */
  9015. shadow: null,
  9016. /**
  9017. * Line endings style of a brush (one of "butt", "round", "square")
  9018. * @type String
  9019. * @default
  9020. */
  9021. strokeLineCap: 'round',
  9022. /**
  9023. * Corner style of a brush (one of "bevel", "round", "miter")
  9024. * @type String
  9025. * @default
  9026. */
  9027. strokeLineJoin: 'round',
  9028. /**
  9029. * Maximum miter length (used for strokeLineJoin = "miter") of a brush's
  9030. * @type Number
  9031. * @default
  9032. */
  9033. strokeMiterLimit: 10,
  9034. /**
  9035. * Stroke Dash Array.
  9036. * @type Array
  9037. * @default
  9038. */
  9039. strokeDashArray: null,
  9040. /**
  9041. * Sets shadow of an object
  9042. * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)")
  9043. * @return {fabric.Object} thisArg
  9044. * @chainable
  9045. */
  9046. setShadow: function(options) {
  9047. this.shadow = new fabric.Shadow(options);
  9048. return this;
  9049. },
  9050. /**
  9051. * Sets brush styles
  9052. * @private
  9053. */
  9054. _setBrushStyles: function() {
  9055. var ctx = this.canvas.contextTop;
  9056. ctx.strokeStyle = this.color;
  9057. ctx.lineWidth = this.width;
  9058. ctx.lineCap = this.strokeLineCap;
  9059. ctx.miterLimit = this.strokeMiterLimit;
  9060. ctx.lineJoin = this.strokeLineJoin;
  9061. if (fabric.StaticCanvas.supports('setLineDash')) {
  9062. ctx.setLineDash(this.strokeDashArray || []);
  9063. }
  9064. },
  9065. /**
  9066. * Sets the transformation on given context
  9067. * @param {RenderingContext2d} ctx context to render on
  9068. * @private
  9069. */
  9070. _saveAndTransform: function(ctx) {
  9071. var v = this.canvas.viewportTransform;
  9072. ctx.save();
  9073. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  9074. },
  9075. /**
  9076. * Sets brush shadow styles
  9077. * @private
  9078. */
  9079. _setShadow: function() {
  9080. if (!this.shadow) {
  9081. return;
  9082. }
  9083. var ctx = this.canvas.contextTop,
  9084. zoom = this.canvas.getZoom();
  9085. ctx.shadowColor = this.shadow.color;
  9086. ctx.shadowBlur = this.shadow.blur * zoom;
  9087. ctx.shadowOffsetX = this.shadow.offsetX * zoom;
  9088. ctx.shadowOffsetY = this.shadow.offsetY * zoom;
  9089. },
  9090. /**
  9091. * Removes brush shadow styles
  9092. * @private
  9093. */
  9094. _resetShadow: function() {
  9095. var ctx = this.canvas.contextTop;
  9096. ctx.shadowColor = '';
  9097. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  9098. }
  9099. });
  9100. (function() {
  9101. /**
  9102. * PencilBrush class
  9103. * @class fabric.PencilBrush
  9104. * @extends fabric.BaseBrush
  9105. */
  9106. fabric.PencilBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.PencilBrush.prototype */ {
  9107. /**
  9108. * Constructor
  9109. * @param {fabric.Canvas} canvas
  9110. * @return {fabric.PencilBrush} Instance of a pencil brush
  9111. */
  9112. initialize: function(canvas) {
  9113. this.canvas = canvas;
  9114. this._points = [];
  9115. },
  9116. /**
  9117. * Invoked inside on mouse down and mouse move
  9118. * @param {Object} pointer
  9119. */
  9120. _drawSegment: function (ctx, p1, p2) {
  9121. var midPoint = p1.midPointFrom(p2);
  9122. ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
  9123. return midPoint;
  9124. },
  9125. /**
  9126. * Inovoked on mouse down
  9127. * @param {Object} pointer
  9128. */
  9129. onMouseDown: function(pointer) {
  9130. this._prepareForDrawing(pointer);
  9131. // capture coordinates immediately
  9132. // this allows to draw dots (when movement never occurs)
  9133. this._captureDrawingPath(pointer);
  9134. this._render();
  9135. },
  9136. /**
  9137. * Inovoked on mouse move
  9138. * @param {Object} pointer
  9139. */
  9140. onMouseMove: function(pointer) {
  9141. if (this._captureDrawingPath(pointer) && this._points.length > 1) {
  9142. if (this.needsFullRender) {
  9143. // redraw curve
  9144. // clear top canvas
  9145. this.canvas.clearContext(this.canvas.contextTop);
  9146. this._render();
  9147. }
  9148. else {
  9149. var points = this._points, length = points.length, ctx = this.canvas.contextTop;
  9150. // draw the curve update
  9151. this._saveAndTransform(ctx);
  9152. if (this.oldEnd) {
  9153. ctx.beginPath();
  9154. ctx.moveTo(this.oldEnd.x, this.oldEnd.y);
  9155. }
  9156. this.oldEnd = this._drawSegment(ctx, points[length - 2], points[length - 1], true);
  9157. ctx.stroke();
  9158. ctx.restore();
  9159. }
  9160. }
  9161. },
  9162. /**
  9163. * Invoked on mouse up
  9164. */
  9165. onMouseUp: function() {
  9166. this.oldEnd = undefined;
  9167. this._finalizeAndAddPath();
  9168. },
  9169. /**
  9170. * @private
  9171. * @param {Object} pointer Actual mouse position related to the canvas.
  9172. */
  9173. _prepareForDrawing: function(pointer) {
  9174. var p = new fabric.Point(pointer.x, pointer.y);
  9175. this._reset();
  9176. this._addPoint(p);
  9177. this.canvas.contextTop.moveTo(p.x, p.y);
  9178. },
  9179. /**
  9180. * @private
  9181. * @param {fabric.Point} point Point to be added to points array
  9182. */
  9183. _addPoint: function(point) {
  9184. if (this._points.length > 1 && point.eq(this._points[this._points.length - 1])) {
  9185. return false;
  9186. }
  9187. this._points.push(point);
  9188. return true;
  9189. },
  9190. /**
  9191. * Clear points array and set contextTop canvas style.
  9192. * @private
  9193. */
  9194. _reset: function() {
  9195. this._points.length = 0;
  9196. this._setBrushStyles();
  9197. var color = new fabric.Color(this.color);
  9198. this.needsFullRender = (color.getAlpha() < 1);
  9199. this._setShadow();
  9200. },
  9201. /**
  9202. * @private
  9203. * @param {Object} pointer Actual mouse position related to the canvas.
  9204. */
  9205. _captureDrawingPath: function(pointer) {
  9206. var pointerPoint = new fabric.Point(pointer.x, pointer.y);
  9207. return this._addPoint(pointerPoint);
  9208. },
  9209. /**
  9210. * Draw a smooth path on the topCanvas using quadraticCurveTo
  9211. * @private
  9212. */
  9213. _render: function() {
  9214. var ctx = this.canvas.contextTop, i, len,
  9215. p1 = this._points[0],
  9216. p2 = this._points[1];
  9217. this._saveAndTransform(ctx);
  9218. ctx.beginPath();
  9219. //if we only have 2 points in the path and they are the same
  9220. //it means that the user only clicked the canvas without moving the mouse
  9221. //then we should be drawing a dot. A path isn't drawn between two identical dots
  9222. //that's why we set them apart a bit
  9223. if (this._points.length === 2 && p1.x === p2.x && p1.y === p2.y) {
  9224. var width = this.width / 1000;
  9225. p1 = new fabric.Point(p1.x, p1.y);
  9226. p2 = new fabric.Point(p2.x, p2.y);
  9227. p1.x -= width;
  9228. p2.x += width;
  9229. }
  9230. ctx.moveTo(p1.x, p1.y);
  9231. for (i = 1, len = this._points.length; i < len; i++) {
  9232. // we pick the point between pi + 1 & pi + 2 as the
  9233. // end point and p1 as our control point.
  9234. this._drawSegment(ctx, p1, p2);
  9235. p1 = this._points[i];
  9236. p2 = this._points[i + 1];
  9237. }
  9238. // Draw last line as a straight line while
  9239. // we wait for the next point to be able to calculate
  9240. // the bezier control point
  9241. ctx.lineTo(p1.x, p1.y);
  9242. ctx.stroke();
  9243. ctx.restore();
  9244. },
  9245. /**
  9246. * Converts points to SVG path
  9247. * @param {Array} points Array of points
  9248. * @return {String} SVG path
  9249. */
  9250. convertPointsToSVGPath: function(points) {
  9251. var path = [], i, width = this.width / 1000,
  9252. p1 = new fabric.Point(points[0].x, points[0].y),
  9253. p2 = new fabric.Point(points[1].x, points[1].y),
  9254. len = points.length, multSignX = 1, multSignY = 1, manyPoints = len > 2;
  9255. if (manyPoints) {
  9256. multSignX = points[2].x < p2.x ? -1 : points[2].x === p2.x ? 0 : 1;
  9257. multSignY = points[2].y < p2.y ? -1 : points[2].y === p2.y ? 0 : 1;
  9258. }
  9259. path.push('M ', p1.x - multSignX * width, ' ', p1.y - multSignY * width, ' ');
  9260. for (i = 1; i < len; i++) {
  9261. if (!p1.eq(p2)) {
  9262. var midPoint = p1.midPointFrom(p2);
  9263. // p1 is our bezier control point
  9264. // midpoint is our endpoint
  9265. // start point is p(i-1) value.
  9266. path.push('Q ', p1.x, ' ', p1.y, ' ', midPoint.x, ' ', midPoint.y, ' ');
  9267. }
  9268. p1 = points[i];
  9269. if ((i + 1) < points.length) {
  9270. p2 = points[i + 1];
  9271. }
  9272. }
  9273. if (manyPoints) {
  9274. multSignX = p1.x > points[i - 2].x ? 1 : p1.x === points[i - 2].x ? 0 : -1;
  9275. multSignY = p1.y > points[i - 2].y ? 1 : p1.y === points[i - 2].y ? 0 : -1;
  9276. }
  9277. path.push('L ', p1.x + multSignX * width, ' ', p1.y + multSignY * width);
  9278. return path;
  9279. },
  9280. /**
  9281. * Creates fabric.Path object to add on canvas
  9282. * @param {String} pathData Path data
  9283. * @return {fabric.Path} Path to add on canvas
  9284. */
  9285. createPath: function(pathData) {
  9286. var path = new fabric.Path(pathData, {
  9287. fill: null,
  9288. stroke: this.color,
  9289. strokeWidth: this.width,
  9290. strokeLineCap: this.strokeLineCap,
  9291. strokeMiterLimit: this.strokeMiterLimit,
  9292. strokeLineJoin: this.strokeLineJoin,
  9293. strokeDashArray: this.strokeDashArray,
  9294. });
  9295. var position = new fabric.Point(path.left + path.width / 2, path.top + path.height / 2);
  9296. position = path.translateToGivenOrigin(position, 'center', 'center', path.originX, path.originY);
  9297. path.top = position.y;
  9298. path.left = position.x;
  9299. if (this.shadow) {
  9300. this.shadow.affectStroke = true;
  9301. path.setShadow(this.shadow);
  9302. }
  9303. return path;
  9304. },
  9305. /**
  9306. * On mouseup after drawing the path on contextTop canvas
  9307. * we use the points captured to create an new fabric path object
  9308. * and add it to the fabric canvas.
  9309. */
  9310. _finalizeAndAddPath: function() {
  9311. var ctx = this.canvas.contextTop;
  9312. ctx.closePath();
  9313. var pathData = this.convertPointsToSVGPath(this._points).join('');
  9314. if (pathData === 'M 0 0 Q 0 0 0 0 L 0 0') {
  9315. // do not create 0 width/height paths, as they are
  9316. // rendered inconsistently across browsers
  9317. // Firefox 4, for example, renders a dot,
  9318. // whereas Chrome 10 renders nothing
  9319. this.canvas.requestRenderAll();
  9320. return;
  9321. }
  9322. var path = this.createPath(pathData);
  9323. this.canvas.clearContext(this.canvas.contextTop);
  9324. this.canvas.add(path);
  9325. this.canvas.renderAll();
  9326. path.setCoords();
  9327. this._resetShadow();
  9328. // fire event 'path' created
  9329. this.canvas.fire('path:created', { path: path });
  9330. }
  9331. });
  9332. })();
  9333. /**
  9334. * CircleBrush class
  9335. * @class fabric.CircleBrush
  9336. */
  9337. fabric.CircleBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.CircleBrush.prototype */ {
  9338. /**
  9339. * Width of a brush
  9340. * @type Number
  9341. * @default
  9342. */
  9343. width: 10,
  9344. /**
  9345. * Constructor
  9346. * @param {fabric.Canvas} canvas
  9347. * @return {fabric.CircleBrush} Instance of a circle brush
  9348. */
  9349. initialize: function(canvas) {
  9350. this.canvas = canvas;
  9351. this.points = [];
  9352. },
  9353. /**
  9354. * Invoked inside on mouse down and mouse move
  9355. * @param {Object} pointer
  9356. */
  9357. drawDot: function(pointer) {
  9358. var point = this.addPoint(pointer),
  9359. ctx = this.canvas.contextTop;
  9360. this._saveAndTransform(ctx);
  9361. ctx.fillStyle = point.fill;
  9362. ctx.beginPath();
  9363. ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);
  9364. ctx.closePath();
  9365. ctx.fill();
  9366. ctx.restore();
  9367. },
  9368. /**
  9369. * Invoked on mouse down
  9370. */
  9371. onMouseDown: function(pointer) {
  9372. this.points.length = 0;
  9373. this.canvas.clearContext(this.canvas.contextTop);
  9374. this._setShadow();
  9375. this.drawDot(pointer);
  9376. },
  9377. /**
  9378. * Render the full state of the brush
  9379. * @private
  9380. */
  9381. _render: function() {
  9382. var ctx = this.canvas.contextTop, i, len,
  9383. points = this.points, point;
  9384. this._saveAndTransform(ctx);
  9385. for (i = 0, len = points.length; i < len; i++) {
  9386. point = points[i];
  9387. ctx.fillStyle = point.fill;
  9388. ctx.beginPath();
  9389. ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);
  9390. ctx.closePath();
  9391. ctx.fill();
  9392. }
  9393. ctx.restore();
  9394. },
  9395. /**
  9396. * Invoked on mouse move
  9397. * @param {Object} pointer
  9398. */
  9399. onMouseMove: function(pointer) {
  9400. this.drawDot(pointer);
  9401. },
  9402. /**
  9403. * Invoked on mouse up
  9404. */
  9405. onMouseUp: function() {
  9406. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove, i, len;
  9407. this.canvas.renderOnAddRemove = false;
  9408. var circles = [];
  9409. for (i = 0, len = this.points.length; i < len; i++) {
  9410. var point = this.points[i],
  9411. circle = new fabric.Circle({
  9412. radius: point.radius,
  9413. left: point.x,
  9414. top: point.y,
  9415. originX: 'center',
  9416. originY: 'center',
  9417. fill: point.fill
  9418. });
  9419. this.shadow && circle.setShadow(this.shadow);
  9420. circles.push(circle);
  9421. }
  9422. var group = new fabric.Group(circles, { originX: 'center', originY: 'center' });
  9423. group.canvas = this.canvas;
  9424. this.canvas.add(group);
  9425. this.canvas.fire('path:created', { path: group });
  9426. this.canvas.clearContext(this.canvas.contextTop);
  9427. this._resetShadow();
  9428. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  9429. this.canvas.requestRenderAll();
  9430. },
  9431. /**
  9432. * @param {Object} pointer
  9433. * @return {fabric.Point} Just added pointer point
  9434. */
  9435. addPoint: function(pointer) {
  9436. var pointerPoint = new fabric.Point(pointer.x, pointer.y),
  9437. circleRadius = fabric.util.getRandomInt(
  9438. Math.max(0, this.width - 20), this.width + 20) / 2,
  9439. circleColor = new fabric.Color(this.color)
  9440. .setAlpha(fabric.util.getRandomInt(0, 100) / 100)
  9441. .toRgba();
  9442. pointerPoint.radius = circleRadius;
  9443. pointerPoint.fill = circleColor;
  9444. this.points.push(pointerPoint);
  9445. return pointerPoint;
  9446. }
  9447. });
  9448. /**
  9449. * SprayBrush class
  9450. * @class fabric.SprayBrush
  9451. */
  9452. fabric.SprayBrush = fabric.util.createClass( fabric.BaseBrush, /** @lends fabric.SprayBrush.prototype */ {
  9453. /**
  9454. * Width of a spray
  9455. * @type Number
  9456. * @default
  9457. */
  9458. width: 10,
  9459. /**
  9460. * Density of a spray (number of dots per chunk)
  9461. * @type Number
  9462. * @default
  9463. */
  9464. density: 20,
  9465. /**
  9466. * Width of spray dots
  9467. * @type Number
  9468. * @default
  9469. */
  9470. dotWidth: 1,
  9471. /**
  9472. * Width variance of spray dots
  9473. * @type Number
  9474. * @default
  9475. */
  9476. dotWidthVariance: 1,
  9477. /**
  9478. * Whether opacity of a dot should be random
  9479. * @type Boolean
  9480. * @default
  9481. */
  9482. randomOpacity: false,
  9483. /**
  9484. * Whether overlapping dots (rectangles) should be removed (for performance reasons)
  9485. * @type Boolean
  9486. * @default
  9487. */
  9488. optimizeOverlapping: true,
  9489. /**
  9490. * Constructor
  9491. * @param {fabric.Canvas} canvas
  9492. * @return {fabric.SprayBrush} Instance of a spray brush
  9493. */
  9494. initialize: function(canvas) {
  9495. this.canvas = canvas;
  9496. this.sprayChunks = [];
  9497. },
  9498. /**
  9499. * Invoked on mouse down
  9500. * @param {Object} pointer
  9501. */
  9502. onMouseDown: function(pointer) {
  9503. this.sprayChunks.length = 0;
  9504. this.canvas.clearContext(this.canvas.contextTop);
  9505. this._setShadow();
  9506. this.addSprayChunk(pointer);
  9507. this.render(this.sprayChunkPoints);
  9508. },
  9509. /**
  9510. * Invoked on mouse move
  9511. * @param {Object} pointer
  9512. */
  9513. onMouseMove: function(pointer) {
  9514. this.addSprayChunk(pointer);
  9515. this.render(this.sprayChunkPoints);
  9516. },
  9517. /**
  9518. * Invoked on mouse up
  9519. */
  9520. onMouseUp: function() {
  9521. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
  9522. this.canvas.renderOnAddRemove = false;
  9523. var rects = [];
  9524. for (var i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {
  9525. var sprayChunk = this.sprayChunks[i];
  9526. for (var j = 0, jlen = sprayChunk.length; j < jlen; j++) {
  9527. var rect = new fabric.Rect({
  9528. width: sprayChunk[j].width,
  9529. height: sprayChunk[j].width,
  9530. left: sprayChunk[j].x + 1,
  9531. top: sprayChunk[j].y + 1,
  9532. originX: 'center',
  9533. originY: 'center',
  9534. fill: this.color
  9535. });
  9536. rects.push(rect);
  9537. }
  9538. }
  9539. if (this.optimizeOverlapping) {
  9540. rects = this._getOptimizedRects(rects);
  9541. }
  9542. var group = new fabric.Group(rects, { originX: 'center', originY: 'center' });
  9543. this.shadow && group.setShadow(this.shadow);
  9544. this.canvas.add(group);
  9545. this.canvas.fire('path:created', { path: group });
  9546. this.canvas.clearContext(this.canvas.contextTop);
  9547. this._resetShadow();
  9548. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  9549. this.canvas.requestRenderAll();
  9550. },
  9551. /**
  9552. * @private
  9553. * @param {Array} rects
  9554. */
  9555. _getOptimizedRects: function(rects) {
  9556. // avoid creating duplicate rects at the same coordinates
  9557. var uniqueRects = { }, key, i, len;
  9558. for (i = 0, len = rects.length; i < len; i++) {
  9559. key = rects[i].left + '' + rects[i].top;
  9560. if (!uniqueRects[key]) {
  9561. uniqueRects[key] = rects[i];
  9562. }
  9563. }
  9564. var uniqueRectsArray = [];
  9565. for (key in uniqueRects) {
  9566. uniqueRectsArray.push(uniqueRects[key]);
  9567. }
  9568. return uniqueRectsArray;
  9569. },
  9570. /**
  9571. * Render new chunk of spray brush
  9572. */
  9573. render: function(sprayChunk) {
  9574. var ctx = this.canvas.contextTop, i, len;
  9575. ctx.fillStyle = this.color;
  9576. this._saveAndTransform(ctx);
  9577. for (i = 0, len = sprayChunk.length; i < len; i++) {
  9578. var point = sprayChunk[i];
  9579. if (typeof point.opacity !== 'undefined') {
  9580. ctx.globalAlpha = point.opacity;
  9581. }
  9582. ctx.fillRect(point.x, point.y, point.width, point.width);
  9583. }
  9584. ctx.restore();
  9585. },
  9586. /**
  9587. * Render all spray chunks
  9588. */
  9589. _render: function() {
  9590. var ctx = this.canvas.contextTop, i, ilen;
  9591. ctx.fillStyle = this.color;
  9592. this._saveAndTransform(ctx);
  9593. for (i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {
  9594. this.render(this.sprayChunks[i]);
  9595. }
  9596. ctx.restore();
  9597. },
  9598. /**
  9599. * @param {Object} pointer
  9600. */
  9601. addSprayChunk: function(pointer) {
  9602. this.sprayChunkPoints = [];
  9603. var x, y, width, radius = this.width / 2, i;
  9604. for (i = 0; i < this.density; i++) {
  9605. x = fabric.util.getRandomInt(pointer.x - radius, pointer.x + radius);
  9606. y = fabric.util.getRandomInt(pointer.y - radius, pointer.y + radius);
  9607. if (this.dotWidthVariance) {
  9608. width = fabric.util.getRandomInt(
  9609. // bottom clamp width to 1
  9610. Math.max(1, this.dotWidth - this.dotWidthVariance),
  9611. this.dotWidth + this.dotWidthVariance);
  9612. }
  9613. else {
  9614. width = this.dotWidth;
  9615. }
  9616. var point = new fabric.Point(x, y);
  9617. point.width = width;
  9618. if (this.randomOpacity) {
  9619. point.opacity = fabric.util.getRandomInt(0, 100) / 100;
  9620. }
  9621. this.sprayChunkPoints.push(point);
  9622. }
  9623. this.sprayChunks.push(this.sprayChunkPoints);
  9624. }
  9625. });
  9626. /**
  9627. * PatternBrush class
  9628. * @class fabric.PatternBrush
  9629. * @extends fabric.BaseBrush
  9630. */
  9631. fabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fabric.PatternBrush.prototype */ {
  9632. getPatternSrc: function() {
  9633. var dotWidth = 20,
  9634. dotDistance = 5,
  9635. patternCanvas = fabric.document.createElement('canvas'),
  9636. patternCtx = patternCanvas.getContext('2d');
  9637. patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;
  9638. patternCtx.fillStyle = this.color;
  9639. patternCtx.beginPath();
  9640. patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);
  9641. patternCtx.closePath();
  9642. patternCtx.fill();
  9643. return patternCanvas;
  9644. },
  9645. getPatternSrcFunction: function() {
  9646. return String(this.getPatternSrc).replace('this.color', '"' + this.color + '"');
  9647. },
  9648. /**
  9649. * Creates "pattern" instance property
  9650. */
  9651. getPattern: function() {
  9652. return this.canvas.contextTop.createPattern(this.source || this.getPatternSrc(), 'repeat');
  9653. },
  9654. /**
  9655. * Sets brush styles
  9656. */
  9657. _setBrushStyles: function() {
  9658. this.callSuper('_setBrushStyles');
  9659. this.canvas.contextTop.strokeStyle = this.getPattern();
  9660. },
  9661. /**
  9662. * Creates path
  9663. */
  9664. createPath: function(pathData) {
  9665. var path = this.callSuper('createPath', pathData),
  9666. topLeft = path._getLeftTopCoords().scalarAdd(path.strokeWidth / 2);
  9667. path.stroke = new fabric.Pattern({
  9668. source: this.source || this.getPatternSrcFunction(),
  9669. offsetX: -topLeft.x,
  9670. offsetY: -topLeft.y
  9671. });
  9672. return path;
  9673. }
  9674. });
  9675. (function() {
  9676. var getPointer = fabric.util.getPointer,
  9677. degreesToRadians = fabric.util.degreesToRadians,
  9678. radiansToDegrees = fabric.util.radiansToDegrees,
  9679. atan2 = Math.atan2,
  9680. abs = Math.abs,
  9681. supportLineDash = fabric.StaticCanvas.supports('setLineDash'),
  9682. STROKE_OFFSET = 0.5;
  9683. /**
  9684. * Canvas class
  9685. * @class fabric.Canvas
  9686. * @extends fabric.StaticCanvas
  9687. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#canvas}
  9688. * @see {@link fabric.Canvas#initialize} for constructor definition
  9689. *
  9690. * @fires object:modified
  9691. * @fires object:rotated
  9692. * @fires object:scaled
  9693. * @fires object:moved
  9694. * @fires object:skewed
  9695. * @fires object:rotating
  9696. * @fires object:scaling
  9697. * @fires object:moving
  9698. * @fires object:skewing
  9699. * @fires object:selected this event is deprecated. use selection:created
  9700. *
  9701. * @fires before:transform
  9702. * @fires before:selection:cleared
  9703. * @fires selection:cleared
  9704. * @fires selection:updated
  9705. * @fires selection:created
  9706. *
  9707. * @fires path:created
  9708. * @fires mouse:down
  9709. * @fires mouse:move
  9710. * @fires mouse:up
  9711. * @fires mouse:down:before
  9712. * @fires mouse:move:before
  9713. * @fires mouse:up:before
  9714. * @fires mouse:over
  9715. * @fires mouse:out
  9716. * @fires mouse:dblclick
  9717. *
  9718. * @fires dragover
  9719. * @fires dragenter
  9720. * @fires dragleave
  9721. * @fires drop
  9722. *
  9723. */
  9724. fabric.Canvas = fabric.util.createClass(fabric.StaticCanvas, /** @lends fabric.Canvas.prototype */ {
  9725. /**
  9726. * Constructor
  9727. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  9728. * @param {Object} [options] Options object
  9729. * @return {Object} thisArg
  9730. */
  9731. initialize: function(el, options) {
  9732. options || (options = { });
  9733. this.renderAndResetBound = this.renderAndReset.bind(this);
  9734. this._initStatic(el, options);
  9735. this._initInteractive();
  9736. this._createCacheCanvas();
  9737. },
  9738. /**
  9739. * When true, objects can be transformed by one side (unproportionally)
  9740. * @type Boolean
  9741. * @default
  9742. */
  9743. uniScaleTransform: false,
  9744. /**
  9745. * Indicates which key enable unproportional scaling
  9746. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  9747. * If `null` or 'none' or any other string that is not a modifier key
  9748. * feature is disabled feature disabled.
  9749. * @since 1.6.2
  9750. * @type String
  9751. * @default
  9752. */
  9753. uniScaleKey: 'shiftKey',
  9754. /**
  9755. * When true, objects use center point as the origin of scale transformation.
  9756. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  9757. * @since 1.3.4
  9758. * @type Boolean
  9759. * @default
  9760. */
  9761. centeredScaling: false,
  9762. /**
  9763. * When true, objects use center point as the origin of rotate transformation.
  9764. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  9765. * @since 1.3.4
  9766. * @type Boolean
  9767. * @default
  9768. */
  9769. centeredRotation: false,
  9770. /**
  9771. * Indicates which key enable centered Transform
  9772. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  9773. * If `null` or 'none' or any other string that is not a modifier key
  9774. * feature is disabled feature disabled.
  9775. * @since 1.6.2
  9776. * @type String
  9777. * @default
  9778. */
  9779. centeredKey: 'altKey',
  9780. /**
  9781. * Indicates which key enable alternate action on corner
  9782. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  9783. * If `null` or 'none' or any other string that is not a modifier key
  9784. * feature is disabled feature disabled.
  9785. * @since 1.6.2
  9786. * @type String
  9787. * @default
  9788. */
  9789. altActionKey: 'shiftKey',
  9790. /**
  9791. * Indicates that canvas is interactive. This property should not be changed.
  9792. * @type Boolean
  9793. * @default
  9794. */
  9795. interactive: true,
  9796. /**
  9797. * Indicates whether group selection should be enabled
  9798. * @type Boolean
  9799. * @default
  9800. */
  9801. selection: true,
  9802. /**
  9803. * Indicates which key or keys enable multiple click selection
  9804. * Pass value as a string or array of strings
  9805. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  9806. * If `null` or empty or containing any other string that is not a modifier key
  9807. * feature is disabled.
  9808. * @since 1.6.2
  9809. * @type String|Array
  9810. * @default
  9811. */
  9812. selectionKey: 'shiftKey',
  9813. /**
  9814. * Indicates which key enable alternative selection
  9815. * in case of target overlapping with active object
  9816. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  9817. * For a series of reason that come from the general expectations on how
  9818. * things should work, this feature works only for preserveObjectStacking true.
  9819. * If `null` or 'none' or any other string that is not a modifier key
  9820. * feature is disabled.
  9821. * @since 1.6.5
  9822. * @type null|String
  9823. * @default
  9824. */
  9825. altSelectionKey: null,
  9826. /**
  9827. * Color of selection
  9828. * @type String
  9829. * @default
  9830. */
  9831. selectionColor: 'rgba(100, 100, 255, 0.3)', // blue
  9832. /**
  9833. * Default dash array pattern
  9834. * If not empty the selection border is dashed
  9835. * @type Array
  9836. */
  9837. selectionDashArray: [],
  9838. /**
  9839. * Color of the border of selection (usually slightly darker than color of selection itself)
  9840. * @type String
  9841. * @default
  9842. */
  9843. selectionBorderColor: 'rgba(255, 255, 255, 0.3)',
  9844. /**
  9845. * Width of a line used in object/group selection
  9846. * @type Number
  9847. * @default
  9848. */
  9849. selectionLineWidth: 1,
  9850. /**
  9851. * Select only shapes that are fully contained in the dragged selection rectangle.
  9852. * @type Boolean
  9853. * @default
  9854. */
  9855. selectionFullyContained: false,
  9856. /**
  9857. * Default cursor value used when hovering over an object on canvas
  9858. * @type String
  9859. * @default
  9860. */
  9861. hoverCursor: 'move',
  9862. /**
  9863. * Default cursor value used when moving an object on canvas
  9864. * @type String
  9865. * @default
  9866. */
  9867. moveCursor: 'move',
  9868. /**
  9869. * Default cursor value used for the entire canvas
  9870. * @type String
  9871. * @default
  9872. */
  9873. defaultCursor: 'default',
  9874. /**
  9875. * Cursor value used during free drawing
  9876. * @type String
  9877. * @default
  9878. */
  9879. freeDrawingCursor: 'crosshair',
  9880. /**
  9881. * Cursor value used for rotation point
  9882. * @type String
  9883. * @default
  9884. */
  9885. rotationCursor: 'crosshair',
  9886. /**
  9887. * Cursor value used for disabled elements ( corners with disabled action )
  9888. * @type String
  9889. * @since 2.0.0
  9890. * @default
  9891. */
  9892. notAllowedCursor: 'not-allowed',
  9893. /**
  9894. * Default element class that's given to wrapper (div) element of canvas
  9895. * @type String
  9896. * @default
  9897. */
  9898. containerClass: 'canvas-container',
  9899. /**
  9900. * When true, object detection happens on per-pixel basis rather than on per-bounding-box
  9901. * @type Boolean
  9902. * @default
  9903. */
  9904. perPixelTargetFind: false,
  9905. /**
  9906. * Number of pixels around target pixel to tolerate (consider active) during object detection
  9907. * @type Number
  9908. * @default
  9909. */
  9910. targetFindTolerance: 0,
  9911. /**
  9912. * When true, target detection is skipped when hovering over canvas. This can be used to improve performance.
  9913. * @type Boolean
  9914. * @default
  9915. */
  9916. skipTargetFind: false,
  9917. /**
  9918. * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing.
  9919. * After mousedown, mousemove creates a shape,
  9920. * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas.
  9921. * @tutorial {@link http://fabricjs.com/fabric-intro-part-4#free_drawing}
  9922. * @type Boolean
  9923. * @default
  9924. */
  9925. isDrawingMode: false,
  9926. /**
  9927. * Indicates whether objects should remain in current stack position when selected.
  9928. * When false objects are brought to top and rendered as part of the selection group
  9929. * @type Boolean
  9930. * @default
  9931. */
  9932. preserveObjectStacking: false,
  9933. /**
  9934. * Indicates the angle that an object will lock to while rotating.
  9935. * @type Number
  9936. * @since 1.6.7
  9937. * @default
  9938. */
  9939. snapAngle: 0,
  9940. /**
  9941. * Indicates the distance from the snapAngle the rotation will lock to the snapAngle.
  9942. * When `null`, the snapThreshold will default to the snapAngle.
  9943. * @type null|Number
  9944. * @since 1.6.7
  9945. * @default
  9946. */
  9947. snapThreshold: null,
  9948. /**
  9949. * Indicates if the right click on canvas can output the context menu or not
  9950. * @type Boolean
  9951. * @since 1.6.5
  9952. * @default
  9953. */
  9954. stopContextMenu: false,
  9955. /**
  9956. * Indicates if the canvas can fire right click events
  9957. * @type Boolean
  9958. * @since 1.6.5
  9959. * @default
  9960. */
  9961. fireRightClick: false,
  9962. /**
  9963. * Indicates if the canvas can fire middle click events
  9964. * @type Boolean
  9965. * @since 1.7.8
  9966. * @default
  9967. */
  9968. fireMiddleClick: false,
  9969. /**
  9970. * @private
  9971. */
  9972. _initInteractive: function() {
  9973. this._currentTransform = null;
  9974. this._groupSelector = null;
  9975. this._initWrapperElement();
  9976. this._createUpperCanvas();
  9977. this._initEventListeners();
  9978. this._initRetinaScaling();
  9979. this.freeDrawingBrush = fabric.PencilBrush && new fabric.PencilBrush(this);
  9980. this.calcOffset();
  9981. },
  9982. /**
  9983. * Divides objects in two groups, one to render immediately
  9984. * and one to render as activeGroup.
  9985. * @return {Array} objects to render immediately and pushes the other in the activeGroup.
  9986. */
  9987. _chooseObjectsToRender: function() {
  9988. var activeObjects = this.getActiveObjects(),
  9989. object, objsToRender, activeGroupObjects;
  9990. if (activeObjects.length > 0 && !this.preserveObjectStacking) {
  9991. objsToRender = [];
  9992. activeGroupObjects = [];
  9993. for (var i = 0, length = this._objects.length; i < length; i++) {
  9994. object = this._objects[i];
  9995. if (activeObjects.indexOf(object) === -1 ) {
  9996. objsToRender.push(object);
  9997. }
  9998. else {
  9999. activeGroupObjects.push(object);
  10000. }
  10001. }
  10002. if (activeObjects.length > 1) {
  10003. this._activeObject._objects = activeGroupObjects;
  10004. }
  10005. objsToRender.push.apply(objsToRender, activeGroupObjects);
  10006. }
  10007. else {
  10008. objsToRender = this._objects;
  10009. }
  10010. return objsToRender;
  10011. },
  10012. /**
  10013. * Renders both the top canvas and the secondary container canvas.
  10014. * @return {fabric.Canvas} instance
  10015. * @chainable
  10016. */
  10017. renderAll: function () {
  10018. if (this.contextTopDirty && !this._groupSelector && !this.isDrawingMode) {
  10019. this.clearContext(this.contextTop);
  10020. this.contextTopDirty = false;
  10021. }
  10022. if (this.hasLostContext) {
  10023. this.renderTopLayer(this.contextTop);
  10024. }
  10025. var canvasToDrawOn = this.contextContainer;
  10026. this.renderCanvas(canvasToDrawOn, this._chooseObjectsToRender());
  10027. return this;
  10028. },
  10029. renderTopLayer: function(ctx) {
  10030. if (this.isDrawingMode && this._isCurrentlyDrawing) {
  10031. this.freeDrawingBrush && this.freeDrawingBrush._render();
  10032. }
  10033. // we render the top context - last object
  10034. if (this.selection && this._groupSelector) {
  10035. this._drawSelection(ctx);
  10036. }
  10037. },
  10038. /**
  10039. * Method to render only the top canvas.
  10040. * Also used to render the group selection box.
  10041. * @return {fabric.Canvas} thisArg
  10042. * @chainable
  10043. */
  10044. renderTop: function () {
  10045. var ctx = this.contextTop;
  10046. this.clearContext(ctx);
  10047. this.renderTopLayer(ctx);
  10048. this.fire('after:render');
  10049. this.contextTopDirty = true;
  10050. return this;
  10051. },
  10052. /**
  10053. * Resets the current transform to its original values and chooses the type of resizing based on the event
  10054. * @private
  10055. */
  10056. _resetCurrentTransform: function() {
  10057. var t = this._currentTransform;
  10058. t.target.set({
  10059. scaleX: t.original.scaleX,
  10060. scaleY: t.original.scaleY,
  10061. skewX: t.original.skewX,
  10062. skewY: t.original.skewY,
  10063. left: t.original.left,
  10064. top: t.original.top
  10065. });
  10066. if (this._shouldCenterTransform(t.target)) {
  10067. if (t.originX !== 'center') {
  10068. if (t.originX === 'right') {
  10069. t.mouseXSign = -1;
  10070. }
  10071. else {
  10072. t.mouseXSign = 1;
  10073. }
  10074. }
  10075. if (t.originY !== 'center') {
  10076. if (t.originY === 'bottom') {
  10077. t.mouseYSign = -1;
  10078. }
  10079. else {
  10080. t.mouseYSign = 1;
  10081. }
  10082. }
  10083. t.originX = 'center';
  10084. t.originY = 'center';
  10085. }
  10086. else {
  10087. t.originX = t.original.originX;
  10088. t.originY = t.original.originY;
  10089. }
  10090. },
  10091. /**
  10092. * Checks if point is contained within an area of given object
  10093. * @param {Event} e Event object
  10094. * @param {fabric.Object} target Object to test against
  10095. * @param {Object} [point] x,y object of point coordinates we want to check.
  10096. * @return {Boolean} true if point is contained within an area of given object
  10097. */
  10098. containsPoint: function (e, target, point) {
  10099. var ignoreZoom = true,
  10100. pointer = point || this.getPointer(e, ignoreZoom),
  10101. xy;
  10102. if (target.group && target.group === this._activeObject && target.group.type === 'activeSelection') {
  10103. xy = this._normalizePointer(target.group, pointer);
  10104. }
  10105. else {
  10106. xy = { x: pointer.x, y: pointer.y };
  10107. }
  10108. // http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html
  10109. // http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html
  10110. return (target.containsPoint(xy) || target._findTargetCorner(pointer));
  10111. },
  10112. /**
  10113. * @private
  10114. */
  10115. _normalizePointer: function (object, pointer) {
  10116. var m = object.calcTransformMatrix(),
  10117. invertedM = fabric.util.invertTransform(m),
  10118. vptPointer = this.restorePointerVpt(pointer);
  10119. return fabric.util.transformPoint(vptPointer, invertedM);
  10120. },
  10121. /**
  10122. * Returns true if object is transparent at a certain location
  10123. * @param {fabric.Object} target Object to check
  10124. * @param {Number} x Left coordinate
  10125. * @param {Number} y Top coordinate
  10126. * @return {Boolean}
  10127. */
  10128. isTargetTransparent: function (target, x, y) {
  10129. if (target.shouldCache() && target._cacheCanvas) {
  10130. var normalizedPointer = this._normalizePointer(target, {x: x, y: y}),
  10131. targetRelativeX = target.cacheTranslationX + (normalizedPointer.x * target.zoomX),
  10132. targetRelativeY = target.cacheTranslationY + (normalizedPointer.y * target.zoomY);
  10133. var isTransparent = fabric.util.isTransparent(
  10134. target._cacheContext, targetRelativeX, targetRelativeY, this.targetFindTolerance);
  10135. return isTransparent;
  10136. }
  10137. var ctx = this.contextCache,
  10138. originalColor = target.selectionBackgroundColor, v = this.viewportTransform;
  10139. target.selectionBackgroundColor = '';
  10140. this.clearContext(ctx);
  10141. ctx.save();
  10142. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  10143. target.render(ctx);
  10144. ctx.restore();
  10145. target === this._activeObject && target._renderControls(ctx, {
  10146. hasBorders: false,
  10147. transparentCorners: false
  10148. }, {
  10149. hasBorders: false,
  10150. });
  10151. target.selectionBackgroundColor = originalColor;
  10152. var isTransparent = fabric.util.isTransparent(
  10153. ctx, x, y, this.targetFindTolerance);
  10154. return isTransparent;
  10155. },
  10156. /**
  10157. * takes an event and determins if selection key has been pressed
  10158. * @private
  10159. * @param {Event} e Event object
  10160. */
  10161. _isSelectionKeyPressed: function(e) {
  10162. var selectionKeyPressed = false;
  10163. if (Object.prototype.toString.call(this.selectionKey) === '[object Array]') {
  10164. selectionKeyPressed = !!this.selectionKey.find(function(key) { return e[key] === true; });
  10165. }
  10166. else {
  10167. selectionKeyPressed = e[this.selectionKey];
  10168. }
  10169. return selectionKeyPressed;
  10170. },
  10171. /**
  10172. * @private
  10173. * @param {Event} e Event object
  10174. * @param {fabric.Object} target
  10175. */
  10176. _shouldClearSelection: function (e, target) {
  10177. var activeObjects = this.getActiveObjects(),
  10178. activeObject = this._activeObject;
  10179. return (
  10180. !target
  10181. ||
  10182. (target &&
  10183. activeObject &&
  10184. activeObjects.length > 1 &&
  10185. activeObjects.indexOf(target) === -1 &&
  10186. activeObject !== target &&
  10187. !this._isSelectionKeyPressed(e))
  10188. ||
  10189. (target && !target.evented)
  10190. ||
  10191. (target &&
  10192. !target.selectable &&
  10193. activeObject &&
  10194. activeObject !== target)
  10195. );
  10196. },
  10197. /**
  10198. * centeredScaling from object can't override centeredScaling from canvas.
  10199. * this should be fixed, since object setting should take precedence over canvas.
  10200. * @private
  10201. * @param {fabric.Object} target
  10202. */
  10203. _shouldCenterTransform: function (target) {
  10204. if (!target) {
  10205. return;
  10206. }
  10207. var t = this._currentTransform,
  10208. centerTransform;
  10209. if (t.action === 'scale' || t.action === 'scaleX' || t.action === 'scaleY') {
  10210. centerTransform = this.centeredScaling || target.centeredScaling;
  10211. }
  10212. else if (t.action === 'rotate') {
  10213. centerTransform = this.centeredRotation || target.centeredRotation;
  10214. }
  10215. return centerTransform ? !t.altKey : t.altKey;
  10216. },
  10217. /**
  10218. * @private
  10219. */
  10220. _getOriginFromCorner: function(target, corner) {
  10221. var origin = {
  10222. x: target.originX,
  10223. y: target.originY
  10224. };
  10225. if (corner === 'ml' || corner === 'tl' || corner === 'bl') {
  10226. origin.x = 'right';
  10227. }
  10228. else if (corner === 'mr' || corner === 'tr' || corner === 'br') {
  10229. origin.x = 'left';
  10230. }
  10231. if (corner === 'tl' || corner === 'mt' || corner === 'tr') {
  10232. origin.y = 'bottom';
  10233. }
  10234. else if (corner === 'bl' || corner === 'mb' || corner === 'br') {
  10235. origin.y = 'top';
  10236. }
  10237. return origin;
  10238. },
  10239. /**
  10240. * @private
  10241. */
  10242. _getActionFromCorner: function(target, corner, e) {
  10243. if (!corner) {
  10244. return 'drag';
  10245. }
  10246. switch (corner) {
  10247. case 'mtr':
  10248. return 'rotate';
  10249. case 'ml':
  10250. case 'mr':
  10251. return e[this.altActionKey] ? 'skewY' : 'scaleX';
  10252. case 'mt':
  10253. case 'mb':
  10254. return e[this.altActionKey] ? 'skewX' : 'scaleY';
  10255. default:
  10256. return 'scale';
  10257. }
  10258. },
  10259. /**
  10260. * @private
  10261. * @param {Event} e Event object
  10262. * @param {fabric.Object} target
  10263. */
  10264. _setupCurrentTransform: function (e, target) {
  10265. if (!target) {
  10266. return;
  10267. }
  10268. var pointer = this.getPointer(e),
  10269. corner = target._findTargetCorner(this.getPointer(e, true)),
  10270. action = this._getActionFromCorner(target, corner, e),
  10271. origin = this._getOriginFromCorner(target, corner);
  10272. this._currentTransform = {
  10273. target: target,
  10274. action: action,
  10275. corner: corner,
  10276. scaleX: target.scaleX,
  10277. scaleY: target.scaleY,
  10278. skewX: target.skewX,
  10279. skewY: target.skewY,
  10280. // used by transation
  10281. offsetX: pointer.x - target.left,
  10282. offsetY: pointer.y - target.top,
  10283. originX: origin.x,
  10284. originY: origin.y,
  10285. ex: pointer.x,
  10286. ey: pointer.y,
  10287. lastX: pointer.x,
  10288. lastY: pointer.y,
  10289. // unsure they are usefull anymore.
  10290. // left: target.left,
  10291. // top: target.top,
  10292. theta: degreesToRadians(target.angle),
  10293. // end of unsure
  10294. width: target.width * target.scaleX,
  10295. mouseXSign: 1,
  10296. mouseYSign: 1,
  10297. shiftKey: e.shiftKey,
  10298. altKey: e[this.centeredKey]
  10299. };
  10300. this._currentTransform.original = {
  10301. left: target.left,
  10302. top: target.top,
  10303. scaleX: target.scaleX,
  10304. scaleY: target.scaleY,
  10305. skewX: target.skewX,
  10306. skewY: target.skewY,
  10307. originX: origin.x,
  10308. originY: origin.y
  10309. };
  10310. this._resetCurrentTransform();
  10311. this._beforeTransform(e);
  10312. },
  10313. /**
  10314. * Translates object by "setting" its left/top
  10315. * @private
  10316. * @param {Number} x pointer's x coordinate
  10317. * @param {Number} y pointer's y coordinate
  10318. * @return {Boolean} true if the translation occurred
  10319. */
  10320. _translateObject: function (x, y) {
  10321. var transform = this._currentTransform,
  10322. target = transform.target,
  10323. newLeft = x - transform.offsetX,
  10324. newTop = y - transform.offsetY,
  10325. moveX = !target.get('lockMovementX') && target.left !== newLeft,
  10326. moveY = !target.get('lockMovementY') && target.top !== newTop;
  10327. moveX && target.set('left', newLeft);
  10328. moveY && target.set('top', newTop);
  10329. return moveX || moveY;
  10330. },
  10331. /**
  10332. * Check if we are increasing a positive skew or lower it,
  10333. * checking mouse direction and pressed corner.
  10334. * @private
  10335. */
  10336. _changeSkewTransformOrigin: function(mouseMove, t, by) {
  10337. var property = 'originX', origins = { 0: 'center' },
  10338. skew = t.target.skewX, originA = 'left', originB = 'right',
  10339. corner = t.corner === 'mt' || t.corner === 'ml' ? 1 : -1,
  10340. flipSign = 1;
  10341. mouseMove = mouseMove > 0 ? 1 : -1;
  10342. if (by === 'y') {
  10343. skew = t.target.skewY;
  10344. originA = 'top';
  10345. originB = 'bottom';
  10346. property = 'originY';
  10347. }
  10348. origins[-1] = originA;
  10349. origins[1] = originB;
  10350. t.target.flipX && (flipSign *= -1);
  10351. t.target.flipY && (flipSign *= -1);
  10352. if (skew === 0) {
  10353. t.skewSign = -corner * mouseMove * flipSign;
  10354. t[property] = origins[-mouseMove];
  10355. }
  10356. else {
  10357. skew = skew > 0 ? 1 : -1;
  10358. t.skewSign = skew;
  10359. t[property] = origins[skew * corner * flipSign];
  10360. }
  10361. },
  10362. /**
  10363. * Skew object by mouse events
  10364. * @private
  10365. * @param {Number} x pointer's x coordinate
  10366. * @param {Number} y pointer's y coordinate
  10367. * @param {String} by Either 'x' or 'y'
  10368. * @return {Boolean} true if the skewing occurred
  10369. */
  10370. _skewObject: function (x, y, by) {
  10371. var t = this._currentTransform,
  10372. target = t.target, skewed = false,
  10373. lockSkewingX = target.get('lockSkewingX'),
  10374. lockSkewingY = target.get('lockSkewingY');
  10375. if ((lockSkewingX && by === 'x') || (lockSkewingY && by === 'y')) {
  10376. return false;
  10377. }
  10378. // Get the constraint point
  10379. var center = target.getCenterPoint(),
  10380. actualMouseByCenter = target.toLocalPoint(new fabric.Point(x, y), 'center', 'center')[by],
  10381. lastMouseByCenter = target.toLocalPoint(new fabric.Point(t.lastX, t.lastY), 'center', 'center')[by],
  10382. actualMouseByOrigin, constraintPosition, dim = target._getTransformedDimensions();
  10383. this._changeSkewTransformOrigin(actualMouseByCenter - lastMouseByCenter, t, by);
  10384. actualMouseByOrigin = target.toLocalPoint(new fabric.Point(x, y), t.originX, t.originY)[by];
  10385. constraintPosition = target.translateToOriginPoint(center, t.originX, t.originY);
  10386. // Actually skew the object
  10387. skewed = this._setObjectSkew(actualMouseByOrigin, t, by, dim);
  10388. t.lastX = x;
  10389. t.lastY = y;
  10390. // Make sure the constraints apply
  10391. target.setPositionByOrigin(constraintPosition, t.originX, t.originY);
  10392. return skewed;
  10393. },
  10394. /**
  10395. * Set object skew
  10396. * @private
  10397. * @return {Boolean} true if the skewing occurred
  10398. */
  10399. _setObjectSkew: function(localMouse, transform, by, _dim) {
  10400. var target = transform.target, newValue, skewed = false,
  10401. skewSign = transform.skewSign, newDim, dimNoSkew,
  10402. otherBy, _otherBy, _by, newDimMouse, skewX, skewY;
  10403. if (by === 'x') {
  10404. otherBy = 'y';
  10405. _otherBy = 'Y';
  10406. _by = 'X';
  10407. skewX = 0;
  10408. skewY = target.skewY;
  10409. }
  10410. else {
  10411. otherBy = 'x';
  10412. _otherBy = 'X';
  10413. _by = 'Y';
  10414. skewX = target.skewX;
  10415. skewY = 0;
  10416. }
  10417. dimNoSkew = target._getTransformedDimensions(skewX, skewY);
  10418. newDimMouse = 2 * Math.abs(localMouse) - dimNoSkew[by];
  10419. if (newDimMouse <= 2) {
  10420. newValue = 0;
  10421. }
  10422. else {
  10423. newValue = skewSign * Math.atan((newDimMouse / target['scale' + _by]) /
  10424. (dimNoSkew[otherBy] / target['scale' + _otherBy]));
  10425. newValue = fabric.util.radiansToDegrees(newValue);
  10426. }
  10427. skewed = target['skew' + _by] !== newValue;
  10428. target.set('skew' + _by, newValue);
  10429. if (target['skew' + _otherBy] !== 0) {
  10430. newDim = target._getTransformedDimensions();
  10431. newValue = (_dim[otherBy] / newDim[otherBy]) * target['scale' + _otherBy];
  10432. target.set('scale' + _otherBy, newValue);
  10433. }
  10434. return skewed;
  10435. },
  10436. /**
  10437. * Scales object by invoking its scaleX/scaleY methods
  10438. * @private
  10439. * @param {Number} x pointer's x coordinate
  10440. * @param {Number} y pointer's y coordinate
  10441. * @param {String} by Either 'x' or 'y' - specifies dimension constraint by which to scale an object.
  10442. * When not provided, an object is scaled by both dimensions equally
  10443. * @return {Boolean} true if the scaling occurred
  10444. */
  10445. _scaleObject: function (x, y, by) {
  10446. var t = this._currentTransform,
  10447. target = t.target,
  10448. lockScalingX = target.lockScalingX,
  10449. lockScalingY = target.lockScalingY,
  10450. lockScalingFlip = target.lockScalingFlip;
  10451. if (lockScalingX && lockScalingY) {
  10452. return false;
  10453. }
  10454. // Get the constraint point
  10455. var constraintPosition = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY),
  10456. localMouse = target.toLocalPoint(new fabric.Point(x, y), t.originX, t.originY),
  10457. dim = target._getTransformedDimensions(), scaled = false;
  10458. this._setLocalMouse(localMouse, t);
  10459. // Actually scale the object
  10460. scaled = this._setObjectScale(localMouse, t, lockScalingX, lockScalingY, by, lockScalingFlip, dim);
  10461. // Make sure the constraints apply
  10462. target.setPositionByOrigin(constraintPosition, t.originX, t.originY);
  10463. return scaled;
  10464. },
  10465. /**
  10466. * @private
  10467. * @return {Boolean} true if the scaling occurred
  10468. */
  10469. _setObjectScale: function(localMouse, transform, lockScalingX, lockScalingY, by, lockScalingFlip, _dim) {
  10470. var target = transform.target, forbidScalingX = false, forbidScalingY = false, scaled = false,
  10471. changeX, changeY, scaleX, scaleY;
  10472. scaleX = localMouse.x * target.scaleX / _dim.x;
  10473. scaleY = localMouse.y * target.scaleY / _dim.y;
  10474. changeX = target.scaleX !== scaleX;
  10475. changeY = target.scaleY !== scaleY;
  10476. if (lockScalingFlip && scaleX <= 0 && scaleX < target.scaleX) {
  10477. forbidScalingX = true;
  10478. localMouse.x = 0;
  10479. }
  10480. if (lockScalingFlip && scaleY <= 0 && scaleY < target.scaleY) {
  10481. forbidScalingY = true;
  10482. localMouse.y = 0;
  10483. }
  10484. if (by === 'equally' && !lockScalingX && !lockScalingY) {
  10485. scaled = this._scaleObjectEqually(localMouse, target, transform, _dim);
  10486. }
  10487. else if (!by) {
  10488. forbidScalingX || lockScalingX || (target.set('scaleX', scaleX) && (scaled = scaled || changeX));
  10489. forbidScalingY || lockScalingY || (target.set('scaleY', scaleY) && (scaled = scaled || changeY));
  10490. }
  10491. else if (by === 'x' && !target.get('lockUniScaling')) {
  10492. forbidScalingX || lockScalingX || (target.set('scaleX', scaleX) && (scaled = scaled || changeX));
  10493. }
  10494. else if (by === 'y' && !target.get('lockUniScaling')) {
  10495. forbidScalingY || lockScalingY || (target.set('scaleY', scaleY) && (scaled = scaled || changeY));
  10496. }
  10497. transform.newScaleX = scaleX;
  10498. transform.newScaleY = scaleY;
  10499. forbidScalingX || forbidScalingY || this._flipObject(transform, by);
  10500. return scaled;
  10501. },
  10502. /**
  10503. * @private
  10504. * @return {Boolean} true if the scaling occurred
  10505. */
  10506. _scaleObjectEqually: function(localMouse, target, transform, _dim) {
  10507. var dist = localMouse.y + localMouse.x,
  10508. lastDist = _dim.y * transform.original.scaleY / target.scaleY +
  10509. _dim.x * transform.original.scaleX / target.scaleX,
  10510. scaled, signX = localMouse.x < 0 ? -1 : 1,
  10511. signY = localMouse.y < 0 ? -1 : 1;
  10512. // We use transform.scaleX/Y instead of target.scaleX/Y
  10513. // because the object may have a min scale and we'll loose the proportions
  10514. transform.newScaleX = signX * Math.abs(transform.original.scaleX * dist / lastDist);
  10515. transform.newScaleY = signY * Math.abs(transform.original.scaleY * dist / lastDist);
  10516. scaled = transform.newScaleX !== target.scaleX || transform.newScaleY !== target.scaleY;
  10517. target.set('scaleX', transform.newScaleX);
  10518. target.set('scaleY', transform.newScaleY);
  10519. return scaled;
  10520. },
  10521. /**
  10522. * @private
  10523. */
  10524. _flipObject: function(transform, by) {
  10525. if (transform.newScaleX < 0 && by !== 'y') {
  10526. if (transform.originX === 'left') {
  10527. transform.originX = 'right';
  10528. }
  10529. else if (transform.originX === 'right') {
  10530. transform.originX = 'left';
  10531. }
  10532. }
  10533. if (transform.newScaleY < 0 && by !== 'x') {
  10534. if (transform.originY === 'top') {
  10535. transform.originY = 'bottom';
  10536. }
  10537. else if (transform.originY === 'bottom') {
  10538. transform.originY = 'top';
  10539. }
  10540. }
  10541. },
  10542. /**
  10543. * @private
  10544. */
  10545. _setLocalMouse: function(localMouse, t) {
  10546. var target = t.target, zoom = this.getZoom(),
  10547. padding = target.padding / zoom;
  10548. if (t.originX === 'right') {
  10549. localMouse.x *= -1;
  10550. }
  10551. else if (t.originX === 'center') {
  10552. localMouse.x *= t.mouseXSign * 2;
  10553. if (localMouse.x < 0) {
  10554. t.mouseXSign = -t.mouseXSign;
  10555. }
  10556. }
  10557. if (t.originY === 'bottom') {
  10558. localMouse.y *= -1;
  10559. }
  10560. else if (t.originY === 'center') {
  10561. localMouse.y *= t.mouseYSign * 2;
  10562. if (localMouse.y < 0) {
  10563. t.mouseYSign = -t.mouseYSign;
  10564. }
  10565. }
  10566. // adjust the mouse coordinates when dealing with padding
  10567. if (abs(localMouse.x) > padding) {
  10568. if (localMouse.x < 0) {
  10569. localMouse.x += padding;
  10570. }
  10571. else {
  10572. localMouse.x -= padding;
  10573. }
  10574. }
  10575. else { // mouse is within the padding, set to 0
  10576. localMouse.x = 0;
  10577. }
  10578. if (abs(localMouse.y) > padding) {
  10579. if (localMouse.y < 0) {
  10580. localMouse.y += padding;
  10581. }
  10582. else {
  10583. localMouse.y -= padding;
  10584. }
  10585. }
  10586. else {
  10587. localMouse.y = 0;
  10588. }
  10589. },
  10590. /**
  10591. * Rotates object by invoking its rotate method
  10592. * @private
  10593. * @param {Number} x pointer's x coordinate
  10594. * @param {Number} y pointer's y coordinate
  10595. * @return {Boolean} true if the rotation occurred
  10596. */
  10597. _rotateObject: function (x, y) {
  10598. var t = this._currentTransform,
  10599. target = t.target, constraintPosition,
  10600. constraintPosition = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY);
  10601. if (target.lockRotation) {
  10602. return false;
  10603. }
  10604. var lastAngle = atan2(t.ey - constraintPosition.y, t.ex - constraintPosition.x),
  10605. curAngle = atan2(y - constraintPosition.y, x - constraintPosition.x),
  10606. angle = radiansToDegrees(curAngle - lastAngle + t.theta),
  10607. hasRotated = true;
  10608. if (target.snapAngle > 0) {
  10609. var snapAngle = target.snapAngle,
  10610. snapThreshold = target.snapThreshold || snapAngle,
  10611. rightAngleLocked = Math.ceil(angle / snapAngle) * snapAngle,
  10612. leftAngleLocked = Math.floor(angle / snapAngle) * snapAngle;
  10613. if (Math.abs(angle - leftAngleLocked) < snapThreshold) {
  10614. angle = leftAngleLocked;
  10615. }
  10616. else if (Math.abs(angle - rightAngleLocked) < snapThreshold) {
  10617. angle = rightAngleLocked;
  10618. }
  10619. }
  10620. // normalize angle to positive value
  10621. if (angle < 0) {
  10622. angle = 360 + angle;
  10623. }
  10624. angle %= 360;
  10625. if (target.angle === angle) {
  10626. hasRotated = false;
  10627. }
  10628. else {
  10629. // rotation only happen here
  10630. target.angle = angle;
  10631. // Make sure the constraints apply
  10632. target.setPositionByOrigin(constraintPosition, t.originX, t.originY);
  10633. }
  10634. return hasRotated;
  10635. },
  10636. /**
  10637. * Set the cursor type of the canvas element
  10638. * @param {String} value Cursor type of the canvas element.
  10639. * @see http://www.w3.org/TR/css3-ui/#cursor
  10640. */
  10641. setCursor: function (value) {
  10642. this.upperCanvasEl.style.cursor = value;
  10643. },
  10644. /**
  10645. * @param {fabric.Object} target to reset transform
  10646. * @private
  10647. */
  10648. _resetObjectTransform: function (target) {
  10649. target.scaleX = 1;
  10650. target.scaleY = 1;
  10651. target.skewX = 0;
  10652. target.skewY = 0;
  10653. target.rotate(0);
  10654. },
  10655. /**
  10656. * @private
  10657. * @param {CanvasRenderingContext2D} ctx to draw the selection on
  10658. */
  10659. _drawSelection: function (ctx) {
  10660. var groupSelector = this._groupSelector,
  10661. left = groupSelector.left,
  10662. top = groupSelector.top,
  10663. aleft = abs(left),
  10664. atop = abs(top);
  10665. if (this.selectionColor) {
  10666. ctx.fillStyle = this.selectionColor;
  10667. ctx.fillRect(
  10668. groupSelector.ex - ((left > 0) ? 0 : -left),
  10669. groupSelector.ey - ((top > 0) ? 0 : -top),
  10670. aleft,
  10671. atop
  10672. );
  10673. }
  10674. if (!this.selectionLineWidth || !this.selectionBorderColor) {
  10675. return;
  10676. }
  10677. ctx.lineWidth = this.selectionLineWidth;
  10678. ctx.strokeStyle = this.selectionBorderColor;
  10679. // selection border
  10680. if (this.selectionDashArray.length > 1 && !supportLineDash) {
  10681. var px = groupSelector.ex + STROKE_OFFSET - ((left > 0) ? 0 : aleft),
  10682. py = groupSelector.ey + STROKE_OFFSET - ((top > 0) ? 0 : atop);
  10683. ctx.beginPath();
  10684. fabric.util.drawDashedLine(ctx, px, py, px + aleft, py, this.selectionDashArray);
  10685. fabric.util.drawDashedLine(ctx, px, py + atop - 1, px + aleft, py + atop - 1, this.selectionDashArray);
  10686. fabric.util.drawDashedLine(ctx, px, py, px, py + atop, this.selectionDashArray);
  10687. fabric.util.drawDashedLine(ctx, px + aleft - 1, py, px + aleft - 1, py + atop, this.selectionDashArray);
  10688. ctx.closePath();
  10689. ctx.stroke();
  10690. }
  10691. else {
  10692. fabric.Object.prototype._setLineDash.call(this, ctx, this.selectionDashArray);
  10693. ctx.strokeRect(
  10694. groupSelector.ex + STROKE_OFFSET - ((left > 0) ? 0 : aleft),
  10695. groupSelector.ey + STROKE_OFFSET - ((top > 0) ? 0 : atop),
  10696. aleft,
  10697. atop
  10698. );
  10699. }
  10700. },
  10701. /**
  10702. * Method that determines what object we are clicking on
  10703. * the skipGroup parameter is for internal use, is needed for shift+click action
  10704. * @param {Event} e mouse event
  10705. * @param {Boolean} skipGroup when true, activeGroup is skipped and only objects are traversed through
  10706. */
  10707. findTarget: function (e, skipGroup) {
  10708. if (this.skipTargetFind) {
  10709. return;
  10710. }
  10711. var ignoreZoom = true,
  10712. pointer = this.getPointer(e, ignoreZoom),
  10713. activeObject = this._activeObject,
  10714. aObjects = this.getActiveObjects(),
  10715. activeTarget, activeTargetSubs;
  10716. // first check current group (if one exists)
  10717. // active group does not check sub targets like normal groups.
  10718. // if active group just exits.
  10719. this.targets = [];
  10720. if (aObjects.length > 1 && !skipGroup && activeObject === this._searchPossibleTargets([activeObject], pointer)) {
  10721. return activeObject;
  10722. }
  10723. // if we hit the corner of an activeObject, let's return that.
  10724. if (aObjects.length === 1 && activeObject._findTargetCorner(pointer)) {
  10725. return activeObject;
  10726. }
  10727. if (aObjects.length === 1 &&
  10728. activeObject === this._searchPossibleTargets([activeObject], pointer)) {
  10729. if (!this.preserveObjectStacking) {
  10730. return activeObject;
  10731. }
  10732. else {
  10733. activeTarget = activeObject;
  10734. activeTargetSubs = this.targets;
  10735. this.targets = [];
  10736. }
  10737. }
  10738. var target = this._searchPossibleTargets(this._objects, pointer);
  10739. if (e[this.altSelectionKey] && target && activeTarget && target !== activeTarget) {
  10740. target = activeTarget;
  10741. this.targets = activeTargetSubs;
  10742. }
  10743. return target;
  10744. },
  10745. /**
  10746. * @private
  10747. */
  10748. _checkTarget: function(pointer, obj) {
  10749. if (obj &&
  10750. obj.visible &&
  10751. obj.evented &&
  10752. this.containsPoint(null, obj, pointer)){
  10753. if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
  10754. var isTransparent = this.isTargetTransparent(obj, pointer.x, pointer.y);
  10755. if (!isTransparent) {
  10756. return true;
  10757. }
  10758. }
  10759. else {
  10760. return true;
  10761. }
  10762. }
  10763. },
  10764. /**
  10765. * @private
  10766. */
  10767. _searchPossibleTargets: function(objects, pointer) {
  10768. // Cache all targets where their bounding box contains point.
  10769. var target, i = objects.length, normalizedPointer, subTarget;
  10770. // Do not check for currently grouped objects, since we check the parent group itself.
  10771. // until we call this function specifically to search inside the activeGroup
  10772. while (i--) {
  10773. if (this._checkTarget(pointer, objects[i])) {
  10774. target = objects[i];
  10775. if (target.subTargetCheck && target instanceof fabric.Group) {
  10776. normalizedPointer = this._normalizePointer(target, pointer);
  10777. subTarget = this._searchPossibleTargets(target._objects, normalizedPointer);
  10778. subTarget && this.targets.push(subTarget);
  10779. }
  10780. break;
  10781. }
  10782. }
  10783. return target;
  10784. },
  10785. /**
  10786. * Returns pointer coordinates without the effect of the viewport
  10787. * @param {Object} pointer with "x" and "y" number values
  10788. * @return {Object} object with "x" and "y" number values
  10789. */
  10790. restorePointerVpt: function(pointer) {
  10791. return fabric.util.transformPoint(
  10792. pointer,
  10793. fabric.util.invertTransform(this.viewportTransform)
  10794. );
  10795. },
  10796. /**
  10797. * Returns pointer coordinates relative to canvas.
  10798. * Can return coordinates with or without viewportTransform.
  10799. * ignoreZoom false gives back coordinates that represent
  10800. * the point clicked on canvas element.
  10801. * ignoreZoom true gives back coordinates after being processed
  10802. * by the viewportTransform ( sort of coordinates of what is displayed
  10803. * on the canvas where you are clicking.
  10804. * ignoreZoom true = HTMLElement coordinates relative to top,left
  10805. * ignoreZoom false, default = fabric space coordinates, the same used for shape position
  10806. * To interact with your shapes top and left you want to use ignoreZoom true
  10807. * most of the time, while ignoreZoom false will give you coordinates
  10808. * compatible with the object.oCoords system.
  10809. * of the time.
  10810. * @param {Event} e
  10811. * @param {Boolean} ignoreZoom
  10812. * @return {Object} object with "x" and "y" number values
  10813. */
  10814. getPointer: function (e, ignoreZoom) {
  10815. // return cached values if we are in the event processing chain
  10816. if (this._absolutePointer && !ignoreZoom) {
  10817. return this._absolutePointer;
  10818. }
  10819. if (this._pointer && ignoreZoom) {
  10820. return this._pointer;
  10821. }
  10822. var pointer = getPointer(e),
  10823. upperCanvasEl = this.upperCanvasEl,
  10824. bounds = upperCanvasEl.getBoundingClientRect(),
  10825. boundsWidth = bounds.width || 0,
  10826. boundsHeight = bounds.height || 0,
  10827. cssScale;
  10828. if (!boundsWidth || !boundsHeight ) {
  10829. if ('top' in bounds && 'bottom' in bounds) {
  10830. boundsHeight = Math.abs( bounds.top - bounds.bottom );
  10831. }
  10832. if ('right' in bounds && 'left' in bounds) {
  10833. boundsWidth = Math.abs( bounds.right - bounds.left );
  10834. }
  10835. }
  10836. this.calcOffset();
  10837. pointer.x = pointer.x - this._offset.left;
  10838. pointer.y = pointer.y - this._offset.top;
  10839. if (!ignoreZoom) {
  10840. pointer = this.restorePointerVpt(pointer);
  10841. }
  10842. if (boundsWidth === 0 || boundsHeight === 0) {
  10843. // If bounds are not available (i.e. not visible), do not apply scale.
  10844. cssScale = { width: 1, height: 1 };
  10845. }
  10846. else {
  10847. cssScale = {
  10848. width: upperCanvasEl.width / boundsWidth,
  10849. height: upperCanvasEl.height / boundsHeight
  10850. };
  10851. }
  10852. return {
  10853. x: pointer.x * cssScale.width,
  10854. y: pointer.y * cssScale.height
  10855. };
  10856. },
  10857. /**
  10858. * @private
  10859. * @throws {CANVAS_INIT_ERROR} If canvas can not be initialized
  10860. */
  10861. _createUpperCanvas: function () {
  10862. var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/, '');
  10863. // there is no need to create a new upperCanvas element if we have already one.
  10864. if (this.upperCanvasEl) {
  10865. this.upperCanvasEl.className = '';
  10866. }
  10867. else {
  10868. this.upperCanvasEl = this._createCanvasElement();
  10869. }
  10870. fabric.util.addClass(this.upperCanvasEl, 'upper-canvas ' + lowerCanvasClass);
  10871. this.wrapperEl.appendChild(this.upperCanvasEl);
  10872. this._copyCanvasStyle(this.lowerCanvasEl, this.upperCanvasEl);
  10873. this._applyCanvasStyle(this.upperCanvasEl);
  10874. this.contextTop = this.upperCanvasEl.getContext('2d');
  10875. },
  10876. /**
  10877. * @private
  10878. */
  10879. _createCacheCanvas: function () {
  10880. this.cacheCanvasEl = this._createCanvasElement();
  10881. this.cacheCanvasEl.setAttribute('width', this.width);
  10882. this.cacheCanvasEl.setAttribute('height', this.height);
  10883. this.contextCache = this.cacheCanvasEl.getContext('2d');
  10884. },
  10885. /**
  10886. * @private
  10887. */
  10888. _initWrapperElement: function () {
  10889. this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, 'div', {
  10890. 'class': this.containerClass
  10891. });
  10892. fabric.util.setStyle(this.wrapperEl, {
  10893. width: this.width + 'px',
  10894. height: this.height + 'px',
  10895. position: 'relative'
  10896. });
  10897. fabric.util.makeElementUnselectable(this.wrapperEl);
  10898. },
  10899. /**
  10900. * @private
  10901. * @param {HTMLElement} element canvas element to apply styles on
  10902. */
  10903. _applyCanvasStyle: function (element) {
  10904. var width = this.width || element.width,
  10905. height = this.height || element.height;
  10906. fabric.util.setStyle(element, {
  10907. position: 'absolute',
  10908. width: width + 'px',
  10909. height: height + 'px',
  10910. left: 0,
  10911. top: 0,
  10912. 'touch-action': this.allowTouchScrolling ? 'manipulation' : 'none'
  10913. });
  10914. element.width = width;
  10915. element.height = height;
  10916. fabric.util.makeElementUnselectable(element);
  10917. },
  10918. /**
  10919. * Copy the entire inline style from one element (fromEl) to another (toEl)
  10920. * @private
  10921. * @param {Element} fromEl Element style is copied from
  10922. * @param {Element} toEl Element copied style is applied to
  10923. */
  10924. _copyCanvasStyle: function (fromEl, toEl) {
  10925. toEl.style.cssText = fromEl.style.cssText;
  10926. },
  10927. /**
  10928. * Returns context of canvas where object selection is drawn
  10929. * @return {CanvasRenderingContext2D}
  10930. */
  10931. getSelectionContext: function() {
  10932. return this.contextTop;
  10933. },
  10934. /**
  10935. * Returns &lt;canvas> element on which object selection is drawn
  10936. * @return {HTMLCanvasElement}
  10937. */
  10938. getSelectionElement: function () {
  10939. return this.upperCanvasEl;
  10940. },
  10941. /**
  10942. * Returns currently active object
  10943. * @return {fabric.Object} active object
  10944. */
  10945. getActiveObject: function () {
  10946. return this._activeObject;
  10947. },
  10948. /**
  10949. * Returns an array with the current selected objects
  10950. * @return {fabric.Object} active object
  10951. */
  10952. getActiveObjects: function () {
  10953. var active = this._activeObject;
  10954. if (active) {
  10955. if (active.type === 'activeSelection' && active._objects) {
  10956. return active._objects.slice(0);
  10957. }
  10958. else {
  10959. return [active];
  10960. }
  10961. }
  10962. return [];
  10963. },
  10964. /**
  10965. * @private
  10966. * @param {fabric.Object} obj Object that was removed
  10967. */
  10968. _onObjectRemoved: function(obj) {
  10969. // removing active object should fire "selection:cleared" events
  10970. if (obj === this._activeObject) {
  10971. this.fire('before:selection:cleared', { target: obj });
  10972. this._discardActiveObject();
  10973. this.fire('selection:cleared', { target: obj });
  10974. obj.fire('deselected');
  10975. }
  10976. if (this._hoveredTarget === obj) {
  10977. this._hoveredTarget = null;
  10978. }
  10979. this.callSuper('_onObjectRemoved', obj);
  10980. },
  10981. /**
  10982. * @private
  10983. * Compares the old activeObject with the current one and fires correct events
  10984. * @param {fabric.Object} obj old activeObject
  10985. */
  10986. _fireSelectionEvents: function(oldObjects, e) {
  10987. var somethingChanged = false, objects = this.getActiveObjects(),
  10988. added = [], removed = [], opt = { e: e };
  10989. oldObjects.forEach(function(oldObject) {
  10990. if (objects.indexOf(oldObject) === -1) {
  10991. somethingChanged = true;
  10992. oldObject.fire('deselected', opt);
  10993. removed.push(oldObject);
  10994. }
  10995. });
  10996. objects.forEach(function(object) {
  10997. if (oldObjects.indexOf(object) === -1) {
  10998. somethingChanged = true;
  10999. object.fire('selected', opt);
  11000. added.push(object);
  11001. }
  11002. });
  11003. if (oldObjects.length > 0 && objects.length > 0) {
  11004. opt.selected = added;
  11005. opt.deselected = removed;
  11006. // added for backward compatibility
  11007. opt.updated = added[0] || removed[0];
  11008. opt.target = this._activeObject;
  11009. somethingChanged && this.fire('selection:updated', opt);
  11010. }
  11011. else if (objects.length > 0) {
  11012. // deprecated event
  11013. if (objects.length === 1) {
  11014. opt.target = added[0];
  11015. this.fire('object:selected', opt);
  11016. }
  11017. opt.selected = added;
  11018. // added for backward compatibility
  11019. opt.target = this._activeObject;
  11020. this.fire('selection:created', opt);
  11021. }
  11022. else if (oldObjects.length > 0) {
  11023. opt.deselected = removed;
  11024. this.fire('selection:cleared', opt);
  11025. }
  11026. },
  11027. /**
  11028. * Sets given object as the only active object on canvas
  11029. * @param {fabric.Object} object Object to set as an active one
  11030. * @param {Event} [e] Event (passed along when firing "object:selected")
  11031. * @return {fabric.Canvas} thisArg
  11032. * @chainable
  11033. */
  11034. setActiveObject: function (object, e) {
  11035. var currentActives = this.getActiveObjects();
  11036. this._setActiveObject(object, e);
  11037. this._fireSelectionEvents(currentActives, e);
  11038. return this;
  11039. },
  11040. /**
  11041. * @private
  11042. * @param {Object} object to set as active
  11043. * @param {Event} [e] Event (passed along when firing "object:selected")
  11044. * @return {Boolean} true if the selection happened
  11045. */
  11046. _setActiveObject: function(object, e) {
  11047. if (this._activeObject === object) {
  11048. return false;
  11049. }
  11050. if (!this._discardActiveObject(e, object)) {
  11051. return false;
  11052. }
  11053. if (object.onSelect({ e: e })) {
  11054. return false;
  11055. }
  11056. this._activeObject = object;
  11057. return true;
  11058. },
  11059. /**
  11060. * @private
  11061. */
  11062. _discardActiveObject: function(e, object) {
  11063. var obj = this._activeObject;
  11064. if (obj) {
  11065. // onDeselect return TRUE to cancel selection;
  11066. if (obj.onDeselect({ e: e, object: object })) {
  11067. return false;
  11068. }
  11069. this._activeObject = null;
  11070. }
  11071. return true;
  11072. },
  11073. /**
  11074. * Discards currently active object and fire events. If the function is called by fabric
  11075. * as a consequence of a mouse event, the event is passed as a parameter and
  11076. * sent to the fire function for the custom events. When used as a method the
  11077. * e param does not have any application.
  11078. * @param {event} e
  11079. * @return {fabric.Canvas} thisArg
  11080. * @chainable
  11081. */
  11082. discardActiveObject: function (e) {
  11083. var currentActives = this.getActiveObjects();
  11084. if (currentActives.length) {
  11085. this.fire('before:selection:cleared', { target: currentActives[0], e: e });
  11086. }
  11087. this._discardActiveObject(e);
  11088. this._fireSelectionEvents(currentActives, e);
  11089. return this;
  11090. },
  11091. /**
  11092. * Clears a canvas element and removes all event listeners
  11093. * @return {fabric.Canvas} thisArg
  11094. * @chainable
  11095. */
  11096. dispose: function () {
  11097. var wrapper = this.wrapperEl;
  11098. this.removeListeners();
  11099. wrapper.removeChild(this.upperCanvasEl);
  11100. wrapper.removeChild(this.lowerCanvasEl);
  11101. this.upperCanvasEl = null;
  11102. this.cacheCanvasEl = null;
  11103. this.contextCache = null;
  11104. this.contextTop = null;
  11105. if (wrapper.parentNode) {
  11106. wrapper.parentNode.replaceChild(this.lowerCanvasEl, this.wrapperEl);
  11107. }
  11108. delete this.wrapperEl;
  11109. fabric.StaticCanvas.prototype.dispose.call(this);
  11110. return this;
  11111. },
  11112. /**
  11113. * Clears all contexts (background, main, top) of an instance
  11114. * @return {fabric.Canvas} thisArg
  11115. * @chainable
  11116. */
  11117. clear: function () {
  11118. // this.discardActiveGroup();
  11119. this.discardActiveObject();
  11120. this.clearContext(this.contextTop);
  11121. return this.callSuper('clear');
  11122. },
  11123. /**
  11124. * Draws objects' controls (borders/controls)
  11125. * @param {CanvasRenderingContext2D} ctx Context to render controls on
  11126. */
  11127. drawControls: function(ctx) {
  11128. var activeObject = this._activeObject;
  11129. if (activeObject) {
  11130. activeObject._renderControls(ctx);
  11131. }
  11132. },
  11133. /**
  11134. * @private
  11135. */
  11136. _toObject: function(instance, methodName, propertiesToInclude) {
  11137. //If the object is part of the current selection group, it should
  11138. //be transformed appropriately
  11139. //i.e. it should be serialised as it would appear if the selection group
  11140. //were to be destroyed.
  11141. var originalProperties = this._realizeGroupTransformOnObject(instance),
  11142. object = this.callSuper('_toObject', instance, methodName, propertiesToInclude);
  11143. //Undo the damage we did by changing all of its properties
  11144. this._unwindGroupTransformOnObject(instance, originalProperties);
  11145. return object;
  11146. },
  11147. /**
  11148. * Realises an object's group transformation on it
  11149. * @private
  11150. * @param {fabric.Object} [instance] the object to transform (gets mutated)
  11151. * @returns the original values of instance which were changed
  11152. */
  11153. _realizeGroupTransformOnObject: function(instance) {
  11154. if (instance.group && instance.group.type === 'activeSelection' && this._activeObject === instance.group) {
  11155. var layoutProps = ['angle', 'flipX', 'flipY', 'left', 'scaleX', 'scaleY', 'skewX', 'skewY', 'top'];
  11156. //Copy all the positionally relevant properties across now
  11157. var originalValues = {};
  11158. layoutProps.forEach(function(prop) {
  11159. originalValues[prop] = instance[prop];
  11160. });
  11161. this._activeObject.realizeTransform(instance);
  11162. return originalValues;
  11163. }
  11164. else {
  11165. return null;
  11166. }
  11167. },
  11168. /**
  11169. * Restores the changed properties of instance
  11170. * @private
  11171. * @param {fabric.Object} [instance] the object to un-transform (gets mutated)
  11172. * @param {Object} [originalValues] the original values of instance, as returned by _realizeGroupTransformOnObject
  11173. */
  11174. _unwindGroupTransformOnObject: function(instance, originalValues) {
  11175. if (originalValues) {
  11176. instance.set(originalValues);
  11177. }
  11178. },
  11179. /**
  11180. * @private
  11181. */
  11182. _setSVGObject: function(markup, instance, reviver) {
  11183. //If the object is in a selection group, simulate what would happen to that
  11184. //object when the group is deselected
  11185. var originalProperties = this._realizeGroupTransformOnObject(instance);
  11186. this.callSuper('_setSVGObject', markup, instance, reviver);
  11187. this._unwindGroupTransformOnObject(instance, originalProperties);
  11188. },
  11189. setViewportTransform: function (vpt) {
  11190. if (this.renderOnAddRemove && this._activeObject && this._activeObject.isEditing) {
  11191. this._activeObject.clearContextTop();
  11192. }
  11193. fabric.StaticCanvas.prototype.setViewportTransform.call(this, vpt);
  11194. }
  11195. });
  11196. // copying static properties manually to work around Opera's bug,
  11197. // where "prototype" property is enumerable and overrides existing prototype
  11198. for (var prop in fabric.StaticCanvas) {
  11199. if (prop !== 'prototype') {
  11200. fabric.Canvas[prop] = fabric.StaticCanvas[prop];
  11201. }
  11202. }
  11203. if (fabric.isTouchSupported) {
  11204. /** @ignore */
  11205. fabric.Canvas.prototype._setCursorFromEvent = function() { };
  11206. }
  11207. })();
  11208. (function() {
  11209. var cursorOffset = {
  11210. mt: 0, // n
  11211. tr: 1, // ne
  11212. mr: 2, // e
  11213. br: 3, // se
  11214. mb: 4, // s
  11215. bl: 5, // sw
  11216. ml: 6, // w
  11217. tl: 7 // nw
  11218. },
  11219. addListener = fabric.util.addListener,
  11220. removeListener = fabric.util.removeListener,
  11221. RIGHT_CLICK = 3, MIDDLE_CLICK = 2, LEFT_CLICK = 1,
  11222. addEventOptions = { passive: false };
  11223. function checkClick(e, value) {
  11224. return 'which' in e ? e.which === value : e.button === value - 1;
  11225. }
  11226. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  11227. /**
  11228. * Map of cursor style values for each of the object controls
  11229. * @private
  11230. */
  11231. cursorMap: [
  11232. 'n-resize',
  11233. 'ne-resize',
  11234. 'e-resize',
  11235. 'se-resize',
  11236. 's-resize',
  11237. 'sw-resize',
  11238. 'w-resize',
  11239. 'nw-resize'
  11240. ],
  11241. /**
  11242. * Adds mouse listeners to canvas
  11243. * @private
  11244. */
  11245. _initEventListeners: function () {
  11246. // in case we initialized the class twice. This should not happen normally
  11247. // but in some kind of applications where the canvas element may be changed
  11248. // this is a workaround to having double listeners.
  11249. this.removeListeners();
  11250. this._bindEvents();
  11251. this.addOrRemove(addListener, 'add');
  11252. },
  11253. addOrRemove: function(functor, eventjsFunctor) {
  11254. functor(fabric.window, 'resize', this._onResize);
  11255. functor(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  11256. functor(this.upperCanvasEl, 'mousemove', this._onMouseMove, addEventOptions);
  11257. functor(this.upperCanvasEl, 'mouseout', this._onMouseOut);
  11258. functor(this.upperCanvasEl, 'mouseenter', this._onMouseEnter);
  11259. functor(this.upperCanvasEl, 'wheel', this._onMouseWheel);
  11260. functor(this.upperCanvasEl, 'contextmenu', this._onContextMenu);
  11261. functor(this.upperCanvasEl, 'dblclick', this._onDoubleClick);
  11262. functor(this.upperCanvasEl, 'touchstart', this._onMouseDown, addEventOptions);
  11263. functor(this.upperCanvasEl, 'touchmove', this._onMouseMove, addEventOptions);
  11264. functor(this.upperCanvasEl, 'dragover', this._onDragOver);
  11265. functor(this.upperCanvasEl, 'dragenter', this._onDragEnter);
  11266. functor(this.upperCanvasEl, 'dragleave', this._onDragLeave);
  11267. functor(this.upperCanvasEl, 'drop', this._onDrop);
  11268. if (typeof eventjs !== 'undefined' && eventjsFunctor in eventjs) {
  11269. eventjs[eventjsFunctor](this.upperCanvasEl, 'gesture', this._onGesture);
  11270. eventjs[eventjsFunctor](this.upperCanvasEl, 'drag', this._onDrag);
  11271. eventjs[eventjsFunctor](this.upperCanvasEl, 'orientation', this._onOrientationChange);
  11272. eventjs[eventjsFunctor](this.upperCanvasEl, 'shake', this._onShake);
  11273. eventjs[eventjsFunctor](this.upperCanvasEl, 'longpress', this._onLongPress);
  11274. }
  11275. },
  11276. /**
  11277. * Removes all event listeners
  11278. */
  11279. removeListeners: function() {
  11280. this.addOrRemove(removeListener, 'remove');
  11281. // if you dispose on a mouseDown, before mouse up, you need to clean document to...
  11282. removeListener(fabric.document, 'mouseup', this._onMouseUp);
  11283. removeListener(fabric.document, 'touchend', this._onMouseUp, addEventOptions);
  11284. removeListener(fabric.document, 'mousemove', this._onMouseMove, addEventOptions);
  11285. removeListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);
  11286. },
  11287. /**
  11288. * @private
  11289. */
  11290. _bindEvents: function() {
  11291. if (this.eventsBound) {
  11292. // for any reason we pass here twice we do not want to bind events twice.
  11293. return;
  11294. }
  11295. this._onMouseDown = this._onMouseDown.bind(this);
  11296. this._onMouseMove = this._onMouseMove.bind(this);
  11297. this._onMouseUp = this._onMouseUp.bind(this);
  11298. this._onResize = this._onResize.bind(this);
  11299. this._onGesture = this._onGesture.bind(this);
  11300. this._onDrag = this._onDrag.bind(this);
  11301. this._onShake = this._onShake.bind(this);
  11302. this._onLongPress = this._onLongPress.bind(this);
  11303. this._onOrientationChange = this._onOrientationChange.bind(this);
  11304. this._onMouseWheel = this._onMouseWheel.bind(this);
  11305. this._onMouseOut = this._onMouseOut.bind(this);
  11306. this._onMouseEnter = this._onMouseEnter.bind(this);
  11307. this._onContextMenu = this._onContextMenu.bind(this);
  11308. this._onDoubleClick = this._onDoubleClick.bind(this);
  11309. this._onDragOver = this._onDragOver.bind(this);
  11310. this._onDragEnter = this._simpleEventHandler.bind(this, 'dragenter');
  11311. this._onDragLeave = this._simpleEventHandler.bind(this, 'dragleave');
  11312. this._onDrop = this._simpleEventHandler.bind(this, 'drop');
  11313. this.eventsBound = true;
  11314. },
  11315. /**
  11316. * @private
  11317. * @param {Event} [e] Event object fired on Event.js gesture
  11318. * @param {Event} [self] Inner Event object
  11319. */
  11320. _onGesture: function(e, self) {
  11321. this.__onTransformGesture && this.__onTransformGesture(e, self);
  11322. },
  11323. /**
  11324. * @private
  11325. * @param {Event} [e] Event object fired on Event.js drag
  11326. * @param {Event} [self] Inner Event object
  11327. */
  11328. _onDrag: function(e, self) {
  11329. this.__onDrag && this.__onDrag(e, self);
  11330. },
  11331. /**
  11332. * @private
  11333. * @param {Event} [e] Event object fired on wheel event
  11334. */
  11335. _onMouseWheel: function(e) {
  11336. this.__onMouseWheel(e);
  11337. },
  11338. /**
  11339. * @private
  11340. * @param {Event} e Event object fired on mousedown
  11341. */
  11342. _onMouseOut: function(e) {
  11343. var target = this._hoveredTarget;
  11344. this.fire('mouse:out', { target: target, e: e });
  11345. this._hoveredTarget = null;
  11346. target && target.fire('mouseout', { e: e });
  11347. if (this._iTextInstances) {
  11348. this._iTextInstances.forEach(function(obj) {
  11349. if (obj.isEditing) {
  11350. obj.hiddenTextarea.focus();
  11351. }
  11352. });
  11353. }
  11354. },
  11355. /**
  11356. * @private
  11357. * @param {Event} e Event object fired on mouseenter
  11358. */
  11359. _onMouseEnter: function(e) {
  11360. if (!this.findTarget(e)) {
  11361. this.fire('mouse:over', { target: null, e: e });
  11362. this._hoveredTarget = null;
  11363. }
  11364. },
  11365. /**
  11366. * @private
  11367. * @param {Event} [e] Event object fired on Event.js orientation change
  11368. * @param {Event} [self] Inner Event object
  11369. */
  11370. _onOrientationChange: function(e, self) {
  11371. this.__onOrientationChange && this.__onOrientationChange(e, self);
  11372. },
  11373. /**
  11374. * @private
  11375. * @param {Event} [e] Event object fired on Event.js shake
  11376. * @param {Event} [self] Inner Event object
  11377. */
  11378. _onShake: function(e, self) {
  11379. this.__onShake && this.__onShake(e, self);
  11380. },
  11381. /**
  11382. * @private
  11383. * @param {Event} [e] Event object fired on Event.js shake
  11384. * @param {Event} [self] Inner Event object
  11385. */
  11386. _onLongPress: function(e, self) {
  11387. this.__onLongPress && this.__onLongPress(e, self);
  11388. },
  11389. /**
  11390. * prevent default to allow drop event to be fired
  11391. * @private
  11392. * @param {Event} [e] Event object fired on Event.js shake
  11393. */
  11394. _onDragOver: function(e) {
  11395. e.preventDefault();
  11396. var target = this._simpleEventHandler('dragover', e);
  11397. this._fireEnterLeaveEvents(target, e);
  11398. },
  11399. /**
  11400. * @private
  11401. * @param {Event} e Event object fired on mousedown
  11402. */
  11403. _onContextMenu: function (e) {
  11404. if (this.stopContextMenu) {
  11405. e.stopPropagation();
  11406. e.preventDefault();
  11407. }
  11408. return false;
  11409. },
  11410. /**
  11411. * @private
  11412. * @param {Event} e Event object fired on mousedown
  11413. */
  11414. _onDoubleClick: function (e) {
  11415. this._cacheTransformEventData(e);
  11416. this._handleEvent(e, 'dblclick');
  11417. this._resetTransformEventData(e);
  11418. },
  11419. /**
  11420. * @private
  11421. * @param {Event} e Event object fired on mousedown
  11422. */
  11423. _onMouseDown: function (e) {
  11424. this.__onMouseDown(e);
  11425. this._resetTransformEventData();
  11426. addListener(fabric.document, 'touchend', this._onMouseUp, addEventOptions);
  11427. addListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);
  11428. removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove, addEventOptions);
  11429. removeListener(this.upperCanvasEl, 'touchmove', this._onMouseMove, addEventOptions);
  11430. if (e.type === 'touchstart') {
  11431. // Unbind mousedown to prevent double triggers from touch devices
  11432. removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  11433. }
  11434. else {
  11435. addListener(fabric.document, 'mouseup', this._onMouseUp);
  11436. addListener(fabric.document, 'mousemove', this._onMouseMove, addEventOptions);
  11437. }
  11438. },
  11439. /**
  11440. * @private
  11441. * @param {Event} e Event object fired on mouseup
  11442. */
  11443. _onMouseUp: function (e) {
  11444. this.__onMouseUp(e);
  11445. this._resetTransformEventData();
  11446. removeListener(fabric.document, 'mouseup', this._onMouseUp);
  11447. removeListener(fabric.document, 'touchend', this._onMouseUp, addEventOptions);
  11448. removeListener(fabric.document, 'mousemove', this._onMouseMove, addEventOptions);
  11449. removeListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);
  11450. addListener(this.upperCanvasEl, 'mousemove', this._onMouseMove, addEventOptions);
  11451. addListener(this.upperCanvasEl, 'touchmove', this._onMouseMove, addEventOptions);
  11452. if (e.type === 'touchend') {
  11453. // Wait 400ms before rebinding mousedown to prevent double triggers
  11454. // from touch devices
  11455. var _this = this;
  11456. setTimeout(function() {
  11457. addListener(_this.upperCanvasEl, 'mousedown', _this._onMouseDown);
  11458. }, 400);
  11459. }
  11460. },
  11461. /**
  11462. * @private
  11463. * @param {Event} e Event object fired on mousemove
  11464. */
  11465. _onMouseMove: function (e) {
  11466. !this.allowTouchScrolling && e.preventDefault && e.preventDefault();
  11467. this.__onMouseMove(e);
  11468. },
  11469. /**
  11470. * @private
  11471. */
  11472. _onResize: function () {
  11473. this.calcOffset();
  11474. },
  11475. /**
  11476. * Decides whether the canvas should be redrawn in mouseup and mousedown events.
  11477. * @private
  11478. * @param {Object} target
  11479. * @param {Object} pointer
  11480. */
  11481. _shouldRender: function(target, pointer) {
  11482. var activeObject = this._activeObject;
  11483. if (activeObject && activeObject.isEditing && target === activeObject) {
  11484. // if we mouse up/down over a editing textbox a cursor change,
  11485. // there is no need to re render
  11486. return false;
  11487. }
  11488. return !!(
  11489. (target && (
  11490. target.isMoving ||
  11491. target !== activeObject))
  11492. ||
  11493. (!target && !!activeObject)
  11494. ||
  11495. (!target && !activeObject && !this._groupSelector)
  11496. ||
  11497. (pointer &&
  11498. this._previousPointer &&
  11499. this.selection && (
  11500. pointer.x !== this._previousPointer.x ||
  11501. pointer.y !== this._previousPointer.y))
  11502. );
  11503. },
  11504. /**
  11505. * Method that defines the actions when mouse is released on canvas.
  11506. * The method resets the currentTransform parameters, store the image corner
  11507. * position in the image object and render the canvas on top.
  11508. * @private
  11509. * @param {Event} e Event object fired on mouseup
  11510. */
  11511. __onMouseUp: function (e) {
  11512. var target, transform = this._currentTransform,
  11513. groupSelector = this._groupSelector,
  11514. isClick = (!groupSelector || (groupSelector.left === 0 && groupSelector.top === 0));
  11515. this._cacheTransformEventData(e);
  11516. target = this._target;
  11517. this._handleEvent(e, 'up:before');
  11518. // if right/middle click just fire events and return
  11519. // target undefined will make the _handleEvent search the target
  11520. if (checkClick(e, RIGHT_CLICK)) {
  11521. if (this.fireRightClick) {
  11522. this._handleEvent(e, 'up', RIGHT_CLICK, isClick);
  11523. }
  11524. return;
  11525. }
  11526. if (checkClick(e, MIDDLE_CLICK)) {
  11527. if (this.fireMiddleClick) {
  11528. this._handleEvent(e, 'up', MIDDLE_CLICK, isClick);
  11529. }
  11530. this._resetTransformEventData();
  11531. return;
  11532. }
  11533. if (this.isDrawingMode && this._isCurrentlyDrawing) {
  11534. this._onMouseUpInDrawingMode(e);
  11535. return;
  11536. }
  11537. if (transform) {
  11538. this._finalizeCurrentTransform(e);
  11539. }
  11540. var shouldRender = this._shouldRender(target, this._absolutePointer);
  11541. if (target || !isClick) {
  11542. this._maybeGroupObjects(e);
  11543. }
  11544. if (target) {
  11545. target.isMoving = false;
  11546. }
  11547. this._setCursorFromEvent(e, target);
  11548. this._handleEvent(e, 'up', LEFT_CLICK, isClick);
  11549. this._groupSelector = null;
  11550. this._currentTransform = null;
  11551. target && (target.__corner = 0);
  11552. shouldRender && this.requestRenderAll();
  11553. },
  11554. /**
  11555. * @private
  11556. * Handle event firing for target and subtargets
  11557. * @param {Event} e event from mouse
  11558. * @param {String} eventType event to fire (up, down or move)
  11559. * @return {Fabric.Object} target return the the target found, for internal reasons.
  11560. */
  11561. _simpleEventHandler: function(eventType, e) {
  11562. var target = this.findTarget(e),
  11563. targets = this.targets,
  11564. options = {
  11565. e: e,
  11566. target: target,
  11567. subTargets: targets,
  11568. };
  11569. this.fire(eventType, options);
  11570. target && target.fire(eventType, options);
  11571. if (!targets) {
  11572. return target;
  11573. }
  11574. for (var i = 0; i < targets.length; i++) {
  11575. targets[i].fire(eventType, options);
  11576. }
  11577. return target;
  11578. },
  11579. /**
  11580. * @private
  11581. * Handle event firing for target and subtargets
  11582. * @param {Event} e event from mouse
  11583. * @param {String} eventType event to fire (up, down or move)
  11584. * @param {fabric.Object} targetObj receiving event
  11585. * @param {Number} [button] button used in the event 1 = left, 2 = middle, 3 = right
  11586. * @param {Boolean} isClick for left button only, indicates that the mouse up happened without move.
  11587. */
  11588. _handleEvent: function(e, eventType, button, isClick) {
  11589. var target = this._target,
  11590. targets = this.targets || [],
  11591. options = {
  11592. e: e,
  11593. target: target,
  11594. subTargets: targets,
  11595. button: button || LEFT_CLICK,
  11596. isClick: isClick || false,
  11597. pointer: this._pointer,
  11598. absolutePointer: this._absolutePointer,
  11599. transform: this._currentTransform
  11600. };
  11601. this.fire('mouse:' + eventType, options);
  11602. target && target.fire('mouse' + eventType, options);
  11603. for (var i = 0; i < targets.length; i++) {
  11604. targets[i].fire('mouse' + eventType, options);
  11605. }
  11606. },
  11607. /**
  11608. * @private
  11609. * @param {Event} e send the mouse event that generate the finalize down, so it can be used in the event
  11610. */
  11611. _finalizeCurrentTransform: function(e) {
  11612. var transform = this._currentTransform,
  11613. target = transform.target,
  11614. eventName,
  11615. options = {
  11616. e: e,
  11617. target: target,
  11618. transform: transform,
  11619. };
  11620. if (target._scaling) {
  11621. target._scaling = false;
  11622. }
  11623. target.setCoords();
  11624. if (transform.actionPerformed || (this.stateful && target.hasStateChanged())) {
  11625. if (transform.actionPerformed) {
  11626. eventName = this._addEventOptions(options, transform);
  11627. this._fire(eventName, options);
  11628. }
  11629. this._fire('modified', options);
  11630. }
  11631. },
  11632. /**
  11633. * Mutate option object in order to add by property and give back the event name.
  11634. * @private
  11635. * @param {Object} options to mutate
  11636. * @param {Object} transform to inspect action from
  11637. */
  11638. _addEventOptions: function(options, transform) {
  11639. // we can probably add more details at low cost
  11640. // scale change, rotation changes, translation changes
  11641. var eventName, by;
  11642. switch (transform.action) {
  11643. case 'scaleX':
  11644. eventName = 'scaled';
  11645. by = 'x';
  11646. break;
  11647. case 'scaleY':
  11648. eventName = 'scaled';
  11649. by = 'y';
  11650. break;
  11651. case 'skewX':
  11652. eventName = 'skewed';
  11653. by = 'x';
  11654. break;
  11655. case 'skewY':
  11656. eventName = 'skewed';
  11657. by = 'y';
  11658. break;
  11659. case 'scale':
  11660. eventName = 'scaled';
  11661. by = 'equally';
  11662. break;
  11663. case 'rotate':
  11664. eventName = 'rotated';
  11665. break;
  11666. case 'drag':
  11667. eventName = 'moved';
  11668. break;
  11669. }
  11670. options.by = by;
  11671. return eventName;
  11672. },
  11673. /**
  11674. * @private
  11675. * @param {Event} e Event object fired on mousedown
  11676. */
  11677. _onMouseDownInDrawingMode: function(e) {
  11678. this._isCurrentlyDrawing = true;
  11679. if (this.getActiveObject()) {
  11680. this.discardActiveObject(e).requestRenderAll();
  11681. }
  11682. if (this.clipTo) {
  11683. fabric.util.clipContext(this, this.contextTop);
  11684. }
  11685. var pointer = this.getPointer(e);
  11686. this.freeDrawingBrush.onMouseDown(pointer);
  11687. this._handleEvent(e, 'down');
  11688. },
  11689. /**
  11690. * @private
  11691. * @param {Event} e Event object fired on mousemove
  11692. */
  11693. _onMouseMoveInDrawingMode: function(e) {
  11694. if (this._isCurrentlyDrawing) {
  11695. var pointer = this.getPointer(e);
  11696. this.freeDrawingBrush.onMouseMove(pointer);
  11697. }
  11698. this.setCursor(this.freeDrawingCursor);
  11699. this._handleEvent(e, 'move');
  11700. },
  11701. /**
  11702. * @private
  11703. * @param {Event} e Event object fired on mouseup
  11704. */
  11705. _onMouseUpInDrawingMode: function(e) {
  11706. this._isCurrentlyDrawing = false;
  11707. if (this.clipTo) {
  11708. this.contextTop.restore();
  11709. }
  11710. this.freeDrawingBrush.onMouseUp();
  11711. this._handleEvent(e, 'up');
  11712. },
  11713. /**
  11714. * Method that defines the actions when mouse is clicked on canvas.
  11715. * The method inits the currentTransform parameters and renders all the
  11716. * canvas so the current image can be placed on the top canvas and the rest
  11717. * in on the container one.
  11718. * @private
  11719. * @param {Event} e Event object fired on mousedown
  11720. */
  11721. __onMouseDown: function (e) {
  11722. this._cacheTransformEventData(e);
  11723. this._handleEvent(e, 'down:before');
  11724. var target = this._target;
  11725. // if right click just fire events
  11726. if (checkClick(e, RIGHT_CLICK)) {
  11727. if (this.fireRightClick) {
  11728. this._handleEvent(e, 'down', RIGHT_CLICK);
  11729. }
  11730. return;
  11731. }
  11732. if (checkClick(e, MIDDLE_CLICK)) {
  11733. if (this.fireMiddleClick) {
  11734. this._handleEvent(e, 'down', MIDDLE_CLICK);
  11735. }
  11736. return;
  11737. }
  11738. if (this.isDrawingMode) {
  11739. this._onMouseDownInDrawingMode(e);
  11740. return;
  11741. }
  11742. // ignore if some object is being transformed at this moment
  11743. if (this._currentTransform) {
  11744. return;
  11745. }
  11746. var pointer = this._pointer;
  11747. // save pointer for check in __onMouseUp event
  11748. this._previousPointer = pointer;
  11749. var shouldRender = this._shouldRender(target, pointer),
  11750. shouldGroup = this._shouldGroup(e, target);
  11751. if (this._shouldClearSelection(e, target)) {
  11752. this.discardActiveObject(e);
  11753. }
  11754. else if (shouldGroup) {
  11755. this._handleGrouping(e, target);
  11756. target = this._activeObject;
  11757. }
  11758. if (this.selection && (!target ||
  11759. (!target.selectable && !target.isEditing && target !== this._activeObject))) {
  11760. this._groupSelector = {
  11761. ex: pointer.x,
  11762. ey: pointer.y,
  11763. top: 0,
  11764. left: 0
  11765. };
  11766. }
  11767. if (target) {
  11768. if (target.selectable) {
  11769. this.setActiveObject(target, e);
  11770. }
  11771. if (target === this._activeObject && (target.__corner || !shouldGroup)) {
  11772. this._setupCurrentTransform(e, target);
  11773. }
  11774. }
  11775. this._handleEvent(e, 'down');
  11776. // we must renderAll so that we update the visuals
  11777. shouldRender && this.requestRenderAll();
  11778. },
  11779. /**
  11780. * reset cache form common information needed during event processing
  11781. * @private
  11782. */
  11783. _resetTransformEventData: function() {
  11784. this._target = null;
  11785. this._pointer = null;
  11786. this._absolutePointer = null;
  11787. },
  11788. /**
  11789. * Cache common information needed during event processing
  11790. * @private
  11791. * @param {Event} e Event object fired on event
  11792. */
  11793. _cacheTransformEventData: function(e) {
  11794. // reset in order to avoid stale caching
  11795. this._resetTransformEventData();
  11796. this._pointer = this.getPointer(e, true);
  11797. this._absolutePointer = this.restorePointerVpt(this._pointer);
  11798. this._target = this._currentTransform ? this._currentTransform.target : this.findTarget(e) || null;
  11799. },
  11800. /**
  11801. * @private
  11802. */
  11803. _beforeTransform: function(e) {
  11804. var t = this._currentTransform;
  11805. this.stateful && t.target.saveState();
  11806. this.fire('before:transform', {
  11807. e: e,
  11808. transform: t,
  11809. });
  11810. // determine if it's a drag or rotate case
  11811. if (t.corner) {
  11812. this.onBeforeScaleRotate(t.target);
  11813. }
  11814. },
  11815. /**
  11816. * Method that defines the actions when mouse is hovering the canvas.
  11817. * The currentTransform parameter will definde whether the user is rotating/scaling/translating
  11818. * an image or neither of them (only hovering). A group selection is also possible and would cancel
  11819. * all any other type of action.
  11820. * In case of an image transformation only the top canvas will be rendered.
  11821. * @private
  11822. * @param {Event} e Event object fired on mousemove
  11823. */
  11824. __onMouseMove: function (e) {
  11825. this._handleEvent(e, 'move:before');
  11826. this._cacheTransformEventData(e);
  11827. var target, pointer;
  11828. if (this.isDrawingMode) {
  11829. this._onMouseMoveInDrawingMode(e);
  11830. return;
  11831. }
  11832. if (typeof e.touches !== 'undefined' && e.touches.length > 1) {
  11833. return;
  11834. }
  11835. var groupSelector = this._groupSelector;
  11836. // We initially clicked in an empty area, so we draw a box for multiple selection
  11837. if (groupSelector) {
  11838. pointer = this._pointer;
  11839. groupSelector.left = pointer.x - groupSelector.ex;
  11840. groupSelector.top = pointer.y - groupSelector.ey;
  11841. this.renderTop();
  11842. }
  11843. else if (!this._currentTransform) {
  11844. target = this.findTarget(e) || null;
  11845. this._setCursorFromEvent(e, target);
  11846. this._fireOverOutEvents(target, e);
  11847. }
  11848. else {
  11849. this._transformObject(e);
  11850. }
  11851. this._handleEvent(e, 'move');
  11852. this._resetTransformEventData();
  11853. },
  11854. /**
  11855. * Manage the mouseout, mouseover events for the fabric object on the canvas
  11856. * @param {Fabric.Object} target the target where the target from the mousemove event
  11857. * @param {Event} e Event object fired on mousemove
  11858. * @private
  11859. */
  11860. _fireOverOutEvents: function(target, e) {
  11861. this.fireSynteticInOutEvents(target, e, {
  11862. targetName: '_hoveredTarget',
  11863. canvasEvtOut: 'mouse:out',
  11864. evtOut: 'mouseout',
  11865. canvasEvtIn: 'mouse:over',
  11866. evtIn: 'mouseover',
  11867. });
  11868. },
  11869. /**
  11870. * Manage the dragEnter, dragLeave events for the fabric objects on the canvas
  11871. * @param {Fabric.Object} target the target where the target from the onDrag event
  11872. * @param {Event} e Event object fired on ondrag
  11873. * @private
  11874. */
  11875. _fireEnterLeaveEvents: function(target, e) {
  11876. this.fireSynteticInOutEvents(target, e, {
  11877. targetName: '_draggedoverTarget',
  11878. evtOut: 'dragleave',
  11879. evtIn: 'dragenter',
  11880. });
  11881. },
  11882. /**
  11883. * Manage the syntetic in/out events for the fabric objects on the canvas
  11884. * @param {Fabric.Object} target the target where the target from the supported events
  11885. * @param {Event} e Event object fired
  11886. * @param {Object} config configuration for the function to work
  11887. * @param {String} config.targetName property on the canvas where the old target is stored
  11888. * @param {String} [config.canvasEvtOut] name of the event to fire at canvas level for out
  11889. * @param {String} config.evtOut name of the event to fire for out
  11890. * @param {String} [config.canvasEvtIn] name of the event to fire at canvas level for in
  11891. * @param {String} config.evtIn name of the event to fire for in
  11892. * @private
  11893. */
  11894. fireSynteticInOutEvents: function(target, e, config) {
  11895. var inOpt, outOpt, oldTarget = this[config.targetName], outFires, inFires,
  11896. targetChanged = oldTarget !== target, canvasEvtIn = config.canvasEvtIn, canvasEvtOut = config.canvasEvtOut;
  11897. if (targetChanged) {
  11898. inOpt = { e: e, target: target, previousTarget: oldTarget };
  11899. outOpt = { e: e, target: oldTarget, nextTarget: target };
  11900. this[config.targetName] = target;
  11901. }
  11902. inFires = target && targetChanged;
  11903. outFires = oldTarget && targetChanged;
  11904. if (outFires) {
  11905. canvasEvtOut && this.fire(canvasEvtOut, outOpt);
  11906. oldTarget.fire(config.evtOut, outOpt);
  11907. }
  11908. if (inFires) {
  11909. canvasEvtIn && this.fire(canvasEvtIn, inOpt);
  11910. target.fire(config.evtIn, inOpt);
  11911. }
  11912. },
  11913. /**
  11914. * Method that defines actions when an Event Mouse Wheel
  11915. * @param {Event} e Event object fired on mouseup
  11916. */
  11917. __onMouseWheel: function(e) {
  11918. this._cacheTransformEventData(e);
  11919. this._handleEvent(e, 'wheel');
  11920. this._resetTransformEventData();
  11921. },
  11922. /**
  11923. * @private
  11924. * @param {Event} e Event fired on mousemove
  11925. */
  11926. _transformObject: function(e) {
  11927. var pointer = this.getPointer(e),
  11928. transform = this._currentTransform;
  11929. transform.reset = false;
  11930. transform.target.isMoving = true;
  11931. transform.shiftKey = e.shiftKey;
  11932. transform.altKey = e[this.centeredKey];
  11933. this._beforeScaleTransform(e, transform);
  11934. this._performTransformAction(e, transform, pointer);
  11935. transform.actionPerformed && this.requestRenderAll();
  11936. },
  11937. /**
  11938. * @private
  11939. */
  11940. _performTransformAction: function(e, transform, pointer) {
  11941. var x = pointer.x,
  11942. y = pointer.y,
  11943. action = transform.action,
  11944. actionPerformed = false,
  11945. options = {
  11946. target: transform.target,
  11947. e: e,
  11948. transform: transform,
  11949. pointer: pointer
  11950. };
  11951. if (action === 'rotate') {
  11952. (actionPerformed = this._rotateObject(x, y)) && this._fire('rotating', options);
  11953. }
  11954. else if (action === 'scale') {
  11955. (actionPerformed = this._onScale(e, transform, x, y)) && this._fire('scaling', options);
  11956. }
  11957. else if (action === 'scaleX') {
  11958. (actionPerformed = this._scaleObject(x, y, 'x')) && this._fire('scaling', options);
  11959. }
  11960. else if (action === 'scaleY') {
  11961. (actionPerformed = this._scaleObject(x, y, 'y')) && this._fire('scaling', options);
  11962. }
  11963. else if (action === 'skewX') {
  11964. (actionPerformed = this._skewObject(x, y, 'x')) && this._fire('skewing', options);
  11965. }
  11966. else if (action === 'skewY') {
  11967. (actionPerformed = this._skewObject(x, y, 'y')) && this._fire('skewing', options);
  11968. }
  11969. else {
  11970. actionPerformed = this._translateObject(x, y);
  11971. if (actionPerformed) {
  11972. this._fire('moving', options);
  11973. this.setCursor(options.target.moveCursor || this.moveCursor);
  11974. }
  11975. }
  11976. transform.actionPerformed = transform.actionPerformed || actionPerformed;
  11977. },
  11978. /**
  11979. * @private
  11980. */
  11981. _fire: function(eventName, options) {
  11982. this.fire('object:' + eventName, options);
  11983. options.target.fire(eventName, options);
  11984. },
  11985. /**
  11986. * @private
  11987. */
  11988. _beforeScaleTransform: function(e, transform) {
  11989. if (transform.action === 'scale' || transform.action === 'scaleX' || transform.action === 'scaleY') {
  11990. var centerTransform = this._shouldCenterTransform(transform.target);
  11991. // Switch from a normal resize to center-based
  11992. if ((centerTransform && (transform.originX !== 'center' || transform.originY !== 'center')) ||
  11993. // Switch from center-based resize to normal one
  11994. (!centerTransform && transform.originX === 'center' && transform.originY === 'center')
  11995. ) {
  11996. this._resetCurrentTransform();
  11997. transform.reset = true;
  11998. }
  11999. }
  12000. },
  12001. /**
  12002. * @private
  12003. * @param {Event} e Event object
  12004. * @param {Object} transform current tranform
  12005. * @param {Number} x mouse position x from origin
  12006. * @param {Number} y mouse poistion y from origin
  12007. * @return {Boolean} true if the scaling occurred
  12008. */
  12009. _onScale: function(e, transform, x, y) {
  12010. if (this._isUniscalePossible(e, transform.target)) {
  12011. transform.currentAction = 'scale';
  12012. return this._scaleObject(x, y);
  12013. }
  12014. else {
  12015. // Switch from a normal resize to proportional
  12016. if (!transform.reset && transform.currentAction === 'scale') {
  12017. this._resetCurrentTransform();
  12018. }
  12019. transform.currentAction = 'scaleEqually';
  12020. return this._scaleObject(x, y, 'equally');
  12021. }
  12022. },
  12023. /**
  12024. * @private
  12025. * @param {Event} e Event object
  12026. * @param {fabric.Object} target current target
  12027. * @return {Boolean} true if unproportional scaling is possible
  12028. */
  12029. _isUniscalePossible: function(e, target) {
  12030. return (e[this.uniScaleKey] || this.uniScaleTransform) && !target.get('lockUniScaling');
  12031. },
  12032. /**
  12033. * Sets the cursor depending on where the canvas is being hovered.
  12034. * Note: very buggy in Opera
  12035. * @param {Event} e Event object
  12036. * @param {Object} target Object that the mouse is hovering, if so.
  12037. */
  12038. _setCursorFromEvent: function (e, target) {
  12039. if (!target) {
  12040. this.setCursor(this.defaultCursor);
  12041. return false;
  12042. }
  12043. var hoverCursor = target.hoverCursor || this.hoverCursor,
  12044. activeSelection = this._activeObject && this._activeObject.type === 'activeSelection' ?
  12045. this._activeObject : null,
  12046. // only show proper corner when group selection is not active
  12047. corner = (!activeSelection || !activeSelection.contains(target))
  12048. && target._findTargetCorner(this.getPointer(e, true));
  12049. if (!corner) {
  12050. this.setCursor(hoverCursor);
  12051. }
  12052. else {
  12053. this.setCursor(this.getCornerCursor(corner, target, e));
  12054. }
  12055. },
  12056. /**
  12057. * @private
  12058. */
  12059. getCornerCursor: function(corner, target, e) {
  12060. if (this.actionIsDisabled(corner, target, e)) {
  12061. return this.notAllowedCursor;
  12062. }
  12063. else if (corner in cursorOffset) {
  12064. return this._getRotatedCornerCursor(corner, target, e);
  12065. }
  12066. else if (corner === 'mtr' && target.hasRotatingPoint) {
  12067. return this.rotationCursor;
  12068. }
  12069. else {
  12070. return this.defaultCursor;
  12071. }
  12072. },
  12073. actionIsDisabled: function(corner, target, e) {
  12074. if (corner === 'mt' || corner === 'mb') {
  12075. return e[this.altActionKey] ? target.lockSkewingX : target.lockScalingY;
  12076. }
  12077. else if (corner === 'ml' || corner === 'mr') {
  12078. return e[this.altActionKey] ? target.lockSkewingY : target.lockScalingX;
  12079. }
  12080. else if (corner === 'mtr') {
  12081. return target.lockRotation;
  12082. }
  12083. else {
  12084. return this._isUniscalePossible(e, target) ?
  12085. target.lockScalingX && target.lockScalingY : target.lockScalingX || target.lockScalingY;
  12086. }
  12087. },
  12088. /**
  12089. * @private
  12090. */
  12091. _getRotatedCornerCursor: function(corner, target, e) {
  12092. var n = Math.round((target.angle % 360) / 45);
  12093. if (n < 0) {
  12094. n += 8; // full circle ahead
  12095. }
  12096. n += cursorOffset[corner];
  12097. if (e[this.altActionKey] && cursorOffset[corner] % 2 === 0) {
  12098. //if we are holding shift and we are on a mx corner...
  12099. n += 2;
  12100. }
  12101. // normalize n to be from 0 to 7
  12102. n %= 8;
  12103. return this.cursorMap[n];
  12104. }
  12105. });
  12106. })();
  12107. (function() {
  12108. var min = Math.min,
  12109. max = Math.max;
  12110. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  12111. /**
  12112. * @private
  12113. * @param {Event} e Event object
  12114. * @param {fabric.Object} target
  12115. * @return {Boolean}
  12116. */
  12117. _shouldGroup: function(e, target) {
  12118. var activeObject = this._activeObject;
  12119. return activeObject && this._isSelectionKeyPressed(e) && target && target.selectable && this.selection &&
  12120. (activeObject !== target || activeObject.type === 'activeSelection');
  12121. },
  12122. /**
  12123. * @private
  12124. * @param {Event} e Event object
  12125. * @param {fabric.Object} target
  12126. */
  12127. _handleGrouping: function (e, target) {
  12128. var activeObject = this._activeObject;
  12129. if (activeObject.__corner) {
  12130. return;
  12131. }
  12132. if (target === activeObject) {
  12133. // if it's a group, find target again, using activeGroup objects
  12134. target = this.findTarget(e, true);
  12135. // if even object is not found or we are on activeObjectCorner, bail out
  12136. if (!target) {
  12137. return;
  12138. }
  12139. }
  12140. if (activeObject && activeObject.type === 'activeSelection') {
  12141. this._updateActiveSelection(target, e);
  12142. }
  12143. else {
  12144. this._createActiveSelection(target, e);
  12145. }
  12146. },
  12147. /**
  12148. * @private
  12149. */
  12150. _updateActiveSelection: function(target, e) {
  12151. var activeSelection = this._activeObject,
  12152. currentActiveObjects = activeSelection._objects.slice(0);
  12153. if (activeSelection.contains(target)) {
  12154. activeSelection.removeWithUpdate(target);
  12155. this._hoveredTarget = target;
  12156. if (activeSelection.size() === 1) {
  12157. // activate last remaining object
  12158. this._setActiveObject(activeSelection.item(0), e);
  12159. }
  12160. }
  12161. else {
  12162. activeSelection.addWithUpdate(target);
  12163. this._hoveredTarget = activeSelection;
  12164. }
  12165. this._fireSelectionEvents(currentActiveObjects, e);
  12166. },
  12167. /**
  12168. * @private
  12169. */
  12170. _createActiveSelection: function(target, e) {
  12171. var currentActives = this.getActiveObjects(), group = this._createGroup(target);
  12172. this._hoveredTarget = group;
  12173. this._setActiveObject(group, e);
  12174. this._fireSelectionEvents(currentActives, e);
  12175. },
  12176. /**
  12177. * @private
  12178. * @param {Object} target
  12179. */
  12180. _createGroup: function(target) {
  12181. var objects = this.getObjects(),
  12182. isActiveLower = objects.indexOf(this._activeObject) < objects.indexOf(target),
  12183. groupObjects = isActiveLower
  12184. ? [this._activeObject, target]
  12185. : [target, this._activeObject];
  12186. this._activeObject.isEditing && this._activeObject.exitEditing();
  12187. return new fabric.ActiveSelection(groupObjects, {
  12188. canvas: this
  12189. });
  12190. },
  12191. /**
  12192. * @private
  12193. * @param {Event} e mouse event
  12194. */
  12195. _groupSelectedObjects: function (e) {
  12196. var group = this._collectObjects(),
  12197. aGroup;
  12198. // do not create group for 1 element only
  12199. if (group.length === 1) {
  12200. this.setActiveObject(group[0], e);
  12201. }
  12202. else if (group.length > 1) {
  12203. aGroup = new fabric.ActiveSelection(group.reverse(), {
  12204. canvas: this
  12205. });
  12206. this.setActiveObject(aGroup, e);
  12207. }
  12208. },
  12209. /**
  12210. * @private
  12211. */
  12212. _collectObjects: function() {
  12213. var group = [],
  12214. currentObject,
  12215. x1 = this._groupSelector.ex,
  12216. y1 = this._groupSelector.ey,
  12217. x2 = x1 + this._groupSelector.left,
  12218. y2 = y1 + this._groupSelector.top,
  12219. selectionX1Y1 = new fabric.Point(min(x1, x2), min(y1, y2)),
  12220. selectionX2Y2 = new fabric.Point(max(x1, x2), max(y1, y2)),
  12221. allowIntersect = !this.selectionFullyContained,
  12222. isClick = x1 === x2 && y1 === y2;
  12223. // we iterate reverse order to collect top first in case of click.
  12224. for (var i = this._objects.length; i--; ) {
  12225. currentObject = this._objects[i];
  12226. if (!currentObject || !currentObject.selectable || !currentObject.visible) {
  12227. continue;
  12228. }
  12229. if ((allowIntersect && currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2)) ||
  12230. currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2) ||
  12231. (allowIntersect && currentObject.containsPoint(selectionX1Y1)) ||
  12232. (allowIntersect && currentObject.containsPoint(selectionX2Y2))
  12233. ) {
  12234. group.push(currentObject);
  12235. // only add one object if it's a click
  12236. if (isClick) {
  12237. break;
  12238. }
  12239. }
  12240. }
  12241. return group;
  12242. },
  12243. /**
  12244. * @private
  12245. */
  12246. _maybeGroupObjects: function(e) {
  12247. if (this.selection && this._groupSelector) {
  12248. this._groupSelectedObjects(e);
  12249. }
  12250. this.setCursor(this.defaultCursor);
  12251. // clear selection and current transformation
  12252. this._groupSelector = null;
  12253. }
  12254. });
  12255. })();
  12256. (function () {
  12257. var supportQuality = fabric.StaticCanvas.supports('toDataURLWithQuality');
  12258. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  12259. /**
  12260. * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
  12261. * @param {Object} [options] Options object
  12262. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  12263. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  12264. * @param {Number} [options.multiplier=1] Multiplier to scale by, to have consistent
  12265. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  12266. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  12267. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  12268. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  12269. * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 2.0.0
  12270. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  12271. * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}
  12272. * @example <caption>Generate jpeg dataURL with lower quality</caption>
  12273. * var dataURL = canvas.toDataURL({
  12274. * format: 'jpeg',
  12275. * quality: 0.8
  12276. * });
  12277. * @example <caption>Generate cropped png dataURL (clipping of canvas)</caption>
  12278. * var dataURL = canvas.toDataURL({
  12279. * format: 'png',
  12280. * left: 100,
  12281. * top: 100,
  12282. * width: 200,
  12283. * height: 200
  12284. * });
  12285. * @example <caption>Generate double scaled png dataURL</caption>
  12286. * var dataURL = canvas.toDataURL({
  12287. * format: 'png',
  12288. * multiplier: 2
  12289. * });
  12290. */
  12291. toDataURL: function (options) {
  12292. options || (options = { });
  12293. var format = options.format || 'png',
  12294. quality = options.quality || 1,
  12295. multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? 1 : 1 / this.getRetinaScaling()),
  12296. cropping = {
  12297. left: options.left || 0,
  12298. top: options.top || 0,
  12299. width: options.width || 0,
  12300. height: options.height || 0,
  12301. };
  12302. return this.__toDataURLWithMultiplier(format, quality, cropping, multiplier);
  12303. },
  12304. /**
  12305. * @private
  12306. */
  12307. __toDataURLWithMultiplier: function(format, quality, cropping, multiplier) {
  12308. var origWidth = this.width,
  12309. origHeight = this.height,
  12310. scaledWidth = (cropping.width || this.width) * multiplier,
  12311. scaledHeight = (cropping.height || this.height) * multiplier,
  12312. zoom = this.getZoom(),
  12313. newZoom = zoom * multiplier,
  12314. vp = this.viewportTransform,
  12315. translateX = (vp[4] - cropping.left) * multiplier,
  12316. translateY = (vp[5] - cropping.top) * multiplier,
  12317. newVp = [newZoom, 0, 0, newZoom, translateX, translateY],
  12318. originalInteractive = this.interactive,
  12319. originalSkipOffScreen = this.skipOffscreen,
  12320. needsResize = origWidth !== scaledWidth || origHeight !== scaledHeight;
  12321. this.viewportTransform = newVp;
  12322. this.skipOffscreen = false;
  12323. // setting interactive to false avoid exporting controls
  12324. this.interactive = false;
  12325. if (needsResize) {
  12326. this.setDimensions({ width: scaledWidth, height: scaledHeight }, { backstoreOnly: true });
  12327. }
  12328. // call a renderAll to force sync update. This will cancel the scheduled requestRenderAll
  12329. // from setDimensions
  12330. this.renderAll();
  12331. var data = this.__toDataURL(format, quality, cropping);
  12332. this.interactive = originalInteractive;
  12333. this.skipOffscreen = originalSkipOffScreen;
  12334. this.viewportTransform = vp;
  12335. //setDimensions with no option object is taking care of:
  12336. //this.width, this.height, this.requestRenderAll()
  12337. if (needsResize) {
  12338. this.setDimensions({ width: origWidth, height: origHeight }, { backstoreOnly: true });
  12339. }
  12340. this.renderAll();
  12341. return data;
  12342. },
  12343. /**
  12344. * @private
  12345. */
  12346. __toDataURL: function(format, quality) {
  12347. var canvasEl = this.contextContainer.canvas;
  12348. // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
  12349. if (format === 'jpg') {
  12350. format = 'jpeg';
  12351. }
  12352. var data = supportQuality
  12353. ? canvasEl.toDataURL('image/' + format, quality)
  12354. : canvasEl.toDataURL('image/' + format);
  12355. return data;
  12356. },
  12357. });
  12358. })();
  12359. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  12360. /**
  12361. * Populates canvas with data from the specified dataless JSON.
  12362. * JSON format must conform to the one of {@link fabric.Canvas#toDatalessJSON}
  12363. * @deprecated since 1.2.2
  12364. * @param {String|Object} json JSON string or object
  12365. * @param {Function} callback Callback, invoked when json is parsed
  12366. * and corresponding objects (e.g: {@link fabric.Image})
  12367. * are initialized
  12368. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  12369. * @return {fabric.Canvas} instance
  12370. * @chainable
  12371. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#deserialization}
  12372. */
  12373. loadFromDatalessJSON: function (json, callback, reviver) {
  12374. return this.loadFromJSON(json, callback, reviver);
  12375. },
  12376. /**
  12377. * Populates canvas with data from the specified JSON.
  12378. * JSON format must conform to the one of {@link fabric.Canvas#toJSON}
  12379. * @param {String|Object} json JSON string or object
  12380. * @param {Function} callback Callback, invoked when json is parsed
  12381. * and corresponding objects (e.g: {@link fabric.Image})
  12382. * are initialized
  12383. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  12384. * @return {fabric.Canvas} instance
  12385. * @chainable
  12386. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#deserialization}
  12387. * @see {@link http://jsfiddle.net/fabricjs/fmgXt/|jsFiddle demo}
  12388. * @example <caption>loadFromJSON</caption>
  12389. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));
  12390. * @example <caption>loadFromJSON with reviver</caption>
  12391. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
  12392. * // `o` = json object
  12393. * // `object` = fabric.Object instance
  12394. * // ... do some stuff ...
  12395. * });
  12396. */
  12397. loadFromJSON: function (json, callback, reviver) {
  12398. if (!json) {
  12399. return;
  12400. }
  12401. // serialize if it wasn't already
  12402. var serialized = (typeof json === 'string')
  12403. ? JSON.parse(json)
  12404. : fabric.util.object.clone(json);
  12405. var _this = this,
  12406. renderOnAddRemove = this.renderOnAddRemove;
  12407. this.renderOnAddRemove = false;
  12408. this._enlivenObjects(serialized.objects, function (enlivenedObjects) {
  12409. _this.clear();
  12410. _this._setBgOverlay(serialized, function () {
  12411. enlivenedObjects.forEach(function(obj, index) {
  12412. // we splice the array just in case some custom classes restored from JSON
  12413. // will add more object to canvas at canvas init.
  12414. _this.insertAt(obj, index);
  12415. });
  12416. _this.renderOnAddRemove = renderOnAddRemove;
  12417. // remove parts i cannot set as options
  12418. delete serialized.objects;
  12419. delete serialized.backgroundImage;
  12420. delete serialized.overlayImage;
  12421. delete serialized.background;
  12422. delete serialized.overlay;
  12423. // this._initOptions does too many things to just
  12424. // call it. Normally loading an Object from JSON
  12425. // create the Object instance. Here the Canvas is
  12426. // already an instance and we are just loading things over it
  12427. _this._setOptions(serialized);
  12428. _this.renderAll();
  12429. callback && callback();
  12430. });
  12431. }, reviver);
  12432. return this;
  12433. },
  12434. /**
  12435. * @private
  12436. * @param {Object} serialized Object with background and overlay information
  12437. * @param {Function} callback Invoked after all background and overlay images/patterns loaded
  12438. */
  12439. _setBgOverlay: function(serialized, callback) {
  12440. var loaded = {
  12441. backgroundColor: false,
  12442. overlayColor: false,
  12443. backgroundImage: false,
  12444. overlayImage: false
  12445. };
  12446. if (!serialized.backgroundImage && !serialized.overlayImage && !serialized.background && !serialized.overlay) {
  12447. callback && callback();
  12448. return;
  12449. }
  12450. var cbIfLoaded = function () {
  12451. if (loaded.backgroundImage && loaded.overlayImage && loaded.backgroundColor && loaded.overlayColor) {
  12452. callback && callback();
  12453. }
  12454. };
  12455. this.__setBgOverlay('backgroundImage', serialized.backgroundImage, loaded, cbIfLoaded);
  12456. this.__setBgOverlay('overlayImage', serialized.overlayImage, loaded, cbIfLoaded);
  12457. this.__setBgOverlay('backgroundColor', serialized.background, loaded, cbIfLoaded);
  12458. this.__setBgOverlay('overlayColor', serialized.overlay, loaded, cbIfLoaded);
  12459. },
  12460. /**
  12461. * @private
  12462. * @param {String} property Property to set (backgroundImage, overlayImage, backgroundColor, overlayColor)
  12463. * @param {(Object|String)} value Value to set
  12464. * @param {Object} loaded Set loaded property to true if property is set
  12465. * @param {Object} callback Callback function to invoke after property is set
  12466. */
  12467. __setBgOverlay: function(property, value, loaded, callback) {
  12468. var _this = this;
  12469. if (!value) {
  12470. loaded[property] = true;
  12471. callback && callback();
  12472. return;
  12473. }
  12474. if (property === 'backgroundImage' || property === 'overlayImage') {
  12475. fabric.util.enlivenObjects([value], function(enlivedObject){
  12476. _this[property] = enlivedObject[0];
  12477. loaded[property] = true;
  12478. callback && callback();
  12479. });
  12480. }
  12481. else {
  12482. this['set' + fabric.util.string.capitalize(property, true)](value, function() {
  12483. loaded[property] = true;
  12484. callback && callback();
  12485. });
  12486. }
  12487. },
  12488. /**
  12489. * @private
  12490. * @param {Array} objects
  12491. * @param {Function} callback
  12492. * @param {Function} [reviver]
  12493. */
  12494. _enlivenObjects: function (objects, callback, reviver) {
  12495. if (!objects || objects.length === 0) {
  12496. callback && callback([]);
  12497. return;
  12498. }
  12499. fabric.util.enlivenObjects(objects, function(enlivenedObjects) {
  12500. callback && callback(enlivenedObjects);
  12501. }, null, reviver);
  12502. },
  12503. /**
  12504. * @private
  12505. * @param {String} format
  12506. * @param {Function} callback
  12507. */
  12508. _toDataURL: function (format, callback) {
  12509. this.clone(function (clone) {
  12510. callback(clone.toDataURL(format));
  12511. });
  12512. },
  12513. /**
  12514. * @private
  12515. * @param {String} format
  12516. * @param {Number} multiplier
  12517. * @param {Function} callback
  12518. */
  12519. _toDataURLWithMultiplier: function (format, multiplier, callback) {
  12520. this.clone(function (clone) {
  12521. callback(clone.toDataURLWithMultiplier(format, multiplier));
  12522. });
  12523. },
  12524. /**
  12525. * Clones canvas instance
  12526. * @param {Object} [callback] Receives cloned instance as a first argument
  12527. * @param {Array} [properties] Array of properties to include in the cloned canvas and children
  12528. */
  12529. clone: function (callback, properties) {
  12530. var data = JSON.stringify(this.toJSON(properties));
  12531. this.cloneWithoutData(function(clone) {
  12532. clone.loadFromJSON(data, function() {
  12533. callback && callback(clone);
  12534. });
  12535. });
  12536. },
  12537. /**
  12538. * Clones canvas instance without cloning existing data.
  12539. * This essentially copies canvas dimensions, clipping properties, etc.
  12540. * but leaves data empty (so that you can populate it with your own)
  12541. * @param {Object} [callback] Receives cloned instance as a first argument
  12542. */
  12543. cloneWithoutData: function(callback) {
  12544. var el = fabric.document.createElement('canvas');
  12545. el.width = this.width;
  12546. el.height = this.height;
  12547. var clone = new fabric.Canvas(el);
  12548. clone.clipTo = this.clipTo;
  12549. if (this.backgroundImage) {
  12550. clone.setBackgroundImage(this.backgroundImage.src, function() {
  12551. clone.renderAll();
  12552. callback && callback(clone);
  12553. });
  12554. clone.backgroundImageOpacity = this.backgroundImageOpacity;
  12555. clone.backgroundImageStretch = this.backgroundImageStretch;
  12556. }
  12557. else {
  12558. callback && callback(clone);
  12559. }
  12560. }
  12561. });
  12562. /**
  12563. * Adds support for multi-touch gestures using the Event.js library.
  12564. * Fires the following custom events:
  12565. * - touch:gesture
  12566. * - touch:drag
  12567. * - touch:orientation
  12568. * - touch:shake
  12569. * - touch:longpress
  12570. */
  12571. (function() {
  12572. var degreesToRadians = fabric.util.degreesToRadians,
  12573. radiansToDegrees = fabric.util.radiansToDegrees;
  12574. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  12575. /**
  12576. * Method that defines actions when an Event.js gesture is detected on an object. Currently only supports
  12577. * 2 finger gestures.
  12578. * @param {Event} e Event object by Event.js
  12579. * @param {Event} self Event proxy object by Event.js
  12580. */
  12581. __onTransformGesture: function(e, self) {
  12582. if (this.isDrawingMode || !e.touches || e.touches.length !== 2 || 'gesture' !== self.gesture) {
  12583. return;
  12584. }
  12585. var target = this.findTarget(e);
  12586. if ('undefined' !== typeof target) {
  12587. this.__gesturesParams = {
  12588. e: e,
  12589. self: self,
  12590. target: target
  12591. };
  12592. this.__gesturesRenderer();
  12593. }
  12594. this.fire('touch:gesture', {
  12595. target: target, e: e, self: self
  12596. });
  12597. },
  12598. __gesturesParams: null,
  12599. __gesturesRenderer: function() {
  12600. if (this.__gesturesParams === null || this._currentTransform === null) {
  12601. return;
  12602. }
  12603. var self = this.__gesturesParams.self,
  12604. t = this._currentTransform,
  12605. e = this.__gesturesParams.e;
  12606. t.action = 'scale';
  12607. t.originX = t.originY = 'center';
  12608. this._scaleObjectBy(self.scale, e);
  12609. if (self.rotation !== 0) {
  12610. t.action = 'rotate';
  12611. this._rotateObjectByAngle(self.rotation, e);
  12612. }
  12613. this.requestRenderAll();
  12614. t.action = 'drag';
  12615. },
  12616. /**
  12617. * Method that defines actions when an Event.js drag is detected.
  12618. *
  12619. * @param {Event} e Event object by Event.js
  12620. * @param {Event} self Event proxy object by Event.js
  12621. */
  12622. __onDrag: function(e, self) {
  12623. this.fire('touch:drag', {
  12624. e: e, self: self
  12625. });
  12626. },
  12627. /**
  12628. * Method that defines actions when an Event.js orientation event is detected.
  12629. *
  12630. * @param {Event} e Event object by Event.js
  12631. * @param {Event} self Event proxy object by Event.js
  12632. */
  12633. __onOrientationChange: function(e, self) {
  12634. this.fire('touch:orientation', {
  12635. e: e, self: self
  12636. });
  12637. },
  12638. /**
  12639. * Method that defines actions when an Event.js shake event is detected.
  12640. *
  12641. * @param {Event} e Event object by Event.js
  12642. * @param {Event} self Event proxy object by Event.js
  12643. */
  12644. __onShake: function(e, self) {
  12645. this.fire('touch:shake', {
  12646. e: e, self: self
  12647. });
  12648. },
  12649. /**
  12650. * Method that defines actions when an Event.js longpress event is detected.
  12651. *
  12652. * @param {Event} e Event object by Event.js
  12653. * @param {Event} self Event proxy object by Event.js
  12654. */
  12655. __onLongPress: function(e, self) {
  12656. this.fire('touch:longpress', {
  12657. e: e, self: self
  12658. });
  12659. },
  12660. /**
  12661. * Scales an object by a factor
  12662. * @param {Number} s The scale factor to apply to the current scale level
  12663. * @param {Event} e Event object by Event.js
  12664. */
  12665. _scaleObjectBy: function(s, e) {
  12666. var t = this._currentTransform,
  12667. target = t.target,
  12668. lockScalingX = target.get('lockScalingX'),
  12669. lockScalingY = target.get('lockScalingY');
  12670. if (lockScalingX && lockScalingY) {
  12671. return;
  12672. }
  12673. target._scaling = true;
  12674. var constraintPosition = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY),
  12675. dim = target._getTransformedDimensions();
  12676. this._setObjectScale(new fabric.Point(t.scaleX * dim.x * s / target.scaleX, t.scaleY * dim.y * s / target.scaleY),
  12677. t, lockScalingX, lockScalingY, null, target.get('lockScalingFlip'), dim);
  12678. target.setPositionByOrigin(constraintPosition, t.originX, t.originY);
  12679. this._fire('scaling', target, e);
  12680. },
  12681. /**
  12682. * Rotates object by an angle
  12683. * @param {Number} curAngle The angle of rotation in degrees
  12684. * @param {Event} e Event object by Event.js
  12685. */
  12686. _rotateObjectByAngle: function(curAngle, e) {
  12687. var t = this._currentTransform;
  12688. if (t.target.get('lockRotation')) {
  12689. return;
  12690. }
  12691. t.target.rotate(radiansToDegrees(degreesToRadians(curAngle) + t.theta));
  12692. this._fire('rotating', t.target, e);
  12693. }
  12694. });
  12695. })();
  12696. (function(global) {
  12697. 'use strict';
  12698. var fabric = global.fabric || (global.fabric = { }),
  12699. extend = fabric.util.object.extend,
  12700. clone = fabric.util.object.clone,
  12701. toFixed = fabric.util.toFixed,
  12702. capitalize = fabric.util.string.capitalize,
  12703. degreesToRadians = fabric.util.degreesToRadians,
  12704. supportsLineDash = fabric.StaticCanvas.supports('setLineDash'),
  12705. objectCaching = !fabric.isLikelyNode,
  12706. ALIASING_LIMIT = 2;
  12707. if (fabric.Object) {
  12708. return;
  12709. }
  12710. /**
  12711. * Root object class from which all 2d shape classes inherit from
  12712. * @class fabric.Object
  12713. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#objects}
  12714. * @see {@link fabric.Object#initialize} for constructor definition
  12715. *
  12716. * @fires added
  12717. * @fires removed
  12718. *
  12719. * @fires selected
  12720. * @fires deselected
  12721. * @fires modified
  12722. * @fires modified
  12723. * @fires moved
  12724. * @fires scaled
  12725. * @fires rotated
  12726. * @fires skewed
  12727. *
  12728. * @fires rotating
  12729. * @fires scaling
  12730. * @fires moving
  12731. * @fires skewing
  12732. *
  12733. * @fires mousedown
  12734. * @fires mouseup
  12735. * @fires mouseover
  12736. * @fires mouseout
  12737. * @fires mousewheel
  12738. * @fires mousedblclick
  12739. *
  12740. * @fires dragover
  12741. * @fires dragenter
  12742. * @fires dragleave
  12743. * @fires drop
  12744. */
  12745. fabric.Object = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.Object.prototype */ {
  12746. /**
  12747. * Type of an object (rect, circle, path, etc.).
  12748. * Note that this property is meant to be read-only and not meant to be modified.
  12749. * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly.
  12750. * @type String
  12751. * @default
  12752. */
  12753. type: 'object',
  12754. /**
  12755. * Horizontal origin of transformation of an object (one of "left", "right", "center")
  12756. * See http://jsfiddle.net/1ow02gea/244/ on how originX/originY affect objects in groups
  12757. * @type String
  12758. * @default
  12759. */
  12760. originX: 'left',
  12761. /**
  12762. * Vertical origin of transformation of an object (one of "top", "bottom", "center")
  12763. * See http://jsfiddle.net/1ow02gea/244/ on how originX/originY affect objects in groups
  12764. * @type String
  12765. * @default
  12766. */
  12767. originY: 'top',
  12768. /**
  12769. * Top position of an object. Note that by default it's relative to object top. You can change this by setting originY={top/center/bottom}
  12770. * @type Number
  12771. * @default
  12772. */
  12773. top: 0,
  12774. /**
  12775. * Left position of an object. Note that by default it's relative to object left. You can change this by setting originX={left/center/right}
  12776. * @type Number
  12777. * @default
  12778. */
  12779. left: 0,
  12780. /**
  12781. * Object width
  12782. * @type Number
  12783. * @default
  12784. */
  12785. width: 0,
  12786. /**
  12787. * Object height
  12788. * @type Number
  12789. * @default
  12790. */
  12791. height: 0,
  12792. /**
  12793. * Object scale factor (horizontal)
  12794. * @type Number
  12795. * @default
  12796. */
  12797. scaleX: 1,
  12798. /**
  12799. * Object scale factor (vertical)
  12800. * @type Number
  12801. * @default
  12802. */
  12803. scaleY: 1,
  12804. /**
  12805. * When true, an object is rendered as flipped horizontally
  12806. * @type Boolean
  12807. * @default
  12808. */
  12809. flipX: false,
  12810. /**
  12811. * When true, an object is rendered as flipped vertically
  12812. * @type Boolean
  12813. * @default
  12814. */
  12815. flipY: false,
  12816. /**
  12817. * Opacity of an object
  12818. * @type Number
  12819. * @default
  12820. */
  12821. opacity: 1,
  12822. /**
  12823. * Angle of rotation of an object (in degrees)
  12824. * @type Number
  12825. * @default
  12826. */
  12827. angle: 0,
  12828. /**
  12829. * Angle of skew on x axes of an object (in degrees)
  12830. * @type Number
  12831. * @default
  12832. */
  12833. skewX: 0,
  12834. /**
  12835. * Angle of skew on y axes of an object (in degrees)
  12836. * @type Number
  12837. * @default
  12838. */
  12839. skewY: 0,
  12840. /**
  12841. * Size of object's controlling corners (in pixels)
  12842. * @type Number
  12843. * @default
  12844. */
  12845. cornerSize: 13,
  12846. /**
  12847. * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill)
  12848. * @type Boolean
  12849. * @default
  12850. */
  12851. transparentCorners: true,
  12852. /**
  12853. * Default cursor value used when hovering over this object on canvas
  12854. * @type String
  12855. * @default
  12856. */
  12857. hoverCursor: null,
  12858. /**
  12859. * Default cursor value used when moving this object on canvas
  12860. * @type String
  12861. * @default
  12862. */
  12863. moveCursor: null,
  12864. /**
  12865. * Padding between object and its controlling borders (in pixels)
  12866. * @type Number
  12867. * @default
  12868. */
  12869. padding: 0,
  12870. /**
  12871. * Color of controlling borders of an object (when it's active)
  12872. * @type String
  12873. * @default
  12874. */
  12875. borderColor: 'rgba(102,153,255,0.75)',
  12876. /**
  12877. * Array specifying dash pattern of an object's borders (hasBorder must be true)
  12878. * @since 1.6.2
  12879. * @type Array
  12880. */
  12881. borderDashArray: null,
  12882. /**
  12883. * Color of controlling corners of an object (when it's active)
  12884. * @type String
  12885. * @default
  12886. */
  12887. cornerColor: 'rgba(102,153,255,0.5)',
  12888. /**
  12889. * Color of controlling corners of an object (when it's active and transparentCorners false)
  12890. * @since 1.6.2
  12891. * @type String
  12892. * @default
  12893. */
  12894. cornerStrokeColor: null,
  12895. /**
  12896. * Specify style of control, 'rect' or 'circle'
  12897. * @since 1.6.2
  12898. * @type String
  12899. */
  12900. cornerStyle: 'rect',
  12901. /**
  12902. * Array specifying dash pattern of an object's control (hasBorder must be true)
  12903. * @since 1.6.2
  12904. * @type Array
  12905. */
  12906. cornerDashArray: null,
  12907. /**
  12908. * When true, this object will use center point as the origin of transformation
  12909. * when being scaled via the controls.
  12910. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  12911. * @since 1.3.4
  12912. * @type Boolean
  12913. * @default
  12914. */
  12915. centeredScaling: false,
  12916. /**
  12917. * When true, this object will use center point as the origin of transformation
  12918. * when being rotated via the controls.
  12919. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  12920. * @since 1.3.4
  12921. * @type Boolean
  12922. * @default
  12923. */
  12924. centeredRotation: true,
  12925. /**
  12926. * Color of object's fill
  12927. * takes css colors https://www.w3.org/TR/css-color-3/
  12928. * @type String
  12929. * @default
  12930. */
  12931. fill: 'rgb(0,0,0)',
  12932. /**
  12933. * Fill rule used to fill an object
  12934. * accepted values are nonzero, evenodd
  12935. * <b>Backwards incompatibility note:</b> This property was used for setting globalCompositeOperation until v1.4.12 (use `fabric.Object#globalCompositeOperation` instead)
  12936. * @type String
  12937. * @default
  12938. */
  12939. fillRule: 'nonzero',
  12940. /**
  12941. * Composite rule used for canvas globalCompositeOperation
  12942. * @type String
  12943. * @default
  12944. */
  12945. globalCompositeOperation: 'source-over',
  12946. /**
  12947. * Background color of an object.
  12948. * takes css colors https://www.w3.org/TR/css-color-3/
  12949. * @type String
  12950. * @default
  12951. */
  12952. backgroundColor: '',
  12953. /**
  12954. * Selection Background color of an object. colored layer behind the object when it is active.
  12955. * does not mix good with globalCompositeOperation methods.
  12956. * @type String
  12957. * @default
  12958. */
  12959. selectionBackgroundColor: '',
  12960. /**
  12961. * When defined, an object is rendered via stroke and this property specifies its color
  12962. * takes css colors https://www.w3.org/TR/css-color-3/
  12963. * @type String
  12964. * @default
  12965. */
  12966. stroke: null,
  12967. /**
  12968. * Width of a stroke used to render this object
  12969. * @type Number
  12970. * @default
  12971. */
  12972. strokeWidth: 1,
  12973. /**
  12974. * Array specifying dash pattern of an object's stroke (stroke must be defined)
  12975. * @type Array
  12976. */
  12977. strokeDashArray: null,
  12978. /**
  12979. * Line endings style of an object's stroke (one of "butt", "round", "square")
  12980. * @type String
  12981. * @default
  12982. */
  12983. strokeLineCap: 'butt',
  12984. /**
  12985. * Corner style of an object's stroke (one of "bevil", "round", "miter")
  12986. * @type String
  12987. * @default
  12988. */
  12989. strokeLineJoin: 'miter',
  12990. /**
  12991. * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke
  12992. * @type Number
  12993. * @default
  12994. */
  12995. strokeMiterLimit: 4,
  12996. /**
  12997. * Shadow object representing shadow of this shape
  12998. * @type fabric.Shadow
  12999. * @default
  13000. */
  13001. shadow: null,
  13002. /**
  13003. * Opacity of object's controlling borders when object is active and moving
  13004. * @type Number
  13005. * @default
  13006. */
  13007. borderOpacityWhenMoving: 0.4,
  13008. /**
  13009. * Scale factor of object's controlling borders
  13010. * @type Number
  13011. * @default
  13012. */
  13013. borderScaleFactor: 1,
  13014. /**
  13015. * Transform matrix (similar to SVG's transform matrix)
  13016. * @type Array
  13017. */
  13018. transformMatrix: null,
  13019. /**
  13020. * Minimum allowed scale value of an object
  13021. * @type Number
  13022. * @default
  13023. */
  13024. minScaleLimit: 0,
  13025. /**
  13026. * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection).
  13027. * But events still fire on it.
  13028. * @type Boolean
  13029. * @default
  13030. */
  13031. selectable: true,
  13032. /**
  13033. * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4
  13034. * @type Boolean
  13035. * @default
  13036. */
  13037. evented: true,
  13038. /**
  13039. * When set to `false`, an object is not rendered on canvas
  13040. * @type Boolean
  13041. * @default
  13042. */
  13043. visible: true,
  13044. /**
  13045. * When set to `false`, object's controls are not displayed and can not be used to manipulate object
  13046. * @type Boolean
  13047. * @default
  13048. */
  13049. hasControls: true,
  13050. /**
  13051. * When set to `false`, object's controlling borders are not rendered
  13052. * @type Boolean
  13053. * @default
  13054. */
  13055. hasBorders: true,
  13056. /**
  13057. * When set to `false`, object's controlling rotating point will not be visible or selectable
  13058. * @type Boolean
  13059. * @default
  13060. */
  13061. hasRotatingPoint: true,
  13062. /**
  13063. * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`)
  13064. * @type Number
  13065. * @default
  13066. */
  13067. rotatingPointOffset: 40,
  13068. /**
  13069. * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box
  13070. * @type Boolean
  13071. * @default
  13072. */
  13073. perPixelTargetFind: false,
  13074. /**
  13075. * When `false`, default object's values are not included in its serialization
  13076. * @type Boolean
  13077. * @default
  13078. */
  13079. includeDefaultValues: true,
  13080. /**
  13081. * Function that determines clipping of an object (context is passed as a first argument)
  13082. * Note that context origin is at the object's center point (not left/top corner)
  13083. * @deprecated since 2.0.0
  13084. * @type Function
  13085. */
  13086. clipTo: null,
  13087. /**
  13088. * When `true`, object horizontal movement is locked
  13089. * @type Boolean
  13090. * @default
  13091. */
  13092. lockMovementX: false,
  13093. /**
  13094. * When `true`, object vertical movement is locked
  13095. * @type Boolean
  13096. * @default
  13097. */
  13098. lockMovementY: false,
  13099. /**
  13100. * When `true`, object rotation is locked
  13101. * @type Boolean
  13102. * @default
  13103. */
  13104. lockRotation: false,
  13105. /**
  13106. * When `true`, object horizontal scaling is locked
  13107. * @type Boolean
  13108. * @default
  13109. */
  13110. lockScalingX: false,
  13111. /**
  13112. * When `true`, object vertical scaling is locked
  13113. * @type Boolean
  13114. * @default
  13115. */
  13116. lockScalingY: false,
  13117. /**
  13118. * When `true`, object non-uniform scaling is locked
  13119. * @type Boolean
  13120. * @default
  13121. */
  13122. lockUniScaling: false,
  13123. /**
  13124. * When `true`, object horizontal skewing is locked
  13125. * @type Boolean
  13126. * @default
  13127. */
  13128. lockSkewingX: false,
  13129. /**
  13130. * When `true`, object vertical skewing is locked
  13131. * @type Boolean
  13132. * @default
  13133. */
  13134. lockSkewingY: false,
  13135. /**
  13136. * When `true`, object cannot be flipped by scaling into negative values
  13137. * @type Boolean
  13138. * @default
  13139. */
  13140. lockScalingFlip: false,
  13141. /**
  13142. * When `true`, object is not exported in OBJECT/JSON
  13143. * since 1.6.3
  13144. * @type Boolean
  13145. * @default
  13146. */
  13147. excludeFromExport: false,
  13148. /**
  13149. * When `true`, object is cached on an additional canvas.
  13150. * default to true
  13151. * since 1.7.0
  13152. * @type Boolean
  13153. * @default true
  13154. */
  13155. objectCaching: objectCaching,
  13156. /**
  13157. * When `true`, object properties are checked for cache invalidation. In some particular
  13158. * situation you may want this to be disabled ( spray brush, very big, groups)
  13159. * or if your application does not allow you to modify properties for groups child you want
  13160. * to disable it for groups.
  13161. * default to false
  13162. * since 1.7.0
  13163. * @type Boolean
  13164. * @default false
  13165. */
  13166. statefullCache: false,
  13167. /**
  13168. * When `true`, cache does not get updated during scaling. The picture will get blocky if scaled
  13169. * too much and will be redrawn with correct details at the end of scaling.
  13170. * this setting is performance and application dependant.
  13171. * default to true
  13172. * since 1.7.0
  13173. * @type Boolean
  13174. * @default true
  13175. */
  13176. noScaleCache: true,
  13177. /**
  13178. * When set to `true`, object's cache will be rerendered next render call.
  13179. * since 1.7.0
  13180. * @type Boolean
  13181. * @default true
  13182. */
  13183. dirty: true,
  13184. /**
  13185. * keeps the value of the last hovered coner during mouse move.
  13186. * 0 is no corner, or 'mt', 'ml', 'mtr' etc..
  13187. * It should be private, but there is no harm in using it as
  13188. * a read-only property.
  13189. * @type number|string|any
  13190. * @default 0
  13191. */
  13192. __corner: 0,
  13193. /**
  13194. * Determins if the fill or the stroke is drawn first (one of "fill" or "stroke")
  13195. * @type String
  13196. * @default
  13197. */
  13198. paintFirst: 'fill',
  13199. /**
  13200. * List of properties to consider when checking if state
  13201. * of an object is changed (fabric.Object#hasStateChanged)
  13202. * as well as for history (undo/redo) purposes
  13203. * @type Array
  13204. */
  13205. stateProperties: (
  13206. 'top left width height scaleX scaleY flipX flipY originX originY transformMatrix ' +
  13207. 'stroke strokeWidth strokeDashArray strokeLineCap strokeLineJoin strokeMiterLimit ' +
  13208. 'angle opacity fill globalCompositeOperation shadow clipTo visible backgroundColor ' +
  13209. 'skewX skewY fillRule paintFirst'
  13210. ).split(' '),
  13211. /**
  13212. * List of properties to consider when checking if cache needs refresh
  13213. * @type Array
  13214. */
  13215. cacheProperties: (
  13216. 'fill stroke strokeWidth strokeDashArray width height paintFirst' +
  13217. ' strokeLineCap strokeLineJoin strokeMiterLimit backgroundColor'
  13218. ).split(' '),
  13219. /**
  13220. * a fabricObject that, without stroke define a clipping area with their opacity
  13221. * @type fabric.Object
  13222. */
  13223. clipPath: undefined,
  13224. /**
  13225. * Constructor
  13226. * @param {Object} [options] Options object
  13227. */
  13228. initialize: function(options) {
  13229. if (options) {
  13230. this.setOptions(options);
  13231. }
  13232. },
  13233. /**
  13234. * Create a the canvas used to keep the cached copy of the object
  13235. * @private
  13236. */
  13237. _createCacheCanvas: function(parentObject) {
  13238. this._cacheProperties = {};
  13239. this._cacheCanvas = fabric.document.createElement('canvas');
  13240. this._cacheContext = this._cacheCanvas.getContext('2d');
  13241. this._updateCacheCanvas(parentObject);
  13242. // if canvas gets created, is empty, so dirty.
  13243. this.dirty = true;
  13244. },
  13245. /**
  13246. * Limit the cache dimensions so that X * Y do not cross fabric.perfLimitSizeTotal
  13247. * and each side do not cross fabric.cacheSideLimit
  13248. * those numbers are configurable so that you can get as much detail as you want
  13249. * making bargain with performances.
  13250. * @param {Object} dims
  13251. * @param {Object} dims.width width of canvas
  13252. * @param {Object} dims.height height of canvas
  13253. * @param {Object} dims.zoomX zoomX zoom value to unscale the canvas before drawing cache
  13254. * @param {Object} dims.zoomY zoomY zoom value to unscale the canvas before drawing cache
  13255. * @return {Object}.width width of canvas
  13256. * @return {Object}.height height of canvas
  13257. * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache
  13258. * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
  13259. */
  13260. _limitCacheSize: function(dims) {
  13261. var perfLimitSizeTotal = fabric.perfLimitSizeTotal,
  13262. width = dims.width, height = dims.height,
  13263. max = fabric.maxCacheSideLimit, min = fabric.minCacheSideLimit;
  13264. if (width <= max && height <= max && width * height <= perfLimitSizeTotal) {
  13265. if (width < min) {
  13266. dims.width = min;
  13267. }
  13268. if (height < min) {
  13269. dims.height = min;
  13270. }
  13271. return dims;
  13272. }
  13273. var ar = width / height, limitedDims = fabric.util.limitDimsByArea(ar, perfLimitSizeTotal),
  13274. capValue = fabric.util.capValue,
  13275. x = capValue(min, limitedDims.x, max),
  13276. y = capValue(min, limitedDims.y, max);
  13277. if (width > x) {
  13278. dims.zoomX /= width / x;
  13279. dims.width = x;
  13280. dims.capped = true;
  13281. }
  13282. if (height > y) {
  13283. dims.zoomY /= height / y;
  13284. dims.height = y;
  13285. dims.capped = true;
  13286. }
  13287. return dims;
  13288. },
  13289. /**
  13290. * Return the dimension and the zoom level needed to create a cache canvas
  13291. * big enough to host the object to be cached.
  13292. * @private
  13293. * @return {Object}.x width of object to be cached
  13294. * @return {Object}.y height of object to be cached
  13295. * @return {Object}.width width of canvas
  13296. * @return {Object}.height height of canvas
  13297. * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache
  13298. * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
  13299. */
  13300. _getCacheCanvasDimensions: function(parentObject) {
  13301. var targetCanvas = this.canvas || (parentObject && parentObject.canvas),
  13302. zoom = targetCanvas && targetCanvas.getZoom() || 1,
  13303. objectScale = this.getObjectScaling(),
  13304. retina = targetCanvas && targetCanvas._isRetinaScaling() ? fabric.devicePixelRatio : 1,
  13305. dim = this._getNonTransformedDimensions(),
  13306. zoomX = objectScale.scaleX * zoom * retina,
  13307. zoomY = objectScale.scaleY * zoom * retina,
  13308. width, height;
  13309. width = dim.x * zoomX;
  13310. height = dim.y * zoomY;
  13311. return {
  13312. // for sure this ALIASING_LIMIT is slightly crating problem
  13313. // in situation in wich the cache canvas gets an upper limit
  13314. width: width + ALIASING_LIMIT,
  13315. height: height + ALIASING_LIMIT,
  13316. zoomX: zoomX,
  13317. zoomY: zoomY,
  13318. x: dim.x,
  13319. y: dim.y
  13320. };
  13321. },
  13322. /**
  13323. * Update width and height of the canvas for cache
  13324. * returns true or false if canvas needed resize.
  13325. * @private
  13326. * @return {Boolean} true if the canvas has been resized
  13327. */
  13328. _updateCacheCanvas: function(parentObject) {
  13329. var targetCanvas = this.canvas || (parentObject && parentObject.canvas);
  13330. if (this.noScaleCache && targetCanvas && targetCanvas._currentTransform) {
  13331. var target = targetCanvas._currentTransform.target,
  13332. action = targetCanvas._currentTransform.action;
  13333. if (this === target && action.slice && action.slice(0, 5) === 'scale') {
  13334. return false;
  13335. }
  13336. }
  13337. var canvas = this._cacheCanvas,
  13338. dims = this._limitCacheSize(this._getCacheCanvasDimensions(parentObject)),
  13339. minCacheSize = fabric.minCacheSideLimit,
  13340. width = dims.width, height = dims.height, drawingWidth, drawingHeight,
  13341. zoomX = dims.zoomX, zoomY = dims.zoomY,
  13342. dimensionsChanged = width !== this.cacheWidth || height !== this.cacheHeight,
  13343. zoomChanged = this.zoomX !== zoomX || this.zoomY !== zoomY,
  13344. shouldRedraw = dimensionsChanged || zoomChanged,
  13345. additionalWidth = 0, additionalHeight = 0, shouldResizeCanvas = false;
  13346. if (dimensionsChanged) {
  13347. var canvasWidth = this._cacheCanvas.width,
  13348. canvasHeight = this._cacheCanvas.height,
  13349. sizeGrowing = width > canvasWidth || height > canvasHeight,
  13350. sizeShrinking = (width < canvasWidth * 0.9 || height < canvasHeight * 0.9) &&
  13351. canvasWidth > minCacheSize && canvasHeight > minCacheSize;
  13352. shouldResizeCanvas = sizeGrowing || sizeShrinking;
  13353. if (sizeGrowing && !dims.capped && (width > minCacheSize || height > minCacheSize)) {
  13354. additionalWidth = width * 0.1;
  13355. additionalHeight = height * 0.1;
  13356. }
  13357. }
  13358. if (shouldRedraw) {
  13359. if (shouldResizeCanvas) {
  13360. canvas.width = Math.ceil(width + additionalWidth);
  13361. canvas.height = Math.ceil(height + additionalHeight);
  13362. }
  13363. else {
  13364. this._cacheContext.setTransform(1, 0, 0, 1, 0, 0);
  13365. this._cacheContext.clearRect(0, 0, canvas.width, canvas.height);
  13366. }
  13367. drawingWidth = dims.x * zoomX / 2;
  13368. drawingHeight = dims.y * zoomY / 2;
  13369. this.cacheTranslationX = Math.round(canvas.width / 2 - drawingWidth) + drawingWidth;
  13370. this.cacheTranslationY = Math.round(canvas.height / 2 - drawingHeight) + drawingHeight;
  13371. this.cacheWidth = width;
  13372. this.cacheHeight = height;
  13373. this._cacheContext.translate(this.cacheTranslationX, this.cacheTranslationY);
  13374. this._cacheContext.scale(zoomX, zoomY);
  13375. this.zoomX = zoomX;
  13376. this.zoomY = zoomY;
  13377. return true;
  13378. }
  13379. return false;
  13380. },
  13381. /**
  13382. * Sets object's properties from options
  13383. * @param {Object} [options] Options object
  13384. */
  13385. setOptions: function(options) {
  13386. this._setOptions(options);
  13387. this._initGradient(options.fill, 'fill');
  13388. this._initGradient(options.stroke, 'stroke');
  13389. this._initClipping(options);
  13390. this._initPattern(options.fill, 'fill');
  13391. this._initPattern(options.stroke, 'stroke');
  13392. },
  13393. /**
  13394. * Transforms context when rendering an object
  13395. * @param {CanvasRenderingContext2D} ctx Context
  13396. */
  13397. transform: function(ctx) {
  13398. var m;
  13399. if (this.group && !this.group._transformDone) {
  13400. m = this.calcTransformMatrix();
  13401. }
  13402. else {
  13403. m = this.calcOwnMatrix();
  13404. }
  13405. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  13406. },
  13407. /**
  13408. * Returns an object representation of an instance
  13409. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  13410. * @return {Object} Object representation of an instance
  13411. */
  13412. toObject: function(propertiesToInclude) {
  13413. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  13414. object = {
  13415. type: this.type,
  13416. version: fabric.version,
  13417. originX: this.originX,
  13418. originY: this.originY,
  13419. left: toFixed(this.left, NUM_FRACTION_DIGITS),
  13420. top: toFixed(this.top, NUM_FRACTION_DIGITS),
  13421. width: toFixed(this.width, NUM_FRACTION_DIGITS),
  13422. height: toFixed(this.height, NUM_FRACTION_DIGITS),
  13423. fill: (this.fill && this.fill.toObject) ? this.fill.toObject() : this.fill,
  13424. stroke: (this.stroke && this.stroke.toObject) ? this.stroke.toObject() : this.stroke,
  13425. strokeWidth: toFixed(this.strokeWidth, NUM_FRACTION_DIGITS),
  13426. strokeDashArray: this.strokeDashArray ? this.strokeDashArray.concat() : this.strokeDashArray,
  13427. strokeLineCap: this.strokeLineCap,
  13428. strokeLineJoin: this.strokeLineJoin,
  13429. strokeMiterLimit: toFixed(this.strokeMiterLimit, NUM_FRACTION_DIGITS),
  13430. scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),
  13431. scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),
  13432. angle: toFixed(this.angle, NUM_FRACTION_DIGITS),
  13433. flipX: this.flipX,
  13434. flipY: this.flipY,
  13435. opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),
  13436. shadow: (this.shadow && this.shadow.toObject) ? this.shadow.toObject() : this.shadow,
  13437. visible: this.visible,
  13438. clipTo: this.clipTo && String(this.clipTo),
  13439. backgroundColor: this.backgroundColor,
  13440. fillRule: this.fillRule,
  13441. paintFirst: this.paintFirst,
  13442. globalCompositeOperation: this.globalCompositeOperation,
  13443. transformMatrix: this.transformMatrix ? this.transformMatrix.concat() : null,
  13444. skewX: toFixed(this.skewX, NUM_FRACTION_DIGITS),
  13445. skewY: toFixed(this.skewY, NUM_FRACTION_DIGITS),
  13446. };
  13447. if (this.clipPath) {
  13448. object.clipPath = this.clipPath.toObject();
  13449. }
  13450. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  13451. if (!this.includeDefaultValues) {
  13452. object = this._removeDefaultValues(object);
  13453. }
  13454. return object;
  13455. },
  13456. /**
  13457. * Returns (dataless) object representation of an instance
  13458. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  13459. * @return {Object} Object representation of an instance
  13460. */
  13461. toDatalessObject: function(propertiesToInclude) {
  13462. // will be overwritten by subclasses
  13463. return this.toObject(propertiesToInclude);
  13464. },
  13465. /**
  13466. * @private
  13467. * @param {Object} object
  13468. */
  13469. _removeDefaultValues: function(object) {
  13470. var prototype = fabric.util.getKlass(object.type).prototype,
  13471. stateProperties = prototype.stateProperties;
  13472. stateProperties.forEach(function(prop) {
  13473. if (object[prop] === prototype[prop]) {
  13474. delete object[prop];
  13475. }
  13476. var isArray = Object.prototype.toString.call(object[prop]) === '[object Array]' &&
  13477. Object.prototype.toString.call(prototype[prop]) === '[object Array]';
  13478. // basically a check for [] === []
  13479. if (isArray && object[prop].length === 0 && prototype[prop].length === 0) {
  13480. delete object[prop];
  13481. }
  13482. });
  13483. return object;
  13484. },
  13485. /**
  13486. * Returns a string representation of an instance
  13487. * @return {String}
  13488. */
  13489. toString: function() {
  13490. return '#<fabric.' + capitalize(this.type) + '>';
  13491. },
  13492. /**
  13493. * Return the object scale factor counting also the group scaling
  13494. * @return {Object} object with scaleX and scaleY properties
  13495. */
  13496. getObjectScaling: function() {
  13497. var scaleX = this.scaleX, scaleY = this.scaleY;
  13498. if (this.group) {
  13499. var scaling = this.group.getObjectScaling();
  13500. scaleX *= scaling.scaleX;
  13501. scaleY *= scaling.scaleY;
  13502. }
  13503. return { scaleX: scaleX, scaleY: scaleY };
  13504. },
  13505. /**
  13506. * Return the object opacity counting also the group property
  13507. * @return {Number}
  13508. */
  13509. getObjectOpacity: function() {
  13510. var opacity = this.opacity;
  13511. if (this.group) {
  13512. opacity *= this.group.getObjectOpacity();
  13513. }
  13514. return opacity;
  13515. },
  13516. /**
  13517. * @private
  13518. * @param {String} key
  13519. * @param {*} value
  13520. * @return {fabric.Object} thisArg
  13521. */
  13522. _set: function(key, value) {
  13523. var shouldConstrainValue = (key === 'scaleX' || key === 'scaleY'),
  13524. isChanged = this[key] !== value, groupNeedsUpdate = false;
  13525. if (shouldConstrainValue) {
  13526. value = this._constrainScale(value);
  13527. }
  13528. if (key === 'scaleX' && value < 0) {
  13529. this.flipX = !this.flipX;
  13530. value *= -1;
  13531. }
  13532. else if (key === 'scaleY' && value < 0) {
  13533. this.flipY = !this.flipY;
  13534. value *= -1;
  13535. }
  13536. else if (key === 'shadow' && value && !(value instanceof fabric.Shadow)) {
  13537. value = new fabric.Shadow(value);
  13538. }
  13539. else if (key === 'dirty' && this.group) {
  13540. this.group.set('dirty', value);
  13541. }
  13542. this[key] = value;
  13543. if (isChanged) {
  13544. groupNeedsUpdate = this.group && this.group.isOnACache();
  13545. if (this.cacheProperties.indexOf(key) > -1) {
  13546. this.dirty = true;
  13547. groupNeedsUpdate && this.group.set('dirty', true);
  13548. }
  13549. else if (groupNeedsUpdate && this.stateProperties.indexOf(key) > -1) {
  13550. this.group.set('dirty', true);
  13551. }
  13552. }
  13553. return this;
  13554. },
  13555. /**
  13556. * This callback function is called by the parent group of an object every
  13557. * time a non-delegated property changes on the group. It is passed the key
  13558. * and value as parameters. Not adding in this function's signature to avoid
  13559. * Travis build error about unused variables.
  13560. */
  13561. setOnGroup: function() {
  13562. // implemented by sub-classes, as needed.
  13563. },
  13564. /**
  13565. * Retrieves viewportTransform from Object's canvas if possible
  13566. * @method getViewportTransform
  13567. * @memberOf fabric.Object.prototype
  13568. * @return {Boolean}
  13569. */
  13570. getViewportTransform: function() {
  13571. if (this.canvas && this.canvas.viewportTransform) {
  13572. return this.canvas.viewportTransform;
  13573. }
  13574. return fabric.iMatrix.concat();
  13575. },
  13576. /*
  13577. * @private
  13578. * return if the object would be visible in rendering
  13579. * @memberOf fabric.Object.prototype
  13580. * @return {Boolean}
  13581. */
  13582. isNotVisible: function() {
  13583. return this.opacity === 0 || (this.width === 0 && this.height === 0) || !this.visible;
  13584. },
  13585. /**
  13586. * Renders an object on a specified context
  13587. * @param {CanvasRenderingContext2D} ctx Context to render on
  13588. */
  13589. render: function(ctx) {
  13590. // do not render if width/height are zeros or object is not visible
  13591. if (this.isNotVisible()) {
  13592. return;
  13593. }
  13594. if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {
  13595. return;
  13596. }
  13597. ctx.save();
  13598. this._setupCompositeOperation(ctx);
  13599. this.drawSelectionBackground(ctx);
  13600. this.transform(ctx);
  13601. this._setOpacity(ctx);
  13602. this._setShadow(ctx, this);
  13603. if (this.transformMatrix) {
  13604. ctx.transform.apply(ctx, this.transformMatrix);
  13605. }
  13606. this.clipTo && fabric.util.clipContext(this, ctx);
  13607. if (this.shouldCache()) {
  13608. this.renderCache();
  13609. this.drawCacheOnCanvas(ctx);
  13610. }
  13611. else {
  13612. this._removeCacheCanvas();
  13613. this.dirty = false;
  13614. this.drawObject(ctx);
  13615. if (this.objectCaching && this.statefullCache) {
  13616. this.saveState({ propertySet: 'cacheProperties' });
  13617. }
  13618. }
  13619. this.clipTo && ctx.restore();
  13620. ctx.restore();
  13621. },
  13622. renderCache: function(parentObject, forClipping) {
  13623. if (!this._cacheCanvas) {
  13624. this._createCacheCanvas(parentObject);
  13625. }
  13626. if (this.isCacheDirty(false, parentObject)) {
  13627. this.statefullCache && this.saveState({ propertySet: 'cacheProperties' });
  13628. this.drawObject(this._cacheContext, forClipping);
  13629. this.dirty = false;
  13630. }
  13631. },
  13632. /**
  13633. * Remove cacheCanvas and its dimensions from the objects
  13634. */
  13635. _removeCacheCanvas: function() {
  13636. this._cacheCanvas = null;
  13637. this.cacheWidth = 0;
  13638. this.cacheHeight = 0;
  13639. },
  13640. /**
  13641. * When set to `true`, force the object to have its own cache, even if it is inside a group
  13642. * it may be needed when your object behave in a particular way on the cache and always needs
  13643. * its own isolated canvas to render correctly.
  13644. * Created to be overridden
  13645. * since 1.7.12
  13646. * @returns false
  13647. */
  13648. needsItsOwnCache: function() {
  13649. if (this.paintFirst === 'stroke' && typeof this.shadow === 'object') {
  13650. return true;
  13651. }
  13652. if (this.clipPath) {
  13653. return true;
  13654. }
  13655. return false;
  13656. },
  13657. /**
  13658. * Decide if the object should cache or not. Create its own cache level
  13659. * objectCaching is a global flag, wins over everything
  13660. * needsItsOwnCache should be used when the object drawing method requires
  13661. * a cache step. None of the fabric classes requires it.
  13662. * Generally you do not cache objects in groups because the group outside is cached.
  13663. * @return {Boolean}
  13664. */
  13665. shouldCache: function() {
  13666. this.ownCaching = this.objectCaching &&
  13667. (!this.group || this.needsItsOwnCache() || !this.group.isOnACache());
  13668. return this.ownCaching;
  13669. },
  13670. /**
  13671. * Check if this object or a child object will cast a shadow
  13672. * used by Group.shouldCache to know if child has a shadow recursively
  13673. * @return {Boolean}
  13674. */
  13675. willDrawShadow: function() {
  13676. return !!this.shadow && (this.shadow.offsetX !== 0 || this.shadow.offsetY !== 0);
  13677. },
  13678. /**
  13679. * Execute the drawing operation for an object clipPath
  13680. * @param {CanvasRenderingContext2D} ctx Context to render on
  13681. */
  13682. drawClipPathOnCache: function(ctx) {
  13683. var path = this.clipPath;
  13684. ctx.save();
  13685. // DEBUG: uncomment this line, comment the following
  13686. // ctx.globalAlpha = 0.4
  13687. ctx.globalCompositeOperation = 'destination-in';
  13688. //ctx.scale(1 / 2, 1 / 2);
  13689. path.transform(ctx);
  13690. ctx.scale(1 / path.zoomX, 1 / path.zoomY);
  13691. ctx.drawImage(path._cacheCanvas, -path.cacheTranslationX, -path.cacheTranslationY);
  13692. ctx.restore();
  13693. },
  13694. /**
  13695. * Execute the drawing operation for an object on a specified context
  13696. * @param {CanvasRenderingContext2D} ctx Context to render on
  13697. */
  13698. drawObject: function(ctx, forClipping) {
  13699. var path = this.clipPath;
  13700. if (forClipping) {
  13701. this._setClippingProperties(ctx);
  13702. }
  13703. else {
  13704. this._renderBackground(ctx);
  13705. this._setStrokeStyles(ctx, this);
  13706. this._setFillStyles(ctx, this);
  13707. }
  13708. this._render(ctx);
  13709. if (path) {
  13710. // needed to setup a couple of variables
  13711. path.shouldCache();
  13712. path._transformDone = true;
  13713. path.renderCache(this, true);
  13714. this.drawClipPathOnCache(ctx);
  13715. }
  13716. },
  13717. /**
  13718. * Paint the cached copy of the object on the target context.
  13719. * @param {CanvasRenderingContext2D} ctx Context to render on
  13720. */
  13721. drawCacheOnCanvas: function(ctx) {
  13722. ctx.scale(1 / this.zoomX, 1 / this.zoomY);
  13723. ctx.drawImage(this._cacheCanvas, -this.cacheTranslationX, -this.cacheTranslationY);
  13724. },
  13725. /**
  13726. * Check if cache is dirty
  13727. * @param {Boolean} skipCanvas skip canvas checks because this object is painted
  13728. * on parent canvas.
  13729. */
  13730. isCacheDirty: function(skipCanvas, parentObject) {
  13731. if (this.isNotVisible()) {
  13732. return false;
  13733. }
  13734. if (this._cacheCanvas && !skipCanvas && this._updateCacheCanvas(parentObject)) {
  13735. // in this case the context is already cleared.
  13736. return true;
  13737. }
  13738. else {
  13739. if (this.dirty || (this.statefullCache && this.hasStateChanged('cacheProperties'))) {
  13740. if (this._cacheCanvas && !skipCanvas) {
  13741. var width = this.cacheWidth / this.zoomX;
  13742. var height = this.cacheHeight / this.zoomY;
  13743. this._cacheContext.clearRect(-width / 2, -height / 2, width, height);
  13744. }
  13745. return true;
  13746. }
  13747. }
  13748. return false;
  13749. },
  13750. /**
  13751. * Draws a background for the object big as its untrasformed dimensions
  13752. * @private
  13753. * @param {CanvasRenderingContext2D} ctx Context to render on
  13754. */
  13755. _renderBackground: function(ctx) {
  13756. if (!this.backgroundColor) {
  13757. return;
  13758. }
  13759. var dim = this._getNonTransformedDimensions();
  13760. ctx.fillStyle = this.backgroundColor;
  13761. ctx.fillRect(
  13762. -dim.x / 2,
  13763. -dim.y / 2,
  13764. dim.x,
  13765. dim.y
  13766. );
  13767. // if there is background color no other shadows
  13768. // should be casted
  13769. this._removeShadow(ctx);
  13770. },
  13771. /**
  13772. * @private
  13773. * @param {CanvasRenderingContext2D} ctx Context to render on
  13774. */
  13775. _setOpacity: function(ctx) {
  13776. if (this.group && !this.group._transformDone) {
  13777. ctx.globalAlpha = this.getObjectOpacity();
  13778. }
  13779. else {
  13780. ctx.globalAlpha *= this.opacity;
  13781. }
  13782. },
  13783. _setStrokeStyles: function(ctx, decl) {
  13784. if (decl.stroke) {
  13785. ctx.lineWidth = decl.strokeWidth;
  13786. ctx.lineCap = decl.strokeLineCap;
  13787. ctx.lineJoin = decl.strokeLineJoin;
  13788. ctx.miterLimit = decl.strokeMiterLimit;
  13789. ctx.strokeStyle = decl.stroke.toLive
  13790. ? decl.stroke.toLive(ctx, this)
  13791. : decl.stroke;
  13792. }
  13793. },
  13794. _setFillStyles: function(ctx, decl) {
  13795. if (decl.fill) {
  13796. ctx.fillStyle = decl.fill.toLive
  13797. ? decl.fill.toLive(ctx, this)
  13798. : decl.fill;
  13799. }
  13800. },
  13801. _setClippingProperties: function(ctx) {
  13802. ctx.globalAlpha = 1;
  13803. ctx.lineWidth = 0;
  13804. ctx.fillStyle = 'black';
  13805. },
  13806. /**
  13807. * @private
  13808. * Sets line dash
  13809. * @param {CanvasRenderingContext2D} ctx Context to set the dash line on
  13810. * @param {Array} dashArray array representing dashes
  13811. * @param {Function} alternative function to call if browaser does not support lineDash
  13812. */
  13813. _setLineDash: function(ctx, dashArray, alternative) {
  13814. if (!dashArray) {
  13815. return;
  13816. }
  13817. // Spec requires the concatenation of two copies the dash list when the number of elements is odd
  13818. if (1 & dashArray.length) {
  13819. dashArray.push.apply(dashArray, dashArray);
  13820. }
  13821. if (supportsLineDash) {
  13822. ctx.setLineDash(dashArray);
  13823. }
  13824. else {
  13825. alternative && alternative(ctx);
  13826. }
  13827. },
  13828. /**
  13829. * Renders controls and borders for the object
  13830. * @param {CanvasRenderingContext2D} ctx Context to render on
  13831. * @param {Object} [styleOverride] properties to override the object style
  13832. */
  13833. _renderControls: function(ctx, styleOverride) {
  13834. var vpt = this.getViewportTransform(),
  13835. matrix = this.calcTransformMatrix(),
  13836. options, drawBorders, drawControls;
  13837. styleOverride = styleOverride || { };
  13838. drawBorders = typeof styleOverride.hasBorders !== 'undefined' ? styleOverride.hasBorders : this.hasBorders;
  13839. drawControls = typeof styleOverride.hasControls !== 'undefined' ? styleOverride.hasControls : this.hasControls;
  13840. matrix = fabric.util.multiplyTransformMatrices(vpt, matrix);
  13841. options = fabric.util.qrDecompose(matrix);
  13842. ctx.save();
  13843. ctx.translate(options.translateX, options.translateY);
  13844. ctx.lineWidth = 1 * this.borderScaleFactor;
  13845. if (!this.group) {
  13846. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  13847. }
  13848. if (styleOverride.forActiveSelection) {
  13849. ctx.rotate(degreesToRadians(options.angle));
  13850. drawBorders && this.drawBordersInGroup(ctx, options, styleOverride);
  13851. }
  13852. else {
  13853. ctx.rotate(degreesToRadians(this.angle));
  13854. drawBorders && this.drawBorders(ctx, styleOverride);
  13855. }
  13856. drawControls && this.drawControls(ctx, styleOverride);
  13857. ctx.restore();
  13858. },
  13859. /**
  13860. * @private
  13861. * @param {CanvasRenderingContext2D} ctx Context to render on
  13862. */
  13863. _setShadow: function(ctx) {
  13864. if (!this.shadow) {
  13865. return;
  13866. }
  13867. var multX = (this.canvas && this.canvas.viewportTransform[0]) || 1,
  13868. multY = (this.canvas && this.canvas.viewportTransform[3]) || 1,
  13869. scaling = this.getObjectScaling();
  13870. if (this.canvas && this.canvas._isRetinaScaling()) {
  13871. multX *= fabric.devicePixelRatio;
  13872. multY *= fabric.devicePixelRatio;
  13873. }
  13874. ctx.shadowColor = this.shadow.color;
  13875. ctx.shadowBlur = this.shadow.blur * fabric.browserShadowBlurConstant *
  13876. (multX + multY) * (scaling.scaleX + scaling.scaleY) / 4;
  13877. ctx.shadowOffsetX = this.shadow.offsetX * multX * scaling.scaleX;
  13878. ctx.shadowOffsetY = this.shadow.offsetY * multY * scaling.scaleY;
  13879. },
  13880. /**
  13881. * @private
  13882. * @param {CanvasRenderingContext2D} ctx Context to render on
  13883. */
  13884. _removeShadow: function(ctx) {
  13885. if (!this.shadow) {
  13886. return;
  13887. }
  13888. ctx.shadowColor = '';
  13889. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  13890. },
  13891. /**
  13892. * @private
  13893. * @param {CanvasRenderingContext2D} ctx Context to render on
  13894. * @param {Object} filler fabric.Pattern or fabric.Gradient
  13895. */
  13896. _applyPatternGradientTransform: function(ctx, filler) {
  13897. if (!filler || !filler.toLive) {
  13898. return { offsetX: 0, offsetY: 0 };
  13899. }
  13900. var t = filler.gradientTransform || filler.patternTransform;
  13901. var offsetX = -this.width / 2 + filler.offsetX || 0,
  13902. offsetY = -this.height / 2 + filler.offsetY || 0;
  13903. ctx.translate(offsetX, offsetY);
  13904. if (t) {
  13905. ctx.transform(t[0], t[1], t[2], t[3], t[4], t[5]);
  13906. }
  13907. return { offsetX: offsetX, offsetY: offsetY };
  13908. },
  13909. /**
  13910. * @private
  13911. * @param {CanvasRenderingContext2D} ctx Context to render on
  13912. */
  13913. _renderPaintInOrder: function(ctx) {
  13914. if (this.paintFirst === 'stroke') {
  13915. this._renderStroke(ctx);
  13916. this._renderFill(ctx);
  13917. }
  13918. else {
  13919. this._renderFill(ctx);
  13920. this._renderStroke(ctx);
  13921. }
  13922. },
  13923. /**
  13924. * @private
  13925. * @param {CanvasRenderingContext2D} ctx Context to render on
  13926. */
  13927. _renderFill: function(ctx) {
  13928. if (!this.fill) {
  13929. return;
  13930. }
  13931. ctx.save();
  13932. this._applyPatternGradientTransform(ctx, this.fill);
  13933. if (this.fillRule === 'evenodd') {
  13934. ctx.fill('evenodd');
  13935. }
  13936. else {
  13937. ctx.fill();
  13938. }
  13939. ctx.restore();
  13940. },
  13941. _renderStroke: function(ctx) {
  13942. if (!this.stroke || this.strokeWidth === 0) {
  13943. return;
  13944. }
  13945. if (this.shadow && !this.shadow.affectStroke) {
  13946. this._removeShadow(ctx);
  13947. }
  13948. ctx.save();
  13949. this._setLineDash(ctx, this.strokeDashArray, this._renderDashedStroke);
  13950. this._applyPatternGradientTransform(ctx, this.stroke);
  13951. ctx.stroke();
  13952. ctx.restore();
  13953. },
  13954. /**
  13955. * This function is an helper for svg import. it returns the center of the object in the svg
  13956. * untransformed coordinates
  13957. * @private
  13958. * @return {Object} center point from element coordinates
  13959. */
  13960. _findCenterFromElement: function() {
  13961. return { x: this.left + this.width / 2, y: this.top + this.height / 2 };
  13962. },
  13963. /**
  13964. * This function is an helper for svg import. it decoompose the transformMatrix
  13965. * and assign properties to object.
  13966. * untransformed coordinates
  13967. * @private
  13968. * @chainable
  13969. */
  13970. _assignTransformMatrixProps: function() {
  13971. if (this.transformMatrix) {
  13972. var options = fabric.util.qrDecompose(this.transformMatrix);
  13973. this.flipX = false;
  13974. this.flipY = false;
  13975. this.set('scaleX', options.scaleX);
  13976. this.set('scaleY', options.scaleY);
  13977. this.angle = options.angle;
  13978. this.skewX = options.skewX;
  13979. this.skewY = 0;
  13980. }
  13981. },
  13982. /**
  13983. * This function is an helper for svg import. it removes the transform matrix
  13984. * and set to object properties that fabricjs can handle
  13985. * @private
  13986. * @param {Object} preserveAspectRatioOptions
  13987. * @return {thisArg}
  13988. */
  13989. _removeTransformMatrix: function(preserveAspectRatioOptions) {
  13990. var center = this._findCenterFromElement();
  13991. if (this.transformMatrix) {
  13992. this._assignTransformMatrixProps();
  13993. center = fabric.util.transformPoint(center, this.transformMatrix);
  13994. }
  13995. this.transformMatrix = null;
  13996. if (preserveAspectRatioOptions) {
  13997. this.scaleX *= preserveAspectRatioOptions.scaleX;
  13998. this.scaleY *= preserveAspectRatioOptions.scaleY;
  13999. this.cropX = preserveAspectRatioOptions.cropX;
  14000. this.cropY = preserveAspectRatioOptions.cropY;
  14001. center.x += preserveAspectRatioOptions.offsetLeft;
  14002. center.y += preserveAspectRatioOptions.offsetTop;
  14003. this.width = preserveAspectRatioOptions.width;
  14004. this.height = preserveAspectRatioOptions.height;
  14005. }
  14006. this.setPositionByOrigin(center, 'center', 'center');
  14007. },
  14008. /**
  14009. * Clones an instance, using a callback method will work for every object.
  14010. * @param {Function} callback Callback is invoked with a clone as a first argument
  14011. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14012. */
  14013. clone: function(callback, propertiesToInclude) {
  14014. var objectForm = this.toObject(propertiesToInclude);
  14015. if (this.constructor.fromObject) {
  14016. this.constructor.fromObject(objectForm, callback);
  14017. }
  14018. else {
  14019. fabric.Object._fromObject('Object', objectForm, callback);
  14020. }
  14021. },
  14022. /**
  14023. * Creates an instance of fabric.Image out of an object
  14024. * @param {Function} callback callback, invoked with an instance as a first argument
  14025. * @param {Object} [options] for clone as image, passed to toDataURL
  14026. * @param {Boolean} [options.enableRetinaScaling] enable retina scaling for the cloned image
  14027. * @return {fabric.Object} thisArg
  14028. */
  14029. cloneAsImage: function(callback, options) {
  14030. var dataUrl = this.toDataURL(options);
  14031. fabric.util.loadImage(dataUrl, function(img) {
  14032. if (callback) {
  14033. callback(new fabric.Image(img));
  14034. }
  14035. });
  14036. return this;
  14037. },
  14038. /**
  14039. * Converts an object into a data-url-like string
  14040. * @param {Object} options Options object
  14041. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  14042. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  14043. * @param {Number} [options.multiplier=1] Multiplier to scale by
  14044. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  14045. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  14046. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  14047. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  14048. * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4
  14049. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  14050. */
  14051. toDataURL: function(options) {
  14052. options || (options = { });
  14053. var el = fabric.util.createCanvasElement(),
  14054. boundingRect = this.getBoundingRect();
  14055. el.width = boundingRect.width;
  14056. el.height = boundingRect.height;
  14057. fabric.util.wrapElement(el, 'div');
  14058. var canvas = new fabric.StaticCanvas(el, {
  14059. enableRetinaScaling: options.enableRetinaScaling,
  14060. renderOnAddRemove: false,
  14061. skipOffscreen: false,
  14062. });
  14063. // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
  14064. if (options.format === 'jpg') {
  14065. options.format = 'jpeg';
  14066. }
  14067. if (options.format === 'jpeg') {
  14068. canvas.backgroundColor = '#fff';
  14069. }
  14070. var origParams = {
  14071. left: this.left,
  14072. top: this.top
  14073. };
  14074. this.setPositionByOrigin(new fabric.Point(canvas.width / 2, canvas.height / 2), 'center', 'center');
  14075. var originalCanvas = this.canvas;
  14076. canvas.add(this);
  14077. var data = canvas.toDataURL(options);
  14078. this.set(origParams).setCoords();
  14079. this.canvas = originalCanvas;
  14080. // canvas.dispose will call image.dispose that will nullify the elements
  14081. // since this canvas is a simple element for the process, we remove references
  14082. // to objects in this way in order to avoid object trashing.
  14083. canvas._objects = [];
  14084. canvas.dispose();
  14085. canvas = null;
  14086. return data;
  14087. },
  14088. /**
  14089. * Returns true if specified type is identical to the type of an instance
  14090. * @param {String} type Type to check against
  14091. * @return {Boolean}
  14092. */
  14093. isType: function(type) {
  14094. return this.type === type;
  14095. },
  14096. /**
  14097. * Returns complexity of an instance
  14098. * @return {Number} complexity of this instance (is 1 unless subclassed)
  14099. */
  14100. complexity: function() {
  14101. return 1;
  14102. },
  14103. /**
  14104. * Returns a JSON representation of an instance
  14105. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14106. * @return {Object} JSON
  14107. */
  14108. toJSON: function(propertiesToInclude) {
  14109. // delegate, not alias
  14110. return this.toObject(propertiesToInclude);
  14111. },
  14112. /**
  14113. * Sets gradient (fill or stroke) of an object
  14114. * <b>Backwards incompatibility note:</b> This method was named "setGradientFill" until v1.1.0
  14115. * @param {String} property Property name 'stroke' or 'fill'
  14116. * @param {Object} [options] Options object
  14117. * @param {String} [options.type] Type of gradient 'radial' or 'linear'
  14118. * @param {Number} [options.x1=0] x-coordinate of start point
  14119. * @param {Number} [options.y1=0] y-coordinate of start point
  14120. * @param {Number} [options.x2=0] x-coordinate of end point
  14121. * @param {Number} [options.y2=0] y-coordinate of end point
  14122. * @param {Number} [options.r1=0] Radius of start point (only for radial gradients)
  14123. * @param {Number} [options.r2=0] Radius of end point (only for radial gradients)
  14124. * @param {Object} [options.colorStops] Color stops object eg. {0: 'ff0000', 1: '000000'}
  14125. * @param {Object} [options.gradientTransform] transforMatrix for gradient
  14126. * @return {fabric.Object} thisArg
  14127. * @chainable
  14128. * @see {@link http://jsfiddle.net/fabricjs/58y8b/|jsFiddle demo}
  14129. * @example <caption>Set linear gradient</caption>
  14130. * object.setGradient('fill', {
  14131. * type: 'linear',
  14132. * x1: -object.width / 2,
  14133. * y1: 0,
  14134. * x2: object.width / 2,
  14135. * y2: 0,
  14136. * colorStops: {
  14137. * 0: 'red',
  14138. * 0.5: '#005555',
  14139. * 1: 'rgba(0,0,255,0.5)'
  14140. * }
  14141. * });
  14142. * canvas.renderAll();
  14143. * @example <caption>Set radial gradient</caption>
  14144. * object.setGradient('fill', {
  14145. * type: 'radial',
  14146. * x1: 0,
  14147. * y1: 0,
  14148. * x2: 0,
  14149. * y2: 0,
  14150. * r1: object.width / 2,
  14151. * r2: 10,
  14152. * colorStops: {
  14153. * 0: 'red',
  14154. * 0.5: '#005555',
  14155. * 1: 'rgba(0,0,255,0.5)'
  14156. * }
  14157. * });
  14158. * canvas.renderAll();
  14159. */
  14160. setGradient: function(property, options) {
  14161. options || (options = { });
  14162. var gradient = { colorStops: [] };
  14163. gradient.type = options.type || (options.r1 || options.r2 ? 'radial' : 'linear');
  14164. gradient.coords = {
  14165. x1: options.x1,
  14166. y1: options.y1,
  14167. x2: options.x2,
  14168. y2: options.y2
  14169. };
  14170. if (options.r1 || options.r2) {
  14171. gradient.coords.r1 = options.r1;
  14172. gradient.coords.r2 = options.r2;
  14173. }
  14174. gradient.gradientTransform = options.gradientTransform;
  14175. fabric.Gradient.prototype.addColorStop.call(gradient, options.colorStops);
  14176. return this.set(property, fabric.Gradient.forObject(this, gradient));
  14177. },
  14178. /**
  14179. * Sets pattern fill of an object
  14180. * @param {Object} options Options object
  14181. * @param {(String|HTMLImageElement)} options.source Pattern source
  14182. * @param {String} [options.repeat=repeat] Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  14183. * @param {Number} [options.offsetX=0] Pattern horizontal offset from object's left/top corner
  14184. * @param {Number} [options.offsetY=0] Pattern vertical offset from object's left/top corner
  14185. * @return {fabric.Object} thisArg
  14186. * @chainable
  14187. * @see {@link http://jsfiddle.net/fabricjs/QT3pa/|jsFiddle demo}
  14188. * @example <caption>Set pattern</caption>
  14189. * fabric.util.loadImage('http://fabricjs.com/assets/escheresque_ste.png', function(img) {
  14190. * object.setPatternFill({
  14191. * source: img,
  14192. * repeat: 'repeat'
  14193. * });
  14194. * canvas.renderAll();
  14195. * });
  14196. */
  14197. setPatternFill: function(options) {
  14198. return this.set('fill', new fabric.Pattern(options));
  14199. },
  14200. /**
  14201. * Sets {@link fabric.Object#shadow|shadow} of an object
  14202. * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)")
  14203. * @param {String} [options.color=rgb(0,0,0)] Shadow color
  14204. * @param {Number} [options.blur=0] Shadow blur
  14205. * @param {Number} [options.offsetX=0] Shadow horizontal offset
  14206. * @param {Number} [options.offsetY=0] Shadow vertical offset
  14207. * @return {fabric.Object} thisArg
  14208. * @chainable
  14209. * @see {@link http://jsfiddle.net/fabricjs/7gvJG/|jsFiddle demo}
  14210. * @example <caption>Set shadow with string notation</caption>
  14211. * object.setShadow('2px 2px 10px rgba(0,0,0,0.2)');
  14212. * canvas.renderAll();
  14213. * @example <caption>Set shadow with object notation</caption>
  14214. * object.setShadow({
  14215. * color: 'red',
  14216. * blur: 10,
  14217. * offsetX: 20,
  14218. * offsetY: 20
  14219. * });
  14220. * canvas.renderAll();
  14221. */
  14222. setShadow: function(options) {
  14223. return this.set('shadow', options ? new fabric.Shadow(options) : null);
  14224. },
  14225. /**
  14226. * Sets "color" of an instance (alias of `set('fill', &hellip;)`)
  14227. * @param {String} color Color value
  14228. * @return {fabric.Object} thisArg
  14229. * @chainable
  14230. */
  14231. setColor: function(color) {
  14232. this.set('fill', color);
  14233. return this;
  14234. },
  14235. /**
  14236. * Sets "angle" of an instance with centered rotation
  14237. * @param {Number} angle Angle value (in degrees)
  14238. * @return {fabric.Object} thisArg
  14239. * @chainable
  14240. */
  14241. rotate: function(angle) {
  14242. var shouldCenterOrigin = (this.originX !== 'center' || this.originY !== 'center') && this.centeredRotation;
  14243. if (shouldCenterOrigin) {
  14244. this._setOriginToCenter();
  14245. }
  14246. this.set('angle', angle);
  14247. if (shouldCenterOrigin) {
  14248. this._resetOrigin();
  14249. }
  14250. return this;
  14251. },
  14252. /**
  14253. * Centers object horizontally on canvas to which it was added last.
  14254. * You might need to call `setCoords` on an object after centering, to update controls area.
  14255. * @return {fabric.Object} thisArg
  14256. * @chainable
  14257. */
  14258. centerH: function () {
  14259. this.canvas && this.canvas.centerObjectH(this);
  14260. return this;
  14261. },
  14262. /**
  14263. * Centers object horizontally on current viewport of canvas to which it was added last.
  14264. * You might need to call `setCoords` on an object after centering, to update controls area.
  14265. * @return {fabric.Object} thisArg
  14266. * @chainable
  14267. */
  14268. viewportCenterH: function () {
  14269. this.canvas && this.canvas.viewportCenterObjectH(this);
  14270. return this;
  14271. },
  14272. /**
  14273. * Centers object vertically on canvas to which it was added last.
  14274. * You might need to call `setCoords` on an object after centering, to update controls area.
  14275. * @return {fabric.Object} thisArg
  14276. * @chainable
  14277. */
  14278. centerV: function () {
  14279. this.canvas && this.canvas.centerObjectV(this);
  14280. return this;
  14281. },
  14282. /**
  14283. * Centers object vertically on current viewport of canvas to which it was added last.
  14284. * You might need to call `setCoords` on an object after centering, to update controls area.
  14285. * @return {fabric.Object} thisArg
  14286. * @chainable
  14287. */
  14288. viewportCenterV: function () {
  14289. this.canvas && this.canvas.viewportCenterObjectV(this);
  14290. return this;
  14291. },
  14292. /**
  14293. * Centers object vertically and horizontally on canvas to which is was added last
  14294. * You might need to call `setCoords` on an object after centering, to update controls area.
  14295. * @return {fabric.Object} thisArg
  14296. * @chainable
  14297. */
  14298. center: function () {
  14299. this.canvas && this.canvas.centerObject(this);
  14300. return this;
  14301. },
  14302. /**
  14303. * Centers object on current viewport of canvas to which it was added last.
  14304. * You might need to call `setCoords` on an object after centering, to update controls area.
  14305. * @return {fabric.Object} thisArg
  14306. * @chainable
  14307. */
  14308. viewportCenter: function () {
  14309. this.canvas && this.canvas.viewportCenterObject(this);
  14310. return this;
  14311. },
  14312. /**
  14313. * Returns coordinates of a pointer relative to an object
  14314. * @param {Event} e Event to operate upon
  14315. * @param {Object} [pointer] Pointer to operate upon (instead of event)
  14316. * @return {Object} Coordinates of a pointer (x, y)
  14317. */
  14318. getLocalPointer: function(e, pointer) {
  14319. pointer = pointer || this.canvas.getPointer(e);
  14320. var pClicked = new fabric.Point(pointer.x, pointer.y),
  14321. objectLeftTop = this._getLeftTopCoords();
  14322. if (this.angle) {
  14323. pClicked = fabric.util.rotatePoint(
  14324. pClicked, objectLeftTop, degreesToRadians(-this.angle));
  14325. }
  14326. return {
  14327. x: pClicked.x - objectLeftTop.x,
  14328. y: pClicked.y - objectLeftTop.y
  14329. };
  14330. },
  14331. /**
  14332. * Sets canvas globalCompositeOperation for specific object
  14333. * custom composition operation for the particular object can be specifed using globalCompositeOperation property
  14334. * @param {CanvasRenderingContext2D} ctx Rendering canvas context
  14335. */
  14336. _setupCompositeOperation: function (ctx) {
  14337. if (this.globalCompositeOperation) {
  14338. ctx.globalCompositeOperation = this.globalCompositeOperation;
  14339. }
  14340. }
  14341. });
  14342. fabric.util.createAccessors && fabric.util.createAccessors(fabric.Object);
  14343. extend(fabric.Object.prototype, fabric.Observable);
  14344. /**
  14345. * Defines the number of fraction digits to use when serializing object values.
  14346. * You can use it to increase/decrease precision of such values like left, top, scaleX, scaleY, etc.
  14347. * @static
  14348. * @memberOf fabric.Object
  14349. * @constant
  14350. * @type Number
  14351. */
  14352. fabric.Object.NUM_FRACTION_DIGITS = 2;
  14353. fabric.Object._fromObject = function(className, object, callback, extraParam) {
  14354. var klass = fabric[className];
  14355. object = clone(object, true);
  14356. fabric.util.enlivenPatterns([object.fill, object.stroke], function(patterns) {
  14357. if (typeof patterns[0] !== 'undefined') {
  14358. object.fill = patterns[0];
  14359. }
  14360. if (typeof patterns[1] !== 'undefined') {
  14361. object.stroke = patterns[1];
  14362. }
  14363. fabric.util.enlivenObjects([object.clipPath], function(enlivedProps) {
  14364. object.clipPath = enlivedProps[0];
  14365. var instance = extraParam ? new klass(object[extraParam], object) : new klass(object);
  14366. callback && callback(instance);
  14367. });
  14368. });
  14369. };
  14370. /**
  14371. * Unique id used internally when creating SVG elements
  14372. * @static
  14373. * @memberOf fabric.Object
  14374. * @type Number
  14375. */
  14376. fabric.Object.__uid = 0;
  14377. })(typeof exports !== 'undefined' ? exports : this);
  14378. (function() {
  14379. var degreesToRadians = fabric.util.degreesToRadians,
  14380. originXOffset = {
  14381. left: -0.5,
  14382. center: 0,
  14383. right: 0.5
  14384. },
  14385. originYOffset = {
  14386. top: -0.5,
  14387. center: 0,
  14388. bottom: 0.5
  14389. };
  14390. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  14391. /**
  14392. * Translates the coordinates from a set of origin to another (based on the object's dimensions)
  14393. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  14394. * @param {String} fromOriginX Horizontal origin: 'left', 'center' or 'right'
  14395. * @param {String} fromOriginY Vertical origin: 'top', 'center' or 'bottom'
  14396. * @param {String} toOriginX Horizontal origin: 'left', 'center' or 'right'
  14397. * @param {String} toOriginY Vertical origin: 'top', 'center' or 'bottom'
  14398. * @return {fabric.Point}
  14399. */
  14400. translateToGivenOrigin: function(point, fromOriginX, fromOriginY, toOriginX, toOriginY) {
  14401. var x = point.x,
  14402. y = point.y,
  14403. offsetX, offsetY, dim;
  14404. if (typeof fromOriginX === 'string') {
  14405. fromOriginX = originXOffset[fromOriginX];
  14406. }
  14407. else {
  14408. fromOriginX -= 0.5;
  14409. }
  14410. if (typeof toOriginX === 'string') {
  14411. toOriginX = originXOffset[toOriginX];
  14412. }
  14413. else {
  14414. toOriginX -= 0.5;
  14415. }
  14416. offsetX = toOriginX - fromOriginX;
  14417. if (typeof fromOriginY === 'string') {
  14418. fromOriginY = originYOffset[fromOriginY];
  14419. }
  14420. else {
  14421. fromOriginY -= 0.5;
  14422. }
  14423. if (typeof toOriginY === 'string') {
  14424. toOriginY = originYOffset[toOriginY];
  14425. }
  14426. else {
  14427. toOriginY -= 0.5;
  14428. }
  14429. offsetY = toOriginY - fromOriginY;
  14430. if (offsetX || offsetY) {
  14431. dim = this._getTransformedDimensions();
  14432. x = point.x + offsetX * dim.x;
  14433. y = point.y + offsetY * dim.y;
  14434. }
  14435. return new fabric.Point(x, y);
  14436. },
  14437. /**
  14438. * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
  14439. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  14440. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  14441. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  14442. * @return {fabric.Point}
  14443. */
  14444. translateToCenterPoint: function(point, originX, originY) {
  14445. var p = this.translateToGivenOrigin(point, originX, originY, 'center', 'center');
  14446. if (this.angle) {
  14447. return fabric.util.rotatePoint(p, point, degreesToRadians(this.angle));
  14448. }
  14449. return p;
  14450. },
  14451. /**
  14452. * Translates the coordinates from center to origin coordinates (based on the object's dimensions)
  14453. * @param {fabric.Point} center The point which corresponds to center of the object
  14454. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  14455. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  14456. * @return {fabric.Point}
  14457. */
  14458. translateToOriginPoint: function(center, originX, originY) {
  14459. var p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
  14460. if (this.angle) {
  14461. return fabric.util.rotatePoint(p, center, degreesToRadians(this.angle));
  14462. }
  14463. return p;
  14464. },
  14465. /**
  14466. * Returns the real center coordinates of the object
  14467. * @return {fabric.Point}
  14468. */
  14469. getCenterPoint: function() {
  14470. var leftTop = new fabric.Point(this.left, this.top);
  14471. return this.translateToCenterPoint(leftTop, this.originX, this.originY);
  14472. },
  14473. /**
  14474. * Returns the coordinates of the object based on center coordinates
  14475. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  14476. * @return {fabric.Point}
  14477. */
  14478. // getOriginPoint: function(center) {
  14479. // return this.translateToOriginPoint(center, this.originX, this.originY);
  14480. // },
  14481. /**
  14482. * Returns the coordinates of the object as if it has a different origin
  14483. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  14484. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  14485. * @return {fabric.Point}
  14486. */
  14487. getPointByOrigin: function(originX, originY) {
  14488. var center = this.getCenterPoint();
  14489. return this.translateToOriginPoint(center, originX, originY);
  14490. },
  14491. /**
  14492. * Returns the point in local coordinates
  14493. * @param {fabric.Point} point The point relative to the global coordinate system
  14494. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  14495. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  14496. * @return {fabric.Point}
  14497. */
  14498. toLocalPoint: function(point, originX, originY) {
  14499. var center = this.getCenterPoint(),
  14500. p, p2;
  14501. if (typeof originX !== 'undefined' && typeof originY !== 'undefined' ) {
  14502. p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
  14503. }
  14504. else {
  14505. p = new fabric.Point(this.left, this.top);
  14506. }
  14507. p2 = new fabric.Point(point.x, point.y);
  14508. if (this.angle) {
  14509. p2 = fabric.util.rotatePoint(p2, center, -degreesToRadians(this.angle));
  14510. }
  14511. return p2.subtractEquals(p);
  14512. },
  14513. /**
  14514. * Returns the point in global coordinates
  14515. * @param {fabric.Point} The point relative to the local coordinate system
  14516. * @return {fabric.Point}
  14517. */
  14518. // toGlobalPoint: function(point) {
  14519. // return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));
  14520. // },
  14521. /**
  14522. * Sets the position of the object taking into consideration the object's origin
  14523. * @param {fabric.Point} pos The new position of the object
  14524. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  14525. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  14526. * @return {void}
  14527. */
  14528. setPositionByOrigin: function(pos, originX, originY) {
  14529. var center = this.translateToCenterPoint(pos, originX, originY),
  14530. position = this.translateToOriginPoint(center, this.originX, this.originY);
  14531. this.set('left', position.x);
  14532. this.set('top', position.y);
  14533. },
  14534. /**
  14535. * @param {String} to One of 'left', 'center', 'right'
  14536. */
  14537. adjustPosition: function(to) {
  14538. var angle = degreesToRadians(this.angle),
  14539. hypotFull = this.getScaledWidth(),
  14540. xFull = fabric.util.cos(angle) * hypotFull,
  14541. yFull = fabric.util.sin(angle) * hypotFull,
  14542. offsetFrom, offsetTo;
  14543. //TODO: this function does not consider mixed situation like top, center.
  14544. if (typeof this.originX === 'string') {
  14545. offsetFrom = originXOffset[this.originX];
  14546. }
  14547. else {
  14548. offsetFrom = this.originX - 0.5;
  14549. }
  14550. if (typeof to === 'string') {
  14551. offsetTo = originXOffset[to];
  14552. }
  14553. else {
  14554. offsetTo = to - 0.5;
  14555. }
  14556. this.left += xFull * (offsetTo - offsetFrom);
  14557. this.top += yFull * (offsetTo - offsetFrom);
  14558. this.setCoords();
  14559. this.originX = to;
  14560. },
  14561. /**
  14562. * Sets the origin/position of the object to it's center point
  14563. * @private
  14564. * @return {void}
  14565. */
  14566. _setOriginToCenter: function() {
  14567. this._originalOriginX = this.originX;
  14568. this._originalOriginY = this.originY;
  14569. var center = this.getCenterPoint();
  14570. this.originX = 'center';
  14571. this.originY = 'center';
  14572. this.left = center.x;
  14573. this.top = center.y;
  14574. },
  14575. /**
  14576. * Resets the origin/position of the object to it's original origin
  14577. * @private
  14578. * @return {void}
  14579. */
  14580. _resetOrigin: function() {
  14581. var originPoint = this.translateToOriginPoint(
  14582. this.getCenterPoint(),
  14583. this._originalOriginX,
  14584. this._originalOriginY);
  14585. this.originX = this._originalOriginX;
  14586. this.originY = this._originalOriginY;
  14587. this.left = originPoint.x;
  14588. this.top = originPoint.y;
  14589. this._originalOriginX = null;
  14590. this._originalOriginY = null;
  14591. },
  14592. /**
  14593. * @private
  14594. */
  14595. _getLeftTopCoords: function() {
  14596. return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');
  14597. },
  14598. });
  14599. })();
  14600. (function() {
  14601. function getCoords(coords) {
  14602. return [
  14603. new fabric.Point(coords.tl.x, coords.tl.y),
  14604. new fabric.Point(coords.tr.x, coords.tr.y),
  14605. new fabric.Point(coords.br.x, coords.br.y),
  14606. new fabric.Point(coords.bl.x, coords.bl.y)
  14607. ];
  14608. }
  14609. var degreesToRadians = fabric.util.degreesToRadians,
  14610. multiplyMatrices = fabric.util.multiplyTransformMatrices,
  14611. transformPoint = fabric.util.transformPoint;
  14612. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  14613. /**
  14614. * Describe object's corner position in canvas element coordinates.
  14615. * properties are tl,mt,tr,ml,mr,bl,mb,br,mtr for the main controls.
  14616. * each property is an object with x, y and corner.
  14617. * The `corner` property contains in a similar manner the 4 points of the
  14618. * interactive area of the corner.
  14619. * The coordinates depends from this properties: width, height, scaleX, scaleY
  14620. * skewX, skewY, angle, strokeWidth, viewportTransform, top, left, padding.
  14621. * The coordinates get updated with @method setCoords.
  14622. * You can calculate them without updating with @method calcCoords;
  14623. * @memberOf fabric.Object.prototype
  14624. */
  14625. oCoords: null,
  14626. /**
  14627. * Describe object's corner position in canvas object absolute coordinates
  14628. * properties are tl,tr,bl,br and describe the four main corner.
  14629. * each property is an object with x, y, instance of Fabric.Point.
  14630. * The coordinates depends from this properties: width, height, scaleX, scaleY
  14631. * skewX, skewY, angle, strokeWidth, top, left.
  14632. * Those coordinates are usefull to understand where an object is. They get updated
  14633. * with oCoords but they do not need to be updated when zoom or panning change.
  14634. * The coordinates get updated with @method setCoords.
  14635. * You can calculate them without updating with @method calcCoords(true);
  14636. * @memberOf fabric.Object.prototype
  14637. */
  14638. aCoords: null,
  14639. /**
  14640. * storage for object transform matrix
  14641. */
  14642. ownMatrixCache: null,
  14643. /**
  14644. * storage for object full transform matrix
  14645. */
  14646. matrixCache: null,
  14647. /**
  14648. * return correct set of coordinates for intersection
  14649. */
  14650. getCoords: function(absolute, calculate) {
  14651. if (!this.oCoords) {
  14652. this.setCoords();
  14653. }
  14654. var coords = absolute ? this.aCoords : this.oCoords;
  14655. return getCoords(calculate ? this.calcCoords(absolute) : coords);
  14656. },
  14657. /**
  14658. * Checks if object intersects with an area formed by 2 points
  14659. * @param {Object} pointTL top-left point of area
  14660. * @param {Object} pointBR bottom-right point of area
  14661. * @param {Boolean} [absolute] use coordinates without viewportTransform
  14662. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14663. * @return {Boolean} true if object intersects with an area formed by 2 points
  14664. */
  14665. intersectsWithRect: function(pointTL, pointBR, absolute, calculate) {
  14666. var coords = this.getCoords(absolute, calculate),
  14667. intersection = fabric.Intersection.intersectPolygonRectangle(
  14668. coords,
  14669. pointTL,
  14670. pointBR
  14671. );
  14672. return intersection.status === 'Intersection';
  14673. },
  14674. /**
  14675. * Checks if object intersects with another object
  14676. * @param {Object} other Object to test
  14677. * @param {Boolean} [absolute] use coordinates without viewportTransform
  14678. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14679. * @return {Boolean} true if object intersects with another object
  14680. */
  14681. intersectsWithObject: function(other, absolute, calculate) {
  14682. var intersection = fabric.Intersection.intersectPolygonPolygon(
  14683. this.getCoords(absolute, calculate),
  14684. other.getCoords(absolute, calculate)
  14685. );
  14686. return intersection.status === 'Intersection'
  14687. || other.isContainedWithinObject(this, absolute, calculate)
  14688. || this.isContainedWithinObject(other, absolute, calculate);
  14689. },
  14690. /**
  14691. * Checks if object is fully contained within area of another object
  14692. * @param {Object} other Object to test
  14693. * @param {Boolean} [absolute] use coordinates without viewportTransform
  14694. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14695. * @return {Boolean} true if object is fully contained within area of another object
  14696. */
  14697. isContainedWithinObject: function(other, absolute, calculate) {
  14698. var points = this.getCoords(absolute, calculate),
  14699. i = 0, lines = other._getImageLines(
  14700. calculate ? other.calcCoords(absolute) : absolute ? other.aCoords : other.oCoords
  14701. );
  14702. for (; i < 4; i++) {
  14703. if (!other.containsPoint(points[i], lines)) {
  14704. return false;
  14705. }
  14706. }
  14707. return true;
  14708. },
  14709. /**
  14710. * Checks if object is fully contained within area formed by 2 points
  14711. * @param {Object} pointTL top-left point of area
  14712. * @param {Object} pointBR bottom-right point of area
  14713. * @param {Boolean} [absolute] use coordinates without viewportTransform
  14714. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14715. * @return {Boolean} true if object is fully contained within area formed by 2 points
  14716. */
  14717. isContainedWithinRect: function(pointTL, pointBR, absolute, calculate) {
  14718. var boundingRect = this.getBoundingRect(absolute, calculate);
  14719. return (
  14720. boundingRect.left >= pointTL.x &&
  14721. boundingRect.left + boundingRect.width <= pointBR.x &&
  14722. boundingRect.top >= pointTL.y &&
  14723. boundingRect.top + boundingRect.height <= pointBR.y
  14724. );
  14725. },
  14726. /**
  14727. * Checks if point is inside the object
  14728. * @param {fabric.Point} point Point to check against
  14729. * @param {Object} [lines] object returned from @method _getImageLines
  14730. * @param {Boolean} [absolute] use coordinates without viewportTransform
  14731. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14732. * @return {Boolean} true if point is inside the object
  14733. */
  14734. containsPoint: function(point, lines, absolute, calculate) {
  14735. var lines = lines || this._getImageLines(
  14736. calculate ? this.calcCoords(absolute) : absolute ? this.aCoords : this.oCoords
  14737. ),
  14738. xPoints = this._findCrossPoints(point, lines);
  14739. // if xPoints is odd then point is inside the object
  14740. return (xPoints !== 0 && xPoints % 2 === 1);
  14741. },
  14742. /**
  14743. * Checks if object is contained within the canvas with current viewportTransform
  14744. * the check is done stopping at first point that appears on screen
  14745. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14746. * @return {Boolean} true if object is fully or partially contained within canvas
  14747. */
  14748. isOnScreen: function(calculate) {
  14749. if (!this.canvas) {
  14750. return false;
  14751. }
  14752. var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;
  14753. var points = this.getCoords(true, calculate), point;
  14754. for (var i = 0; i < 4; i++) {
  14755. point = points[i];
  14756. if (point.x <= pointBR.x && point.x >= pointTL.x && point.y <= pointBR.y && point.y >= pointTL.y) {
  14757. return true;
  14758. }
  14759. }
  14760. // no points on screen, check intersection with absolute coordinates
  14761. if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {
  14762. return true;
  14763. }
  14764. return this._containsCenterOfCanvas(pointTL, pointBR, calculate);
  14765. },
  14766. /**
  14767. * Checks if the object contains the midpoint between canvas extremities
  14768. * Does not make sense outside the context of isOnScreen and isPartiallyOnScreen
  14769. * @private
  14770. * @param {Fabric.Point} pointTL Top Left point
  14771. * @param {Fabric.Point} pointBR Top Right point
  14772. * @param {Boolean} calculate use coordinates of current position instead of .oCoords
  14773. * @return {Boolean} true if the objects containe the point
  14774. */
  14775. _containsCenterOfCanvas: function(pointTL, pointBR, calculate) {
  14776. // worst case scenario the object is so big that contains the screen
  14777. var centerPoint = { x: (pointTL.x + pointBR.x) / 2, y: (pointTL.y + pointBR.y) / 2 };
  14778. if (this.containsPoint(centerPoint, null, true, calculate)) {
  14779. return true;
  14780. }
  14781. return false;
  14782. },
  14783. /**
  14784. * Checks if object is partially contained within the canvas with current viewportTransform
  14785. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  14786. * @return {Boolean} true if object is partially contained within canvas
  14787. */
  14788. isPartiallyOnScreen: function(calculate) {
  14789. if (!this.canvas) {
  14790. return false;
  14791. }
  14792. var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;
  14793. if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {
  14794. return true;
  14795. }
  14796. return this._containsCenterOfCanvas(pointTL, pointBR, calculate);
  14797. },
  14798. /**
  14799. * Method that returns an object with the object edges in it, given the coordinates of the corners
  14800. * @private
  14801. * @param {Object} oCoords Coordinates of the object corners
  14802. */
  14803. _getImageLines: function(oCoords) {
  14804. return {
  14805. topline: {
  14806. o: oCoords.tl,
  14807. d: oCoords.tr
  14808. },
  14809. rightline: {
  14810. o: oCoords.tr,
  14811. d: oCoords.br
  14812. },
  14813. bottomline: {
  14814. o: oCoords.br,
  14815. d: oCoords.bl
  14816. },
  14817. leftline: {
  14818. o: oCoords.bl,
  14819. d: oCoords.tl
  14820. }
  14821. };
  14822. },
  14823. /**
  14824. * Helper method to determine how many cross points are between the 4 object edges
  14825. * and the horizontal line determined by a point on canvas
  14826. * @private
  14827. * @param {fabric.Point} point Point to check
  14828. * @param {Object} lines Coordinates of the object being evaluated
  14829. */
  14830. // remove yi, not used but left code here just in case.
  14831. _findCrossPoints: function(point, lines) {
  14832. var b1, b2, a1, a2, xi, // yi,
  14833. xcount = 0,
  14834. iLine;
  14835. for (var lineKey in lines) {
  14836. iLine = lines[lineKey];
  14837. // optimisation 1: line below point. no cross
  14838. if ((iLine.o.y < point.y) && (iLine.d.y < point.y)) {
  14839. continue;
  14840. }
  14841. // optimisation 2: line above point. no cross
  14842. if ((iLine.o.y >= point.y) && (iLine.d.y >= point.y)) {
  14843. continue;
  14844. }
  14845. // optimisation 3: vertical line case
  14846. if ((iLine.o.x === iLine.d.x) && (iLine.o.x >= point.x)) {
  14847. xi = iLine.o.x;
  14848. // yi = point.y;
  14849. }
  14850. // calculate the intersection point
  14851. else {
  14852. b1 = 0;
  14853. b2 = (iLine.d.y - iLine.o.y) / (iLine.d.x - iLine.o.x);
  14854. a1 = point.y - b1 * point.x;
  14855. a2 = iLine.o.y - b2 * iLine.o.x;
  14856. xi = -(a1 - a2) / (b1 - b2);
  14857. // yi = a1 + b1 * xi;
  14858. }
  14859. // dont count xi < point.x cases
  14860. if (xi >= point.x) {
  14861. xcount += 1;
  14862. }
  14863. // optimisation 4: specific for square images
  14864. if (xcount === 2) {
  14865. break;
  14866. }
  14867. }
  14868. return xcount;
  14869. },
  14870. /**
  14871. * Returns coordinates of object's bounding rectangle (left, top, width, height)
  14872. * the box is intented as aligned to axis of canvas.
  14873. * @param {Boolean} [absolute] use coordinates without viewportTransform
  14874. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords / .aCoords
  14875. * @return {Object} Object with left, top, width, height properties
  14876. */
  14877. getBoundingRect: function(absolute, calculate) {
  14878. var coords = this.getCoords(absolute, calculate);
  14879. return fabric.util.makeBoundingBoxFromPoints(coords);
  14880. },
  14881. /**
  14882. * Returns width of an object bounding box counting transformations
  14883. * before 2.0 it was named getWidth();
  14884. * @return {Number} width value
  14885. */
  14886. getScaledWidth: function() {
  14887. return this._getTransformedDimensions().x;
  14888. },
  14889. /**
  14890. * Returns height of an object bounding box counting transformations
  14891. * before 2.0 it was named getHeight();
  14892. * @return {Number} height value
  14893. */
  14894. getScaledHeight: function() {
  14895. return this._getTransformedDimensions().y;
  14896. },
  14897. /**
  14898. * Makes sure the scale is valid and modifies it if necessary
  14899. * @private
  14900. * @param {Number} value
  14901. * @return {Number}
  14902. */
  14903. _constrainScale: function(value) {
  14904. if (Math.abs(value) < this.minScaleLimit) {
  14905. if (value < 0) {
  14906. return -this.minScaleLimit;
  14907. }
  14908. else {
  14909. return this.minScaleLimit;
  14910. }
  14911. }
  14912. else if (value === 0) {
  14913. return 0.0001;
  14914. }
  14915. return value;
  14916. },
  14917. /**
  14918. * Scales an object (equally by x and y)
  14919. * @param {Number} value Scale factor
  14920. * @return {fabric.Object} thisArg
  14921. * @chainable
  14922. */
  14923. scale: function(value) {
  14924. this._set('scaleX', value);
  14925. this._set('scaleY', value);
  14926. return this.setCoords();
  14927. },
  14928. /**
  14929. * Scales an object to a given width, with respect to bounding box (scaling by x/y equally)
  14930. * @param {Number} value New width value
  14931. * @param {Boolean} absolute ignore viewport
  14932. * @return {fabric.Object} thisArg
  14933. * @chainable
  14934. */
  14935. scaleToWidth: function(value, absolute) {
  14936. // adjust to bounding rect factor so that rotated shapes would fit as well
  14937. var boundingRectFactor = this.getBoundingRect(absolute).width / this.getScaledWidth();
  14938. return this.scale(value / this.width / boundingRectFactor);
  14939. },
  14940. /**
  14941. * Scales an object to a given height, with respect to bounding box (scaling by x/y equally)
  14942. * @param {Number} value New height value
  14943. * @param {Boolean} absolute ignore viewport
  14944. * @return {fabric.Object} thisArg
  14945. * @chainable
  14946. */
  14947. scaleToHeight: function(value, absolute) {
  14948. // adjust to bounding rect factor so that rotated shapes would fit as well
  14949. var boundingRectFactor = this.getBoundingRect(absolute).height / this.getScaledHeight();
  14950. return this.scale(value / this.height / boundingRectFactor);
  14951. },
  14952. /**
  14953. * Calculate and returns the .coords of an object.
  14954. * @return {Object} Object with tl, tr, br, bl ....
  14955. * @chainable
  14956. */
  14957. calcCoords: function(absolute) {
  14958. var rotateMatrix = this._calcRotateMatrix(),
  14959. translateMatrix = this._calcTranslateMatrix(),
  14960. startMatrix = multiplyMatrices(translateMatrix, rotateMatrix),
  14961. vpt = this.getViewportTransform(),
  14962. finalMatrix = absolute ? startMatrix : multiplyMatrices(vpt, startMatrix),
  14963. dim = this._getTransformedDimensions(),
  14964. w = dim.x / 2, h = dim.y / 2,
  14965. tl = transformPoint({ x: -w, y: -h }, finalMatrix),
  14966. tr = transformPoint({ x: w, y: -h }, finalMatrix),
  14967. bl = transformPoint({ x: -w, y: h }, finalMatrix),
  14968. br = transformPoint({ x: w, y: h }, finalMatrix);
  14969. if (!absolute) {
  14970. var padding = this.padding, angle = degreesToRadians(this.angle),
  14971. cos = fabric.util.cos(angle), sin = fabric.util.sin(angle),
  14972. cosP = cos * padding, sinP = sin * padding, cosPSinP = cosP + sinP,
  14973. cosPMinusSinP = cosP - sinP;
  14974. if (padding) {
  14975. tl.x -= cosPMinusSinP;
  14976. tl.y -= cosPSinP;
  14977. tr.x += cosPSinP;
  14978. tr.y -= cosPMinusSinP;
  14979. bl.x -= cosPSinP;
  14980. bl.y += cosPMinusSinP;
  14981. br.x += cosPMinusSinP;
  14982. br.y += cosPSinP;
  14983. }
  14984. var ml = new fabric.Point((tl.x + bl.x) / 2, (tl.y + bl.y) / 2),
  14985. mt = new fabric.Point((tr.x + tl.x) / 2, (tr.y + tl.y) / 2),
  14986. mr = new fabric.Point((br.x + tr.x) / 2, (br.y + tr.y) / 2),
  14987. mb = new fabric.Point((br.x + bl.x) / 2, (br.y + bl.y) / 2),
  14988. mtr = new fabric.Point(mt.x + sin * this.rotatingPointOffset, mt.y - cos * this.rotatingPointOffset);
  14989. }
  14990. // if (!absolute) {
  14991. // var canvas = this.canvas;
  14992. // setTimeout(function() {
  14993. // canvas.contextTop.clearRect(0, 0, 700, 700);
  14994. // canvas.contextTop.fillStyle = 'green';
  14995. // canvas.contextTop.fillRect(mb.x, mb.y, 3, 3);
  14996. // canvas.contextTop.fillRect(bl.x, bl.y, 3, 3);
  14997. // canvas.contextTop.fillRect(br.x, br.y, 3, 3);
  14998. // canvas.contextTop.fillRect(tl.x, tl.y, 3, 3);
  14999. // canvas.contextTop.fillRect(tr.x, tr.y, 3, 3);
  15000. // canvas.contextTop.fillRect(ml.x, ml.y, 3, 3);
  15001. // canvas.contextTop.fillRect(mr.x, mr.y, 3, 3);
  15002. // canvas.contextTop.fillRect(mt.x, mt.y, 3, 3);
  15003. // canvas.contextTop.fillRect(mtr.x, mtr.y, 3, 3);
  15004. // }, 50);
  15005. // }
  15006. var coords = {
  15007. // corners
  15008. tl: tl, tr: tr, br: br, bl: bl,
  15009. };
  15010. if (!absolute) {
  15011. // middle
  15012. coords.ml = ml;
  15013. coords.mt = mt;
  15014. coords.mr = mr;
  15015. coords.mb = mb;
  15016. // rotating point
  15017. coords.mtr = mtr;
  15018. }
  15019. return coords;
  15020. },
  15021. /**
  15022. * Sets corner position coordinates based on current angle, width and height
  15023. * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords
  15024. * @param {Boolean} [ignoreZoom] set oCoords with or without the viewport transform.
  15025. * @param {Boolean} [skipAbsolute] skip calculation of aCoords, usefull in setViewportTransform
  15026. * @return {fabric.Object} thisArg
  15027. * @chainable
  15028. */
  15029. setCoords: function(ignoreZoom, skipAbsolute) {
  15030. this.oCoords = this.calcCoords(ignoreZoom);
  15031. if (!skipAbsolute) {
  15032. this.aCoords = this.calcCoords(true);
  15033. }
  15034. // set coordinates of the draggable boxes in the corners used to scale/rotate the image
  15035. ignoreZoom || (this._setCornerCoords && this._setCornerCoords());
  15036. return this;
  15037. },
  15038. /**
  15039. * calculate rotation matrix of an object
  15040. * @return {Array} rotation matrix for the object
  15041. */
  15042. _calcRotateMatrix: function() {
  15043. if (this.angle) {
  15044. var theta = degreesToRadians(this.angle), cos = fabric.util.cos(theta), sin = fabric.util.sin(theta);
  15045. return [cos, sin, -sin, cos, 0, 0];
  15046. }
  15047. return fabric.iMatrix.concat();
  15048. },
  15049. /**
  15050. * calculate the translation matrix for an object transform
  15051. * @return {Array} rotation matrix for the object
  15052. */
  15053. _calcTranslateMatrix: function() {
  15054. var center = this.getCenterPoint();
  15055. return [1, 0, 0, 1, center.x, center.y];
  15056. },
  15057. transformMatrixKey: function(skipGroup) {
  15058. var sep = '_', prefix = '';
  15059. if (!skipGroup && this.group) {
  15060. prefix = this.group.transformMatrixKey(skipGroup) + sep;
  15061. };
  15062. return prefix + this.top + sep + this.left + sep + this.scaleX + sep + this.scaleY +
  15063. sep + this.skewX + sep + this.skewY + sep + this.angle + sep + this.originX + sep + this.originY +
  15064. sep + this.width + sep + this.height + sep + this.strokeWidth + this.flipX + this.flipY;
  15065. },
  15066. /**
  15067. * calculate trasform Matrix that represent current transformation from
  15068. * object properties.
  15069. * @param {Boolean} [skipGroup] return transformMatrix for object and not go upward with parents
  15070. * @return {Array} matrix Transform Matrix for the object
  15071. */
  15072. calcTransformMatrix: function(skipGroup) {
  15073. if (skipGroup) {
  15074. return this.calcOwnMatrix();
  15075. }
  15076. var key = this.transformMatrixKey(), cache = this.matrixCache || (this.matrixCache = {});
  15077. if (cache.key === key) {
  15078. return cache.value;
  15079. }
  15080. var matrix = this.calcOwnMatrix();
  15081. if (this.group) {
  15082. matrix = multiplyMatrices(this.group.calcTransformMatrix(), matrix);
  15083. }
  15084. cache.key = key;
  15085. cache.value = matrix;
  15086. return matrix;
  15087. },
  15088. calcOwnMatrix: function() {
  15089. var key = this.transformMatrixKey(true), cache = this.ownMatrixCache || (this.ownMatrixCache = {});
  15090. if (cache.key === key) {
  15091. return cache.value;
  15092. }
  15093. var matrix = this._calcTranslateMatrix(),
  15094. rotateMatrix,
  15095. dimensionMatrix = this._calcDimensionsTransformMatrix(this.skewX, this.skewY, true);
  15096. if (this.angle) {
  15097. rotateMatrix = this._calcRotateMatrix();
  15098. matrix = multiplyMatrices(matrix, rotateMatrix);
  15099. }
  15100. matrix = multiplyMatrices(matrix, dimensionMatrix);
  15101. cache.key = key;
  15102. cache.value = matrix;
  15103. return matrix;
  15104. },
  15105. _calcDimensionsTransformMatrix: function(skewX, skewY, flipping) {
  15106. var skewMatrix,
  15107. scaleX = this.scaleX * (flipping && this.flipX ? -1 : 1),
  15108. scaleY = this.scaleY * (flipping && this.flipY ? -1 : 1),
  15109. scaleMatrix = [scaleX, 0, 0, scaleY, 0, 0];
  15110. if (skewX) {
  15111. skewMatrix = [1, 0, Math.tan(degreesToRadians(skewX)), 1];
  15112. scaleMatrix = multiplyMatrices(scaleMatrix, skewMatrix, true);
  15113. }
  15114. if (skewY) {
  15115. skewMatrix = [1, Math.tan(degreesToRadians(skewY)), 0, 1];
  15116. scaleMatrix = multiplyMatrices(scaleMatrix, skewMatrix, true);
  15117. }
  15118. return scaleMatrix;
  15119. },
  15120. /*
  15121. * Calculate object dimensions from its properties
  15122. * @private
  15123. * @return {Object} .x width dimension
  15124. * @return {Object} .y height dimension
  15125. */
  15126. _getNonTransformedDimensions: function() {
  15127. var strokeWidth = this.strokeWidth,
  15128. w = this.width + strokeWidth,
  15129. h = this.height + strokeWidth;
  15130. return { x: w, y: h };
  15131. },
  15132. /*
  15133. * Calculate object bounding boxdimensions from its properties scale, skew.
  15134. * @private
  15135. * @return {Object} .x width dimension
  15136. * @return {Object} .y height dimension
  15137. */
  15138. _getTransformedDimensions: function(skewX, skewY) {
  15139. if (typeof skewX === 'undefined') {
  15140. skewX = this.skewX;
  15141. }
  15142. if (typeof skewY === 'undefined') {
  15143. skewY = this.skewY;
  15144. }
  15145. var dimensions = this._getNonTransformedDimensions();
  15146. if (skewX === 0 && skewY === 0) {
  15147. return { x: dimensions.x * this.scaleX, y: dimensions.y * this.scaleY };
  15148. }
  15149. var dimX = dimensions.x / 2, dimY = dimensions.y / 2,
  15150. points = [
  15151. {
  15152. x: -dimX,
  15153. y: -dimY
  15154. },
  15155. {
  15156. x: dimX,
  15157. y: -dimY
  15158. },
  15159. {
  15160. x: -dimX,
  15161. y: dimY
  15162. },
  15163. {
  15164. x: dimX,
  15165. y: dimY
  15166. }],
  15167. i, transformMatrix = this._calcDimensionsTransformMatrix(skewX, skewY, false),
  15168. bbox;
  15169. for (i = 0; i < points.length; i++) {
  15170. points[i] = fabric.util.transformPoint(points[i], transformMatrix);
  15171. }
  15172. bbox = fabric.util.makeBoundingBoxFromPoints(points);
  15173. return { x: bbox.width, y: bbox.height };
  15174. },
  15175. /*
  15176. * Calculate object dimensions for controls. include padding and canvas zoom
  15177. * private
  15178. */
  15179. _calculateCurrentDimensions: function() {
  15180. var vpt = this.getViewportTransform(),
  15181. dim = this._getTransformedDimensions(),
  15182. p = fabric.util.transformPoint(dim, vpt, true);
  15183. return p.scalarAdd(2 * this.padding);
  15184. },
  15185. });
  15186. })();
  15187. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15188. /**
  15189. * Moves an object to the bottom of the stack of drawn objects
  15190. * @return {fabric.Object} thisArg
  15191. * @chainable
  15192. */
  15193. sendToBack: function() {
  15194. if (this.group) {
  15195. fabric.StaticCanvas.prototype.sendToBack.call(this.group, this);
  15196. }
  15197. else {
  15198. this.canvas.sendToBack(this);
  15199. }
  15200. return this;
  15201. },
  15202. /**
  15203. * Moves an object to the top of the stack of drawn objects
  15204. * @return {fabric.Object} thisArg
  15205. * @chainable
  15206. */
  15207. bringToFront: function() {
  15208. if (this.group) {
  15209. fabric.StaticCanvas.prototype.bringToFront.call(this.group, this);
  15210. }
  15211. else {
  15212. this.canvas.bringToFront(this);
  15213. }
  15214. return this;
  15215. },
  15216. /**
  15217. * Moves an object down in stack of drawn objects
  15218. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  15219. * @return {fabric.Object} thisArg
  15220. * @chainable
  15221. */
  15222. sendBackwards: function(intersecting) {
  15223. if (this.group) {
  15224. fabric.StaticCanvas.prototype.sendBackwards.call(this.group, this, intersecting);
  15225. }
  15226. else {
  15227. this.canvas.sendBackwards(this, intersecting);
  15228. }
  15229. return this;
  15230. },
  15231. /**
  15232. * Moves an object up in stack of drawn objects
  15233. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  15234. * @return {fabric.Object} thisArg
  15235. * @chainable
  15236. */
  15237. bringForward: function(intersecting) {
  15238. if (this.group) {
  15239. fabric.StaticCanvas.prototype.bringForward.call(this.group, this, intersecting);
  15240. }
  15241. else {
  15242. this.canvas.bringForward(this, intersecting);
  15243. }
  15244. return this;
  15245. },
  15246. /**
  15247. * Moves an object to specified level in stack of drawn objects
  15248. * @param {Number} index New position of object
  15249. * @return {fabric.Object} thisArg
  15250. * @chainable
  15251. */
  15252. moveTo: function(index) {
  15253. if (this.group && this.group.type !== 'activeSelection') {
  15254. fabric.StaticCanvas.prototype.moveTo.call(this.group, this, index);
  15255. }
  15256. else {
  15257. this.canvas.moveTo(this, index);
  15258. }
  15259. return this;
  15260. }
  15261. });
  15262. (function() {
  15263. var extend = fabric.util.object.extend,
  15264. originalSet = 'stateProperties';
  15265. /*
  15266. Depends on `stateProperties`
  15267. */
  15268. function saveProps(origin, destination, props) {
  15269. var tmpObj = { }, deep = true;
  15270. props.forEach(function(prop) {
  15271. tmpObj[prop] = origin[prop];
  15272. });
  15273. extend(origin[destination], tmpObj, deep);
  15274. }
  15275. function _isEqual(origValue, currentValue, firstPass) {
  15276. if (origValue === currentValue) {
  15277. // if the objects are identical, return
  15278. return true;
  15279. }
  15280. else if (Array.isArray(origValue)) {
  15281. if (!Array.isArray(currentValue) || origValue.length !== currentValue.length) {
  15282. return false;
  15283. }
  15284. for (var i = 0, len = origValue.length; i < len; i++) {
  15285. if (!_isEqual(origValue[i], currentValue[i])) {
  15286. return false;
  15287. }
  15288. }
  15289. return true;
  15290. }
  15291. else if (origValue && typeof origValue === 'object') {
  15292. var keys = Object.keys(origValue), key;
  15293. if (!currentValue ||
  15294. typeof currentValue !== 'object' ||
  15295. (!firstPass && keys.length !== Object.keys(currentValue).length)
  15296. ) {
  15297. return false;
  15298. }
  15299. for (var i = 0, len = keys.length; i < len; i++) {
  15300. key = keys[i];
  15301. if (!_isEqual(origValue[key], currentValue[key])) {
  15302. return false;
  15303. }
  15304. }
  15305. return true;
  15306. }
  15307. }
  15308. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15309. /**
  15310. * Returns true if object state (one of its state properties) was changed
  15311. * @param {String} [propertySet] optional name for the set of property we want to save
  15312. * @return {Boolean} true if instance' state has changed since `{@link fabric.Object#saveState}` was called
  15313. */
  15314. hasStateChanged: function(propertySet) {
  15315. propertySet = propertySet || originalSet;
  15316. var dashedPropertySet = '_' + propertySet;
  15317. if (Object.keys(this[dashedPropertySet]).length < this[propertySet].length) {
  15318. return true;
  15319. }
  15320. return !_isEqual(this[dashedPropertySet], this, true);
  15321. },
  15322. /**
  15323. * Saves state of an object
  15324. * @param {Object} [options] Object with additional `stateProperties` array to include when saving state
  15325. * @return {fabric.Object} thisArg
  15326. */
  15327. saveState: function(options) {
  15328. var propertySet = options && options.propertySet || originalSet,
  15329. destination = '_' + propertySet;
  15330. if (!this[destination]) {
  15331. return this.setupState(options);
  15332. }
  15333. saveProps(this, destination, this[propertySet]);
  15334. if (options && options.stateProperties) {
  15335. saveProps(this, destination, options.stateProperties);
  15336. }
  15337. return this;
  15338. },
  15339. /**
  15340. * Setups state of an object
  15341. * @param {Object} [options] Object with additional `stateProperties` array to include when saving state
  15342. * @return {fabric.Object} thisArg
  15343. */
  15344. setupState: function(options) {
  15345. options = options || { };
  15346. var propertySet = options.propertySet || originalSet;
  15347. options.propertySet = propertySet;
  15348. this['_' + propertySet] = { };
  15349. this.saveState(options);
  15350. return this;
  15351. }
  15352. });
  15353. })();
  15354. (function() {
  15355. var degreesToRadians = fabric.util.degreesToRadians;
  15356. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15357. /**
  15358. * The object interactivity controls.
  15359. * @private
  15360. */
  15361. _controlsVisibility: null,
  15362. /**
  15363. * Determines which corner has been clicked
  15364. * @private
  15365. * @param {Object} pointer The pointer indicating the mouse position
  15366. * @return {String|Boolean} corner code (tl, tr, bl, br, etc.), or false if nothing is found
  15367. */
  15368. _findTargetCorner: function(pointer) {
  15369. // objects in group, anykind, are not self modificable,
  15370. // must not return an hovered corner.
  15371. if (!this.hasControls || this.group || (!this.canvas || this.canvas._activeObject !== this)) {
  15372. return false;
  15373. }
  15374. var ex = pointer.x,
  15375. ey = pointer.y,
  15376. xPoints,
  15377. lines;
  15378. this.__corner = 0;
  15379. for (var i in this.oCoords) {
  15380. if (!this.isControlVisible(i)) {
  15381. continue;
  15382. }
  15383. if (i === 'mtr' && !this.hasRotatingPoint) {
  15384. continue;
  15385. }
  15386. if (this.get('lockUniScaling') &&
  15387. (i === 'mt' || i === 'mr' || i === 'mb' || i === 'ml')) {
  15388. continue;
  15389. }
  15390. lines = this._getImageLines(this.oCoords[i].corner);
  15391. // debugging
  15392. // canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);
  15393. // canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);
  15394. // canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);
  15395. // canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);
  15396. // canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);
  15397. // canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);
  15398. // canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);
  15399. // canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);
  15400. xPoints = this._findCrossPoints({ x: ex, y: ey }, lines);
  15401. if (xPoints !== 0 && xPoints % 2 === 1) {
  15402. this.__corner = i;
  15403. return i;
  15404. }
  15405. }
  15406. return false;
  15407. },
  15408. /**
  15409. * Sets the coordinates of the draggable boxes in the corners of
  15410. * the image used to scale/rotate it.
  15411. * @private
  15412. */
  15413. _setCornerCoords: function() {
  15414. var coords = this.oCoords,
  15415. newTheta = degreesToRadians(45 - this.angle),
  15416. /* Math.sqrt(2 * Math.pow(this.cornerSize, 2)) / 2, */
  15417. /* 0.707106 stands for sqrt(2)/2 */
  15418. cornerHypotenuse = this.cornerSize * 0.707106,
  15419. cosHalfOffset = cornerHypotenuse * fabric.util.cos(newTheta),
  15420. sinHalfOffset = cornerHypotenuse * fabric.util.sin(newTheta),
  15421. x, y;
  15422. for (var point in coords) {
  15423. x = coords[point].x;
  15424. y = coords[point].y;
  15425. coords[point].corner = {
  15426. tl: {
  15427. x: x - sinHalfOffset,
  15428. y: y - cosHalfOffset
  15429. },
  15430. tr: {
  15431. x: x + cosHalfOffset,
  15432. y: y - sinHalfOffset
  15433. },
  15434. bl: {
  15435. x: x - cosHalfOffset,
  15436. y: y + sinHalfOffset
  15437. },
  15438. br: {
  15439. x: x + sinHalfOffset,
  15440. y: y + cosHalfOffset
  15441. }
  15442. };
  15443. }
  15444. },
  15445. /**
  15446. * Draws a colored layer behind the object, inside its selection borders.
  15447. * Requires public options: padding, selectionBackgroundColor
  15448. * this function is called when the context is transformed
  15449. * has checks to be skipped when the object is on a staticCanvas
  15450. * @param {CanvasRenderingContext2D} ctx Context to draw on
  15451. * @return {fabric.Object} thisArg
  15452. * @chainable
  15453. */
  15454. drawSelectionBackground: function(ctx) {
  15455. if (!this.selectionBackgroundColor ||
  15456. (this.canvas && !this.canvas.interactive) ||
  15457. (this.canvas && this.canvas._activeObject !== this)
  15458. ) {
  15459. return this;
  15460. }
  15461. ctx.save();
  15462. var center = this.getCenterPoint(), wh = this._calculateCurrentDimensions(),
  15463. vpt = this.canvas.viewportTransform;
  15464. ctx.translate(center.x, center.y);
  15465. ctx.scale(1 / vpt[0], 1 / vpt[3]);
  15466. ctx.rotate(degreesToRadians(this.angle));
  15467. ctx.fillStyle = this.selectionBackgroundColor;
  15468. ctx.fillRect(-wh.x / 2, -wh.y / 2, wh.x, wh.y);
  15469. ctx.restore();
  15470. return this;
  15471. },
  15472. /**
  15473. * Draws borders of an object's bounding box.
  15474. * Requires public properties: width, height
  15475. * Requires public options: padding, borderColor
  15476. * @param {CanvasRenderingContext2D} ctx Context to draw on
  15477. * @param {Object} styleOverride object to override the object style
  15478. * @return {fabric.Object} thisArg
  15479. * @chainable
  15480. */
  15481. drawBorders: function(ctx, styleOverride) {
  15482. styleOverride = styleOverride || {};
  15483. var wh = this._calculateCurrentDimensions(),
  15484. strokeWidth = 1 / this.borderScaleFactor,
  15485. width = wh.x + strokeWidth,
  15486. height = wh.y + strokeWidth,
  15487. drawRotatingPoint = typeof styleOverride.hasRotatingPoint !== 'undefined' ?
  15488. styleOverride.hasRotatingPoint : this.hasRotatingPoint,
  15489. hasControls = typeof styleOverride.hasControls !== 'undefined' ?
  15490. styleOverride.hasControls : this.hasControls,
  15491. rotatingPointOffset = typeof styleOverride.rotatingPointOffset !== 'undefined' ?
  15492. styleOverride.rotatingPointOffset : this.rotatingPointOffset;
  15493. ctx.save();
  15494. ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
  15495. this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray, null);
  15496. ctx.strokeRect(
  15497. -width / 2,
  15498. -height / 2,
  15499. width,
  15500. height
  15501. );
  15502. if (drawRotatingPoint && this.isControlVisible('mtr') && hasControls) {
  15503. var rotateHeight = -height / 2;
  15504. ctx.beginPath();
  15505. ctx.moveTo(0, rotateHeight);
  15506. ctx.lineTo(0, rotateHeight - rotatingPointOffset);
  15507. ctx.stroke();
  15508. }
  15509. ctx.restore();
  15510. return this;
  15511. },
  15512. /**
  15513. * Draws borders of an object's bounding box when it is inside a group.
  15514. * Requires public properties: width, height
  15515. * Requires public options: padding, borderColor
  15516. * @param {CanvasRenderingContext2D} ctx Context to draw on
  15517. * @param {object} options object representing current object parameters
  15518. * @param {Object} styleOverride object to override the object style
  15519. * @return {fabric.Object} thisArg
  15520. * @chainable
  15521. */
  15522. drawBordersInGroup: function(ctx, options, styleOverride) {
  15523. styleOverride = styleOverride || {};
  15524. var p = this._getNonTransformedDimensions(),
  15525. matrix = fabric.util.customTransformMatrix(options.scaleX, options.scaleY, options.skewX),
  15526. wh = fabric.util.transformPoint(p, matrix),
  15527. strokeWidth = 1 / this.borderScaleFactor,
  15528. width = wh.x + strokeWidth,
  15529. height = wh.y + strokeWidth;
  15530. ctx.save();
  15531. this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray, null);
  15532. ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
  15533. ctx.strokeRect(
  15534. -width / 2,
  15535. -height / 2,
  15536. width,
  15537. height
  15538. );
  15539. ctx.restore();
  15540. return this;
  15541. },
  15542. /**
  15543. * Draws corners of an object's bounding box.
  15544. * Requires public properties: width, height
  15545. * Requires public options: cornerSize, padding
  15546. * @param {CanvasRenderingContext2D} ctx Context to draw on
  15547. * @param {Object} styleOverride object to override the object style
  15548. * @return {fabric.Object} thisArg
  15549. * @chainable
  15550. */
  15551. drawControls: function(ctx, styleOverride) {
  15552. styleOverride = styleOverride || {};
  15553. var wh = this._calculateCurrentDimensions(),
  15554. width = wh.x,
  15555. height = wh.y,
  15556. scaleOffset = styleOverride.cornerSize || this.cornerSize,
  15557. left = -(width + scaleOffset) / 2,
  15558. top = -(height + scaleOffset) / 2,
  15559. transparentCorners = typeof styleOverride.transparentCorners !== 'undefined' ?
  15560. styleOverride.transparentCorners : this.transparentCorners,
  15561. hasRotatingPoint = typeof styleOverride.hasRotatingPoint !== 'undefined' ?
  15562. styleOverride.hasRotatingPoint : this.hasRotatingPoint,
  15563. methodName = transparentCorners ? 'stroke' : 'fill';
  15564. ctx.save();
  15565. ctx.strokeStyle = ctx.fillStyle = styleOverride.cornerColor || this.cornerColor;
  15566. if (!this.transparentCorners) {
  15567. ctx.strokeStyle = styleOverride.cornerStrokeColor || this.cornerStrokeColor;
  15568. }
  15569. this._setLineDash(ctx, styleOverride.cornerDashArray || this.cornerDashArray, null);
  15570. // top-left
  15571. this._drawControl('tl', ctx, methodName,
  15572. left,
  15573. top, styleOverride);
  15574. // top-right
  15575. this._drawControl('tr', ctx, methodName,
  15576. left + width,
  15577. top, styleOverride);
  15578. // bottom-left
  15579. this._drawControl('bl', ctx, methodName,
  15580. left,
  15581. top + height, styleOverride);
  15582. // bottom-right
  15583. this._drawControl('br', ctx, methodName,
  15584. left + width,
  15585. top + height, styleOverride);
  15586. if (!this.get('lockUniScaling')) {
  15587. // middle-top
  15588. this._drawControl('mt', ctx, methodName,
  15589. left + width / 2,
  15590. top, styleOverride);
  15591. // middle-bottom
  15592. this._drawControl('mb', ctx, methodName,
  15593. left + width / 2,
  15594. top + height, styleOverride);
  15595. // middle-right
  15596. this._drawControl('mr', ctx, methodName,
  15597. left + width,
  15598. top + height / 2, styleOverride);
  15599. // middle-left
  15600. this._drawControl('ml', ctx, methodName,
  15601. left,
  15602. top + height / 2, styleOverride);
  15603. }
  15604. // middle-top-rotate
  15605. if (hasRotatingPoint) {
  15606. this._drawControl('mtr', ctx, methodName,
  15607. left + width / 2,
  15608. top - this.rotatingPointOffset, styleOverride);
  15609. }
  15610. ctx.restore();
  15611. return this;
  15612. },
  15613. /**
  15614. * @private
  15615. */
  15616. _drawControl: function(control, ctx, methodName, left, top, styleOverride) {
  15617. styleOverride = styleOverride || {};
  15618. if (!this.isControlVisible(control)) {
  15619. return;
  15620. }
  15621. var size = this.cornerSize, stroke = !this.transparentCorners && this.cornerStrokeColor;
  15622. switch (styleOverride.cornerStyle || this.cornerStyle) {
  15623. case 'circle':
  15624. ctx.beginPath();
  15625. ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
  15626. ctx[methodName]();
  15627. if (stroke) {
  15628. ctx.stroke();
  15629. }
  15630. break;
  15631. default:
  15632. this.transparentCorners || ctx.clearRect(left, top, size, size);
  15633. ctx[methodName + 'Rect'](left, top, size, size);
  15634. if (stroke) {
  15635. ctx.strokeRect(left, top, size, size);
  15636. }
  15637. }
  15638. },
  15639. /**
  15640. * Returns true if the specified control is visible, false otherwise.
  15641. * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  15642. * @returns {Boolean} true if the specified control is visible, false otherwise
  15643. */
  15644. isControlVisible: function(controlName) {
  15645. return this._getControlsVisibility()[controlName];
  15646. },
  15647. /**
  15648. * Sets the visibility of the specified control.
  15649. * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  15650. * @param {Boolean} visible true to set the specified control visible, false otherwise
  15651. * @return {fabric.Object} thisArg
  15652. * @chainable
  15653. */
  15654. setControlVisible: function(controlName, visible) {
  15655. this._getControlsVisibility()[controlName] = visible;
  15656. return this;
  15657. },
  15658. /**
  15659. * Sets the visibility state of object controls.
  15660. * @param {Object} [options] Options object
  15661. * @param {Boolean} [options.bl] true to enable the bottom-left control, false to disable it
  15662. * @param {Boolean} [options.br] true to enable the bottom-right control, false to disable it
  15663. * @param {Boolean} [options.mb] true to enable the middle-bottom control, false to disable it
  15664. * @param {Boolean} [options.ml] true to enable the middle-left control, false to disable it
  15665. * @param {Boolean} [options.mr] true to enable the middle-right control, false to disable it
  15666. * @param {Boolean} [options.mt] true to enable the middle-top control, false to disable it
  15667. * @param {Boolean} [options.tl] true to enable the top-left control, false to disable it
  15668. * @param {Boolean} [options.tr] true to enable the top-right control, false to disable it
  15669. * @param {Boolean} [options.mtr] true to enable the middle-top-rotate control, false to disable it
  15670. * @return {fabric.Object} thisArg
  15671. * @chainable
  15672. */
  15673. setControlsVisibility: function(options) {
  15674. options || (options = { });
  15675. for (var p in options) {
  15676. this.setControlVisible(p, options[p]);
  15677. }
  15678. return this;
  15679. },
  15680. /**
  15681. * Returns the instance of the control visibility set for this object.
  15682. * @private
  15683. * @returns {Object}
  15684. */
  15685. _getControlsVisibility: function() {
  15686. if (!this._controlsVisibility) {
  15687. this._controlsVisibility = {
  15688. tl: true,
  15689. tr: true,
  15690. br: true,
  15691. bl: true,
  15692. ml: true,
  15693. mt: true,
  15694. mr: true,
  15695. mb: true,
  15696. mtr: true
  15697. };
  15698. }
  15699. return this._controlsVisibility;
  15700. },
  15701. /**
  15702. * This callback function is called every time _discardActiveObject or _setActiveObject
  15703. * try to to deselect this object. If the function returns true, the process is cancelled
  15704. * @param {Object} [options] options sent from the upper functions
  15705. * @param {Event} [options.e] event if the process is generated by an event
  15706. */
  15707. onDeselect: function() {
  15708. // implemented by sub-classes, as needed.
  15709. },
  15710. /**
  15711. * This callback function is called every time _discardActiveObject or _setActiveObject
  15712. * try to to select this object. If the function returns true, the process is cancelled
  15713. * @param {Object} [options] options sent from the upper functions
  15714. * @param {Event} [options.e] event if the process is generated by an event
  15715. */
  15716. onSelect: function() {
  15717. // implemented by sub-classes, as needed.
  15718. }
  15719. });
  15720. })();
  15721. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  15722. /**
  15723. * Animation duration (in ms) for fx* methods
  15724. * @type Number
  15725. * @default
  15726. */
  15727. FX_DURATION: 500,
  15728. /**
  15729. * Centers object horizontally with animation.
  15730. * @param {fabric.Object} object Object to center
  15731. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  15732. * @param {Function} [callbacks.onComplete] Invoked on completion
  15733. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  15734. * @return {fabric.Canvas} thisArg
  15735. * @chainable
  15736. */
  15737. fxCenterObjectH: function (object, callbacks) {
  15738. callbacks = callbacks || { };
  15739. var empty = function() { },
  15740. onComplete = callbacks.onComplete || empty,
  15741. onChange = callbacks.onChange || empty,
  15742. _this = this;
  15743. fabric.util.animate({
  15744. startValue: object.left,
  15745. endValue: this.getCenter().left,
  15746. duration: this.FX_DURATION,
  15747. onChange: function(value) {
  15748. object.set('left', value);
  15749. _this.requestRenderAll();
  15750. onChange();
  15751. },
  15752. onComplete: function() {
  15753. object.setCoords();
  15754. onComplete();
  15755. }
  15756. });
  15757. return this;
  15758. },
  15759. /**
  15760. * Centers object vertically with animation.
  15761. * @param {fabric.Object} object Object to center
  15762. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  15763. * @param {Function} [callbacks.onComplete] Invoked on completion
  15764. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  15765. * @return {fabric.Canvas} thisArg
  15766. * @chainable
  15767. */
  15768. fxCenterObjectV: function (object, callbacks) {
  15769. callbacks = callbacks || { };
  15770. var empty = function() { },
  15771. onComplete = callbacks.onComplete || empty,
  15772. onChange = callbacks.onChange || empty,
  15773. _this = this;
  15774. fabric.util.animate({
  15775. startValue: object.top,
  15776. endValue: this.getCenter().top,
  15777. duration: this.FX_DURATION,
  15778. onChange: function(value) {
  15779. object.set('top', value);
  15780. _this.requestRenderAll();
  15781. onChange();
  15782. },
  15783. onComplete: function() {
  15784. object.setCoords();
  15785. onComplete();
  15786. }
  15787. });
  15788. return this;
  15789. },
  15790. /**
  15791. * Same as `fabric.Canvas#remove` but animated
  15792. * @param {fabric.Object} object Object to remove
  15793. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  15794. * @param {Function} [callbacks.onComplete] Invoked on completion
  15795. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  15796. * @return {fabric.Canvas} thisArg
  15797. * @chainable
  15798. */
  15799. fxRemove: function (object, callbacks) {
  15800. callbacks = callbacks || { };
  15801. var empty = function() { },
  15802. onComplete = callbacks.onComplete || empty,
  15803. onChange = callbacks.onChange || empty,
  15804. _this = this;
  15805. fabric.util.animate({
  15806. startValue: object.opacity,
  15807. endValue: 0,
  15808. duration: this.FX_DURATION,
  15809. onChange: function(value) {
  15810. object.set('opacity', value);
  15811. _this.requestRenderAll();
  15812. onChange();
  15813. },
  15814. onComplete: function () {
  15815. _this.remove(object);
  15816. onComplete();
  15817. }
  15818. });
  15819. return this;
  15820. }
  15821. });
  15822. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15823. /**
  15824. * Animates object's properties
  15825. * @param {String|Object} property Property to animate (if string) or properties to animate (if object)
  15826. * @param {Number|Object} value Value to animate property to (if string was given first) or options object
  15827. * @return {fabric.Object} thisArg
  15828. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#animation}
  15829. * @chainable
  15830. *
  15831. * As object — multiple properties
  15832. *
  15833. * object.animate({ left: ..., top: ... });
  15834. * object.animate({ left: ..., top: ... }, { duration: ... });
  15835. *
  15836. * As string — one property
  15837. *
  15838. * object.animate('left', ...);
  15839. * object.animate('left', { duration: ... });
  15840. *
  15841. */
  15842. animate: function() {
  15843. if (arguments[0] && typeof arguments[0] === 'object') {
  15844. var propsToAnimate = [], prop, skipCallbacks;
  15845. for (prop in arguments[0]) {
  15846. propsToAnimate.push(prop);
  15847. }
  15848. for (var i = 0, len = propsToAnimate.length; i < len; i++) {
  15849. prop = propsToAnimate[i];
  15850. skipCallbacks = i !== len - 1;
  15851. this._animate(prop, arguments[0][prop], arguments[1], skipCallbacks);
  15852. }
  15853. }
  15854. else {
  15855. this._animate.apply(this, arguments);
  15856. }
  15857. return this;
  15858. },
  15859. /**
  15860. * @private
  15861. * @param {String} property Property to animate
  15862. * @param {String} to Value to animate to
  15863. * @param {Object} [options] Options object
  15864. * @param {Boolean} [skipCallbacks] When true, callbacks like onchange and oncomplete are not invoked
  15865. */
  15866. _animate: function(property, to, options, skipCallbacks) {
  15867. var _this = this, propPair;
  15868. to = to.toString();
  15869. if (!options) {
  15870. options = { };
  15871. }
  15872. else {
  15873. options = fabric.util.object.clone(options);
  15874. }
  15875. if (~property.indexOf('.')) {
  15876. propPair = property.split('.');
  15877. }
  15878. var currentValue = propPair
  15879. ? this.get(propPair[0])[propPair[1]]
  15880. : this.get(property);
  15881. if (!('from' in options)) {
  15882. options.from = currentValue;
  15883. }
  15884. if (~to.indexOf('=')) {
  15885. to = currentValue + parseFloat(to.replace('=', ''));
  15886. }
  15887. else {
  15888. to = parseFloat(to);
  15889. }
  15890. fabric.util.animate({
  15891. startValue: options.from,
  15892. endValue: to,
  15893. byValue: options.by,
  15894. easing: options.easing,
  15895. duration: options.duration,
  15896. abort: options.abort && function() {
  15897. return options.abort.call(_this);
  15898. },
  15899. onChange: function(value, valueProgress, timeProgress) {
  15900. if (propPair) {
  15901. _this[propPair[0]][propPair[1]] = value;
  15902. }
  15903. else {
  15904. _this.set(property, value);
  15905. }
  15906. if (skipCallbacks) {
  15907. return;
  15908. }
  15909. options.onChange && options.onChange(value, valueProgress, timeProgress);
  15910. },
  15911. onComplete: function(value, valueProgress, timeProgress) {
  15912. if (skipCallbacks) {
  15913. return;
  15914. }
  15915. _this.setCoords();
  15916. options.onComplete && options.onComplete(value, valueProgress, timeProgress);
  15917. }
  15918. });
  15919. }
  15920. });
  15921. (function(global) {
  15922. 'use strict';
  15923. var fabric = global.fabric || (global.fabric = { }),
  15924. extend = fabric.util.object.extend,
  15925. clone = fabric.util.object.clone,
  15926. coordProps = { x1: 1, x2: 1, y1: 1, y2: 1 },
  15927. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  15928. if (fabric.Line) {
  15929. fabric.warn('fabric.Line is already defined');
  15930. return;
  15931. }
  15932. /**
  15933. * Line class
  15934. * @class fabric.Line
  15935. * @extends fabric.Object
  15936. * @see {@link fabric.Line#initialize} for constructor definition
  15937. */
  15938. fabric.Line = fabric.util.createClass(fabric.Object, /** @lends fabric.Line.prototype */ {
  15939. /**
  15940. * Type of an object
  15941. * @type String
  15942. * @default
  15943. */
  15944. type: 'line',
  15945. /**
  15946. * x value or first line edge
  15947. * @type Number
  15948. * @default
  15949. */
  15950. x1: 0,
  15951. /**
  15952. * y value or first line edge
  15953. * @type Number
  15954. * @default
  15955. */
  15956. y1: 0,
  15957. /**
  15958. * x value or second line edge
  15959. * @type Number
  15960. * @default
  15961. */
  15962. x2: 0,
  15963. /**
  15964. * y value or second line edge
  15965. * @type Number
  15966. * @default
  15967. */
  15968. y2: 0,
  15969. cacheProperties: fabric.Object.prototype.cacheProperties.concat('x1', 'x2', 'y1', 'y2'),
  15970. /**
  15971. * Constructor
  15972. * @param {Array} [points] Array of points
  15973. * @param {Object} [options] Options object
  15974. * @return {fabric.Line} thisArg
  15975. */
  15976. initialize: function(points, options) {
  15977. if (!points) {
  15978. points = [0, 0, 0, 0];
  15979. }
  15980. this.callSuper('initialize', options);
  15981. this.set('x1', points[0]);
  15982. this.set('y1', points[1]);
  15983. this.set('x2', points[2]);
  15984. this.set('y2', points[3]);
  15985. this._setWidthHeight(options);
  15986. },
  15987. /**
  15988. * @private
  15989. * @param {Object} [options] Options
  15990. */
  15991. _setWidthHeight: function(options) {
  15992. options || (options = { });
  15993. this.width = Math.abs(this.x2 - this.x1);
  15994. this.height = Math.abs(this.y2 - this.y1);
  15995. this.left = 'left' in options
  15996. ? options.left
  15997. : this._getLeftToOriginX();
  15998. this.top = 'top' in options
  15999. ? options.top
  16000. : this._getTopToOriginY();
  16001. },
  16002. /**
  16003. * @private
  16004. * @param {String} key
  16005. * @param {*} value
  16006. */
  16007. _set: function(key, value) {
  16008. this.callSuper('_set', key, value);
  16009. if (typeof coordProps[key] !== 'undefined') {
  16010. this._setWidthHeight();
  16011. }
  16012. return this;
  16013. },
  16014. /**
  16015. * @private
  16016. * @return {Number} leftToOriginX Distance from left edge of canvas to originX of Line.
  16017. */
  16018. _getLeftToOriginX: makeEdgeToOriginGetter(
  16019. { // property names
  16020. origin: 'originX',
  16021. axis1: 'x1',
  16022. axis2: 'x2',
  16023. dimension: 'width'
  16024. },
  16025. { // possible values of origin
  16026. nearest: 'left',
  16027. center: 'center',
  16028. farthest: 'right'
  16029. }
  16030. ),
  16031. /**
  16032. * @private
  16033. * @return {Number} topToOriginY Distance from top edge of canvas to originY of Line.
  16034. */
  16035. _getTopToOriginY: makeEdgeToOriginGetter(
  16036. { // property names
  16037. origin: 'originY',
  16038. axis1: 'y1',
  16039. axis2: 'y2',
  16040. dimension: 'height'
  16041. },
  16042. { // possible values of origin
  16043. nearest: 'top',
  16044. center: 'center',
  16045. farthest: 'bottom'
  16046. }
  16047. ),
  16048. /**
  16049. * @private
  16050. * @param {CanvasRenderingContext2D} ctx Context to render on
  16051. */
  16052. _render: function(ctx) {
  16053. ctx.beginPath();
  16054. if (!this.strokeDashArray || this.strokeDashArray && supportsLineDash) {
  16055. // move from center (of virtual box) to its left/top corner
  16056. // we can't assume x1, y1 is top left and x2, y2 is bottom right
  16057. var p = this.calcLinePoints();
  16058. ctx.moveTo(p.x1, p.y1);
  16059. ctx.lineTo(p.x2, p.y2);
  16060. }
  16061. ctx.lineWidth = this.strokeWidth;
  16062. // TODO: test this
  16063. // make sure setting "fill" changes color of a line
  16064. // (by copying fillStyle to strokeStyle, since line is stroked, not filled)
  16065. var origStrokeStyle = ctx.strokeStyle;
  16066. ctx.strokeStyle = this.stroke || ctx.fillStyle;
  16067. this.stroke && this._renderStroke(ctx);
  16068. ctx.strokeStyle = origStrokeStyle;
  16069. },
  16070. /**
  16071. * @private
  16072. * @param {CanvasRenderingContext2D} ctx Context to render on
  16073. */
  16074. _renderDashedStroke: function(ctx) {
  16075. var p = this.calcLinePoints();
  16076. ctx.beginPath();
  16077. fabric.util.drawDashedLine(ctx, p.x1, p.y1, p.x2, p.y2, this.strokeDashArray);
  16078. ctx.closePath();
  16079. },
  16080. /**
  16081. * This function is an helper for svg import. it returns the center of the object in the svg
  16082. * untransformed coordinates
  16083. * @private
  16084. * @return {Object} center point from element coordinates
  16085. */
  16086. _findCenterFromElement: function() {
  16087. return {
  16088. x: (this.x1 + this.x2) / 2,
  16089. y: (this.y1 + this.y2) / 2,
  16090. };
  16091. },
  16092. /**
  16093. * Returns object representation of an instance
  16094. * @methd toObject
  16095. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16096. * @return {Object} object representation of an instance
  16097. */
  16098. toObject: function(propertiesToInclude) {
  16099. return extend(this.callSuper('toObject', propertiesToInclude), this.calcLinePoints());
  16100. },
  16101. /*
  16102. * Calculate object dimensions from its properties
  16103. * @private
  16104. */
  16105. _getNonTransformedDimensions: function() {
  16106. var dim = this.callSuper('_getNonTransformedDimensions');
  16107. if (this.strokeLineCap === 'butt') {
  16108. if (this.width === 0) {
  16109. dim.y -= this.strokeWidth;
  16110. }
  16111. if (this.height === 0) {
  16112. dim.x -= this.strokeWidth;
  16113. }
  16114. }
  16115. return dim;
  16116. },
  16117. /**
  16118. * Recalculates line points given width and height
  16119. * @private
  16120. */
  16121. calcLinePoints: function() {
  16122. var xMult = this.x1 <= this.x2 ? -1 : 1,
  16123. yMult = this.y1 <= this.y2 ? -1 : 1,
  16124. x1 = (xMult * this.width * 0.5),
  16125. y1 = (yMult * this.height * 0.5),
  16126. x2 = (xMult * this.width * -0.5),
  16127. y2 = (yMult * this.height * -0.5);
  16128. return {
  16129. x1: x1,
  16130. x2: x2,
  16131. y1: y1,
  16132. y2: y2
  16133. };
  16134. },
  16135. });
  16136. /**
  16137. * Returns fabric.Line instance from an object representation
  16138. * @static
  16139. * @memberOf fabric.Line
  16140. * @param {Object} object Object to create an instance from
  16141. * @param {function} [callback] invoked with new instance as first argument
  16142. */
  16143. fabric.Line.fromObject = function(object, callback) {
  16144. function _callback(instance) {
  16145. delete instance.points;
  16146. callback && callback(instance);
  16147. };
  16148. var options = clone(object, true);
  16149. options.points = [object.x1, object.y1, object.x2, object.y2];
  16150. fabric.Object._fromObject('Line', options, _callback, 'points');
  16151. };
  16152. /**
  16153. * Produces a function that calculates distance from canvas edge to Line origin.
  16154. */
  16155. function makeEdgeToOriginGetter(propertyNames, originValues) {
  16156. var origin = propertyNames.origin,
  16157. axis1 = propertyNames.axis1,
  16158. axis2 = propertyNames.axis2,
  16159. dimension = propertyNames.dimension,
  16160. nearest = originValues.nearest,
  16161. center = originValues.center,
  16162. farthest = originValues.farthest;
  16163. return function() {
  16164. switch (this.get(origin)) {
  16165. case nearest:
  16166. return Math.min(this.get(axis1), this.get(axis2));
  16167. case center:
  16168. return Math.min(this.get(axis1), this.get(axis2)) + (0.5 * this.get(dimension));
  16169. case farthest:
  16170. return Math.max(this.get(axis1), this.get(axis2));
  16171. }
  16172. };
  16173. }
  16174. })(typeof exports !== 'undefined' ? exports : this);
  16175. (function(global) {
  16176. 'use strict';
  16177. var fabric = global.fabric || (global.fabric = { }),
  16178. pi = Math.PI;
  16179. if (fabric.Circle) {
  16180. fabric.warn('fabric.Circle is already defined.');
  16181. return;
  16182. }
  16183. /**
  16184. * Circle class
  16185. * @class fabric.Circle
  16186. * @extends fabric.Object
  16187. * @see {@link fabric.Circle#initialize} for constructor definition
  16188. */
  16189. fabric.Circle = fabric.util.createClass(fabric.Object, /** @lends fabric.Circle.prototype */ {
  16190. /**
  16191. * Type of an object
  16192. * @type String
  16193. * @default
  16194. */
  16195. type: 'circle',
  16196. /**
  16197. * Radius of this circle
  16198. * @type Number
  16199. * @default
  16200. */
  16201. radius: 0,
  16202. /**
  16203. * Start angle of the circle, moving clockwise
  16204. * deprectated type, this should be in degree, this was an oversight.
  16205. * probably will change to degrees in next major version
  16206. * @type Number
  16207. * @default 0
  16208. */
  16209. startAngle: 0,
  16210. /**
  16211. * End angle of the circle
  16212. * deprectated type, this should be in degree, this was an oversight.
  16213. * probably will change to degrees in next major version
  16214. * @type Number
  16215. * @default 2Pi
  16216. */
  16217. endAngle: pi * 2,
  16218. cacheProperties: fabric.Object.prototype.cacheProperties.concat('radius', 'startAngle', 'endAngle'),
  16219. /**
  16220. * @private
  16221. * @param {String} key
  16222. * @param {*} value
  16223. * @return {fabric.Circle} thisArg
  16224. */
  16225. _set: function(key, value) {
  16226. this.callSuper('_set', key, value);
  16227. if (key === 'radius') {
  16228. this.setRadius(value);
  16229. }
  16230. return this;
  16231. },
  16232. /**
  16233. * Returns object representation of an instance
  16234. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16235. * @return {Object} object representation of an instance
  16236. */
  16237. toObject: function(propertiesToInclude) {
  16238. return this.callSuper('toObject', ['radius', 'startAngle', 'endAngle'].concat(propertiesToInclude));
  16239. },
  16240. /**
  16241. * @private
  16242. * @param {CanvasRenderingContext2D} ctx context to render on
  16243. */
  16244. _render: function(ctx) {
  16245. ctx.beginPath();
  16246. ctx.arc(
  16247. 0,
  16248. 0,
  16249. this.radius,
  16250. this.startAngle,
  16251. this.endAngle, false);
  16252. this._renderPaintInOrder(ctx);
  16253. },
  16254. /**
  16255. * Returns horizontal radius of an object (according to how an object is scaled)
  16256. * @return {Number}
  16257. */
  16258. getRadiusX: function() {
  16259. return this.get('radius') * this.get('scaleX');
  16260. },
  16261. /**
  16262. * Returns vertical radius of an object (according to how an object is scaled)
  16263. * @return {Number}
  16264. */
  16265. getRadiusY: function() {
  16266. return this.get('radius') * this.get('scaleY');
  16267. },
  16268. /**
  16269. * Sets radius of an object (and updates width accordingly)
  16270. * @return {fabric.Circle} thisArg
  16271. */
  16272. setRadius: function(value) {
  16273. this.radius = value;
  16274. return this.set('width', value * 2).set('height', value * 2);
  16275. },
  16276. });
  16277. /**
  16278. * Returns {@link fabric.Circle} instance from an object representation
  16279. * @static
  16280. * @memberOf fabric.Circle
  16281. * @param {Object} object Object to create an instance from
  16282. * @param {function} [callback] invoked with new instance as first argument
  16283. * @return {Object} Instance of fabric.Circle
  16284. */
  16285. fabric.Circle.fromObject = function(object, callback) {
  16286. return fabric.Object._fromObject('Circle', object, callback);
  16287. };
  16288. })(typeof exports !== 'undefined' ? exports : this);
  16289. (function(global) {
  16290. 'use strict';
  16291. var fabric = global.fabric || (global.fabric = { });
  16292. if (fabric.Triangle) {
  16293. fabric.warn('fabric.Triangle is already defined');
  16294. return;
  16295. }
  16296. /**
  16297. * Triangle class
  16298. * @class fabric.Triangle
  16299. * @extends fabric.Object
  16300. * @return {fabric.Triangle} thisArg
  16301. * @see {@link fabric.Triangle#initialize} for constructor definition
  16302. */
  16303. fabric.Triangle = fabric.util.createClass(fabric.Object, /** @lends fabric.Triangle.prototype */ {
  16304. /**
  16305. * Type of an object
  16306. * @type String
  16307. * @default
  16308. */
  16309. type: 'triangle',
  16310. /**
  16311. * Width is set to 100 to compensate the old initialize code that was setting it to 100
  16312. * @type Number
  16313. * @default
  16314. */
  16315. width: 100,
  16316. /**
  16317. * Height is set to 100 to compensate the old initialize code that was setting it to 100
  16318. * @type Number
  16319. * @default
  16320. */
  16321. height: 100,
  16322. /**
  16323. * @private
  16324. * @param {CanvasRenderingContext2D} ctx Context to render on
  16325. */
  16326. _render: function(ctx) {
  16327. var widthBy2 = this.width / 2,
  16328. heightBy2 = this.height / 2;
  16329. ctx.beginPath();
  16330. ctx.moveTo(-widthBy2, heightBy2);
  16331. ctx.lineTo(0, -heightBy2);
  16332. ctx.lineTo(widthBy2, heightBy2);
  16333. ctx.closePath();
  16334. this._renderPaintInOrder(ctx);
  16335. },
  16336. /**
  16337. * @private
  16338. * @param {CanvasRenderingContext2D} ctx Context to render on
  16339. */
  16340. _renderDashedStroke: function(ctx) {
  16341. var widthBy2 = this.width / 2,
  16342. heightBy2 = this.height / 2;
  16343. ctx.beginPath();
  16344. fabric.util.drawDashedLine(ctx, -widthBy2, heightBy2, 0, -heightBy2, this.strokeDashArray);
  16345. fabric.util.drawDashedLine(ctx, 0, -heightBy2, widthBy2, heightBy2, this.strokeDashArray);
  16346. fabric.util.drawDashedLine(ctx, widthBy2, heightBy2, -widthBy2, heightBy2, this.strokeDashArray);
  16347. ctx.closePath();
  16348. },
  16349. });
  16350. /**
  16351. * Returns {@link fabric.Triangle} instance from an object representation
  16352. * @static
  16353. * @memberOf fabric.Triangle
  16354. * @param {Object} object Object to create an instance from
  16355. * @param {function} [callback] invoked with new instance as first argument
  16356. */
  16357. fabric.Triangle.fromObject = function(object, callback) {
  16358. return fabric.Object._fromObject('Triangle', object, callback);
  16359. };
  16360. })(typeof exports !== 'undefined' ? exports : this);
  16361. (function(global) {
  16362. 'use strict';
  16363. var fabric = global.fabric || (global.fabric = { }),
  16364. piBy2 = Math.PI * 2;
  16365. if (fabric.Ellipse) {
  16366. fabric.warn('fabric.Ellipse is already defined.');
  16367. return;
  16368. }
  16369. /**
  16370. * Ellipse class
  16371. * @class fabric.Ellipse
  16372. * @extends fabric.Object
  16373. * @return {fabric.Ellipse} thisArg
  16374. * @see {@link fabric.Ellipse#initialize} for constructor definition
  16375. */
  16376. fabric.Ellipse = fabric.util.createClass(fabric.Object, /** @lends fabric.Ellipse.prototype */ {
  16377. /**
  16378. * Type of an object
  16379. * @type String
  16380. * @default
  16381. */
  16382. type: 'ellipse',
  16383. /**
  16384. * Horizontal radius
  16385. * @type Number
  16386. * @default
  16387. */
  16388. rx: 0,
  16389. /**
  16390. * Vertical radius
  16391. * @type Number
  16392. * @default
  16393. */
  16394. ry: 0,
  16395. cacheProperties: fabric.Object.prototype.cacheProperties.concat('rx', 'ry'),
  16396. /**
  16397. * Constructor
  16398. * @param {Object} [options] Options object
  16399. * @return {fabric.Ellipse} thisArg
  16400. */
  16401. initialize: function(options) {
  16402. this.callSuper('initialize', options);
  16403. this.set('rx', options && options.rx || 0);
  16404. this.set('ry', options && options.ry || 0);
  16405. },
  16406. /**
  16407. * @private
  16408. * @param {String} key
  16409. * @param {*} value
  16410. * @return {fabric.Ellipse} thisArg
  16411. */
  16412. _set: function(key, value) {
  16413. this.callSuper('_set', key, value);
  16414. switch (key) {
  16415. case 'rx':
  16416. this.rx = value;
  16417. this.set('width', value * 2);
  16418. break;
  16419. case 'ry':
  16420. this.ry = value;
  16421. this.set('height', value * 2);
  16422. break;
  16423. }
  16424. return this;
  16425. },
  16426. /**
  16427. * Returns horizontal radius of an object (according to how an object is scaled)
  16428. * @return {Number}
  16429. */
  16430. getRx: function() {
  16431. return this.get('rx') * this.get('scaleX');
  16432. },
  16433. /**
  16434. * Returns Vertical radius of an object (according to how an object is scaled)
  16435. * @return {Number}
  16436. */
  16437. getRy: function() {
  16438. return this.get('ry') * this.get('scaleY');
  16439. },
  16440. /**
  16441. * Returns object representation of an instance
  16442. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16443. * @return {Object} object representation of an instance
  16444. */
  16445. toObject: function(propertiesToInclude) {
  16446. return this.callSuper('toObject', ['rx', 'ry'].concat(propertiesToInclude));
  16447. },
  16448. /**
  16449. * @private
  16450. * @param {CanvasRenderingContext2D} ctx context to render on
  16451. */
  16452. _render: function(ctx) {
  16453. ctx.beginPath();
  16454. ctx.save();
  16455. ctx.transform(1, 0, 0, this.ry / this.rx, 0, 0);
  16456. ctx.arc(
  16457. 0,
  16458. 0,
  16459. this.rx,
  16460. 0,
  16461. piBy2,
  16462. false);
  16463. ctx.restore();
  16464. this._renderPaintInOrder(ctx);
  16465. },
  16466. });
  16467. /**
  16468. * Returns {@link fabric.Ellipse} instance from an object representation
  16469. * @static
  16470. * @memberOf fabric.Ellipse
  16471. * @param {Object} object Object to create an instance from
  16472. * @param {function} [callback] invoked with new instance as first argument
  16473. * @return {fabric.Ellipse}
  16474. */
  16475. fabric.Ellipse.fromObject = function(object, callback) {
  16476. return fabric.Object._fromObject('Ellipse', object, callback);
  16477. };
  16478. })(typeof exports !== 'undefined' ? exports : this);
  16479. (function(global) {
  16480. 'use strict';
  16481. var fabric = global.fabric || (global.fabric = { }),
  16482. extend = fabric.util.object.extend;
  16483. if (fabric.Rect) {
  16484. fabric.warn('fabric.Rect is already defined');
  16485. return;
  16486. }
  16487. /**
  16488. * Rectangle class
  16489. * @class fabric.Rect
  16490. * @extends fabric.Object
  16491. * @return {fabric.Rect} thisArg
  16492. * @see {@link fabric.Rect#initialize} for constructor definition
  16493. */
  16494. fabric.Rect = fabric.util.createClass(fabric.Object, /** @lends fabric.Rect.prototype */ {
  16495. /**
  16496. * List of properties to consider when checking if state of an object is changed ({@link fabric.Object#hasStateChanged})
  16497. * as well as for history (undo/redo) purposes
  16498. * @type Array
  16499. */
  16500. stateProperties: fabric.Object.prototype.stateProperties.concat('rx', 'ry'),
  16501. /**
  16502. * Type of an object
  16503. * @type String
  16504. * @default
  16505. */
  16506. type: 'rect',
  16507. /**
  16508. * Horizontal border radius
  16509. * @type Number
  16510. * @default
  16511. */
  16512. rx: 0,
  16513. /**
  16514. * Vertical border radius
  16515. * @type Number
  16516. * @default
  16517. */
  16518. ry: 0,
  16519. cacheProperties: fabric.Object.prototype.cacheProperties.concat('rx', 'ry'),
  16520. /**
  16521. * Constructor
  16522. * @param {Object} [options] Options object
  16523. * @return {Object} thisArg
  16524. */
  16525. initialize: function(options) {
  16526. this.callSuper('initialize', options);
  16527. this._initRxRy();
  16528. },
  16529. /**
  16530. * Initializes rx/ry attributes
  16531. * @private
  16532. */
  16533. _initRxRy: function() {
  16534. if (this.rx && !this.ry) {
  16535. this.ry = this.rx;
  16536. }
  16537. else if (this.ry && !this.rx) {
  16538. this.rx = this.ry;
  16539. }
  16540. },
  16541. /**
  16542. * @private
  16543. * @param {CanvasRenderingContext2D} ctx Context to render on
  16544. */
  16545. _render: function(ctx) {
  16546. // optimize 1x1 case (used in spray brush)
  16547. if (this.width === 1 && this.height === 1) {
  16548. ctx.fillRect(-0.5, -0.5, 1, 1);
  16549. return;
  16550. }
  16551. var rx = this.rx ? Math.min(this.rx, this.width / 2) : 0,
  16552. ry = this.ry ? Math.min(this.ry, this.height / 2) : 0,
  16553. w = this.width,
  16554. h = this.height,
  16555. x = -this.width / 2,
  16556. y = -this.height / 2,
  16557. isRounded = rx !== 0 || ry !== 0,
  16558. /* "magic number" for bezier approximations of arcs (http://itc.ktu.lt/itc354/Riskus354.pdf) */
  16559. k = 1 - 0.5522847498;
  16560. ctx.beginPath();
  16561. ctx.moveTo(x + rx, y);
  16562. ctx.lineTo(x + w - rx, y);
  16563. isRounded && ctx.bezierCurveTo(x + w - k * rx, y, x + w, y + k * ry, x + w, y + ry);
  16564. ctx.lineTo(x + w, y + h - ry);
  16565. isRounded && ctx.bezierCurveTo(x + w, y + h - k * ry, x + w - k * rx, y + h, x + w - rx, y + h);
  16566. ctx.lineTo(x + rx, y + h);
  16567. isRounded && ctx.bezierCurveTo(x + k * rx, y + h, x, y + h - k * ry, x, y + h - ry);
  16568. ctx.lineTo(x, y + ry);
  16569. isRounded && ctx.bezierCurveTo(x, y + k * ry, x + k * rx, y, x + rx, y);
  16570. ctx.closePath();
  16571. this._renderPaintInOrder(ctx);
  16572. },
  16573. /**
  16574. * @private
  16575. * @param {CanvasRenderingContext2D} ctx Context to render on
  16576. */
  16577. _renderDashedStroke: function(ctx) {
  16578. var x = -this.width / 2,
  16579. y = -this.height / 2,
  16580. w = this.width,
  16581. h = this.height;
  16582. ctx.beginPath();
  16583. fabric.util.drawDashedLine(ctx, x, y, x + w, y, this.strokeDashArray);
  16584. fabric.util.drawDashedLine(ctx, x + w, y, x + w, y + h, this.strokeDashArray);
  16585. fabric.util.drawDashedLine(ctx, x + w, y + h, x, y + h, this.strokeDashArray);
  16586. fabric.util.drawDashedLine(ctx, x, y + h, x, y, this.strokeDashArray);
  16587. ctx.closePath();
  16588. },
  16589. /**
  16590. * Returns object representation of an instance
  16591. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16592. * @return {Object} object representation of an instance
  16593. */
  16594. toObject: function(propertiesToInclude) {
  16595. return this.callSuper('toObject', ['rx', 'ry'].concat(propertiesToInclude));
  16596. },
  16597. });
  16598. /**
  16599. * Returns {@link fabric.Rect} instance from an object representation
  16600. * @static
  16601. * @memberOf fabric.Rect
  16602. * @param {Object} object Object to create an instance from
  16603. * @param {Function} [callback] Callback to invoke when an fabric.Rect instance is created
  16604. */
  16605. fabric.Rect.fromObject = function(object, callback) {
  16606. return fabric.Object._fromObject('Rect', object, callback);
  16607. };
  16608. })(typeof exports !== 'undefined' ? exports : this);
  16609. (function(global) {
  16610. 'use strict';
  16611. var fabric = global.fabric || (global.fabric = { }),
  16612. extend = fabric.util.object.extend,
  16613. min = fabric.util.array.min,
  16614. max = fabric.util.array.max,
  16615. toFixed = fabric.util.toFixed;
  16616. if (fabric.Polyline) {
  16617. fabric.warn('fabric.Polyline is already defined');
  16618. return;
  16619. }
  16620. /**
  16621. * Polyline class
  16622. * @class fabric.Polyline
  16623. * @extends fabric.Object
  16624. * @see {@link fabric.Polyline#initialize} for constructor definition
  16625. */
  16626. fabric.Polyline = fabric.util.createClass(fabric.Object, /** @lends fabric.Polyline.prototype */ {
  16627. /**
  16628. * Type of an object
  16629. * @type String
  16630. * @default
  16631. */
  16632. type: 'polyline',
  16633. /**
  16634. * Points array
  16635. * @type Array
  16636. * @default
  16637. */
  16638. points: null,
  16639. cacheProperties: fabric.Object.prototype.cacheProperties.concat('points'),
  16640. /**
  16641. * Constructor
  16642. * @param {Array} points Array of points (where each point is an object with x and y)
  16643. * @param {Object} [options] Options object
  16644. * @return {fabric.Polyline} thisArg
  16645. * @example
  16646. * var poly = new fabric.Polyline([
  16647. * { x: 10, y: 10 },
  16648. * { x: 50, y: 30 },
  16649. * { x: 40, y: 70 },
  16650. * { x: 60, y: 50 },
  16651. * { x: 100, y: 150 },
  16652. * { x: 40, y: 100 }
  16653. * ], {
  16654. * stroke: 'red',
  16655. * left: 100,
  16656. * top: 100
  16657. * });
  16658. */
  16659. initialize: function(points, options) {
  16660. options = options || {};
  16661. this.points = points || [];
  16662. this.callSuper('initialize', options);
  16663. var calcDim = this._calcDimensions();
  16664. if (typeof options.left === 'undefined') {
  16665. this.left = calcDim.left;
  16666. }
  16667. if (typeof options.top === 'undefined') {
  16668. this.top = calcDim.top;
  16669. }
  16670. this.width = calcDim.width;
  16671. this.height = calcDim.height;
  16672. this.pathOffset = {
  16673. x: calcDim.left + this.width / 2,
  16674. y: calcDim.top + this.height / 2
  16675. };
  16676. },
  16677. /**
  16678. * Calculate the polygon min and max point from points array,
  16679. * returning an object with left, top, widht, height to measure the
  16680. * polygon size
  16681. * @return {Object} object.left X coordinate of the polygon leftmost point
  16682. * @return {Object} object.top Y coordinate of the polygon topmost point
  16683. * @return {Object} object.width distance between X coordinates of the polygon leftmost and rightmost point
  16684. * @return {Object} object.height distance between Y coordinates of the polygon topmost and bottommost point
  16685. * @private
  16686. */
  16687. _calcDimensions: function() {
  16688. var points = this.points,
  16689. minX = min(points, 'x') || 0,
  16690. minY = min(points, 'y') || 0,
  16691. maxX = max(points, 'x') || 0,
  16692. maxY = max(points, 'y') || 0,
  16693. width = (maxX - minX),
  16694. height = (maxY - minY);
  16695. return {
  16696. left: minX,
  16697. top: minY,
  16698. width: width,
  16699. height: height
  16700. };
  16701. },
  16702. /**
  16703. * Returns object representation of an instance
  16704. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  16705. * @return {Object} Object representation of an instance
  16706. */
  16707. toObject: function(propertiesToInclude) {
  16708. return extend(this.callSuper('toObject', propertiesToInclude), {
  16709. points: this.points.concat()
  16710. });
  16711. },
  16712. /**
  16713. * @private
  16714. * @param {CanvasRenderingContext2D} ctx Context to render on
  16715. */
  16716. commonRender: function(ctx) {
  16717. var point, len = this.points.length,
  16718. x = this.pathOffset.x,
  16719. y = this.pathOffset.y;
  16720. if (!len || isNaN(this.points[len - 1].y)) {
  16721. // do not draw if no points or odd points
  16722. // NaN comes from parseFloat of a empty string in parser
  16723. return false;
  16724. }
  16725. ctx.beginPath();
  16726. ctx.moveTo(this.points[0].x - x, this.points[0].y - y);
  16727. for (var i = 0; i < len; i++) {
  16728. point = this.points[i];
  16729. ctx.lineTo(point.x - x, point.y - y);
  16730. }
  16731. return true;
  16732. },
  16733. /**
  16734. * @private
  16735. * @param {CanvasRenderingContext2D} ctx Context to render on
  16736. */
  16737. _render: function(ctx) {
  16738. if (!this.commonRender(ctx)) {
  16739. return;
  16740. }
  16741. this._renderPaintInOrder(ctx);
  16742. },
  16743. /**
  16744. * @private
  16745. * @param {CanvasRenderingContext2D} ctx Context to render on
  16746. */
  16747. _renderDashedStroke: function(ctx) {
  16748. var p1, p2;
  16749. ctx.beginPath();
  16750. for (var i = 0, len = this.points.length; i < len; i++) {
  16751. p1 = this.points[i];
  16752. p2 = this.points[i + 1] || p1;
  16753. fabric.util.drawDashedLine(ctx, p1.x, p1.y, p2.x, p2.y, this.strokeDashArray);
  16754. }
  16755. },
  16756. /**
  16757. * Returns complexity of an instance
  16758. * @return {Number} complexity of this instance
  16759. */
  16760. complexity: function() {
  16761. return this.get('points').length;
  16762. }
  16763. });
  16764. /**
  16765. * Returns fabric.Polyline instance from an object representation
  16766. * @static
  16767. * @memberOf fabric.Polyline
  16768. * @param {Object} object Object to create an instance from
  16769. * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created
  16770. */
  16771. fabric.Polyline.fromObject = function(object, callback) {
  16772. return fabric.Object._fromObject('Polyline', object, callback, 'points');
  16773. };
  16774. })(typeof exports !== 'undefined' ? exports : this);
  16775. (function(global) {
  16776. 'use strict';
  16777. var fabric = global.fabric || (global.fabric = { }),
  16778. extend = fabric.util.object.extend;
  16779. if (fabric.Polygon) {
  16780. fabric.warn('fabric.Polygon is already defined');
  16781. return;
  16782. }
  16783. /**
  16784. * Polygon class
  16785. * @class fabric.Polygon
  16786. * @extends fabric.Polyline
  16787. * @see {@link fabric.Polygon#initialize} for constructor definition
  16788. */
  16789. fabric.Polygon = fabric.util.createClass(fabric.Polyline, /** @lends fabric.Polygon.prototype */ {
  16790. /**
  16791. * Type of an object
  16792. * @type String
  16793. * @default
  16794. */
  16795. type: 'polygon',
  16796. /**
  16797. * @private
  16798. * @param {CanvasRenderingContext2D} ctx Context to render on
  16799. */
  16800. _render: function(ctx) {
  16801. if (!this.commonRender(ctx)) {
  16802. return;
  16803. }
  16804. ctx.closePath();
  16805. this._renderPaintInOrder(ctx);
  16806. },
  16807. /**
  16808. * @private
  16809. * @param {CanvasRenderingContext2D} ctx Context to render on
  16810. */
  16811. _renderDashedStroke: function(ctx) {
  16812. this.callSuper('_renderDashedStroke', ctx);
  16813. ctx.closePath();
  16814. },
  16815. });
  16816. /**
  16817. * Returns fabric.Polygon instance from an object representation
  16818. * @static
  16819. * @memberOf fabric.Polygon
  16820. * @param {Object} object Object to create an instance from
  16821. * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created
  16822. */
  16823. fabric.Polygon.fromObject = function(object, callback) {
  16824. return fabric.Object._fromObject('Polygon', object, callback, 'points');
  16825. };
  16826. })(typeof exports !== 'undefined' ? exports : this);
  16827. (function(global) {
  16828. 'use strict';
  16829. var fabric = global.fabric || (global.fabric = { }),
  16830. min = fabric.util.array.min,
  16831. max = fabric.util.array.max,
  16832. extend = fabric.util.object.extend,
  16833. _toString = Object.prototype.toString,
  16834. drawArc = fabric.util.drawArc,
  16835. commandLengths = {
  16836. m: 2,
  16837. l: 2,
  16838. h: 1,
  16839. v: 1,
  16840. c: 6,
  16841. s: 4,
  16842. q: 4,
  16843. t: 2,
  16844. a: 7
  16845. },
  16846. repeatedCommands = {
  16847. m: 'l',
  16848. M: 'L'
  16849. };
  16850. if (fabric.Path) {
  16851. fabric.warn('fabric.Path is already defined');
  16852. return;
  16853. }
  16854. /**
  16855. * Path class
  16856. * @class fabric.Path
  16857. * @extends fabric.Object
  16858. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#path_and_pathgroup}
  16859. * @see {@link fabric.Path#initialize} for constructor definition
  16860. */
  16861. fabric.Path = fabric.util.createClass(fabric.Object, /** @lends fabric.Path.prototype */ {
  16862. /**
  16863. * Type of an object
  16864. * @type String
  16865. * @default
  16866. */
  16867. type: 'path',
  16868. /**
  16869. * Array of path points
  16870. * @type Array
  16871. * @default
  16872. */
  16873. path: null,
  16874. cacheProperties: fabric.Object.prototype.cacheProperties.concat('path', 'fillRule'),
  16875. stateProperties: fabric.Object.prototype.stateProperties.concat('path'),
  16876. /**
  16877. * Constructor
  16878. * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens)
  16879. * @param {Object} [options] Options object
  16880. * @return {fabric.Path} thisArg
  16881. */
  16882. initialize: function(path, options) {
  16883. options = options || { };
  16884. this.callSuper('initialize', options);
  16885. if (!path) {
  16886. path = [];
  16887. }
  16888. var fromArray = _toString.call(path) === '[object Array]';
  16889. this.path = fromArray
  16890. ? path
  16891. // one of commands (m,M,l,L,q,Q,c,C,etc.) followed by non-command characters (i.e. command values)
  16892. : path.match && path.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);
  16893. if (!this.path) {
  16894. return;
  16895. }
  16896. if (!fromArray) {
  16897. this.path = this._parsePath();
  16898. }
  16899. this._setPositionDimensions(options);
  16900. },
  16901. /**
  16902. * @private
  16903. * @param {Object} options Options object
  16904. */
  16905. _setPositionDimensions: function(options) {
  16906. var calcDim = this._parseDimensions();
  16907. this.width = calcDim.width;
  16908. this.height = calcDim.height;
  16909. if (typeof options.left === 'undefined') {
  16910. this.left = calcDim.left;
  16911. }
  16912. if (typeof options.top === 'undefined') {
  16913. this.top = calcDim.top;
  16914. }
  16915. this.pathOffset = this.pathOffset || {
  16916. x: calcDim.left + this.width / 2,
  16917. y: calcDim.top + this.height / 2
  16918. };
  16919. },
  16920. /**
  16921. * @private
  16922. * @param {CanvasRenderingContext2D} ctx context to render path on
  16923. */
  16924. _renderPathCommands: function(ctx) {
  16925. var current, // current instruction
  16926. previous = null,
  16927. subpathStartX = 0,
  16928. subpathStartY = 0,
  16929. x = 0, // current x
  16930. y = 0, // current y
  16931. controlX = 0, // current control point x
  16932. controlY = 0, // current control point y
  16933. tempX,
  16934. tempY,
  16935. l = -this.pathOffset.x,
  16936. t = -this.pathOffset.y;
  16937. ctx.beginPath();
  16938. for (var i = 0, len = this.path.length; i < len; ++i) {
  16939. current = this.path[i];
  16940. switch (current[0]) { // first letter
  16941. case 'l': // lineto, relative
  16942. x += current[1];
  16943. y += current[2];
  16944. ctx.lineTo(x + l, y + t);
  16945. break;
  16946. case 'L': // lineto, absolute
  16947. x = current[1];
  16948. y = current[2];
  16949. ctx.lineTo(x + l, y + t);
  16950. break;
  16951. case 'h': // horizontal lineto, relative
  16952. x += current[1];
  16953. ctx.lineTo(x + l, y + t);
  16954. break;
  16955. case 'H': // horizontal lineto, absolute
  16956. x = current[1];
  16957. ctx.lineTo(x + l, y + t);
  16958. break;
  16959. case 'v': // vertical lineto, relative
  16960. y += current[1];
  16961. ctx.lineTo(x + l, y + t);
  16962. break;
  16963. case 'V': // verical lineto, absolute
  16964. y = current[1];
  16965. ctx.lineTo(x + l, y + t);
  16966. break;
  16967. case 'm': // moveTo, relative
  16968. x += current[1];
  16969. y += current[2];
  16970. subpathStartX = x;
  16971. subpathStartY = y;
  16972. ctx.moveTo(x + l, y + t);
  16973. break;
  16974. case 'M': // moveTo, absolute
  16975. x = current[1];
  16976. y = current[2];
  16977. subpathStartX = x;
  16978. subpathStartY = y;
  16979. ctx.moveTo(x + l, y + t);
  16980. break;
  16981. case 'c': // bezierCurveTo, relative
  16982. tempX = x + current[5];
  16983. tempY = y + current[6];
  16984. controlX = x + current[3];
  16985. controlY = y + current[4];
  16986. ctx.bezierCurveTo(
  16987. x + current[1] + l, // x1
  16988. y + current[2] + t, // y1
  16989. controlX + l, // x2
  16990. controlY + t, // y2
  16991. tempX + l,
  16992. tempY + t
  16993. );
  16994. x = tempX;
  16995. y = tempY;
  16996. break;
  16997. case 'C': // bezierCurveTo, absolute
  16998. x = current[5];
  16999. y = current[6];
  17000. controlX = current[3];
  17001. controlY = current[4];
  17002. ctx.bezierCurveTo(
  17003. current[1] + l,
  17004. current[2] + t,
  17005. controlX + l,
  17006. controlY + t,
  17007. x + l,
  17008. y + t
  17009. );
  17010. break;
  17011. case 's': // shorthand cubic bezierCurveTo, relative
  17012. // transform to absolute x,y
  17013. tempX = x + current[3];
  17014. tempY = y + current[4];
  17015. if (previous[0].match(/[CcSs]/) === null) {
  17016. // If there is no previous command or if the previous command was not a C, c, S, or s,
  17017. // the control point is coincident with the current point
  17018. controlX = x;
  17019. controlY = y;
  17020. }
  17021. else {
  17022. // calculate reflection of previous control points
  17023. controlX = 2 * x - controlX;
  17024. controlY = 2 * y - controlY;
  17025. }
  17026. ctx.bezierCurveTo(
  17027. controlX + l,
  17028. controlY + t,
  17029. x + current[1] + l,
  17030. y + current[2] + t,
  17031. tempX + l,
  17032. tempY + t
  17033. );
  17034. // set control point to 2nd one of this command
  17035. // "... the first control point is assumed to be
  17036. // the reflection of the second control point on
  17037. // the previous command relative to the current point."
  17038. controlX = x + current[1];
  17039. controlY = y + current[2];
  17040. x = tempX;
  17041. y = tempY;
  17042. break;
  17043. case 'S': // shorthand cubic bezierCurveTo, absolute
  17044. tempX = current[3];
  17045. tempY = current[4];
  17046. if (previous[0].match(/[CcSs]/) === null) {
  17047. // If there is no previous command or if the previous command was not a C, c, S, or s,
  17048. // the control point is coincident with the current point
  17049. controlX = x;
  17050. controlY = y;
  17051. }
  17052. else {
  17053. // calculate reflection of previous control points
  17054. controlX = 2 * x - controlX;
  17055. controlY = 2 * y - controlY;
  17056. }
  17057. ctx.bezierCurveTo(
  17058. controlX + l,
  17059. controlY + t,
  17060. current[1] + l,
  17061. current[2] + t,
  17062. tempX + l,
  17063. tempY + t
  17064. );
  17065. x = tempX;
  17066. y = tempY;
  17067. // set control point to 2nd one of this command
  17068. // "... the first control point is assumed to be
  17069. // the reflection of the second control point on
  17070. // the previous command relative to the current point."
  17071. controlX = current[1];
  17072. controlY = current[2];
  17073. break;
  17074. case 'q': // quadraticCurveTo, relative
  17075. // transform to absolute x,y
  17076. tempX = x + current[3];
  17077. tempY = y + current[4];
  17078. controlX = x + current[1];
  17079. controlY = y + current[2];
  17080. ctx.quadraticCurveTo(
  17081. controlX + l,
  17082. controlY + t,
  17083. tempX + l,
  17084. tempY + t
  17085. );
  17086. x = tempX;
  17087. y = tempY;
  17088. break;
  17089. case 'Q': // quadraticCurveTo, absolute
  17090. tempX = current[3];
  17091. tempY = current[4];
  17092. ctx.quadraticCurveTo(
  17093. current[1] + l,
  17094. current[2] + t,
  17095. tempX + l,
  17096. tempY + t
  17097. );
  17098. x = tempX;
  17099. y = tempY;
  17100. controlX = current[1];
  17101. controlY = current[2];
  17102. break;
  17103. case 't': // shorthand quadraticCurveTo, relative
  17104. // transform to absolute x,y
  17105. tempX = x + current[1];
  17106. tempY = y + current[2];
  17107. if (previous[0].match(/[QqTt]/) === null) {
  17108. // If there is no previous command or if the previous command was not a Q, q, T or t,
  17109. // assume the control point is coincident with the current point
  17110. controlX = x;
  17111. controlY = y;
  17112. }
  17113. else {
  17114. // calculate reflection of previous control point
  17115. controlX = 2 * x - controlX;
  17116. controlY = 2 * y - controlY;
  17117. }
  17118. ctx.quadraticCurveTo(
  17119. controlX + l,
  17120. controlY + t,
  17121. tempX + l,
  17122. tempY + t
  17123. );
  17124. x = tempX;
  17125. y = tempY;
  17126. break;
  17127. case 'T':
  17128. tempX = current[1];
  17129. tempY = current[2];
  17130. if (previous[0].match(/[QqTt]/) === null) {
  17131. // If there is no previous command or if the previous command was not a Q, q, T or t,
  17132. // assume the control point is coincident with the current point
  17133. controlX = x;
  17134. controlY = y;
  17135. }
  17136. else {
  17137. // calculate reflection of previous control point
  17138. controlX = 2 * x - controlX;
  17139. controlY = 2 * y - controlY;
  17140. }
  17141. ctx.quadraticCurveTo(
  17142. controlX + l,
  17143. controlY + t,
  17144. tempX + l,
  17145. tempY + t
  17146. );
  17147. x = tempX;
  17148. y = tempY;
  17149. break;
  17150. case 'a':
  17151. // TODO: optimize this
  17152. drawArc(ctx, x + l, y + t, [
  17153. current[1],
  17154. current[2],
  17155. current[3],
  17156. current[4],
  17157. current[5],
  17158. current[6] + x + l,
  17159. current[7] + y + t
  17160. ]);
  17161. x += current[6];
  17162. y += current[7];
  17163. break;
  17164. case 'A':
  17165. // TODO: optimize this
  17166. drawArc(ctx, x + l, y + t, [
  17167. current[1],
  17168. current[2],
  17169. current[3],
  17170. current[4],
  17171. current[5],
  17172. current[6] + l,
  17173. current[7] + t
  17174. ]);
  17175. x = current[6];
  17176. y = current[7];
  17177. break;
  17178. case 'z':
  17179. case 'Z':
  17180. x = subpathStartX;
  17181. y = subpathStartY;
  17182. ctx.closePath();
  17183. break;
  17184. }
  17185. previous = current;
  17186. }
  17187. },
  17188. /**
  17189. * @private
  17190. * @param {CanvasRenderingContext2D} ctx context to render path on
  17191. */
  17192. _render: function(ctx) {
  17193. this._renderPathCommands(ctx);
  17194. this._renderPaintInOrder(ctx);
  17195. },
  17196. /**
  17197. * Returns string representation of an instance
  17198. * @return {String} string representation of an instance
  17199. */
  17200. toString: function() {
  17201. return '#<fabric.Path (' + this.complexity() +
  17202. '): { "top": ' + this.top + ', "left": ' + this.left + ' }>';
  17203. },
  17204. /**
  17205. * Returns object representation of an instance
  17206. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17207. * @return {Object} object representation of an instance
  17208. */
  17209. toObject: function(propertiesToInclude) {
  17210. var o = extend(this.callSuper('toObject', propertiesToInclude), {
  17211. path: this.path.map(function(item) { return item.slice(); }),
  17212. top: this.top,
  17213. left: this.left,
  17214. });
  17215. return o;
  17216. },
  17217. /**
  17218. * Returns dataless object representation of an instance
  17219. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17220. * @return {Object} object representation of an instance
  17221. */
  17222. toDatalessObject: function(propertiesToInclude) {
  17223. var o = this.toObject(['sourcePath'].concat(propertiesToInclude));
  17224. if (o.sourcePath) {
  17225. delete o.path;
  17226. }
  17227. return o;
  17228. },
  17229. /**
  17230. * Returns number representation of an instance complexity
  17231. * @return {Number} complexity of this instance
  17232. */
  17233. complexity: function() {
  17234. return this.path.length;
  17235. },
  17236. /**
  17237. * @private
  17238. */
  17239. _parsePath: function() {
  17240. var result = [],
  17241. coords = [],
  17242. currentPath,
  17243. parsed,
  17244. re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/ig,
  17245. match,
  17246. coordsStr;
  17247. for (var i = 0, coordsParsed, len = this.path.length; i < len; i++) {
  17248. currentPath = this.path[i];
  17249. coordsStr = currentPath.slice(1).trim();
  17250. coords.length = 0;
  17251. while ((match = re.exec(coordsStr))) {
  17252. coords.push(match[0]);
  17253. }
  17254. coordsParsed = [currentPath.charAt(0)];
  17255. for (var j = 0, jlen = coords.length; j < jlen; j++) {
  17256. parsed = parseFloat(coords[j]);
  17257. if (!isNaN(parsed)) {
  17258. coordsParsed.push(parsed);
  17259. }
  17260. }
  17261. var command = coordsParsed[0],
  17262. commandLength = commandLengths[command.toLowerCase()],
  17263. repeatedCommand = repeatedCommands[command] || command;
  17264. if (coordsParsed.length - 1 > commandLength) {
  17265. for (var k = 1, klen = coordsParsed.length; k < klen; k += commandLength) {
  17266. result.push([command].concat(coordsParsed.slice(k, k + commandLength)));
  17267. command = repeatedCommand;
  17268. }
  17269. }
  17270. else {
  17271. result.push(coordsParsed);
  17272. }
  17273. }
  17274. return result;
  17275. },
  17276. /**
  17277. * @private
  17278. */
  17279. _parseDimensions: function() {
  17280. var aX = [],
  17281. aY = [],
  17282. current, // current instruction
  17283. previous = null,
  17284. subpathStartX = 0,
  17285. subpathStartY = 0,
  17286. x = 0, // current x
  17287. y = 0, // current y
  17288. controlX = 0, // current control point x
  17289. controlY = 0, // current control point y
  17290. tempX,
  17291. tempY,
  17292. bounds;
  17293. for (var i = 0, len = this.path.length; i < len; ++i) {
  17294. current = this.path[i];
  17295. switch (current[0]) { // first letter
  17296. case 'l': // lineto, relative
  17297. x += current[1];
  17298. y += current[2];
  17299. bounds = [];
  17300. break;
  17301. case 'L': // lineto, absolute
  17302. x = current[1];
  17303. y = current[2];
  17304. bounds = [];
  17305. break;
  17306. case 'h': // horizontal lineto, relative
  17307. x += current[1];
  17308. bounds = [];
  17309. break;
  17310. case 'H': // horizontal lineto, absolute
  17311. x = current[1];
  17312. bounds = [];
  17313. break;
  17314. case 'v': // vertical lineto, relative
  17315. y += current[1];
  17316. bounds = [];
  17317. break;
  17318. case 'V': // verical lineto, absolute
  17319. y = current[1];
  17320. bounds = [];
  17321. break;
  17322. case 'm': // moveTo, relative
  17323. x += current[1];
  17324. y += current[2];
  17325. subpathStartX = x;
  17326. subpathStartY = y;
  17327. bounds = [];
  17328. break;
  17329. case 'M': // moveTo, absolute
  17330. x = current[1];
  17331. y = current[2];
  17332. subpathStartX = x;
  17333. subpathStartY = y;
  17334. bounds = [];
  17335. break;
  17336. case 'c': // bezierCurveTo, relative
  17337. tempX = x + current[5];
  17338. tempY = y + current[6];
  17339. controlX = x + current[3];
  17340. controlY = y + current[4];
  17341. bounds = fabric.util.getBoundsOfCurve(x, y,
  17342. x + current[1], // x1
  17343. y + current[2], // y1
  17344. controlX, // x2
  17345. controlY, // y2
  17346. tempX,
  17347. tempY
  17348. );
  17349. x = tempX;
  17350. y = tempY;
  17351. break;
  17352. case 'C': // bezierCurveTo, absolute
  17353. controlX = current[3];
  17354. controlY = current[4];
  17355. bounds = fabric.util.getBoundsOfCurve(x, y,
  17356. current[1],
  17357. current[2],
  17358. controlX,
  17359. controlY,
  17360. current[5],
  17361. current[6]
  17362. );
  17363. x = current[5];
  17364. y = current[6];
  17365. break;
  17366. case 's': // shorthand cubic bezierCurveTo, relative
  17367. // transform to absolute x,y
  17368. tempX = x + current[3];
  17369. tempY = y + current[4];
  17370. if (previous[0].match(/[CcSs]/) === null) {
  17371. // If there is no previous command or if the previous command was not a C, c, S, or s,
  17372. // the control point is coincident with the current point
  17373. controlX = x;
  17374. controlY = y;
  17375. }
  17376. else {
  17377. // calculate reflection of previous control points
  17378. controlX = 2 * x - controlX;
  17379. controlY = 2 * y - controlY;
  17380. }
  17381. bounds = fabric.util.getBoundsOfCurve(x, y,
  17382. controlX,
  17383. controlY,
  17384. x + current[1],
  17385. y + current[2],
  17386. tempX,
  17387. tempY
  17388. );
  17389. // set control point to 2nd one of this command
  17390. // "... the first control point is assumed to be
  17391. // the reflection of the second control point on
  17392. // the previous command relative to the current point."
  17393. controlX = x + current[1];
  17394. controlY = y + current[2];
  17395. x = tempX;
  17396. y = tempY;
  17397. break;
  17398. case 'S': // shorthand cubic bezierCurveTo, absolute
  17399. tempX = current[3];
  17400. tempY = current[4];
  17401. if (previous[0].match(/[CcSs]/) === null) {
  17402. // If there is no previous command or if the previous command was not a C, c, S, or s,
  17403. // the control point is coincident with the current point
  17404. controlX = x;
  17405. controlY = y;
  17406. }
  17407. else {
  17408. // calculate reflection of previous control points
  17409. controlX = 2 * x - controlX;
  17410. controlY = 2 * y - controlY;
  17411. }
  17412. bounds = fabric.util.getBoundsOfCurve(x, y,
  17413. controlX,
  17414. controlY,
  17415. current[1],
  17416. current[2],
  17417. tempX,
  17418. tempY
  17419. );
  17420. x = tempX;
  17421. y = tempY;
  17422. // set control point to 2nd one of this command
  17423. // "... the first control point is assumed to be
  17424. // the reflection of the second control point on
  17425. // the previous command relative to the current point."
  17426. controlX = current[1];
  17427. controlY = current[2];
  17428. break;
  17429. case 'q': // quadraticCurveTo, relative
  17430. // transform to absolute x,y
  17431. tempX = x + current[3];
  17432. tempY = y + current[4];
  17433. controlX = x + current[1];
  17434. controlY = y + current[2];
  17435. bounds = fabric.util.getBoundsOfCurve(x, y,
  17436. controlX,
  17437. controlY,
  17438. controlX,
  17439. controlY,
  17440. tempX,
  17441. tempY
  17442. );
  17443. x = tempX;
  17444. y = tempY;
  17445. break;
  17446. case 'Q': // quadraticCurveTo, absolute
  17447. controlX = current[1];
  17448. controlY = current[2];
  17449. bounds = fabric.util.getBoundsOfCurve(x, y,
  17450. controlX,
  17451. controlY,
  17452. controlX,
  17453. controlY,
  17454. current[3],
  17455. current[4]
  17456. );
  17457. x = current[3];
  17458. y = current[4];
  17459. break;
  17460. case 't': // shorthand quadraticCurveTo, relative
  17461. // transform to absolute x,y
  17462. tempX = x + current[1];
  17463. tempY = y + current[2];
  17464. if (previous[0].match(/[QqTt]/) === null) {
  17465. // If there is no previous command or if the previous command was not a Q, q, T or t,
  17466. // assume the control point is coincident with the current point
  17467. controlX = x;
  17468. controlY = y;
  17469. }
  17470. else {
  17471. // calculate reflection of previous control point
  17472. controlX = 2 * x - controlX;
  17473. controlY = 2 * y - controlY;
  17474. }
  17475. bounds = fabric.util.getBoundsOfCurve(x, y,
  17476. controlX,
  17477. controlY,
  17478. controlX,
  17479. controlY,
  17480. tempX,
  17481. tempY
  17482. );
  17483. x = tempX;
  17484. y = tempY;
  17485. break;
  17486. case 'T':
  17487. tempX = current[1];
  17488. tempY = current[2];
  17489. if (previous[0].match(/[QqTt]/) === null) {
  17490. // If there is no previous command or if the previous command was not a Q, q, T or t,
  17491. // assume the control point is coincident with the current point
  17492. controlX = x;
  17493. controlY = y;
  17494. }
  17495. else {
  17496. // calculate reflection of previous control point
  17497. controlX = 2 * x - controlX;
  17498. controlY = 2 * y - controlY;
  17499. }
  17500. bounds = fabric.util.getBoundsOfCurve(x, y,
  17501. controlX,
  17502. controlY,
  17503. controlX,
  17504. controlY,
  17505. tempX,
  17506. tempY
  17507. );
  17508. x = tempX;
  17509. y = tempY;
  17510. break;
  17511. case 'a':
  17512. // TODO: optimize this
  17513. bounds = fabric.util.getBoundsOfArc(x, y,
  17514. current[1],
  17515. current[2],
  17516. current[3],
  17517. current[4],
  17518. current[5],
  17519. current[6] + x,
  17520. current[7] + y
  17521. );
  17522. x += current[6];
  17523. y += current[7];
  17524. break;
  17525. case 'A':
  17526. // TODO: optimize this
  17527. bounds = fabric.util.getBoundsOfArc(x, y,
  17528. current[1],
  17529. current[2],
  17530. current[3],
  17531. current[4],
  17532. current[5],
  17533. current[6],
  17534. current[7]
  17535. );
  17536. x = current[6];
  17537. y = current[7];
  17538. break;
  17539. case 'z':
  17540. case 'Z':
  17541. x = subpathStartX;
  17542. y = subpathStartY;
  17543. break;
  17544. }
  17545. previous = current;
  17546. bounds.forEach(function (point) {
  17547. aX.push(point.x);
  17548. aY.push(point.y);
  17549. });
  17550. aX.push(x);
  17551. aY.push(y);
  17552. }
  17553. var minX = min(aX) || 0,
  17554. minY = min(aY) || 0,
  17555. maxX = max(aX) || 0,
  17556. maxY = max(aY) || 0,
  17557. deltaX = maxX - minX,
  17558. deltaY = maxY - minY,
  17559. o = {
  17560. left: minX,
  17561. top: minY,
  17562. width: deltaX,
  17563. height: deltaY
  17564. };
  17565. return o;
  17566. }
  17567. });
  17568. /**
  17569. * Creates an instance of fabric.Path from an object
  17570. * @static
  17571. * @memberOf fabric.Path
  17572. * @param {Object} object
  17573. * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created
  17574. */
  17575. fabric.Path.fromObject = function(object, callback) {
  17576. if (typeof object.sourcePath === 'string') {
  17577. var pathUrl = object.sourcePath;
  17578. fabric.loadSVGFromURL(pathUrl, function (elements) {
  17579. var path = elements[0];
  17580. path.setOptions(object);
  17581. callback && callback(path);
  17582. });
  17583. }
  17584. else {
  17585. fabric.Object._fromObject('Path', object, callback, 'path');
  17586. }
  17587. };
  17588. })(typeof exports !== 'undefined' ? exports : this);
  17589. (function(global) {
  17590. 'use strict';
  17591. var fabric = global.fabric || (global.fabric = { }),
  17592. extend = fabric.util.object.extend,
  17593. min = fabric.util.array.min,
  17594. max = fabric.util.array.max;
  17595. if (fabric.Group) {
  17596. return;
  17597. }
  17598. /**
  17599. * Group class
  17600. * @class fabric.Group
  17601. * @extends fabric.Object
  17602. * @mixes fabric.Collection
  17603. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#groups}
  17604. * @see {@link fabric.Group#initialize} for constructor definition
  17605. */
  17606. fabric.Group = fabric.util.createClass(fabric.Object, fabric.Collection, /** @lends fabric.Group.prototype */ {
  17607. /**
  17608. * Type of an object
  17609. * @type String
  17610. * @default
  17611. */
  17612. type: 'group',
  17613. /**
  17614. * Width of stroke
  17615. * @type Number
  17616. * @default
  17617. */
  17618. strokeWidth: 0,
  17619. /**
  17620. * Indicates if click events should also check for subtargets
  17621. * @type Boolean
  17622. * @default
  17623. */
  17624. subTargetCheck: false,
  17625. /**
  17626. * Groups are container, do not render anything on theyr own, ence no cache properties
  17627. * @type Array
  17628. * @default
  17629. */
  17630. cacheProperties: [],
  17631. /**
  17632. * setOnGroup is a method used for TextBox that is no more used since 2.0.0 The behavior is still
  17633. * available setting this boolean to true.
  17634. * @type Boolean
  17635. * @since 2.0.0
  17636. * @default
  17637. */
  17638. useSetOnGroup: false,
  17639. /**
  17640. * Constructor
  17641. * @param {Object} objects Group objects
  17642. * @param {Object} [options] Options object
  17643. * @param {Boolean} [isAlreadyGrouped] if true, objects have been grouped already.
  17644. * @return {Object} thisArg
  17645. */
  17646. initialize: function(objects, options, isAlreadyGrouped) {
  17647. options = options || {};
  17648. this._objects = [];
  17649. // if objects enclosed in a group have been grouped already,
  17650. // we cannot change properties of objects.
  17651. // Thus we need to set options to group without objects,
  17652. isAlreadyGrouped && this.callSuper('initialize', options);
  17653. this._objects = objects || [];
  17654. for (var i = this._objects.length; i--; ) {
  17655. this._objects[i].group = this;
  17656. }
  17657. if (options.originX) {
  17658. this.originX = options.originX;
  17659. }
  17660. if (options.originY) {
  17661. this.originY = options.originY;
  17662. }
  17663. if (!isAlreadyGrouped) {
  17664. var center = options && options.centerPoint;
  17665. // if coming from svg i do not want to calc bounds.
  17666. // i assume width and height are passed along options
  17667. center || this._calcBounds();
  17668. this._updateObjectsCoords(center);
  17669. delete options.centerPoint;
  17670. this.callSuper('initialize', options);
  17671. }
  17672. else {
  17673. this._updateObjectsACoords();
  17674. }
  17675. this.setCoords();
  17676. },
  17677. /**
  17678. * @private
  17679. * @param {Boolean} [skipCoordsChange] if true, coordinates of objects enclosed in a group do not change
  17680. */
  17681. _updateObjectsACoords: function() {
  17682. var ignoreZoom = true, skipAbsolute = true;
  17683. for (var i = this._objects.length; i--; ){
  17684. this._objects[i].setCoords(ignoreZoom, skipAbsolute);
  17685. }
  17686. },
  17687. /**
  17688. * @private
  17689. * @param {Boolean} [skipCoordsChange] if true, coordinates of objects enclosed in a group do not change
  17690. */
  17691. _updateObjectsCoords: function(center) {
  17692. var center = center || this.getCenterPoint();
  17693. for (var i = this._objects.length; i--; ){
  17694. this._updateObjectCoords(this._objects[i], center);
  17695. }
  17696. },
  17697. /**
  17698. * @private
  17699. * @param {Object} object
  17700. * @param {fabric.Point} center, current center of group.
  17701. */
  17702. _updateObjectCoords: function(object, center) {
  17703. var objectLeft = object.left,
  17704. objectTop = object.top,
  17705. ignoreZoom = true, skipAbsolute = true;
  17706. object.set({
  17707. left: objectLeft - center.x,
  17708. top: objectTop - center.y
  17709. });
  17710. object.group = this;
  17711. object.setCoords(ignoreZoom, skipAbsolute);
  17712. },
  17713. /**
  17714. * Returns string represenation of a group
  17715. * @return {String}
  17716. */
  17717. toString: function() {
  17718. return '#<fabric.Group: (' + this.complexity() + ')>';
  17719. },
  17720. /**
  17721. * Adds an object to a group; Then recalculates group's dimension, position.
  17722. * @param {Object} object
  17723. * @return {fabric.Group} thisArg
  17724. * @chainable
  17725. */
  17726. addWithUpdate: function(object) {
  17727. this._restoreObjectsState();
  17728. fabric.util.resetObjectTransform(this);
  17729. if (object) {
  17730. this._objects.push(object);
  17731. object.group = this;
  17732. object._set('canvas', this.canvas);
  17733. }
  17734. this._calcBounds();
  17735. this._updateObjectsCoords();
  17736. this.setCoords();
  17737. this.dirty = true;
  17738. return this;
  17739. },
  17740. /**
  17741. * Removes an object from a group; Then recalculates group's dimension, position.
  17742. * @param {Object} object
  17743. * @return {fabric.Group} thisArg
  17744. * @chainable
  17745. */
  17746. removeWithUpdate: function(object) {
  17747. this._restoreObjectsState();
  17748. fabric.util.resetObjectTransform(this);
  17749. this.remove(object);
  17750. this._calcBounds();
  17751. this._updateObjectsCoords();
  17752. this.setCoords();
  17753. this.dirty = true;
  17754. return this;
  17755. },
  17756. /**
  17757. * @private
  17758. */
  17759. _onObjectAdded: function(object) {
  17760. this.dirty = true;
  17761. object.group = this;
  17762. object._set('canvas', this.canvas);
  17763. },
  17764. /**
  17765. * @private
  17766. */
  17767. _onObjectRemoved: function(object) {
  17768. this.dirty = true;
  17769. delete object.group;
  17770. },
  17771. /**
  17772. * @private
  17773. */
  17774. _set: function(key, value) {
  17775. var i = this._objects.length;
  17776. if (this.useSetOnGroup) {
  17777. while (i--) {
  17778. this._objects[i].setOnGroup(key, value);
  17779. }
  17780. }
  17781. if (key === 'canvas') {
  17782. i = this._objects.length;
  17783. while (i--) {
  17784. this._objects[i]._set(key, value);
  17785. }
  17786. }
  17787. this.callSuper('_set', key, value);
  17788. },
  17789. /**
  17790. * Returns object representation of an instance
  17791. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17792. * @return {Object} object representation of an instance
  17793. */
  17794. toObject: function(propertiesToInclude) {
  17795. var objsToObject = this.getObjects().map(function(obj) {
  17796. var originalDefaults = obj.includeDefaultValues;
  17797. obj.includeDefaultValues = obj.group.includeDefaultValues;
  17798. var _obj = obj.toObject(propertiesToInclude);
  17799. obj.includeDefaultValues = originalDefaults;
  17800. return _obj;
  17801. });
  17802. return extend(this.callSuper('toObject', propertiesToInclude), {
  17803. objects: objsToObject
  17804. });
  17805. },
  17806. /**
  17807. * Returns object representation of an instance, in dataless mode.
  17808. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17809. * @return {Object} object representation of an instance
  17810. */
  17811. toDatalessObject: function(propertiesToInclude) {
  17812. var objsToObject, sourcePath = this.sourcePath;
  17813. if (sourcePath) {
  17814. objsToObject = sourcePath;
  17815. }
  17816. else {
  17817. objsToObject = this.getObjects().map(function(obj) {
  17818. var originalDefaults = obj.includeDefaultValues;
  17819. obj.includeDefaultValues = obj.group.includeDefaultValues;
  17820. var _obj = obj.toDatalessObject(propertiesToInclude);
  17821. obj.includeDefaultValues = originalDefaults;
  17822. return _obj;
  17823. });
  17824. }
  17825. return extend(this.callSuper('toDatalessObject', propertiesToInclude), {
  17826. objects: objsToObject
  17827. });
  17828. },
  17829. /**
  17830. * Renders instance on a given context
  17831. * @param {CanvasRenderingContext2D} ctx context to render instance on
  17832. */
  17833. render: function(ctx) {
  17834. this._transformDone = true;
  17835. this.callSuper('render', ctx);
  17836. this._transformDone = false;
  17837. },
  17838. /**
  17839. * Decide if the object should cache or not. Create its own cache level
  17840. * objectCaching is a global flag, wins over everything
  17841. * needsItsOwnCache should be used when the object drawing method requires
  17842. * a cache step. None of the fabric classes requires it.
  17843. * Generally you do not cache objects in groups because the group outside is cached.
  17844. * @return {Boolean}
  17845. */
  17846. shouldCache: function() {
  17847. var ownCache = this.objectCaching && (!this.group || this.needsItsOwnCache() || !this.group.isOnACache());
  17848. this.ownCaching = ownCache;
  17849. if (ownCache) {
  17850. for (var i = 0, len = this._objects.length; i < len; i++) {
  17851. if (this._objects[i].willDrawShadow()) {
  17852. this.ownCaching = false;
  17853. return false;
  17854. }
  17855. }
  17856. }
  17857. return ownCache;
  17858. },
  17859. /**
  17860. * Check if this object or a child object will cast a shadow
  17861. * @return {Boolean}
  17862. */
  17863. willDrawShadow: function() {
  17864. if (this.shadow) {
  17865. return this.callSuper('willDrawShadow');
  17866. }
  17867. for (var i = 0, len = this._objects.length; i < len; i++) {
  17868. if (this._objects[i].willDrawShadow()) {
  17869. return true;
  17870. }
  17871. }
  17872. return false;
  17873. },
  17874. /**
  17875. * Check if this group or its parent group are caching, recursively up
  17876. * @return {Boolean}
  17877. */
  17878. isOnACache: function() {
  17879. return this.ownCaching || (this.group && this.group.isOnACache());
  17880. },
  17881. /**
  17882. * Execute the drawing operation for an object on a specified context
  17883. * @param {CanvasRenderingContext2D} ctx Context to render on
  17884. */
  17885. drawObject: function(ctx) {
  17886. var path = this.clipPath;
  17887. for (var i = 0, len = this._objects.length; i < len; i++) {
  17888. this._objects[i].render(ctx);
  17889. }
  17890. if (path) {
  17891. // needed to setup a couple of variables
  17892. path.shouldCache();
  17893. path._transformDone = true;
  17894. path.renderCache(this, true);
  17895. this.drawClipPathOnCache(ctx);
  17896. }
  17897. },
  17898. /**
  17899. * Check if cache is dirty
  17900. */
  17901. isCacheDirty: function(skipCanvas, parentObject) {
  17902. if (this.callSuper('isCacheDirty', skipCanvas, parentObject)) {
  17903. return true;
  17904. }
  17905. if (!this.statefullCache) {
  17906. return false;
  17907. }
  17908. for (var i = 0, len = this._objects.length; i < len; i++) {
  17909. if (this._objects[i].isCacheDirty(true, parentObject)) {
  17910. if (this._cacheCanvas) {
  17911. // if this group has not a cache canvas there is nothing to clean
  17912. var x = this.cacheWidth / this.zoomX, y = this.cacheHeight / this.zoomY;
  17913. this._cacheContext.clearRect(-x / 2, -y / 2, x, y);
  17914. }
  17915. return true;
  17916. }
  17917. }
  17918. return false;
  17919. },
  17920. /**
  17921. * Retores original state of each of group objects (original state is that which was before group was created).
  17922. * @private
  17923. * @return {fabric.Group} thisArg
  17924. * @chainable
  17925. */
  17926. _restoreObjectsState: function() {
  17927. this._objects.forEach(this._restoreObjectState, this);
  17928. return this;
  17929. },
  17930. /**
  17931. * Realises the transform from this group onto the supplied object
  17932. * i.e. it tells you what would happen if the supplied object was in
  17933. * the group, and then the group was destroyed. It mutates the supplied
  17934. * object.
  17935. * @param {fabric.Object} object
  17936. * @return {fabric.Object} transformedObject
  17937. */
  17938. realizeTransform: function(object) {
  17939. var matrix = object.calcTransformMatrix(),
  17940. options = fabric.util.qrDecompose(matrix),
  17941. center = new fabric.Point(options.translateX, options.translateY);
  17942. object.flipX = false;
  17943. object.flipY = false;
  17944. object.set('scaleX', options.scaleX);
  17945. object.set('scaleY', options.scaleY);
  17946. object.skewX = options.skewX;
  17947. object.skewY = options.skewY;
  17948. object.angle = options.angle;
  17949. object.setPositionByOrigin(center, 'center', 'center');
  17950. return object;
  17951. },
  17952. /**
  17953. * Restores original state of a specified object in group
  17954. * @private
  17955. * @param {fabric.Object} object
  17956. * @return {fabric.Group} thisArg
  17957. */
  17958. _restoreObjectState: function(object) {
  17959. this.realizeTransform(object);
  17960. object.setCoords();
  17961. delete object.group;
  17962. return this;
  17963. },
  17964. /**
  17965. * Destroys a group (restoring state of its objects)
  17966. * @return {fabric.Group} thisArg
  17967. * @chainable
  17968. */
  17969. destroy: function() {
  17970. // when group is destroyed objects needs to get a repaint to be eventually
  17971. // displayed on canvas.
  17972. this._objects.forEach(function(object) {
  17973. object.set('dirty', true);
  17974. });
  17975. return this._restoreObjectsState();
  17976. },
  17977. /**
  17978. * make a group an active selection, remove the group from canvas
  17979. * the group has to be on canvas for this to work.
  17980. * @return {fabric.ActiveSelection} thisArg
  17981. * @chainable
  17982. */
  17983. toActiveSelection: function() {
  17984. if (!this.canvas) {
  17985. return;
  17986. }
  17987. var objects = this._objects, canvas = this.canvas;
  17988. this._objects = [];
  17989. var options = this.toObject();
  17990. delete options.objects;
  17991. var activeSelection = new fabric.ActiveSelection([]);
  17992. activeSelection.set(options);
  17993. activeSelection.type = 'activeSelection';
  17994. canvas.remove(this);
  17995. objects.forEach(function(object) {
  17996. object.group = activeSelection;
  17997. object.dirty = true;
  17998. canvas.add(object);
  17999. });
  18000. activeSelection.canvas = canvas;
  18001. activeSelection._objects = objects;
  18002. canvas._activeObject = activeSelection;
  18003. activeSelection.setCoords();
  18004. return activeSelection;
  18005. },
  18006. /**
  18007. * Destroys a group (restoring state of its objects)
  18008. * @return {fabric.Group} thisArg
  18009. * @chainable
  18010. */
  18011. ungroupOnCanvas: function() {
  18012. return this._restoreObjectsState();
  18013. },
  18014. /**
  18015. * Sets coordinates of all objects inside group
  18016. * @return {fabric.Group} thisArg
  18017. * @chainable
  18018. */
  18019. setObjectsCoords: function() {
  18020. var ignoreZoom = true, skipAbsolute = true;
  18021. this.forEachObject(function(object) {
  18022. object.setCoords(ignoreZoom, skipAbsolute);
  18023. });
  18024. return this;
  18025. },
  18026. /**
  18027. * @private
  18028. */
  18029. _calcBounds: function(onlyWidthHeight) {
  18030. var aX = [],
  18031. aY = [],
  18032. o, prop,
  18033. props = ['tr', 'br', 'bl', 'tl'],
  18034. i = 0, iLen = this._objects.length,
  18035. j, jLen = props.length,
  18036. ignoreZoom = true;
  18037. for ( ; i < iLen; ++i) {
  18038. o = this._objects[i];
  18039. o.setCoords(ignoreZoom);
  18040. for (j = 0; j < jLen; j++) {
  18041. prop = props[j];
  18042. aX.push(o.oCoords[prop].x);
  18043. aY.push(o.oCoords[prop].y);
  18044. }
  18045. }
  18046. this.set(this._getBounds(aX, aY, onlyWidthHeight));
  18047. },
  18048. /**
  18049. * @private
  18050. */
  18051. _getBounds: function(aX, aY, onlyWidthHeight) {
  18052. var minXY = new fabric.Point(min(aX), min(aY)),
  18053. maxXY = new fabric.Point(max(aX), max(aY)),
  18054. obj = {
  18055. width: (maxXY.x - minXY.x) || 0,
  18056. height: (maxXY.y - minXY.y) || 0
  18057. };
  18058. if (!onlyWidthHeight) {
  18059. obj.left = minXY.x || 0;
  18060. obj.top = minXY.y || 0;
  18061. if (this.originX === 'center') {
  18062. obj.left += obj.width / 2;
  18063. }
  18064. if (this.originX === 'right') {
  18065. obj.left += obj.width;
  18066. }
  18067. if (this.originY === 'center') {
  18068. obj.top += obj.height / 2;
  18069. }
  18070. if (this.originY === 'bottom') {
  18071. obj.top += obj.height;
  18072. }
  18073. }
  18074. return obj;
  18075. },
  18076. });
  18077. /**
  18078. * Returns {@link fabric.Group} instance from an object representation
  18079. * @static
  18080. * @memberOf fabric.Group
  18081. * @param {Object} object Object to create a group from
  18082. * @param {Function} [callback] Callback to invoke when an group instance is created
  18083. */
  18084. fabric.Group.fromObject = function(object, callback) {
  18085. fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
  18086. var options = fabric.util.object.clone(object, true);
  18087. delete options.objects;
  18088. callback && callback(new fabric.Group(enlivenedObjects, options, true));
  18089. });
  18090. };
  18091. })(typeof exports !== 'undefined' ? exports : this);
  18092. (function(global) {
  18093. 'use strict';
  18094. var fabric = global.fabric || (global.fabric = { });
  18095. if (fabric.ActiveSelection) {
  18096. return;
  18097. }
  18098. /**
  18099. * Group class
  18100. * @class fabric.ActiveSelection
  18101. * @extends fabric.Group
  18102. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#groups}
  18103. * @see {@link fabric.ActiveSelection#initialize} for constructor definition
  18104. */
  18105. fabric.ActiveSelection = fabric.util.createClass(fabric.Group, /** @lends fabric.ActiveSelection.prototype */ {
  18106. /**
  18107. * Type of an object
  18108. * @type String
  18109. * @default
  18110. */
  18111. type: 'activeSelection',
  18112. /**
  18113. * Constructor
  18114. * @param {Object} objects ActiveSelection objects
  18115. * @param {Object} [options] Options object
  18116. * @return {Object} thisArg
  18117. */
  18118. initialize: function(objects, options) {
  18119. options = options || {};
  18120. this._objects = objects || [];
  18121. for (var i = this._objects.length; i--; ) {
  18122. this._objects[i].group = this;
  18123. }
  18124. if (options.originX) {
  18125. this.originX = options.originX;
  18126. }
  18127. if (options.originY) {
  18128. this.originY = options.originY;
  18129. }
  18130. this._calcBounds();
  18131. this._updateObjectsCoords();
  18132. fabric.Object.prototype.initialize.call(this, options);
  18133. this.setCoords();
  18134. },
  18135. /**
  18136. * Change te activeSelection to a normal group,
  18137. * High level function that automatically adds it to canvas as
  18138. * active object. no events fired.
  18139. * @since 2.0.0
  18140. * @return {fabric.Group}
  18141. */
  18142. toGroup: function() {
  18143. var objects = this._objects;
  18144. this._objects = [];
  18145. var options = this.toObject();
  18146. var newGroup = new fabric.Group([]);
  18147. delete options.objects;
  18148. newGroup.set(options);
  18149. newGroup.type = 'group';
  18150. objects.forEach(function(object) {
  18151. object.group = newGroup;
  18152. object.canvas.remove(object);
  18153. });
  18154. newGroup._objects = objects;
  18155. if (!this.canvas) {
  18156. return newGroup;
  18157. }
  18158. var canvas = this.canvas;
  18159. canvas.add(newGroup);
  18160. canvas._activeObject = newGroup;
  18161. newGroup.setCoords();
  18162. return newGroup;
  18163. },
  18164. /**
  18165. * If returns true, deselection is cancelled.
  18166. * @since 2.0.0
  18167. * @return {Boolean} [cancel]
  18168. */
  18169. onDeselect: function() {
  18170. this.destroy();
  18171. return false;
  18172. },
  18173. /**
  18174. * Returns string representation of a group
  18175. * @return {String}
  18176. */
  18177. toString: function() {
  18178. return '#<fabric.ActiveSelection: (' + this.complexity() + ')>';
  18179. },
  18180. /**
  18181. * @private
  18182. */
  18183. _set: function(key, value) {
  18184. var i = this._objects.length;
  18185. if (key === 'canvas') {
  18186. while (i--) {
  18187. this._objects[i].set(key, value);
  18188. }
  18189. }
  18190. if (this.useSetOnGroup) {
  18191. while (i--) {
  18192. this._objects[i].setOnGroup(key, value);
  18193. }
  18194. }
  18195. fabric.Object.prototype._set.call(this, key, value);
  18196. },
  18197. /**
  18198. * Decide if the object should cache or not. Create its own cache level
  18199. * objectCaching is a global flag, wins over everything
  18200. * needsItsOwnCache should be used when the object drawing method requires
  18201. * a cache step. None of the fabric classes requires it.
  18202. * Generally you do not cache objects in groups because the group outside is cached.
  18203. * @return {Boolean}
  18204. */
  18205. shouldCache: function() {
  18206. return false;
  18207. },
  18208. /**
  18209. * Check if this object or a child object will cast a shadow
  18210. * @return {Boolean}
  18211. */
  18212. willDrawShadow: function() {
  18213. if (this.shadow) {
  18214. return this.callSuper('willDrawShadow');
  18215. }
  18216. for (var i = 0, len = this._objects.length; i < len; i++) {
  18217. if (this._objects[i].willDrawShadow()) {
  18218. return true;
  18219. }
  18220. }
  18221. return false;
  18222. },
  18223. /**
  18224. * Check if this group or its parent group are caching, recursively up
  18225. * @return {Boolean}
  18226. */
  18227. isOnACache: function() {
  18228. return false;
  18229. },
  18230. /**
  18231. * Renders controls and borders for the object
  18232. * @param {CanvasRenderingContext2D} ctx Context to render on
  18233. * @param {Object} [styleOverride] properties to override the object style
  18234. * @param {Object} [childrenOverride] properties to override the children overrides
  18235. */
  18236. _renderControls: function(ctx, styleOverride, childrenOverride) {
  18237. ctx.save();
  18238. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  18239. this.callSuper('_renderControls', ctx, styleOverride);
  18240. childrenOverride = childrenOverride || { };
  18241. if (typeof childrenOverride.hasControls === 'undefined') {
  18242. childrenOverride.hasControls = false;
  18243. }
  18244. if (typeof childrenOverride.hasRotatingPoint === 'undefined') {
  18245. childrenOverride.hasRotatingPoint = false;
  18246. }
  18247. childrenOverride.forActiveSelection = true;
  18248. for (var i = 0, len = this._objects.length; i < len; i++) {
  18249. this._objects[i]._renderControls(ctx, childrenOverride);
  18250. }
  18251. ctx.restore();
  18252. },
  18253. });
  18254. /**
  18255. * Returns {@link fabric.ActiveSelection} instance from an object representation
  18256. * @static
  18257. * @memberOf fabric.ActiveSelection
  18258. * @param {Object} object Object to create a group from
  18259. * @param {Function} [callback] Callback to invoke when an ActiveSelection instance is created
  18260. */
  18261. fabric.ActiveSelection.fromObject = function(object, callback) {
  18262. fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
  18263. delete object.objects;
  18264. callback && callback(new fabric.ActiveSelection(enlivenedObjects, object, true));
  18265. });
  18266. };
  18267. })(typeof exports !== 'undefined' ? exports : this);
  18268. (function(global) {
  18269. 'use strict';
  18270. var extend = fabric.util.object.extend;
  18271. if (!global.fabric) {
  18272. global.fabric = { };
  18273. }
  18274. if (global.fabric.Image) {
  18275. fabric.warn('fabric.Image is already defined.');
  18276. return;
  18277. }
  18278. /**
  18279. * Image class
  18280. * @class fabric.Image
  18281. * @extends fabric.Object
  18282. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#images}
  18283. * @see {@link fabric.Image#initialize} for constructor definition
  18284. */
  18285. fabric.Image = fabric.util.createClass(fabric.Object, /** @lends fabric.Image.prototype */ {
  18286. /**
  18287. * Type of an object
  18288. * @type String
  18289. * @default
  18290. */
  18291. type: 'image',
  18292. /**
  18293. * crossOrigin value (one of "", "anonymous", "use-credentials")
  18294. * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
  18295. * @type String
  18296. * @default
  18297. */
  18298. crossOrigin: '',
  18299. /**
  18300. * Width of a stroke.
  18301. * For image quality a stroke multiple of 2 gives better results.
  18302. * @type Number
  18303. * @default
  18304. */
  18305. strokeWidth: 0,
  18306. /**
  18307. * private
  18308. * contains last value of scaleX to detect
  18309. * if the Image got resized after the last Render
  18310. * @type Number
  18311. */
  18312. _lastScaleX: 1,
  18313. /**
  18314. * private
  18315. * contains last value of scaleY to detect
  18316. * if the Image got resized after the last Render
  18317. * @type Number
  18318. */
  18319. _lastScaleY: 1,
  18320. /**
  18321. * private
  18322. * contains last value of scaling applied by the apply filter chain
  18323. * @type Number
  18324. */
  18325. _filterScalingX: 1,
  18326. /**
  18327. * private
  18328. * contains last value of scaling applied by the apply filter chain
  18329. * @type Number
  18330. */
  18331. _filterScalingY: 1,
  18332. /**
  18333. * minimum scale factor under which any resizeFilter is triggered to resize the image
  18334. * 0 will disable the automatic resize. 1 will trigger automatically always.
  18335. * number bigger than 1 are not implemented yet.
  18336. * @type Number
  18337. */
  18338. minimumScaleTrigger: 0.5,
  18339. /**
  18340. * List of properties to consider when checking if
  18341. * state of an object is changed ({@link fabric.Object#hasStateChanged})
  18342. * as well as for history (undo/redo) purposes
  18343. * @type Array
  18344. */
  18345. stateProperties: fabric.Object.prototype.stateProperties.concat('cropX', 'cropY'),
  18346. /**
  18347. * key used to retrieve the texture representing this image
  18348. * since 2.0.0
  18349. * @type String
  18350. * @default
  18351. */
  18352. cacheKey: '',
  18353. /**
  18354. * Image crop in pixels from original image size.
  18355. * since 2.0.0
  18356. * @type Number
  18357. * @default
  18358. */
  18359. cropX: 0,
  18360. /**
  18361. * Image crop in pixels from original image size.
  18362. * since 2.0.0
  18363. * @type Number
  18364. * @default
  18365. */
  18366. cropY: 0,
  18367. /**
  18368. * Constructor
  18369. * @param {HTMLImageElement | String} element Image element
  18370. * @param {Object} [options] Options object
  18371. * @param {function} [callback] callback function to call after eventual filters applied.
  18372. * @return {fabric.Image} thisArg
  18373. */
  18374. initialize: function(element, options) {
  18375. options || (options = { });
  18376. this.filters = [];
  18377. this.cacheKey = 'texture' + fabric.Object.__uid++;
  18378. this.callSuper('initialize', options);
  18379. this._initElement(element, options);
  18380. },
  18381. /**
  18382. * Returns image element which this instance if based on
  18383. * @return {HTMLImageElement} Image element
  18384. */
  18385. getElement: function() {
  18386. return this._element;
  18387. },
  18388. /**
  18389. * Sets image element for this instance to a specified one.
  18390. * If filters defined they are applied to new image.
  18391. * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area.
  18392. * @param {HTMLImageElement} element
  18393. * @param {Object} [options] Options object
  18394. * @return {fabric.Image} thisArg
  18395. * @chainable
  18396. */
  18397. setElement: function(element, options) {
  18398. var backend = fabric.filterBackend;
  18399. if (backend && backend.evictCachesForKey) {
  18400. backend.evictCachesForKey(this.cacheKey);
  18401. backend.evictCachesForKey(this.cacheKey + '_filtered');
  18402. }
  18403. this._element = element;
  18404. this._originalElement = element;
  18405. this._initConfig(options);
  18406. if (this.resizeFilter) {
  18407. this.applyResizeFilters();
  18408. }
  18409. if (this.filters.length !== 0) {
  18410. this.applyFilters();
  18411. }
  18412. return this;
  18413. },
  18414. /**
  18415. * Delete cacheKey if we have a webGlBackend
  18416. * delete reference to image elements
  18417. */
  18418. dispose: function() {
  18419. var backend = fabric.filterBackend;
  18420. if (backend && backend.evictCachesForKey) {
  18421. backend.evictCachesForKey(this.cacheKey);
  18422. backend.evictCachesForKey(this.cacheKey + '_filtered');
  18423. }
  18424. this._originalElement = undefined;
  18425. this._element = undefined;
  18426. this._filteredEl = undefined;
  18427. },
  18428. /**
  18429. * Sets crossOrigin value (on an instance and corresponding image element)
  18430. * @return {fabric.Image} thisArg
  18431. * @chainable
  18432. */
  18433. setCrossOrigin: function(value) {
  18434. this.crossOrigin = value;
  18435. this._element.crossOrigin = value;
  18436. return this;
  18437. },
  18438. /**
  18439. * Returns original size of an image
  18440. * @return {Object} Object with "width" and "height" properties
  18441. */
  18442. getOriginalSize: function() {
  18443. var element = this.getElement();
  18444. return {
  18445. width: element.width,
  18446. height: element.height
  18447. };
  18448. },
  18449. /**
  18450. * @private
  18451. * @param {CanvasRenderingContext2D} ctx Context to render on
  18452. */
  18453. _stroke: function(ctx) {
  18454. if (!this.stroke || this.strokeWidth === 0) {
  18455. return;
  18456. }
  18457. var w = this.width / 2, h = this.height / 2;
  18458. ctx.beginPath();
  18459. ctx.moveTo(-w, -h);
  18460. ctx.lineTo(w, -h);
  18461. ctx.lineTo(w, h);
  18462. ctx.lineTo(-w, h);
  18463. ctx.lineTo(-w, -h);
  18464. ctx.closePath();
  18465. },
  18466. /**
  18467. * @private
  18468. * @param {CanvasRenderingContext2D} ctx Context to render on
  18469. */
  18470. _renderDashedStroke: function(ctx) {
  18471. var x = -this.width / 2,
  18472. y = -this.height / 2,
  18473. w = this.width,
  18474. h = this.height;
  18475. ctx.save();
  18476. this._setStrokeStyles(ctx, this);
  18477. ctx.beginPath();
  18478. fabric.util.drawDashedLine(ctx, x, y, x + w, y, this.strokeDashArray);
  18479. fabric.util.drawDashedLine(ctx, x + w, y, x + w, y + h, this.strokeDashArray);
  18480. fabric.util.drawDashedLine(ctx, x + w, y + h, x, y + h, this.strokeDashArray);
  18481. fabric.util.drawDashedLine(ctx, x, y + h, x, y, this.strokeDashArray);
  18482. ctx.closePath();
  18483. ctx.restore();
  18484. },
  18485. /**
  18486. * Returns object representation of an instance
  18487. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18488. * @return {Object} Object representation of an instance
  18489. */
  18490. toObject: function(propertiesToInclude) {
  18491. var filters = [];
  18492. this.filters.forEach(function(filterObj) {
  18493. if (filterObj) {
  18494. filters.push(filterObj.toObject());
  18495. }
  18496. });
  18497. var object = extend(
  18498. this.callSuper(
  18499. 'toObject',
  18500. ['crossOrigin', 'cropX', 'cropY'].concat(propertiesToInclude)
  18501. ), {
  18502. src: this.getSrc(),
  18503. filters: filters,
  18504. });
  18505. if (this.resizeFilter) {
  18506. object.resizeFilter = this.resizeFilter.toObject();
  18507. }
  18508. return object;
  18509. },
  18510. /**
  18511. * Returns true if an image has crop applied, inspecting values of cropX,cropY,width,hight.
  18512. * @return {Boolean}
  18513. */
  18514. hasCrop: function() {
  18515. return this.cropX || this.cropY || this.width < this._element.width || this.height < this._element.height;
  18516. },
  18517. /**
  18518. * Returns source of an image
  18519. * @param {Boolean} filtered indicates if the src is needed for svg
  18520. * @return {String} Source of an image
  18521. */
  18522. getSrc: function(filtered) {
  18523. var element = filtered ? this._element : this._originalElement;
  18524. if (element) {
  18525. if (element.toDataURL) {
  18526. return element.toDataURL();
  18527. }
  18528. return element.src;
  18529. }
  18530. else {
  18531. return this.src || '';
  18532. }
  18533. },
  18534. /**
  18535. * Sets source of an image
  18536. * @param {String} src Source string (URL)
  18537. * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied)
  18538. * @param {Object} [options] Options object
  18539. * @return {fabric.Image} thisArg
  18540. * @chainable
  18541. */
  18542. setSrc: function(src, callback, options) {
  18543. fabric.util.loadImage(src, function(img) {
  18544. this.setElement(img, options);
  18545. this._setWidthHeight();
  18546. callback(this);
  18547. }, this, options && options.crossOrigin);
  18548. return this;
  18549. },
  18550. /**
  18551. * Returns string representation of an instance
  18552. * @return {String} String representation of an instance
  18553. */
  18554. toString: function() {
  18555. return '#<fabric.Image: { src: "' + this.getSrc() + '" }>';
  18556. },
  18557. applyResizeFilters: function() {
  18558. var filter = this.resizeFilter,
  18559. retinaScaling = this.canvas ? this.canvas.getRetinaScaling() : 1,
  18560. minimumScale = this.minimumScaleTrigger,
  18561. scaleX = this.scaleX * retinaScaling,
  18562. scaleY = this.scaleY * retinaScaling,
  18563. elementToFilter = this._filteredEl || this._originalElement;
  18564. if (this.group) {
  18565. this.set('dirty', true);
  18566. }
  18567. if (!filter || (scaleX > minimumScale && scaleY > minimumScale)) {
  18568. this._element = elementToFilter;
  18569. this._filterScalingX = 1;
  18570. this._filterScalingY = 1;
  18571. return;
  18572. }
  18573. if (!fabric.filterBackend) {
  18574. fabric.filterBackend = fabric.initFilterBackend();
  18575. }
  18576. var canvasEl = fabric.util.createCanvasElement(),
  18577. cacheKey = this._filteredEl ? this.cacheKey : (this.cacheKey + '_filtered'),
  18578. sourceWidth = elementToFilter.width, sourceHeight = elementToFilter.height;
  18579. canvasEl.width = sourceWidth;
  18580. canvasEl.height = sourceHeight;
  18581. this._element = canvasEl;
  18582. filter.scaleX = scaleX;
  18583. filter.scaleY = scaleY;
  18584. fabric.filterBackend.applyFilters(
  18585. [filter], elementToFilter, sourceWidth, sourceHeight, this._element, cacheKey);
  18586. this._filterScalingX = canvasEl.width / this._originalElement.width;
  18587. this._filterScalingY = canvasEl.height / this._originalElement.height;
  18588. },
  18589. /**
  18590. * Applies filters assigned to this image (from "filters" array) or from filter param
  18591. * @method applyFilters
  18592. * @param {Array} filters to be applied
  18593. * @param {Boolean} forResizing specify if the filter operation is a resize operation
  18594. * @return {thisArg} return the fabric.Image object
  18595. * @chainable
  18596. */
  18597. applyFilters: function(filters) {
  18598. filters = filters || this.filters || [];
  18599. filters = filters.filter(function(filter) { return filter; });
  18600. if (this.group) {
  18601. this.set('dirty', true);
  18602. }
  18603. if (filters.length === 0) {
  18604. this._element = this._originalElement;
  18605. this._filteredEl = null;
  18606. this._filterScalingX = 1;
  18607. this._filterScalingY = 1;
  18608. return this;
  18609. }
  18610. var imgElement = this._originalElement,
  18611. sourceWidth = imgElement.naturalWidth || imgElement.width,
  18612. sourceHeight = imgElement.naturalHeight || imgElement.height;
  18613. if (this._element === this._originalElement) {
  18614. // if the element is the same we need to create a new element
  18615. var canvasEl = fabric.util.createCanvasElement();
  18616. canvasEl.width = sourceWidth;
  18617. canvasEl.height = sourceHeight;
  18618. this._element = canvasEl;
  18619. this._filteredEl = canvasEl;
  18620. }
  18621. else {
  18622. // clear the existing element to get new filter data
  18623. this._element.getContext('2d').clearRect(0, 0, sourceWidth, sourceHeight);
  18624. }
  18625. if (!fabric.filterBackend) {
  18626. fabric.filterBackend = fabric.initFilterBackend();
  18627. }
  18628. fabric.filterBackend.applyFilters(
  18629. filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);
  18630. if (this._originalElement.width !== this._element.width ||
  18631. this._originalElement.height !== this._element.height) {
  18632. this._filterScalingX = this._element.width / this._originalElement.width;
  18633. this._filterScalingY = this._element.height / this._originalElement.height;
  18634. }
  18635. return this;
  18636. },
  18637. /**
  18638. * @private
  18639. * @param {CanvasRenderingContext2D} ctx Context to render on
  18640. */
  18641. _render: function(ctx) {
  18642. if (this.isMoving === false && this.resizeFilter && this._needsResize()) {
  18643. this._lastScaleX = this.scaleX;
  18644. this._lastScaleY = this.scaleY;
  18645. this.applyResizeFilters();
  18646. }
  18647. this._stroke(ctx);
  18648. this._renderPaintInOrder(ctx);
  18649. },
  18650. _renderFill: function(ctx) {
  18651. var w = this.width, h = this.height, sW = w * this._filterScalingX, sH = h * this._filterScalingY,
  18652. x = -w / 2, y = -h / 2, elementToDraw = this._element;
  18653. elementToDraw && ctx.drawImage(elementToDraw,
  18654. this.cropX * this._filterScalingX,
  18655. this.cropY * this._filterScalingY,
  18656. sW,
  18657. sH,
  18658. x, y, w, h);
  18659. },
  18660. /**
  18661. * @private, needed to check if image needs resize
  18662. */
  18663. _needsResize: function() {
  18664. return (this.scaleX !== this._lastScaleX || this.scaleY !== this._lastScaleY);
  18665. },
  18666. /**
  18667. * @private
  18668. */
  18669. _resetWidthHeight: function() {
  18670. var element = this.getElement();
  18671. this.set('width', element.width);
  18672. this.set('height', element.height);
  18673. },
  18674. /**
  18675. * The Image class's initialization method. This method is automatically
  18676. * called by the constructor.
  18677. * @private
  18678. * @param {HTMLImageElement|String} element The element representing the image
  18679. * @param {Object} [options] Options object
  18680. */
  18681. _initElement: function(element, options) {
  18682. this.setElement(fabric.util.getById(element), options);
  18683. fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);
  18684. },
  18685. /**
  18686. * @private
  18687. * @param {Object} [options] Options object
  18688. */
  18689. _initConfig: function(options) {
  18690. options || (options = { });
  18691. this.setOptions(options);
  18692. this._setWidthHeight(options);
  18693. if (this._element && this.crossOrigin) {
  18694. this._element.crossOrigin = this.crossOrigin;
  18695. }
  18696. },
  18697. /**
  18698. * @private
  18699. * @param {Array} filters to be initialized
  18700. * @param {Function} callback Callback to invoke when all fabric.Image.filters instances are created
  18701. */
  18702. _initFilters: function(filters, callback) {
  18703. if (filters && filters.length) {
  18704. fabric.util.enlivenObjects(filters, function(enlivenedObjects) {
  18705. callback && callback(enlivenedObjects);
  18706. }, 'fabric.Image.filters');
  18707. }
  18708. else {
  18709. callback && callback();
  18710. }
  18711. },
  18712. /**
  18713. * @private
  18714. * @param {Object} [options] Object with width/height properties
  18715. */
  18716. _setWidthHeight: function(options) {
  18717. this.width = options && ('width' in options)
  18718. ? options.width
  18719. : (this.getElement()
  18720. ? this.getElement().width || 0
  18721. : 0);
  18722. this.height = options && ('height' in options)
  18723. ? options.height
  18724. : (this.getElement()
  18725. ? this.getElement().height || 0
  18726. : 0);
  18727. },
  18728. /**
  18729. * Calculate offset for center and scale factor for the image in order to respect
  18730. * the preserveAspectRatio attribute
  18731. * @private
  18732. * @return {Object}
  18733. */
  18734. parsePreserveAspectRatioAttribute: function() {
  18735. var pAR = fabric.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio || ''),
  18736. rWidth = this._element.width, rHeight = this._element.height,
  18737. scaleX = 1, scaleY = 1, offsetLeft = 0, offsetTop = 0, cropX = 0, cropY = 0,
  18738. offset, pWidth = this.width, pHeight = this.height, parsedAttributes = { width: pWidth, height: pHeight };
  18739. if (pAR && (pAR.alignX !== 'none' || pAR.alignY !== 'none')) {
  18740. if (pAR.meetOrSlice === 'meet') {
  18741. scaleX = scaleY = fabric.util.findScaleToFit(this._element, parsedAttributes);
  18742. offset = (pWidth - rWidth * scaleX) / 2;
  18743. if (pAR.alignX === 'Min') {
  18744. offsetLeft = -offset;
  18745. }
  18746. if (pAR.alignX === 'Max') {
  18747. offsetLeft = offset;
  18748. }
  18749. offset = (pHeight - rHeight * scaleY) / 2;
  18750. if (pAR.alignY === 'Min') {
  18751. offsetTop = -offset;
  18752. }
  18753. if (pAR.alignY === 'Max') {
  18754. offsetTop = offset;
  18755. }
  18756. }
  18757. if (pAR.meetOrSlice === 'slice') {
  18758. scaleX = scaleY = fabric.util.findScaleToCover(this._element, parsedAttributes);
  18759. offset = rWidth - pWidth / scaleX;
  18760. if (pAR.alignX === 'Mid') {
  18761. cropX = offset / 2;
  18762. }
  18763. if (pAR.alignX === 'Max') {
  18764. cropX = offset;
  18765. }
  18766. offset = rHeight - pHeight / scaleY;
  18767. if (pAR.alignY === 'Mid') {
  18768. cropY = offset / 2;
  18769. }
  18770. if (pAR.alignY === 'Max') {
  18771. cropY = offset;
  18772. }
  18773. rWidth = pWidth / scaleX;
  18774. rHeight = pHeight / scaleY;
  18775. }
  18776. }
  18777. else {
  18778. scaleX = pWidth / rWidth;
  18779. scaleY = pHeight / rHeight;
  18780. }
  18781. return {
  18782. width: rWidth,
  18783. height: rHeight,
  18784. scaleX: scaleX,
  18785. scaleY: scaleY,
  18786. offsetLeft: offsetLeft,
  18787. offsetTop: offsetTop,
  18788. cropX: cropX,
  18789. cropY: cropY
  18790. };
  18791. }
  18792. });
  18793. /**
  18794. * Default CSS class name for canvas
  18795. * @static
  18796. * @type String
  18797. * @default
  18798. */
  18799. fabric.Image.CSS_CANVAS = 'canvas-img';
  18800. /**
  18801. * Alias for getSrc
  18802. * @static
  18803. */
  18804. fabric.Image.prototype.getSvgSrc = fabric.Image.prototype.getSrc;
  18805. /**
  18806. * Creates an instance of fabric.Image from its object representation
  18807. * @static
  18808. * @param {Object} object Object to create an instance from
  18809. * @param {Function} callback Callback to invoke when an image instance is created
  18810. */
  18811. fabric.Image.fromObject = function(_object, callback) {
  18812. var object = fabric.util.object.clone(_object);
  18813. fabric.util.loadImage(object.src, function(img, error) {
  18814. if (error) {
  18815. callback && callback(null, error);
  18816. return;
  18817. }
  18818. fabric.Image.prototype._initFilters.call(object, object.filters, function(filters) {
  18819. object.filters = filters || [];
  18820. fabric.Image.prototype._initFilters.call(object, [object.resizeFilter], function(resizeFilters) {
  18821. object.resizeFilter = resizeFilters[0];
  18822. var image = new fabric.Image(img, object);
  18823. callback(image);
  18824. });
  18825. });
  18826. }, null, object.crossOrigin);
  18827. };
  18828. /**
  18829. * Creates an instance of fabric.Image from an URL string
  18830. * @static
  18831. * @param {String} url URL to create an image from
  18832. * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument)
  18833. * @param {Object} [imgOptions] Options object
  18834. */
  18835. fabric.Image.fromURL = function(url, callback, imgOptions) {
  18836. fabric.util.loadImage(url, function(img) {
  18837. callback && callback(new fabric.Image(img, imgOptions));
  18838. }, null, imgOptions && imgOptions.crossOrigin);
  18839. };
  18840. })(typeof exports !== 'undefined' ? exports : this);
  18841. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  18842. /**
  18843. * @private
  18844. * @return {Number} angle value
  18845. */
  18846. _getAngleValueForStraighten: function() {
  18847. var angle = this.angle % 360;
  18848. if (angle > 0) {
  18849. return Math.round((angle - 1) / 90) * 90;
  18850. }
  18851. return Math.round(angle / 90) * 90;
  18852. },
  18853. /**
  18854. * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer)
  18855. * @return {fabric.Object} thisArg
  18856. * @chainable
  18857. */
  18858. straighten: function() {
  18859. this.rotate(this._getAngleValueForStraighten());
  18860. return this;
  18861. },
  18862. /**
  18863. * Same as {@link fabric.Object.prototype.straighten} but with animation
  18864. * @param {Object} callbacks Object with callback functions
  18865. * @param {Function} [callbacks.onComplete] Invoked on completion
  18866. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  18867. * @return {fabric.Object} thisArg
  18868. * @chainable
  18869. */
  18870. fxStraighten: function(callbacks) {
  18871. callbacks = callbacks || { };
  18872. var empty = function() { },
  18873. onComplete = callbacks.onComplete || empty,
  18874. onChange = callbacks.onChange || empty,
  18875. _this = this;
  18876. fabric.util.animate({
  18877. startValue: this.get('angle'),
  18878. endValue: this._getAngleValueForStraighten(),
  18879. duration: this.FX_DURATION,
  18880. onChange: function(value) {
  18881. _this.rotate(value);
  18882. onChange();
  18883. },
  18884. onComplete: function() {
  18885. _this.setCoords();
  18886. onComplete();
  18887. },
  18888. });
  18889. return this;
  18890. }
  18891. });
  18892. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  18893. /**
  18894. * Straightens object, then rerenders canvas
  18895. * @param {fabric.Object} object Object to straighten
  18896. * @return {fabric.Canvas} thisArg
  18897. * @chainable
  18898. */
  18899. straightenObject: function (object) {
  18900. object.straighten();
  18901. this.requestRenderAll();
  18902. return this;
  18903. },
  18904. /**
  18905. * Same as {@link fabric.Canvas.prototype.straightenObject}, but animated
  18906. * @param {fabric.Object} object Object to straighten
  18907. * @return {fabric.Canvas} thisArg
  18908. * @chainable
  18909. */
  18910. fxStraightenObject: function (object) {
  18911. object.fxStraighten({
  18912. onChange: this.requestRenderAllBound
  18913. });
  18914. return this;
  18915. }
  18916. });
  18917. (function() {
  18918. 'use strict';
  18919. /**
  18920. * Tests if webgl supports certain precision
  18921. * @param {WebGL} Canvas WebGL context to test on
  18922. * @param {String} Precision to test can be any of following: 'lowp', 'mediump', 'highp'
  18923. * @returns {Boolean} Whether the user's browser WebGL supports given precision.
  18924. */
  18925. function testPrecision(gl, precision){
  18926. var fragmentSource = 'precision ' + precision + ' float;\nvoid main(){}';
  18927. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  18928. gl.shaderSource(fragmentShader, fragmentSource);
  18929. gl.compileShader(fragmentShader);
  18930. if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
  18931. return false;
  18932. }
  18933. return true;
  18934. }
  18935. /**
  18936. * Indicate whether this filtering backend is supported by the user's browser.
  18937. * @param {Number} tileSize check if the tileSize is supported
  18938. * @returns {Boolean} Whether the user's browser supports WebGL.
  18939. */
  18940. fabric.isWebglSupported = function(tileSize) {
  18941. if (fabric.isLikelyNode) {
  18942. return false;
  18943. }
  18944. tileSize = tileSize || fabric.WebglFilterBackend.prototype.tileSize;
  18945. var canvas = document.createElement('canvas');
  18946. var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  18947. var isSupported = false;
  18948. // eslint-disable-next-line
  18949. if (gl) {
  18950. fabric.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  18951. isSupported = fabric.maxTextureSize >= tileSize;
  18952. var precisions = ['highp', 'mediump', 'lowp'];
  18953. for (var i = 0; i < 3; i++){
  18954. if (testPrecision(gl, precisions[i])){
  18955. fabric.webGlPrecision = precisions[i];
  18956. break;
  18957. };
  18958. }
  18959. }
  18960. this.isSupported = isSupported;
  18961. return isSupported;
  18962. };
  18963. fabric.WebglFilterBackend = WebglFilterBackend;
  18964. /**
  18965. * WebGL filter backend.
  18966. */
  18967. function WebglFilterBackend(options) {
  18968. if (options && options.tileSize) {
  18969. this.tileSize = options.tileSize;
  18970. }
  18971. this.setupGLContext(this.tileSize, this.tileSize);
  18972. this.captureGPUInfo();
  18973. };
  18974. WebglFilterBackend.prototype = /** @lends fabric.WebglFilterBackend.prototype */ {
  18975. tileSize: 2048,
  18976. /**
  18977. * Experimental. This object is a sort of repository of help layers used to avoid
  18978. * of recreating them during frequent filtering. If you are previewing a filter with
  18979. * a slider you problably do not want to create help layers every filter step.
  18980. * in this object there will be appended some canvases, created once, resized sometimes
  18981. * cleared never. Clearing is left to the developer.
  18982. **/
  18983. resources: {
  18984. },
  18985. /**
  18986. * Setup a WebGL context suitable for filtering, and bind any needed event handlers.
  18987. */
  18988. setupGLContext: function(width, height) {
  18989. this.dispose();
  18990. this.createWebGLCanvas(width, height);
  18991. // eslint-disable-next-line
  18992. this.aPosition = new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]);
  18993. this.chooseFastestCopyGLTo2DMethod(width, height);
  18994. },
  18995. /**
  18996. * Pick a method to copy data from GL context to 2d canvas. In some browsers using
  18997. * putImageData is faster than drawImage for that specific operation.
  18998. */
  18999. chooseFastestCopyGLTo2DMethod: function(width, height) {
  19000. var canMeasurePerf = typeof window.performance !== 'undefined';
  19001. var canUseImageData;
  19002. try {
  19003. new ImageData(1, 1);
  19004. canUseImageData = true;
  19005. }
  19006. catch (e) {
  19007. canUseImageData = false;
  19008. }
  19009. // eslint-disable-next-line no-undef
  19010. var canUseArrayBuffer = typeof ArrayBuffer !== 'undefined';
  19011. // eslint-disable-next-line no-undef
  19012. var canUseUint8Clamped = typeof Uint8ClampedArray !== 'undefined';
  19013. if (!(canMeasurePerf && canUseImageData && canUseArrayBuffer && canUseUint8Clamped)) {
  19014. return;
  19015. }
  19016. var targetCanvas = fabric.util.createCanvasElement();
  19017. // eslint-disable-next-line no-undef
  19018. var imageBuffer = new ArrayBuffer(width * height * 4);
  19019. var testContext = {
  19020. imageBuffer: imageBuffer,
  19021. destinationWidth: width,
  19022. destinationHeight: height,
  19023. targetCanvas: targetCanvas
  19024. };
  19025. var startTime, drawImageTime, putImageDataTime;
  19026. targetCanvas.width = width;
  19027. targetCanvas.height = height;
  19028. startTime = window.performance.now();
  19029. copyGLTo2DDrawImage.call(testContext, this.gl, testContext);
  19030. drawImageTime = window.performance.now() - startTime;
  19031. startTime = window.performance.now();
  19032. copyGLTo2DPutImageData.call(testContext, this.gl, testContext);
  19033. putImageDataTime = window.performance.now() - startTime;
  19034. if (drawImageTime > putImageDataTime) {
  19035. this.imageBuffer = imageBuffer;
  19036. this.copyGLTo2D = copyGLTo2DPutImageData;
  19037. }
  19038. else {
  19039. this.copyGLTo2D = copyGLTo2DDrawImage;
  19040. }
  19041. },
  19042. /**
  19043. * Create a canvas element and associated WebGL context and attaches them as
  19044. * class properties to the GLFilterBackend class.
  19045. */
  19046. createWebGLCanvas: function(width, height) {
  19047. var canvas = fabric.util.createCanvasElement();
  19048. canvas.width = width;
  19049. canvas.height = height;
  19050. var glOptions = {
  19051. alpha: true,
  19052. premultipliedAlpha: false,
  19053. depth: false,
  19054. stencil: false,
  19055. antialias: false
  19056. },
  19057. gl = canvas.getContext('webgl', glOptions);
  19058. if (!gl) {
  19059. gl = canvas.getContext('experimental-webgl', glOptions);
  19060. }
  19061. if (!gl) {
  19062. return;
  19063. }
  19064. gl.clearColor(0, 0, 0, 0);
  19065. // this canvas can fire webglcontextlost and webglcontextrestored
  19066. this.canvas = canvas;
  19067. this.gl = gl;
  19068. },
  19069. /**
  19070. * Attempts to apply the requested filters to the source provided, drawing the filtered output
  19071. * to the provided target canvas.
  19072. *
  19073. * @param {Array} filters The filters to apply.
  19074. * @param {HTMLImageElement|HTMLCanvasElement} source The source to be filtered.
  19075. * @param {Number} width The width of the source input.
  19076. * @param {Number} height The height of the source input.
  19077. * @param {HTMLCanvasElement} targetCanvas The destination for filtered output to be drawn.
  19078. * @param {String|undefined} cacheKey A key used to cache resources related to the source. If
  19079. * omitted, caching will be skipped.
  19080. */
  19081. applyFilters: function(filters, source, width, height, targetCanvas, cacheKey) {
  19082. var gl = this.gl;
  19083. var cachedTexture;
  19084. if (cacheKey) {
  19085. cachedTexture = this.getCachedTexture(cacheKey, source);
  19086. }
  19087. var pipelineState = {
  19088. originalWidth: source.width || source.originalWidth,
  19089. originalHeight: source.height || source.originalHeight,
  19090. sourceWidth: width,
  19091. sourceHeight: height,
  19092. destinationWidth: width,
  19093. destinationHeight: height,
  19094. context: gl,
  19095. sourceTexture: this.createTexture(gl, width, height, !cachedTexture && source),
  19096. targetTexture: this.createTexture(gl, width, height),
  19097. originalTexture: cachedTexture ||
  19098. this.createTexture(gl, width, height, !cachedTexture && source),
  19099. passes: filters.length,
  19100. webgl: true,
  19101. aPosition: this.aPosition,
  19102. programCache: this.programCache,
  19103. pass: 0,
  19104. filterBackend: this,
  19105. targetCanvas: targetCanvas
  19106. };
  19107. var tempFbo = gl.createFramebuffer();
  19108. gl.bindFramebuffer(gl.FRAMEBUFFER, tempFbo);
  19109. filters.forEach(function(filter) { filter && filter.applyTo(pipelineState); });
  19110. resizeCanvasIfNeeded(pipelineState);
  19111. this.copyGLTo2D(gl, pipelineState);
  19112. gl.bindTexture(gl.TEXTURE_2D, null);
  19113. gl.deleteTexture(pipelineState.sourceTexture);
  19114. gl.deleteTexture(pipelineState.targetTexture);
  19115. gl.deleteFramebuffer(tempFbo);
  19116. targetCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);
  19117. return pipelineState;
  19118. },
  19119. /**
  19120. * The same as the applyFilter method but with additional logging of WebGL
  19121. * errors.
  19122. */
  19123. applyFiltersDebug: function(filters, source, width, height, targetCanvas, cacheKey) {
  19124. // The following code is useful when debugging a specific issue but adds ~10x slowdown.
  19125. var gl = this.gl;
  19126. var ret = this.applyFilters(filters, source, width, height, targetCanvas, cacheKey);
  19127. var glError = gl.getError();
  19128. if (glError !== gl.NO_ERROR) {
  19129. var errorString = this.glErrorToString(gl, glError);
  19130. var error = new Error('WebGL Error ' + errorString);
  19131. error.glErrorCode = glError;
  19132. throw error;
  19133. }
  19134. return ret;
  19135. },
  19136. glErrorToString: function(context, errorCode) {
  19137. if (!context) {
  19138. return 'Context undefined for error code: ' + errorCode;
  19139. }
  19140. else if (typeof errorCode !== 'number') {
  19141. return 'Error code is not a number';
  19142. }
  19143. switch (errorCode) {
  19144. case context.NO_ERROR:
  19145. return 'NO_ERROR';
  19146. case context.INVALID_ENUM:
  19147. return 'INVALID_ENUM';
  19148. case context.INVALID_VALUE:
  19149. return 'INVALID_VALUE';
  19150. case context.INVALID_OPERATION:
  19151. return 'INVALID_OPERATION';
  19152. case context.INVALID_FRAMEBUFFER_OPERATION:
  19153. return 'INVALID_FRAMEBUFFER_OPERATION';
  19154. case context.OUT_OF_MEMORY:
  19155. return 'OUT_OF_MEMORY';
  19156. case context.CONTEXT_LOST_WEBGL:
  19157. return 'CONTEXT_LOST_WEBGL';
  19158. default:
  19159. return 'UNKNOWN_ERROR';
  19160. }
  19161. },
  19162. /**
  19163. * Detach event listeners, remove references, and clean up caches.
  19164. */
  19165. dispose: function() {
  19166. if (this.canvas) {
  19167. this.canvas = null;
  19168. this.gl = null;
  19169. }
  19170. this.clearWebGLCaches();
  19171. },
  19172. /**
  19173. * Wipe out WebGL-related caches.
  19174. */
  19175. clearWebGLCaches: function() {
  19176. this.programCache = {};
  19177. this.textureCache = {};
  19178. },
  19179. /**
  19180. * Create a WebGL texture object.
  19181. *
  19182. * Accepts specific dimensions to initialize the textuer to or a source image.
  19183. *
  19184. * @param {WebGLRenderingContext} gl The GL context to use for creating the texture.
  19185. * @param {Number} width The width to initialize the texture at.
  19186. * @param {Number} height The height to initialize the texture.
  19187. * @param {HTMLImageElement|HTMLCanvasElement} textureImageSource A source for the texture data.
  19188. * @returns {WebGLTexture}
  19189. */
  19190. createTexture: function(gl, width, height, textureImageSource) {
  19191. var texture = gl.createTexture();
  19192. gl.bindTexture(gl.TEXTURE_2D, texture);
  19193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  19194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  19195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  19196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  19197. if (textureImageSource) {
  19198. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImageSource);
  19199. }
  19200. else {
  19201. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  19202. }
  19203. return texture;
  19204. },
  19205. /**
  19206. * Can be optionally used to get a texture from the cache array
  19207. *
  19208. * If an existing texture is not found, a new texture is created and cached.
  19209. *
  19210. * @param {String} uniqueId A cache key to use to find an existing texture.
  19211. * @param {HTMLImageElement|HTMLCanvasElement} textureImageSource A source to use to create the
  19212. * texture cache entry if one does not already exist.
  19213. */
  19214. getCachedTexture: function(uniqueId, textureImageSource) {
  19215. if (this.textureCache[uniqueId]) {
  19216. return this.textureCache[uniqueId];
  19217. }
  19218. else {
  19219. var texture = this.createTexture(
  19220. this.gl, textureImageSource.width, textureImageSource.height, textureImageSource);
  19221. this.textureCache[uniqueId] = texture;
  19222. return texture;
  19223. }
  19224. },
  19225. /**
  19226. * Clear out cached resources related to a source image that has been
  19227. * filtered previously.
  19228. *
  19229. * @param {String} cacheKey The cache key provided when the source image was filtered.
  19230. */
  19231. evictCachesForKey: function(cacheKey) {
  19232. if (this.textureCache[cacheKey]) {
  19233. this.gl.deleteTexture(this.textureCache[cacheKey]);
  19234. delete this.textureCache[cacheKey];
  19235. }
  19236. },
  19237. copyGLTo2D: copyGLTo2DDrawImage,
  19238. /**
  19239. * Attempt to extract GPU information strings from a WebGL context.
  19240. *
  19241. * Useful information when debugging or blacklisting specific GPUs.
  19242. *
  19243. * @returns {Object} A GPU info object with renderer and vendor strings.
  19244. */
  19245. captureGPUInfo: function() {
  19246. if (this.gpuInfo) {
  19247. return this.gpuInfo;
  19248. }
  19249. var gl = this.gl;
  19250. var ext = gl.getExtension('WEBGL_debug_renderer_info');
  19251. var gpuInfo = { renderer: '', vendor: '' };
  19252. if (ext) {
  19253. var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
  19254. var vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);
  19255. if (renderer) {
  19256. gpuInfo.renderer = renderer.toLowerCase();
  19257. }
  19258. if (vendor) {
  19259. gpuInfo.vendor = vendor.toLowerCase();
  19260. }
  19261. }
  19262. this.gpuInfo = gpuInfo;
  19263. return gpuInfo;
  19264. },
  19265. };
  19266. })();
  19267. function resizeCanvasIfNeeded(pipelineState) {
  19268. var targetCanvas = pipelineState.targetCanvas,
  19269. width = targetCanvas.width, height = targetCanvas.height,
  19270. dWidth = pipelineState.destinationWidth,
  19271. dHeight = pipelineState.destinationHeight;
  19272. if (width !== dWidth || height !== dHeight) {
  19273. targetCanvas.width = dWidth;
  19274. targetCanvas.height = dHeight;
  19275. }
  19276. }
  19277. /**
  19278. * Copy an input WebGL canvas on to an output 2D canvas.
  19279. *
  19280. * The WebGL canvas is assumed to be upside down, with the top-left pixel of the
  19281. * desired output image appearing in the bottom-left corner of the WebGL canvas.
  19282. *
  19283. * @param {WebGLRenderingContext} sourceContext The WebGL context to copy from.
  19284. * @param {HTMLCanvasElement} targetCanvas The 2D target canvas to copy on to.
  19285. * @param {Object} pipelineState The 2D target canvas to copy on to.
  19286. */
  19287. function copyGLTo2DDrawImage(gl, pipelineState) {
  19288. var glCanvas = gl.canvas, targetCanvas = pipelineState.targetCanvas,
  19289. ctx = targetCanvas.getContext('2d');
  19290. ctx.translate(0, targetCanvas.height); // move it down again
  19291. ctx.scale(1, -1); // vertical flip
  19292. // where is my image on the big glcanvas?
  19293. var sourceY = glCanvas.height - targetCanvas.height;
  19294. ctx.drawImage(glCanvas, 0, sourceY, targetCanvas.width, targetCanvas.height, 0, 0,
  19295. targetCanvas.width, targetCanvas.height);
  19296. }
  19297. /**
  19298. * Copy an input WebGL canvas on to an output 2D canvas using 2d canvas' putImageData
  19299. * API. Measurably faster than using ctx.drawImage in Firefox (version 54 on OSX Sierra).
  19300. *
  19301. * @param {WebGLRenderingContext} sourceContext The WebGL context to copy from.
  19302. * @param {HTMLCanvasElement} targetCanvas The 2D target canvas to copy on to.
  19303. * @param {Object} pipelineState The 2D target canvas to copy on to.
  19304. */
  19305. function copyGLTo2DPutImageData(gl, pipelineState) {
  19306. var targetCanvas = pipelineState.targetCanvas, ctx = targetCanvas.getContext('2d'),
  19307. dWidth = pipelineState.destinationWidth,
  19308. dHeight = pipelineState.destinationHeight,
  19309. numBytes = dWidth * dHeight * 4;
  19310. // eslint-disable-next-line no-undef
  19311. var u8 = new Uint8Array(this.imageBuffer, 0, numBytes);
  19312. // eslint-disable-next-line no-undef
  19313. var u8Clamped = new Uint8ClampedArray(this.imageBuffer, 0, numBytes);
  19314. gl.readPixels(0, 0, dWidth, dHeight, gl.RGBA, gl.UNSIGNED_BYTE, u8);
  19315. var imgData = new ImageData(u8Clamped, dWidth, dHeight);
  19316. ctx.putImageData(imgData, 0, 0);
  19317. }
  19318. (function() {
  19319. 'use strict';
  19320. var noop = function() {};
  19321. fabric.Canvas2dFilterBackend = Canvas2dFilterBackend;
  19322. /**
  19323. * Canvas 2D filter backend.
  19324. */
  19325. function Canvas2dFilterBackend() {};
  19326. Canvas2dFilterBackend.prototype = /** @lends fabric.Canvas2dFilterBackend.prototype */ {
  19327. evictCachesForKey: noop,
  19328. dispose: noop,
  19329. clearWebGLCaches: noop,
  19330. /**
  19331. * Experimental. This object is a sort of repository of help layers used to avoid
  19332. * of recreating them during frequent filtering. If you are previewing a filter with
  19333. * a slider you probably do not want to create help layers every filter step.
  19334. * in this object there will be appended some canvases, created once, resized sometimes
  19335. * cleared never. Clearing is left to the developer.
  19336. **/
  19337. resources: {
  19338. },
  19339. /**
  19340. * Apply a set of filters against a source image and draw the filtered output
  19341. * to the provided destination canvas.
  19342. *
  19343. * @param {EnhancedFilter} filters The filter to apply.
  19344. * @param {HTMLImageElement|HTMLCanvasElement} sourceElement The source to be filtered.
  19345. * @param {Number} sourceWidth The width of the source input.
  19346. * @param {Number} sourceHeight The height of the source input.
  19347. * @param {HTMLCanvasElement} targetCanvas The destination for filtered output to be drawn.
  19348. */
  19349. applyFilters: function(filters, sourceElement, sourceWidth, sourceHeight, targetCanvas) {
  19350. var ctx = targetCanvas.getContext('2d');
  19351. ctx.drawImage(sourceElement, 0, 0, sourceWidth, sourceHeight);
  19352. var imageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);
  19353. var originalImageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);
  19354. var pipelineState = {
  19355. sourceWidth: sourceWidth,
  19356. sourceHeight: sourceHeight,
  19357. imageData: imageData,
  19358. originalEl: sourceElement,
  19359. originalImageData: originalImageData,
  19360. canvasEl: targetCanvas,
  19361. ctx: ctx,
  19362. filterBackend: this,
  19363. };
  19364. filters.forEach(function(filter) { filter.applyTo(pipelineState); });
  19365. if (pipelineState.imageData.width !== sourceWidth || pipelineState.imageData.height !== sourceHeight) {
  19366. targetCanvas.width = pipelineState.imageData.width;
  19367. targetCanvas.height = pipelineState.imageData.height;
  19368. }
  19369. ctx.putImageData(pipelineState.imageData, 0, 0);
  19370. return pipelineState;
  19371. },
  19372. };
  19373. })();
  19374. /**
  19375. * @namespace fabric.Image.filters
  19376. * @memberOf fabric.Image
  19377. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#image_filters}
  19378. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  19379. */
  19380. fabric.Image.filters = fabric.Image.filters || { };
  19381. /**
  19382. * Root filter class from which all filter classes inherit from
  19383. * @class fabric.Image.filters.BaseFilter
  19384. * @memberOf fabric.Image.filters
  19385. */
  19386. fabric.Image.filters.BaseFilter = fabric.util.createClass(/** @lends fabric.Image.filters.BaseFilter.prototype */ {
  19387. /**
  19388. * Filter type
  19389. * @param {String} type
  19390. * @default
  19391. */
  19392. type: 'BaseFilter',
  19393. /**
  19394. * Array of attributes to send with buffers. do not modify
  19395. * @private
  19396. */
  19397. vertexSource: 'attribute vec2 aPosition;\n' +
  19398. 'varying vec2 vTexCoord;\n' +
  19399. 'void main() {\n' +
  19400. 'vTexCoord = aPosition;\n' +
  19401. 'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n' +
  19402. '}',
  19403. fragmentSource: 'precision highp float;\n' +
  19404. 'varying vec2 vTexCoord;\n' +
  19405. 'uniform sampler2D uTexture;\n' +
  19406. 'void main() {\n' +
  19407. 'gl_FragColor = texture2D(uTexture, vTexCoord);\n' +
  19408. '}',
  19409. /**
  19410. * Constructor
  19411. * @param {Object} [options] Options object
  19412. */
  19413. initialize: function(options) {
  19414. if (options) {
  19415. this.setOptions(options);
  19416. }
  19417. },
  19418. /**
  19419. * Sets filter's properties from options
  19420. * @param {Object} [options] Options object
  19421. */
  19422. setOptions: function(options) {
  19423. for (var prop in options) {
  19424. this[prop] = options[prop];
  19425. }
  19426. },
  19427. /**
  19428. * Compile this filter's shader program.
  19429. *
  19430. * @param {WebGLRenderingContext} gl The GL canvas context to use for shader compilation.
  19431. * @param {String} fragmentSource fragmentShader source for compilation
  19432. * @param {String} vertexSource vertexShader source for compilation
  19433. */
  19434. createProgram: function(gl, fragmentSource, vertexSource) {
  19435. fragmentSource = fragmentSource || this.fragmentSource;
  19436. vertexSource = vertexSource || this.vertexSource;
  19437. if (fabric.webGlPrecision !== 'highp'){
  19438. fragmentSource = fragmentSource.replace(
  19439. /precision highp float/g,
  19440. 'precision ' + fabric.webGlPrecision + ' float'
  19441. );
  19442. }
  19443. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  19444. gl.shaderSource(vertexShader, vertexSource);
  19445. gl.compileShader(vertexShader);
  19446. if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
  19447. throw new Error(
  19448. // eslint-disable-next-line prefer-template
  19449. 'Vertex shader compile error for ' + this.type + ': ' +
  19450. gl.getShaderInfoLog(vertexShader)
  19451. );
  19452. }
  19453. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  19454. gl.shaderSource(fragmentShader, fragmentSource);
  19455. gl.compileShader(fragmentShader);
  19456. if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
  19457. throw new Error(
  19458. // eslint-disable-next-line prefer-template
  19459. 'Fragment shader compile error for ' + this.type + ': ' +
  19460. gl.getShaderInfoLog(fragmentShader)
  19461. );
  19462. }
  19463. var program = gl.createProgram();
  19464. gl.attachShader(program, vertexShader);
  19465. gl.attachShader(program, fragmentShader);
  19466. gl.linkProgram(program);
  19467. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  19468. throw new Error(
  19469. // eslint-disable-next-line prefer-template
  19470. 'Shader link error for "${this.type}" ' +
  19471. gl.getProgramInfoLog(program)
  19472. );
  19473. }
  19474. var attributeLocations = this.getAttributeLocations(gl, program);
  19475. var uniformLocations = this.getUniformLocations(gl, program) || { };
  19476. uniformLocations.uStepW = gl.getUniformLocation(program, 'uStepW');
  19477. uniformLocations.uStepH = gl.getUniformLocation(program, 'uStepH');
  19478. return {
  19479. program: program,
  19480. attributeLocations: attributeLocations,
  19481. uniformLocations: uniformLocations
  19482. };
  19483. },
  19484. /**
  19485. * Return a map of attribute names to WebGLAttributeLocation objects.
  19486. *
  19487. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  19488. * @param {WebGLShaderProgram} program The shader program from which to take attribute locations.
  19489. * @returns {Object} A map of attribute names to attribute locations.
  19490. */
  19491. getAttributeLocations: function(gl, program) {
  19492. return {
  19493. aPosition: gl.getAttribLocation(program, 'aPosition'),
  19494. };
  19495. },
  19496. /**
  19497. * Return a map of uniform names to WebGLUniformLocation objects.
  19498. *
  19499. * Intended to be overridden by subclasses.
  19500. *
  19501. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  19502. * @param {WebGLShaderProgram} program The shader program from which to take uniform locations.
  19503. * @returns {Object} A map of uniform names to uniform locations.
  19504. */
  19505. getUniformLocations: function (/* gl, program */) {
  19506. // in case i do not need any special uniform i need to return an empty object
  19507. return { };
  19508. },
  19509. /**
  19510. * Send attribute data from this filter to its shader program on the GPU.
  19511. *
  19512. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  19513. * @param {Object} attributeLocations A map of shader attribute names to their locations.
  19514. */
  19515. sendAttributeData: function(gl, attributeLocations, aPositionData) {
  19516. var attributeLocation = attributeLocations.aPosition;
  19517. var buffer = gl.createBuffer();
  19518. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  19519. gl.enableVertexAttribArray(attributeLocation);
  19520. gl.vertexAttribPointer(attributeLocation, 2, gl.FLOAT, false, 0, 0);
  19521. gl.bufferData(gl.ARRAY_BUFFER, aPositionData, gl.STATIC_DRAW);
  19522. },
  19523. _setupFrameBuffer: function(options) {
  19524. var gl = options.context, width, height;
  19525. if (options.passes > 1) {
  19526. width = options.destinationWidth;
  19527. height = options.destinationHeight;
  19528. if (options.sourceWidth !== width || options.sourceHeight !== height) {
  19529. gl.deleteTexture(options.targetTexture);
  19530. options.targetTexture = options.filterBackend.createTexture(gl, width, height);
  19531. }
  19532. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D,
  19533. options.targetTexture, 0);
  19534. }
  19535. else {
  19536. // draw last filter on canvas and not to framebuffer.
  19537. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  19538. gl.finish();
  19539. }
  19540. },
  19541. _swapTextures: function(options) {
  19542. options.passes--;
  19543. options.pass++;
  19544. var temp = options.targetTexture;
  19545. options.targetTexture = options.sourceTexture;
  19546. options.sourceTexture = temp;
  19547. },
  19548. /**
  19549. * Intentionally left blank, to be overridden in custom filters
  19550. * @param {Object} options
  19551. **/
  19552. isNeutralState: function(/* options */) {
  19553. return false;
  19554. },
  19555. /**
  19556. * Apply this filter to the input image data provided.
  19557. *
  19558. * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
  19559. *
  19560. * @param {Object} options
  19561. * @param {Number} options.passes The number of filters remaining to be executed
  19562. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  19563. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  19564. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  19565. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  19566. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  19567. */
  19568. applyTo: function(options) {
  19569. if (options.webgl) {
  19570. if (options.passes > 1 && this.isNeutralState(options)) {
  19571. // avoid doing something that we do not need
  19572. return;
  19573. }
  19574. this._setupFrameBuffer(options);
  19575. this.applyToWebGL(options);
  19576. this._swapTextures(options);
  19577. }
  19578. else if (!this.isNeutralState()) {
  19579. this.applyTo2d(options);
  19580. }
  19581. },
  19582. /**
  19583. * Retrieves the cached shader.
  19584. * @param {Object} options
  19585. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  19586. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  19587. */
  19588. retrieveShader: function(options) {
  19589. if (!options.programCache.hasOwnProperty(this.type)) {
  19590. options.programCache[this.type] = this.createProgram(options.context);
  19591. }
  19592. return options.programCache[this.type];
  19593. },
  19594. /**
  19595. * Apply this filter using webgl.
  19596. *
  19597. * @param {Object} options
  19598. * @param {Number} options.passes The number of filters remaining to be executed
  19599. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  19600. * @param {WebGLTexture} options.originalTexture The texture of the original input image.
  19601. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  19602. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  19603. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  19604. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  19605. */
  19606. applyToWebGL: function(options) {
  19607. var gl = options.context;
  19608. var shader = this.retrieveShader(options);
  19609. if (options.pass === 0 && options.originalTexture) {
  19610. gl.bindTexture(gl.TEXTURE_2D, options.originalTexture);
  19611. }
  19612. else {
  19613. gl.bindTexture(gl.TEXTURE_2D, options.sourceTexture);
  19614. }
  19615. gl.useProgram(shader.program);
  19616. this.sendAttributeData(gl, shader.attributeLocations, options.aPosition);
  19617. gl.uniform1f(shader.uniformLocations.uStepW, 1 / options.sourceWidth);
  19618. gl.uniform1f(shader.uniformLocations.uStepH, 1 / options.sourceHeight);
  19619. this.sendUniformData(gl, shader.uniformLocations);
  19620. gl.viewport(0, 0, options.destinationWidth, options.destinationHeight);
  19621. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  19622. },
  19623. bindAdditionalTexture: function(gl, texture, textureUnit) {
  19624. gl.activeTexture(textureUnit);
  19625. gl.bindTexture(gl.TEXTURE_2D, texture);
  19626. // reset active texture to 0 as usual
  19627. gl.activeTexture(gl.TEXTURE0);
  19628. },
  19629. unbindAdditionalTexture: function(gl, textureUnit) {
  19630. gl.activeTexture(textureUnit);
  19631. gl.bindTexture(gl.TEXTURE_2D, null);
  19632. gl.activeTexture(gl.TEXTURE0);
  19633. },
  19634. getMainParameter: function() {
  19635. return this[this.mainParameter];
  19636. },
  19637. setMainParameter: function(value) {
  19638. this[this.mainParameter] = value;
  19639. },
  19640. /**
  19641. * Send uniform data from this filter to its shader program on the GPU.
  19642. *
  19643. * Intended to be overridden by subclasses.
  19644. *
  19645. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  19646. * @param {Object} uniformLocations A map of shader uniform names to their locations.
  19647. */
  19648. sendUniformData: function(/* gl, uniformLocations */) {
  19649. // Intentionally left blank. Override me in subclasses.
  19650. },
  19651. /**
  19652. * If needed by a 2d filter, this functions can create an helper canvas to be used
  19653. * remember that options.targetCanvas is available for use till end of chain.
  19654. */
  19655. createHelpLayer: function(options) {
  19656. if (!options.helpLayer) {
  19657. var helpLayer = document.createElement('canvas');
  19658. helpLayer.width = options.sourceWidth;
  19659. helpLayer.height = options.sourceHeight;
  19660. options.helpLayer = helpLayer;
  19661. }
  19662. },
  19663. /**
  19664. * Returns object representation of an instance
  19665. * @return {Object} Object representation of an instance
  19666. */
  19667. toObject: function() {
  19668. var object = { type: this.type }, mainP = this.mainParameter;
  19669. if (mainP) {
  19670. object[mainP] = this[mainP];
  19671. }
  19672. return object;
  19673. },
  19674. /**
  19675. * Returns a JSON representation of an instance
  19676. * @return {Object} JSON
  19677. */
  19678. toJSON: function() {
  19679. // delegate, not alias
  19680. return this.toObject();
  19681. }
  19682. });
  19683. fabric.Image.filters.BaseFilter.fromObject = function(object, callback) {
  19684. var filter = new fabric.Image.filters[object.type](object);
  19685. callback && callback(filter);
  19686. return filter;
  19687. };
  19688. (function(global) {
  19689. 'use strict';
  19690. var fabric = global.fabric || (global.fabric = { }),
  19691. filters = fabric.Image.filters,
  19692. createClass = fabric.util.createClass;
  19693. /**
  19694. * Color Matrix filter class
  19695. * @class fabric.Image.filters.ColorMatrix
  19696. * @memberOf fabric.Image.filters
  19697. * @extends fabric.Image.filters.BaseFilter
  19698. * @see {@link fabric.Image.filters.ColorMatrix#initialize} for constructor definition
  19699. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  19700. * @see {@Link http://www.webwasp.co.uk/tutorials/219/Color_Matrix_Filter.php}
  19701. * @see {@Link http://phoboslab.org/log/2013/11/fast-image-filters-with-webgl}
  19702. * @example <caption>Kodachrome filter</caption>
  19703. * var filter = new fabric.Image.filters.ColorMatrix({
  19704. * matrix: [
  19705. 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,
  19706. -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,
  19707. -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,
  19708. 0, 0, 0, 1, 0
  19709. ]
  19710. * });
  19711. * object.filters.push(filter);
  19712. * object.applyFilters();
  19713. */
  19714. filters.ColorMatrix = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.ColorMatrix.prototype */ {
  19715. /**
  19716. * Filter type
  19717. * @param {String} type
  19718. * @default
  19719. */
  19720. type: 'ColorMatrix',
  19721. fragmentSource: 'precision highp float;\n' +
  19722. 'uniform sampler2D uTexture;\n' +
  19723. 'varying vec2 vTexCoord;\n' +
  19724. 'uniform mat4 uColorMatrix;\n' +
  19725. 'uniform vec4 uConstants;\n' +
  19726. 'void main() {\n' +
  19727. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  19728. 'color *= uColorMatrix;\n' +
  19729. 'color += uConstants;\n' +
  19730. 'gl_FragColor = color;\n' +
  19731. '}',
  19732. /**
  19733. * Colormatrix for pixels.
  19734. * array of 20 floats. Numbers in positions 4, 9, 14, 19 loose meaning
  19735. * outside the -1, 1 range.
  19736. * 0.0039215686 is the part of 1 that get translated to 1 in 2d
  19737. * @param {Array} matrix array of 20 numbers.
  19738. * @default
  19739. */
  19740. matrix: [
  19741. 1, 0, 0, 0, 0,
  19742. 0, 1, 0, 0, 0,
  19743. 0, 0, 1, 0, 0,
  19744. 0, 0, 0, 1, 0
  19745. ],
  19746. mainParameter: 'matrix',
  19747. /**
  19748. * Lock the colormatrix on the color part, skipping alpha, manly for non webgl scenario
  19749. * to save some calculation
  19750. */
  19751. colorsOnly: true,
  19752. /**
  19753. * Constructor
  19754. * @param {Object} [options] Options object
  19755. */
  19756. initialize: function(options) {
  19757. this.callSuper('initialize', options);
  19758. // create a new array instead mutating the prototype with push
  19759. this.matrix = this.matrix.slice(0);
  19760. },
  19761. /**
  19762. * Intentionally left blank, to be overridden in custom filters
  19763. * @param {Object} options
  19764. **/
  19765. isNeutralState: function(/* options */) {
  19766. var _class = filters.ColorMatrix;
  19767. for (var i = 20; i--;) {
  19768. if (this.matrix[i] !== _class.prototype.matrix[i]) {
  19769. return false;
  19770. }
  19771. }
  19772. return true;
  19773. },
  19774. /**
  19775. * Apply the ColorMatrix operation to a Uint8Array representing the pixels of an image.
  19776. *
  19777. * @param {Object} options
  19778. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  19779. */
  19780. applyTo2d: function(options) {
  19781. var imageData = options.imageData,
  19782. data = imageData.data,
  19783. iLen = data.length,
  19784. m = this.matrix,
  19785. r, g, b, a, i, colorsOnly = this.colorsOnly;
  19786. for (i = 0; i < iLen; i += 4) {
  19787. r = data[i];
  19788. g = data[i + 1];
  19789. b = data[i + 2];
  19790. if (colorsOnly) {
  19791. data[i] = r * m[0] + g * m[1] + b * m[2] + m[4] * 255;
  19792. data[i + 1] = r * m[5] + g * m[6] + b * m[7] + m[9] * 255;
  19793. data[i + 2] = r * m[10] + g * m[11] + b * m[12] + m[14] * 255;
  19794. }
  19795. else {
  19796. a = data[i + 3];
  19797. data[i] = r * m[0] + g * m[1] + b * m[2] + a * m[3] + m[4] * 255;
  19798. data[i + 1] = r * m[5] + g * m[6] + b * m[7] + a * m[8] + m[9] * 255;
  19799. data[i + 2] = r * m[10] + g * m[11] + b * m[12] + a * m[13] + m[14] * 255;
  19800. data[i + 3] = r * m[15] + g * m[16] + b * m[17] + a * m[18] + m[19] * 255;
  19801. }
  19802. }
  19803. },
  19804. /**
  19805. * Return WebGL uniform locations for this filter's shader.
  19806. *
  19807. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  19808. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  19809. */
  19810. getUniformLocations: function(gl, program) {
  19811. return {
  19812. uColorMatrix: gl.getUniformLocation(program, 'uColorMatrix'),
  19813. uConstants: gl.getUniformLocation(program, 'uConstants'),
  19814. };
  19815. },
  19816. /**
  19817. * Send data from this filter to its shader program's uniforms.
  19818. *
  19819. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  19820. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  19821. */
  19822. sendUniformData: function(gl, uniformLocations) {
  19823. var m = this.matrix,
  19824. matrix = [
  19825. m[0], m[1], m[2], m[3],
  19826. m[5], m[6], m[7], m[8],
  19827. m[10], m[11], m[12], m[13],
  19828. m[15], m[16], m[17], m[18]
  19829. ],
  19830. constants = [m[4], m[9], m[14], m[19]];
  19831. gl.uniformMatrix4fv(uniformLocations.uColorMatrix, false, matrix);
  19832. gl.uniform4fv(uniformLocations.uConstants, constants);
  19833. },
  19834. });
  19835. /**
  19836. * Returns filter instance from an object representation
  19837. * @static
  19838. * @param {Object} object Object to create an instance from
  19839. * @param {function} [callback] function to invoke after filter creation
  19840. * @return {fabric.Image.filters.ColorMatrix} Instance of fabric.Image.filters.ColorMatrix
  19841. */
  19842. fabric.Image.filters.ColorMatrix.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  19843. })(typeof exports !== 'undefined' ? exports : this);
  19844. (function(global) {
  19845. 'use strict';
  19846. var fabric = global.fabric || (global.fabric = { }),
  19847. filters = fabric.Image.filters,
  19848. createClass = fabric.util.createClass;
  19849. /**
  19850. * Brightness filter class
  19851. * @class fabric.Image.filters.Brightness
  19852. * @memberOf fabric.Image.filters
  19853. * @extends fabric.Image.filters.BaseFilter
  19854. * @see {@link fabric.Image.filters.Brightness#initialize} for constructor definition
  19855. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  19856. * @example
  19857. * var filter = new fabric.Image.filters.Brightness({
  19858. * brightness: 0.05
  19859. * });
  19860. * object.filters.push(filter);
  19861. * object.applyFilters();
  19862. */
  19863. filters.Brightness = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ {
  19864. /**
  19865. * Filter type
  19866. * @param {String} type
  19867. * @default
  19868. */
  19869. type: 'Brightness',
  19870. /**
  19871. * Fragment source for the brightness program
  19872. */
  19873. fragmentSource: 'precision highp float;\n' +
  19874. 'uniform sampler2D uTexture;\n' +
  19875. 'uniform float uBrightness;\n' +
  19876. 'varying vec2 vTexCoord;\n' +
  19877. 'void main() {\n' +
  19878. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  19879. 'color.rgb += uBrightness;\n' +
  19880. 'gl_FragColor = color;\n' +
  19881. '}',
  19882. /**
  19883. * Brightness value, from -1 to 1.
  19884. * translated to -255 to 255 for 2d
  19885. * 0.0039215686 is the part of 1 that get translated to 1 in 2d
  19886. * @param {Number} brightness
  19887. * @default
  19888. */
  19889. brightness: 0,
  19890. /**
  19891. * Describe the property that is the filter parameter
  19892. * @param {String} m
  19893. * @default
  19894. */
  19895. mainParameter: 'brightness',
  19896. /**
  19897. * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.
  19898. *
  19899. * @param {Object} options
  19900. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  19901. */
  19902. applyTo2d: function(options) {
  19903. if (this.brightness === 0) {
  19904. return;
  19905. }
  19906. var imageData = options.imageData,
  19907. data = imageData.data, i, len = data.length,
  19908. brightness = Math.round(this.brightness * 255);
  19909. for (i = 0; i < len; i += 4) {
  19910. data[i] = data[i] + brightness;
  19911. data[i + 1] = data[i + 1] + brightness;
  19912. data[i + 2] = data[i + 2] + brightness;
  19913. }
  19914. },
  19915. /**
  19916. * Return WebGL uniform locations for this filter's shader.
  19917. *
  19918. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  19919. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  19920. */
  19921. getUniformLocations: function(gl, program) {
  19922. return {
  19923. uBrightness: gl.getUniformLocation(program, 'uBrightness'),
  19924. };
  19925. },
  19926. /**
  19927. * Send data from this filter to its shader program's uniforms.
  19928. *
  19929. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  19930. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  19931. */
  19932. sendUniformData: function(gl, uniformLocations) {
  19933. gl.uniform1f(uniformLocations.uBrightness, this.brightness);
  19934. },
  19935. });
  19936. /**
  19937. * Returns filter instance from an object representation
  19938. * @static
  19939. * @param {Object} object Object to create an instance from
  19940. * @param {function} [callback] to be invoked after filter creation
  19941. * @return {fabric.Image.filters.Brightness} Instance of fabric.Image.filters.Brightness
  19942. */
  19943. fabric.Image.filters.Brightness.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  19944. })(typeof exports !== 'undefined' ? exports : this);
  19945. (function(global) {
  19946. 'use strict';
  19947. var fabric = global.fabric || (global.fabric = { }),
  19948. extend = fabric.util.object.extend,
  19949. filters = fabric.Image.filters,
  19950. createClass = fabric.util.createClass;
  19951. /**
  19952. * Adapted from <a href="http://www.html5rocks.com/en/tutorials/canvas/imagefilters/">html5rocks article</a>
  19953. * @class fabric.Image.filters.Convolute
  19954. * @memberOf fabric.Image.filters
  19955. * @extends fabric.Image.filters.BaseFilter
  19956. * @see {@link fabric.Image.filters.Convolute#initialize} for constructor definition
  19957. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  19958. * @example <caption>Sharpen filter</caption>
  19959. * var filter = new fabric.Image.filters.Convolute({
  19960. * matrix: [ 0, -1, 0,
  19961. * -1, 5, -1,
  19962. * 0, -1, 0 ]
  19963. * });
  19964. * object.filters.push(filter);
  19965. * object.applyFilters();
  19966. * canvas.renderAll();
  19967. * @example <caption>Blur filter</caption>
  19968. * var filter = new fabric.Image.filters.Convolute({
  19969. * matrix: [ 1/9, 1/9, 1/9,
  19970. * 1/9, 1/9, 1/9,
  19971. * 1/9, 1/9, 1/9 ]
  19972. * });
  19973. * object.filters.push(filter);
  19974. * object.applyFilters();
  19975. * canvas.renderAll();
  19976. * @example <caption>Emboss filter</caption>
  19977. * var filter = new fabric.Image.filters.Convolute({
  19978. * matrix: [ 1, 1, 1,
  19979. * 1, 0.7, -1,
  19980. * -1, -1, -1 ]
  19981. * });
  19982. * object.filters.push(filter);
  19983. * object.applyFilters();
  19984. * canvas.renderAll();
  19985. * @example <caption>Emboss filter with opaqueness</caption>
  19986. * var filter = new fabric.Image.filters.Convolute({
  19987. * opaque: true,
  19988. * matrix: [ 1, 1, 1,
  19989. * 1, 0.7, -1,
  19990. * -1, -1, -1 ]
  19991. * });
  19992. * object.filters.push(filter);
  19993. * object.applyFilters();
  19994. * canvas.renderAll();
  19995. */
  19996. filters.Convolute = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Convolute.prototype */ {
  19997. /**
  19998. * Filter type
  19999. * @param {String} type
  20000. * @default
  20001. */
  20002. type: 'Convolute',
  20003. /*
  20004. * Opaque value (true/false)
  20005. */
  20006. opaque: false,
  20007. /*
  20008. * matrix for the filter, max 9x9
  20009. */
  20010. matrix: [0, 0, 0, 0, 1, 0, 0, 0, 0],
  20011. /**
  20012. * Fragment source for the brightness program
  20013. */
  20014. fragmentSource: {
  20015. Convolute_3_1: 'precision highp float;\n' +
  20016. 'uniform sampler2D uTexture;\n' +
  20017. 'uniform float uMatrix[9];\n' +
  20018. 'uniform float uStepW;\n' +
  20019. 'uniform float uStepH;\n' +
  20020. 'varying vec2 vTexCoord;\n' +
  20021. 'void main() {\n' +
  20022. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  20023. 'for (float h = 0.0; h < 3.0; h+=1.0) {\n' +
  20024. 'for (float w = 0.0; w < 3.0; w+=1.0) {\n' +
  20025. 'vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\n' +
  20026. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n' +
  20027. '}\n' +
  20028. '}\n' +
  20029. 'gl_FragColor = color;\n' +
  20030. '}',
  20031. Convolute_3_0: 'precision highp float;\n' +
  20032. 'uniform sampler2D uTexture;\n' +
  20033. 'uniform float uMatrix[9];\n' +
  20034. 'uniform float uStepW;\n' +
  20035. 'uniform float uStepH;\n' +
  20036. 'varying vec2 vTexCoord;\n' +
  20037. 'void main() {\n' +
  20038. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  20039. 'for (float h = 0.0; h < 3.0; h+=1.0) {\n' +
  20040. 'for (float w = 0.0; w < 3.0; w+=1.0) {\n' +
  20041. 'vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\n' +
  20042. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n' +
  20043. '}\n' +
  20044. '}\n' +
  20045. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  20046. 'gl_FragColor = color;\n' +
  20047. 'gl_FragColor.a = alpha;\n' +
  20048. '}',
  20049. Convolute_5_1: 'precision highp float;\n' +
  20050. 'uniform sampler2D uTexture;\n' +
  20051. 'uniform float uMatrix[25];\n' +
  20052. 'uniform float uStepW;\n' +
  20053. 'uniform float uStepH;\n' +
  20054. 'varying vec2 vTexCoord;\n' +
  20055. 'void main() {\n' +
  20056. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  20057. 'for (float h = 0.0; h < 5.0; h+=1.0) {\n' +
  20058. 'for (float w = 0.0; w < 5.0; w+=1.0) {\n' +
  20059. 'vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n' +
  20060. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n' +
  20061. '}\n' +
  20062. '}\n' +
  20063. 'gl_FragColor = color;\n' +
  20064. '}',
  20065. Convolute_5_0: 'precision highp float;\n' +
  20066. 'uniform sampler2D uTexture;\n' +
  20067. 'uniform float uMatrix[25];\n' +
  20068. 'uniform float uStepW;\n' +
  20069. 'uniform float uStepH;\n' +
  20070. 'varying vec2 vTexCoord;\n' +
  20071. 'void main() {\n' +
  20072. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  20073. 'for (float h = 0.0; h < 5.0; h+=1.0) {\n' +
  20074. 'for (float w = 0.0; w < 5.0; w+=1.0) {\n' +
  20075. 'vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n' +
  20076. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n' +
  20077. '}\n' +
  20078. '}\n' +
  20079. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  20080. 'gl_FragColor = color;\n' +
  20081. 'gl_FragColor.a = alpha;\n' +
  20082. '}',
  20083. Convolute_7_1: 'precision highp float;\n' +
  20084. 'uniform sampler2D uTexture;\n' +
  20085. 'uniform float uMatrix[49];\n' +
  20086. 'uniform float uStepW;\n' +
  20087. 'uniform float uStepH;\n' +
  20088. 'varying vec2 vTexCoord;\n' +
  20089. 'void main() {\n' +
  20090. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  20091. 'for (float h = 0.0; h < 7.0; h+=1.0) {\n' +
  20092. 'for (float w = 0.0; w < 7.0; w+=1.0) {\n' +
  20093. 'vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n' +
  20094. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n' +
  20095. '}\n' +
  20096. '}\n' +
  20097. 'gl_FragColor = color;\n' +
  20098. '}',
  20099. Convolute_7_0: 'precision highp float;\n' +
  20100. 'uniform sampler2D uTexture;\n' +
  20101. 'uniform float uMatrix[49];\n' +
  20102. 'uniform float uStepW;\n' +
  20103. 'uniform float uStepH;\n' +
  20104. 'varying vec2 vTexCoord;\n' +
  20105. 'void main() {\n' +
  20106. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  20107. 'for (float h = 0.0; h < 7.0; h+=1.0) {\n' +
  20108. 'for (float w = 0.0; w < 7.0; w+=1.0) {\n' +
  20109. 'vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n' +
  20110. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n' +
  20111. '}\n' +
  20112. '}\n' +
  20113. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  20114. 'gl_FragColor = color;\n' +
  20115. 'gl_FragColor.a = alpha;\n' +
  20116. '}',
  20117. Convolute_9_1: 'precision highp float;\n' +
  20118. 'uniform sampler2D uTexture;\n' +
  20119. 'uniform float uMatrix[81];\n' +
  20120. 'uniform float uStepW;\n' +
  20121. 'uniform float uStepH;\n' +
  20122. 'varying vec2 vTexCoord;\n' +
  20123. 'void main() {\n' +
  20124. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  20125. 'for (float h = 0.0; h < 9.0; h+=1.0) {\n' +
  20126. 'for (float w = 0.0; w < 9.0; w+=1.0) {\n' +
  20127. 'vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n' +
  20128. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n' +
  20129. '}\n' +
  20130. '}\n' +
  20131. 'gl_FragColor = color;\n' +
  20132. '}',
  20133. Convolute_9_0: 'precision highp float;\n' +
  20134. 'uniform sampler2D uTexture;\n' +
  20135. 'uniform float uMatrix[81];\n' +
  20136. 'uniform float uStepW;\n' +
  20137. 'uniform float uStepH;\n' +
  20138. 'varying vec2 vTexCoord;\n' +
  20139. 'void main() {\n' +
  20140. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  20141. 'for (float h = 0.0; h < 9.0; h+=1.0) {\n' +
  20142. 'for (float w = 0.0; w < 9.0; w+=1.0) {\n' +
  20143. 'vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n' +
  20144. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n' +
  20145. '}\n' +
  20146. '}\n' +
  20147. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  20148. 'gl_FragColor = color;\n' +
  20149. 'gl_FragColor.a = alpha;\n' +
  20150. '}',
  20151. },
  20152. /**
  20153. * Constructor
  20154. * @memberOf fabric.Image.filters.Convolute.prototype
  20155. * @param {Object} [options] Options object
  20156. * @param {Boolean} [options.opaque=false] Opaque value (true/false)
  20157. * @param {Array} [options.matrix] Filter matrix
  20158. */
  20159. /**
  20160. * Retrieves the cached shader.
  20161. * @param {Object} options
  20162. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  20163. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  20164. */
  20165. retrieveShader: function(options) {
  20166. var size = Math.sqrt(this.matrix.length);
  20167. var cacheKey = this.type + '_' + size + '_' + (this.opaque ? 1 : 0);
  20168. var shaderSource = this.fragmentSource[cacheKey];
  20169. if (!options.programCache.hasOwnProperty(cacheKey)) {
  20170. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  20171. }
  20172. return options.programCache[cacheKey];
  20173. },
  20174. /**
  20175. * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.
  20176. *
  20177. * @param {Object} options
  20178. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  20179. */
  20180. applyTo2d: function(options) {
  20181. var imageData = options.imageData,
  20182. data = imageData.data,
  20183. weights = this.matrix,
  20184. side = Math.round(Math.sqrt(weights.length)),
  20185. halfSide = Math.floor(side / 2),
  20186. sw = imageData.width,
  20187. sh = imageData.height,
  20188. output = options.ctx.createImageData(sw, sh),
  20189. dst = output.data,
  20190. // go through the destination image pixels
  20191. alphaFac = this.opaque ? 1 : 0,
  20192. r, g, b, a, dstOff,
  20193. scx, scy, srcOff, wt,
  20194. x, y, cx, cy;
  20195. for (y = 0; y < sh; y++) {
  20196. for (x = 0; x < sw; x++) {
  20197. dstOff = (y * sw + x) * 4;
  20198. // calculate the weighed sum of the source image pixels that
  20199. // fall under the convolution matrix
  20200. r = 0; g = 0; b = 0; a = 0;
  20201. for (cy = 0; cy < side; cy++) {
  20202. for (cx = 0; cx < side; cx++) {
  20203. scy = y + cy - halfSide;
  20204. scx = x + cx - halfSide;
  20205. // eslint-disable-next-line max-depth
  20206. if (scy < 0 || scy > sh || scx < 0 || scx > sw) {
  20207. continue;
  20208. }
  20209. srcOff = (scy * sw + scx) * 4;
  20210. wt = weights[cy * side + cx];
  20211. r += data[srcOff] * wt;
  20212. g += data[srcOff + 1] * wt;
  20213. b += data[srcOff + 2] * wt;
  20214. // eslint-disable-next-line max-depth
  20215. if (!alphaFac) {
  20216. a += data[srcOff + 3] * wt;
  20217. }
  20218. }
  20219. }
  20220. dst[dstOff] = r;
  20221. dst[dstOff + 1] = g;
  20222. dst[dstOff + 2] = b;
  20223. if (!alphaFac) {
  20224. dst[dstOff + 3] = a;
  20225. }
  20226. else {
  20227. dst[dstOff + 3] = data[dstOff + 3];
  20228. }
  20229. }
  20230. }
  20231. options.imageData = output;
  20232. },
  20233. /**
  20234. * Return WebGL uniform locations for this filter's shader.
  20235. *
  20236. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20237. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20238. */
  20239. getUniformLocations: function(gl, program) {
  20240. return {
  20241. uMatrix: gl.getUniformLocation(program, 'uMatrix'),
  20242. uOpaque: gl.getUniformLocation(program, 'uOpaque'),
  20243. uHalfSize: gl.getUniformLocation(program, 'uHalfSize'),
  20244. uSize: gl.getUniformLocation(program, 'uSize'),
  20245. };
  20246. },
  20247. /**
  20248. * Send data from this filter to its shader program's uniforms.
  20249. *
  20250. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20251. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20252. */
  20253. sendUniformData: function(gl, uniformLocations) {
  20254. gl.uniform1fv(uniformLocations.uMatrix, this.matrix);
  20255. },
  20256. /**
  20257. * Returns object representation of an instance
  20258. * @return {Object} Object representation of an instance
  20259. */
  20260. toObject: function() {
  20261. return extend(this.callSuper('toObject'), {
  20262. opaque: this.opaque,
  20263. matrix: this.matrix
  20264. });
  20265. }
  20266. });
  20267. /**
  20268. * Returns filter instance from an object representation
  20269. * @static
  20270. * @param {Object} object Object to create an instance from
  20271. * @param {function} [callback] to be invoked after filter creation
  20272. * @return {fabric.Image.filters.Convolute} Instance of fabric.Image.filters.Convolute
  20273. */
  20274. fabric.Image.filters.Convolute.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20275. })(typeof exports !== 'undefined' ? exports : this);
  20276. (function(global) {
  20277. 'use strict';
  20278. var fabric = global.fabric || (global.fabric = { }),
  20279. filters = fabric.Image.filters,
  20280. createClass = fabric.util.createClass;
  20281. /**
  20282. * Grayscale image filter class
  20283. * @class fabric.Image.filters.Grayscale
  20284. * @memberOf fabric.Image.filters
  20285. * @extends fabric.Image.filters.BaseFilter
  20286. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20287. * @example
  20288. * var filter = new fabric.Image.filters.Grayscale();
  20289. * object.filters.push(filter);
  20290. * object.applyFilters();
  20291. */
  20292. filters.Grayscale = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Grayscale.prototype */ {
  20293. /**
  20294. * Filter type
  20295. * @param {String} type
  20296. * @default
  20297. */
  20298. type: 'Grayscale',
  20299. fragmentSource: {
  20300. average: 'precision highp float;\n' +
  20301. 'uniform sampler2D uTexture;\n' +
  20302. 'varying vec2 vTexCoord;\n' +
  20303. 'void main() {\n' +
  20304. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  20305. 'float average = (color.r + color.b + color.g) / 3.0;\n' +
  20306. 'gl_FragColor = vec4(average, average, average, color.a);\n' +
  20307. '}',
  20308. lightness: 'precision highp float;\n' +
  20309. 'uniform sampler2D uTexture;\n' +
  20310. 'uniform int uMode;\n' +
  20311. 'varying vec2 vTexCoord;\n' +
  20312. 'void main() {\n' +
  20313. 'vec4 col = texture2D(uTexture, vTexCoord);\n' +
  20314. 'float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\n' +
  20315. 'gl_FragColor = vec4(average, average, average, col.a);\n' +
  20316. '}',
  20317. luminosity: 'precision highp float;\n' +
  20318. 'uniform sampler2D uTexture;\n' +
  20319. 'uniform int uMode;\n' +
  20320. 'varying vec2 vTexCoord;\n' +
  20321. 'void main() {\n' +
  20322. 'vec4 col = texture2D(uTexture, vTexCoord);\n' +
  20323. 'float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\n' +
  20324. 'gl_FragColor = vec4(average, average, average, col.a);\n' +
  20325. '}',
  20326. },
  20327. /**
  20328. * Grayscale mode, between 'average', 'lightness', 'luminosity'
  20329. * @param {String} type
  20330. * @default
  20331. */
  20332. mode: 'average',
  20333. mainParameter: 'mode',
  20334. /**
  20335. * Apply the Grayscale operation to a Uint8Array representing the pixels of an image.
  20336. *
  20337. * @param {Object} options
  20338. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  20339. */
  20340. applyTo2d: function(options) {
  20341. var imageData = options.imageData,
  20342. data = imageData.data, i,
  20343. len = data.length, value,
  20344. mode = this.mode;
  20345. for (i = 0; i < len; i += 4) {
  20346. if (mode === 'average') {
  20347. value = (data[i] + data[i + 1] + data[i + 2]) / 3;
  20348. }
  20349. else if (mode === 'lightness') {
  20350. value = (Math.min(data[i], data[i + 1], data[i + 2]) +
  20351. Math.max(data[i], data[i + 1], data[i + 2])) / 2;
  20352. }
  20353. else if (mode === 'luminosity') {
  20354. value = 0.21 * data[i] + 0.72 * data[i + 1] + 0.07 * data[i + 2];
  20355. }
  20356. data[i] = value;
  20357. data[i + 1] = value;
  20358. data[i + 2] = value;
  20359. }
  20360. },
  20361. /**
  20362. * Retrieves the cached shader.
  20363. * @param {Object} options
  20364. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  20365. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  20366. */
  20367. retrieveShader: function(options) {
  20368. var cacheKey = this.type + '_' + this.mode;
  20369. if (!options.programCache.hasOwnProperty(cacheKey)) {
  20370. var shaderSource = this.fragmentSource[this.mode];
  20371. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  20372. }
  20373. return options.programCache[cacheKey];
  20374. },
  20375. /**
  20376. * Return WebGL uniform locations for this filter's shader.
  20377. *
  20378. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20379. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20380. */
  20381. getUniformLocations: function(gl, program) {
  20382. return {
  20383. uMode: gl.getUniformLocation(program, 'uMode'),
  20384. };
  20385. },
  20386. /**
  20387. * Send data from this filter to its shader program's uniforms.
  20388. *
  20389. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20390. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20391. */
  20392. sendUniformData: function(gl, uniformLocations) {
  20393. // default average mode.
  20394. var mode = 1;
  20395. gl.uniform1i(uniformLocations.uMode, mode);
  20396. },
  20397. });
  20398. /**
  20399. * Returns filter instance from an object representation
  20400. * @static
  20401. * @param {Object} object Object to create an instance from
  20402. * @param {function} [callback] to be invoked after filter creation
  20403. * @return {fabric.Image.filters.Grayscale} Instance of fabric.Image.filters.Grayscale
  20404. */
  20405. fabric.Image.filters.Grayscale.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20406. })(typeof exports !== 'undefined' ? exports : this);
  20407. (function(global) {
  20408. 'use strict';
  20409. var fabric = global.fabric || (global.fabric = { }),
  20410. filters = fabric.Image.filters,
  20411. createClass = fabric.util.createClass;
  20412. /**
  20413. * Invert filter class
  20414. * @class fabric.Image.filters.Invert
  20415. * @memberOf fabric.Image.filters
  20416. * @extends fabric.Image.filters.BaseFilter
  20417. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20418. * @example
  20419. * var filter = new fabric.Image.filters.Invert();
  20420. * object.filters.push(filter);
  20421. * object.applyFilters(canvas.renderAll.bind(canvas));
  20422. */
  20423. filters.Invert = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Invert.prototype */ {
  20424. /**
  20425. * Filter type
  20426. * @param {String} type
  20427. * @default
  20428. */
  20429. type: 'Invert',
  20430. fragmentSource: 'precision highp float;\n' +
  20431. 'uniform sampler2D uTexture;\n' +
  20432. 'uniform int uInvert;\n' +
  20433. 'varying vec2 vTexCoord;\n' +
  20434. 'void main() {\n' +
  20435. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  20436. 'if (uInvert == 1) {\n' +
  20437. 'gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n' +
  20438. '} else {\n' +
  20439. 'gl_FragColor = color;\n' +
  20440. '}\n' +
  20441. '}',
  20442. /**
  20443. * Filter invert. if false, does nothing
  20444. * @param {Boolean} invert
  20445. * @default
  20446. */
  20447. invert: true,
  20448. mainParameter: 'invert',
  20449. /**
  20450. * Apply the Invert operation to a Uint8Array representing the pixels of an image.
  20451. *
  20452. * @param {Object} options
  20453. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  20454. */
  20455. applyTo2d: function(options) {
  20456. if (!this.invert) {
  20457. return;
  20458. }
  20459. var imageData = options.imageData,
  20460. data = imageData.data, i,
  20461. len = data.length;
  20462. for (i = 0; i < len; i += 4) {
  20463. data[i] = 255 - data[i];
  20464. data[i + 1] = 255 - data[i + 1];
  20465. data[i + 2] = 255 - data[i + 2];
  20466. }
  20467. },
  20468. /**
  20469. * Return WebGL uniform locations for this filter's shader.
  20470. *
  20471. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20472. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20473. */
  20474. getUniformLocations: function(gl, program) {
  20475. return {
  20476. uInvert: gl.getUniformLocation(program, 'uInvert'),
  20477. };
  20478. },
  20479. /**
  20480. * Send data from this filter to its shader program's uniforms.
  20481. *
  20482. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20483. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20484. */
  20485. sendUniformData: function(gl, uniformLocations) {
  20486. gl.uniform1i(uniformLocations.uInvert, this.invert);
  20487. },
  20488. });
  20489. /**
  20490. * Returns filter instance from an object representation
  20491. * @static
  20492. * @param {Object} object Object to create an instance from
  20493. * @param {function} [callback] to be invoked after filter creation
  20494. * @return {fabric.Image.filters.Invert} Instance of fabric.Image.filters.Invert
  20495. */
  20496. fabric.Image.filters.Invert.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20497. })(typeof exports !== 'undefined' ? exports : this);
  20498. (function(global) {
  20499. 'use strict';
  20500. var fabric = global.fabric || (global.fabric = { }),
  20501. extend = fabric.util.object.extend,
  20502. filters = fabric.Image.filters,
  20503. createClass = fabric.util.createClass;
  20504. /**
  20505. * Noise filter class
  20506. * @class fabric.Image.filters.Noise
  20507. * @memberOf fabric.Image.filters
  20508. * @extends fabric.Image.filters.BaseFilter
  20509. * @see {@link fabric.Image.filters.Noise#initialize} for constructor definition
  20510. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20511. * @example
  20512. * var filter = new fabric.Image.filters.Noise({
  20513. * noise: 700
  20514. * });
  20515. * object.filters.push(filter);
  20516. * object.applyFilters();
  20517. * canvas.renderAll();
  20518. */
  20519. filters.Noise = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Noise.prototype */ {
  20520. /**
  20521. * Filter type
  20522. * @param {String} type
  20523. * @default
  20524. */
  20525. type: 'Noise',
  20526. /**
  20527. * Fragment source for the noise program
  20528. */
  20529. fragmentSource: 'precision highp float;\n' +
  20530. 'uniform sampler2D uTexture;\n' +
  20531. 'uniform float uStepH;\n' +
  20532. 'uniform float uNoise;\n' +
  20533. 'uniform float uSeed;\n' +
  20534. 'varying vec2 vTexCoord;\n' +
  20535. 'float rand(vec2 co, float seed, float vScale) {\n' +
  20536. 'return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n' +
  20537. '}\n' +
  20538. 'void main() {\n' +
  20539. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  20540. 'color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\n' +
  20541. 'gl_FragColor = color;\n' +
  20542. '}',
  20543. /**
  20544. * Describe the property that is the filter parameter
  20545. * @param {String} m
  20546. * @default
  20547. */
  20548. mainParameter: 'noise',
  20549. /**
  20550. * Noise value, from
  20551. * @param {Number} noise
  20552. * @default
  20553. */
  20554. noise: 0,
  20555. /**
  20556. * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.
  20557. *
  20558. * @param {Object} options
  20559. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  20560. */
  20561. applyTo2d: function(options) {
  20562. if (this.noise === 0) {
  20563. return;
  20564. }
  20565. var imageData = options.imageData,
  20566. data = imageData.data, i, len = data.length,
  20567. noise = this.noise, rand;
  20568. for (i = 0, len = data.length; i < len; i += 4) {
  20569. rand = (0.5 - Math.random()) * noise;
  20570. data[i] += rand;
  20571. data[i + 1] += rand;
  20572. data[i + 2] += rand;
  20573. }
  20574. },
  20575. /**
  20576. * Return WebGL uniform locations for this filter's shader.
  20577. *
  20578. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20579. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20580. */
  20581. getUniformLocations: function(gl, program) {
  20582. return {
  20583. uNoise: gl.getUniformLocation(program, 'uNoise'),
  20584. uSeed: gl.getUniformLocation(program, 'uSeed'),
  20585. };
  20586. },
  20587. /**
  20588. * Send data from this filter to its shader program's uniforms.
  20589. *
  20590. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20591. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20592. */
  20593. sendUniformData: function(gl, uniformLocations) {
  20594. gl.uniform1f(uniformLocations.uNoise, this.noise / 255);
  20595. gl.uniform1f(uniformLocations.uSeed, Math.random());
  20596. },
  20597. /**
  20598. * Returns object representation of an instance
  20599. * @return {Object} Object representation of an instance
  20600. */
  20601. toObject: function() {
  20602. return extend(this.callSuper('toObject'), {
  20603. noise: this.noise
  20604. });
  20605. }
  20606. });
  20607. /**
  20608. * Returns filter instance from an object representation
  20609. * @static
  20610. * @param {Object} object Object to create an instance from
  20611. * @param {Function} [callback] to be invoked after filter creation
  20612. * @return {fabric.Image.filters.Noise} Instance of fabric.Image.filters.Noise
  20613. */
  20614. fabric.Image.filters.Noise.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20615. })(typeof exports !== 'undefined' ? exports : this);
  20616. (function(global) {
  20617. 'use strict';
  20618. var fabric = global.fabric || (global.fabric = { }),
  20619. filters = fabric.Image.filters,
  20620. createClass = fabric.util.createClass;
  20621. /**
  20622. * Pixelate filter class
  20623. * @class fabric.Image.filters.Pixelate
  20624. * @memberOf fabric.Image.filters
  20625. * @extends fabric.Image.filters.BaseFilter
  20626. * @see {@link fabric.Image.filters.Pixelate#initialize} for constructor definition
  20627. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20628. * @example
  20629. * var filter = new fabric.Image.filters.Pixelate({
  20630. * blocksize: 8
  20631. * });
  20632. * object.filters.push(filter);
  20633. * object.applyFilters();
  20634. */
  20635. filters.Pixelate = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Pixelate.prototype */ {
  20636. /**
  20637. * Filter type
  20638. * @param {String} type
  20639. * @default
  20640. */
  20641. type: 'Pixelate',
  20642. blocksize: 4,
  20643. mainParameter: 'blocksize',
  20644. /**
  20645. * Fragment source for the Pixelate program
  20646. */
  20647. fragmentSource: 'precision highp float;\n' +
  20648. 'uniform sampler2D uTexture;\n' +
  20649. 'uniform float uBlocksize;\n' +
  20650. 'uniform float uStepW;\n' +
  20651. 'uniform float uStepH;\n' +
  20652. 'varying vec2 vTexCoord;\n' +
  20653. 'void main() {\n' +
  20654. 'float blockW = uBlocksize * uStepW;\n' +
  20655. 'float blockH = uBlocksize * uStepW;\n' +
  20656. 'int posX = int(vTexCoord.x / blockW);\n' +
  20657. 'int posY = int(vTexCoord.y / blockH);\n' +
  20658. 'float fposX = float(posX);\n' +
  20659. 'float fposY = float(posY);\n' +
  20660. 'vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\n' +
  20661. 'vec4 color = texture2D(uTexture, squareCoords);\n' +
  20662. 'gl_FragColor = color;\n' +
  20663. '}',
  20664. /**
  20665. * Apply the Pixelate operation to a Uint8ClampedArray representing the pixels of an image.
  20666. *
  20667. * @param {Object} options
  20668. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  20669. */
  20670. applyTo2d: function(options) {
  20671. if (this.blocksize === 1) {
  20672. return;
  20673. }
  20674. var imageData = options.imageData,
  20675. data = imageData.data,
  20676. iLen = imageData.height,
  20677. jLen = imageData.width,
  20678. index, i, j, r, g, b, a,
  20679. _i, _j, _iLen, _jLen;
  20680. for (i = 0; i < iLen; i += this.blocksize) {
  20681. for (j = 0; j < jLen; j += this.blocksize) {
  20682. index = (i * 4) * jLen + (j * 4);
  20683. r = data[index];
  20684. g = data[index + 1];
  20685. b = data[index + 2];
  20686. a = data[index + 3];
  20687. _iLen = Math.min(i + this.blocksize, iLen);
  20688. _jLen = Math.min(j + this.blocksize, jLen);
  20689. for (_i = i; _i < _iLen; _i++) {
  20690. for (_j = j; _j < _jLen; _j++) {
  20691. index = (_i * 4) * jLen + (_j * 4);
  20692. data[index] = r;
  20693. data[index + 1] = g;
  20694. data[index + 2] = b;
  20695. data[index + 3] = a;
  20696. }
  20697. }
  20698. }
  20699. }
  20700. },
  20701. /**
  20702. * Indicate when the filter is not gonna apply changes to the image
  20703. **/
  20704. isNeutralState: function() {
  20705. return this.blocksize === 1;
  20706. },
  20707. /**
  20708. * Return WebGL uniform locations for this filter's shader.
  20709. *
  20710. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20711. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20712. */
  20713. getUniformLocations: function(gl, program) {
  20714. return {
  20715. uBlocksize: gl.getUniformLocation(program, 'uBlocksize'),
  20716. uStepW: gl.getUniformLocation(program, 'uStepW'),
  20717. uStepH: gl.getUniformLocation(program, 'uStepH'),
  20718. };
  20719. },
  20720. /**
  20721. * Send data from this filter to its shader program's uniforms.
  20722. *
  20723. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20724. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20725. */
  20726. sendUniformData: function(gl, uniformLocations) {
  20727. gl.uniform1f(uniformLocations.uBlocksize, this.blocksize);
  20728. },
  20729. });
  20730. /**
  20731. * Returns filter instance from an object representation
  20732. * @static
  20733. * @param {Object} object Object to create an instance from
  20734. * @param {Function} [callback] to be invoked after filter creation
  20735. * @return {fabric.Image.filters.Pixelate} Instance of fabric.Image.filters.Pixelate
  20736. */
  20737. fabric.Image.filters.Pixelate.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20738. })(typeof exports !== 'undefined' ? exports : this);
  20739. (function(global) {
  20740. 'use strict';
  20741. var fabric = global.fabric || (global.fabric = { }),
  20742. extend = fabric.util.object.extend,
  20743. filters = fabric.Image.filters,
  20744. createClass = fabric.util.createClass;
  20745. /**
  20746. * Remove white filter class
  20747. * @class fabric.Image.filters.RemoveColor
  20748. * @memberOf fabric.Image.filters
  20749. * @extends fabric.Image.filters.BaseFilter
  20750. * @see {@link fabric.Image.filters.RemoveColor#initialize} for constructor definition
  20751. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20752. * @example
  20753. * var filter = new fabric.Image.filters.RemoveColor({
  20754. * threshold: 0.2,
  20755. * });
  20756. * object.filters.push(filter);
  20757. * object.applyFilters();
  20758. * canvas.renderAll();
  20759. */
  20760. filters.RemoveColor = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.RemoveColor.prototype */ {
  20761. /**
  20762. * Filter type
  20763. * @param {String} type
  20764. * @default
  20765. */
  20766. type: 'RemoveColor',
  20767. /**
  20768. * Color to remove, in any format understood by fabric.Color.
  20769. * @param {String} type
  20770. * @default
  20771. */
  20772. color: '#FFFFFF',
  20773. /**
  20774. * Fragment source for the brightness program
  20775. */
  20776. fragmentSource: 'precision highp float;\n' +
  20777. 'uniform sampler2D uTexture;\n' +
  20778. 'uniform vec4 uLow;\n' +
  20779. 'uniform vec4 uHigh;\n' +
  20780. 'varying vec2 vTexCoord;\n' +
  20781. 'void main() {\n' +
  20782. 'gl_FragColor = texture2D(uTexture, vTexCoord);\n' +
  20783. 'if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\n' +
  20784. 'gl_FragColor.a = 0.0;\n' +
  20785. '}\n' +
  20786. '}',
  20787. /**
  20788. * distance to actual color, as value up or down from each r,g,b
  20789. * between 0 and 1
  20790. **/
  20791. distance: 0.02,
  20792. /**
  20793. * For color to remove inside distance, use alpha channel for a smoother deletion
  20794. * NOT IMPLEMENTED YET
  20795. **/
  20796. useAlpha: false,
  20797. /**
  20798. * Constructor
  20799. * @memberOf fabric.Image.filters.RemoveWhite.prototype
  20800. * @param {Object} [options] Options object
  20801. * @param {Number} [options.color=#RRGGBB] Threshold value
  20802. * @param {Number} [options.distance=10] Distance value
  20803. */
  20804. /**
  20805. * Applies filter to canvas element
  20806. * @param {Object} canvasEl Canvas element to apply filter to
  20807. */
  20808. applyTo2d: function(options) {
  20809. var imageData = options.imageData,
  20810. data = imageData.data, i,
  20811. distance = this.distance * 255,
  20812. r, g, b,
  20813. source = new fabric.Color(this.color).getSource(),
  20814. lowC = [
  20815. source[0] - distance,
  20816. source[1] - distance,
  20817. source[2] - distance,
  20818. ],
  20819. highC = [
  20820. source[0] + distance,
  20821. source[1] + distance,
  20822. source[2] + distance,
  20823. ];
  20824. for (i = 0; i < data.length; i += 4) {
  20825. r = data[i];
  20826. g = data[i + 1];
  20827. b = data[i + 2];
  20828. if (r > lowC[0] &&
  20829. g > lowC[1] &&
  20830. b > lowC[2] &&
  20831. r < highC[0] &&
  20832. g < highC[1] &&
  20833. b < highC[2]) {
  20834. data[i + 3] = 0;
  20835. }
  20836. }
  20837. },
  20838. /**
  20839. * Return WebGL uniform locations for this filter's shader.
  20840. *
  20841. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20842. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20843. */
  20844. getUniformLocations: function(gl, program) {
  20845. return {
  20846. uLow: gl.getUniformLocation(program, 'uLow'),
  20847. uHigh: gl.getUniformLocation(program, 'uHigh'),
  20848. };
  20849. },
  20850. /**
  20851. * Send data from this filter to its shader program's uniforms.
  20852. *
  20853. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20854. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20855. */
  20856. sendUniformData: function(gl, uniformLocations) {
  20857. var source = new fabric.Color(this.color).getSource(),
  20858. distance = parseFloat(this.distance),
  20859. lowC = [
  20860. 0 + source[0] / 255 - distance,
  20861. 0 + source[1] / 255 - distance,
  20862. 0 + source[2] / 255 - distance,
  20863. 1
  20864. ],
  20865. highC = [
  20866. source[0] / 255 + distance,
  20867. source[1] / 255 + distance,
  20868. source[2] / 255 + distance,
  20869. 1
  20870. ];
  20871. gl.uniform4fv(uniformLocations.uLow, lowC);
  20872. gl.uniform4fv(uniformLocations.uHigh, highC);
  20873. },
  20874. /**
  20875. * Returns object representation of an instance
  20876. * @return {Object} Object representation of an instance
  20877. */
  20878. toObject: function() {
  20879. return extend(this.callSuper('toObject'), {
  20880. color: this.color,
  20881. distance: this.distance
  20882. });
  20883. }
  20884. });
  20885. /**
  20886. * Returns filter instance from an object representation
  20887. * @static
  20888. * @param {Object} object Object to create an instance from
  20889. * @param {Function} [callback] to be invoked after filter creation
  20890. * @return {fabric.Image.filters.RemoveColor} Instance of fabric.Image.filters.RemoveWhite
  20891. */
  20892. fabric.Image.filters.RemoveColor.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20893. })(typeof exports !== 'undefined' ? exports : this);
  20894. (function(global) {
  20895. 'use strict';
  20896. var fabric = global.fabric || (global.fabric = { }),
  20897. filters = fabric.Image.filters,
  20898. createClass = fabric.util.createClass;
  20899. var matrices = {
  20900. Brownie: [
  20901. 0.59970,0.34553,-0.27082,0,0.186,
  20902. -0.03770,0.86095,0.15059,0,-0.1449,
  20903. 0.24113,-0.07441,0.44972,0,-0.02965,
  20904. 0,0,0,1,0
  20905. ],
  20906. Vintage: [
  20907. 0.62793,0.32021,-0.03965,0,0.03784,
  20908. 0.02578,0.64411,0.03259,0,0.02926,
  20909. 0.04660,-0.08512,0.52416,0,0.02023,
  20910. 0,0,0,1,0
  20911. ],
  20912. Kodachrome: [
  20913. 1.12855,-0.39673,-0.03992,0,0.24991,
  20914. -0.16404,1.08352,-0.05498,0,0.09698,
  20915. -0.16786,-0.56034,1.60148,0,0.13972,
  20916. 0,0,0,1,0
  20917. ],
  20918. Technicolor: [
  20919. 1.91252,-0.85453,-0.09155,0,0.04624,
  20920. -0.30878,1.76589,-0.10601,0,-0.27589,
  20921. -0.23110,-0.75018,1.84759,0,0.12137,
  20922. 0,0,0,1,0
  20923. ],
  20924. Polaroid: [
  20925. 1.438,-0.062,-0.062,0,0,
  20926. -0.122,1.378,-0.122,0,0,
  20927. -0.016,-0.016,1.483,0,0,
  20928. 0,0,0,1,0
  20929. ],
  20930. Sepia: [
  20931. 0.393, 0.769, 0.189, 0, 0,
  20932. 0.349, 0.686, 0.168, 0, 0,
  20933. 0.272, 0.534, 0.131, 0, 0,
  20934. 0, 0, 0, 1, 0
  20935. ],
  20936. BlackWhite: [
  20937. 1.5, 1.5, 1.5, 0, -1,
  20938. 1.5, 1.5, 1.5, 0, -1,
  20939. 1.5, 1.5, 1.5, 0, -1,
  20940. 0, 0, 0, 1, 0,
  20941. ]
  20942. };
  20943. for (var key in matrices) {
  20944. filters[key] = createClass(filters.ColorMatrix, /** @lends fabric.Image.filters.Sepia.prototype */ {
  20945. /**
  20946. * Filter type
  20947. * @param {String} type
  20948. * @default
  20949. */
  20950. type: key,
  20951. /**
  20952. * Colormatrix for the effect
  20953. * array of 20 floats. Numbers in positions 4, 9, 14, 19 loose meaning
  20954. * outside the -1, 1 range.
  20955. * @param {Array} matrix array of 20 numbers.
  20956. * @default
  20957. */
  20958. matrix: matrices[key],
  20959. /**
  20960. * Lock the matrix export for this kind of static, parameter less filters.
  20961. */
  20962. mainParameter: false,
  20963. /**
  20964. * Lock the colormatrix on the color part, skipping alpha
  20965. */
  20966. colorsOnly: true,
  20967. });
  20968. fabric.Image.filters[key].fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20969. }
  20970. })(typeof exports !== 'undefined' ? exports : this);
  20971. (function(global) {
  20972. 'use strict';
  20973. var fabric = global.fabric,
  20974. filters = fabric.Image.filters,
  20975. createClass = fabric.util.createClass;
  20976. /**
  20977. * Color Blend filter class
  20978. * @class fabric.Image.filter.BlendColor
  20979. * @memberOf fabric.Image.filters
  20980. * @extends fabric.Image.filters.BaseFilter
  20981. * @example
  20982. * var filter = new fabric.Image.filters.BlendColor({
  20983. * color: '#000',
  20984. * mode: 'multiply'
  20985. * });
  20986. *
  20987. * var filter = new fabric.Image.filters.BlendImage({
  20988. * image: fabricImageObject,
  20989. * mode: 'multiply',
  20990. * alpha: 0.5
  20991. * });
  20992. * object.filters.push(filter);
  20993. * object.applyFilters();
  20994. * canvas.renderAll();
  20995. */
  20996. filters.BlendColor = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Blend.prototype */ {
  20997. type: 'BlendColor',
  20998. /**
  20999. * Color to make the blend operation with. default to a reddish color since black or white
  21000. * gives always strong result.
  21001. **/
  21002. color: '#F95C63',
  21003. /**
  21004. * Blend mode for the filter: one of multiply, add, diff, screen, subtract,
  21005. * darken, lighten, overlay, exclusion, tint.
  21006. **/
  21007. mode: 'multiply',
  21008. /**
  21009. * alpha value. represent the strength of the blend color operation.
  21010. **/
  21011. alpha: 1,
  21012. /**
  21013. * Fragment source for the Multiply program
  21014. */
  21015. fragmentSource: {
  21016. multiply: 'gl_FragColor.rgb *= uColor.rgb;\n',
  21017. screen: 'gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n',
  21018. add: 'gl_FragColor.rgb += uColor.rgb;\n',
  21019. diff: 'gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n',
  21020. subtract: 'gl_FragColor.rgb -= uColor.rgb;\n',
  21021. lighten: 'gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n',
  21022. darken: 'gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n',
  21023. exclusion: 'gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n',
  21024. overlay: 'if (uColor.r < 0.5) {\n' +
  21025. 'gl_FragColor.r *= 2.0 * uColor.r;\n' +
  21026. '} else {\n' +
  21027. 'gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n' +
  21028. '}\n' +
  21029. 'if (uColor.g < 0.5) {\n' +
  21030. 'gl_FragColor.g *= 2.0 * uColor.g;\n' +
  21031. '} else {\n' +
  21032. 'gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n' +
  21033. '}\n' +
  21034. 'if (uColor.b < 0.5) {\n' +
  21035. 'gl_FragColor.b *= 2.0 * uColor.b;\n' +
  21036. '} else {\n' +
  21037. 'gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n' +
  21038. '}\n',
  21039. tint: 'gl_FragColor.rgb *= (1.0 - uColor.a);\n' +
  21040. 'gl_FragColor.rgb += uColor.rgb;\n',
  21041. },
  21042. /**
  21043. * build the fragment source for the filters, joining the common part with
  21044. * the specific one.
  21045. * @param {String} mode the mode of the filter, a key of this.fragmentSource
  21046. * @return {String} the source to be compiled
  21047. * @private
  21048. */
  21049. buildSource: function(mode) {
  21050. return 'precision highp float;\n' +
  21051. 'uniform sampler2D uTexture;\n' +
  21052. 'uniform vec4 uColor;\n' +
  21053. 'varying vec2 vTexCoord;\n' +
  21054. 'void main() {\n' +
  21055. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21056. 'gl_FragColor = color;\n' +
  21057. 'if (color.a > 0.0) {\n' +
  21058. this.fragmentSource[mode] +
  21059. '}\n' +
  21060. '}';
  21061. },
  21062. /**
  21063. * Retrieves the cached shader.
  21064. * @param {Object} options
  21065. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21066. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21067. */
  21068. retrieveShader: function(options) {
  21069. var cacheKey = this.type + '_' + this.mode, shaderSource;
  21070. if (!options.programCache.hasOwnProperty(cacheKey)) {
  21071. shaderSource = this.buildSource(this.mode);
  21072. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  21073. }
  21074. return options.programCache[cacheKey];
  21075. },
  21076. /**
  21077. * Apply the Blend operation to a Uint8ClampedArray representing the pixels of an image.
  21078. *
  21079. * @param {Object} options
  21080. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  21081. */
  21082. applyTo2d: function(options) {
  21083. var imageData = options.imageData,
  21084. data = imageData.data, iLen = data.length,
  21085. tr, tg, tb,
  21086. r, g, b,
  21087. source, alpha1 = 1 - this.alpha;
  21088. source = new fabric.Color(this.color).getSource();
  21089. tr = source[0] * this.alpha;
  21090. tg = source[1] * this.alpha;
  21091. tb = source[2] * this.alpha;
  21092. for (var i = 0; i < iLen; i += 4) {
  21093. r = data[i];
  21094. g = data[i + 1];
  21095. b = data[i + 2];
  21096. switch (this.mode) {
  21097. case 'multiply':
  21098. data[i] = r * tr / 255;
  21099. data[i + 1] = g * tg / 255;
  21100. data[i + 2] = b * tb / 255;
  21101. break;
  21102. case 'screen':
  21103. data[i] = 255 - (255 - r) * (255 - tr) / 255;
  21104. data[i + 1] = 255 - (255 - g) * (255 - tg) / 255;
  21105. data[i + 2] = 255 - (255 - b) * (255 - tb) / 255;
  21106. break;
  21107. case 'add':
  21108. data[i] = r + tr;
  21109. data[i + 1] = g + tg;
  21110. data[i + 2] = b + tb;
  21111. break;
  21112. case 'diff':
  21113. case 'difference':
  21114. data[i] = Math.abs(r - tr);
  21115. data[i + 1] = Math.abs(g - tg);
  21116. data[i + 2] = Math.abs(b - tb);
  21117. break;
  21118. case 'subtract':
  21119. data[i] = r - tr;
  21120. data[i + 1] = g - tg;
  21121. data[i + 2] = b - tb;
  21122. break;
  21123. case 'darken':
  21124. data[i] = Math.min(r, tr);
  21125. data[i + 1] = Math.min(g, tg);
  21126. data[i + 2] = Math.min(b, tb);
  21127. break;
  21128. case 'lighten':
  21129. data[i] = Math.max(r, tr);
  21130. data[i + 1] = Math.max(g, tg);
  21131. data[i + 2] = Math.max(b, tb);
  21132. break;
  21133. case 'overlay':
  21134. data[i] = tr < 128 ? (2 * r * tr / 255) : (255 - 2 * (255 - r) * (255 - tr) / 255);
  21135. data[i + 1] = tg < 128 ? (2 * g * tg / 255) : (255 - 2 * (255 - g) * (255 - tg) / 255);
  21136. data[i + 2] = tb < 128 ? (2 * b * tb / 255) : (255 - 2 * (255 - b) * (255 - tb) / 255);
  21137. break;
  21138. case 'exclusion':
  21139. data[i] = tr + r - ((2 * tr * r) / 255);
  21140. data[i + 1] = tg + g - ((2 * tg * g) / 255);
  21141. data[i + 2] = tb + b - ((2 * tb * b) / 255);
  21142. break;
  21143. case 'tint':
  21144. data[i] = tr + r * alpha1;
  21145. data[i + 1] = tg + g * alpha1;
  21146. data[i + 2] = tb + b * alpha1;
  21147. }
  21148. }
  21149. },
  21150. /**
  21151. * Return WebGL uniform locations for this filter's shader.
  21152. *
  21153. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21154. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21155. */
  21156. getUniformLocations: function(gl, program) {
  21157. return {
  21158. uColor: gl.getUniformLocation(program, 'uColor'),
  21159. };
  21160. },
  21161. /**
  21162. * Send data from this filter to its shader program's uniforms.
  21163. *
  21164. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21165. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21166. */
  21167. sendUniformData: function(gl, uniformLocations) {
  21168. var source = new fabric.Color(this.color).getSource();
  21169. source[0] = this.alpha * source[0] / 255;
  21170. source[1] = this.alpha * source[1] / 255;
  21171. source[2] = this.alpha * source[2] / 255;
  21172. source[3] = this.alpha;
  21173. gl.uniform4fv(uniformLocations.uColor, source);
  21174. },
  21175. /**
  21176. * Returns object representation of an instance
  21177. * @return {Object} Object representation of an instance
  21178. */
  21179. toObject: function() {
  21180. return {
  21181. type: this.type,
  21182. color: this.color,
  21183. mode: this.mode,
  21184. alpha: this.alpha
  21185. };
  21186. }
  21187. });
  21188. /**
  21189. * Returns filter instance from an object representation
  21190. * @static
  21191. * @param {Object} object Object to create an instance from
  21192. * @param {function} [callback] to be invoked after filter creation
  21193. * @return {fabric.Image.filters.BlendColor} Instance of fabric.Image.filters.BlendColor
  21194. */
  21195. fabric.Image.filters.BlendColor.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21196. })(typeof exports !== 'undefined' ? exports : this);
  21197. (function(global) {
  21198. 'use strict';
  21199. var fabric = global.fabric,
  21200. filters = fabric.Image.filters,
  21201. createClass = fabric.util.createClass;
  21202. /**
  21203. * Image Blend filter class
  21204. * @class fabric.Image.filter.BlendImage
  21205. * @memberOf fabric.Image.filters
  21206. * @extends fabric.Image.filters.BaseFilter
  21207. * @example
  21208. * var filter = new fabric.Image.filters.BlendColor({
  21209. * color: '#000',
  21210. * mode: 'multiply'
  21211. * });
  21212. *
  21213. * var filter = new fabric.Image.filters.BlendImage({
  21214. * image: fabricImageObject,
  21215. * mode: 'multiply',
  21216. * alpha: 0.5
  21217. * });
  21218. * object.filters.push(filter);
  21219. * object.applyFilters();
  21220. * canvas.renderAll();
  21221. */
  21222. filters.BlendImage = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.BlendImage.prototype */ {
  21223. type: 'BlendImage',
  21224. /**
  21225. * Color to make the blend operation with. default to a reddish color since black or white
  21226. * gives always strong result.
  21227. **/
  21228. image: null,
  21229. /**
  21230. * Blend mode for the filter: one of multiply, add, diff, screen, subtract,
  21231. * darken, lighten, overlay, exclusion, tint.
  21232. **/
  21233. mode: 'multiply',
  21234. /**
  21235. * alpha value. represent the strength of the blend color operation.
  21236. **/
  21237. alpha: 1,
  21238. vertexSource: 'attribute vec2 aPosition;\n' +
  21239. 'varying vec2 vTexCoord;\n' +
  21240. 'varying vec2 vTexCoord2;\n' +
  21241. 'uniform mat3 uTransformMatrix;\n' +
  21242. 'void main() {\n' +
  21243. 'vTexCoord = aPosition;\n' +
  21244. 'vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\n' +
  21245. 'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n' +
  21246. '}',
  21247. /**
  21248. * Fragment source for the Multiply program
  21249. */
  21250. fragmentSource: {
  21251. multiply: 'precision highp float;\n' +
  21252. 'uniform sampler2D uTexture;\n' +
  21253. 'uniform sampler2D uImage;\n' +
  21254. 'uniform vec4 uColor;\n' +
  21255. 'varying vec2 vTexCoord;\n' +
  21256. 'varying vec2 vTexCoord2;\n' +
  21257. 'void main() {\n' +
  21258. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21259. 'vec4 color2 = texture2D(uImage, vTexCoord2);\n' +
  21260. 'color.rgba *= color2.rgba;\n' +
  21261. 'gl_FragColor = color;\n' +
  21262. '}',
  21263. mask: 'precision highp float;\n' +
  21264. 'uniform sampler2D uTexture;\n' +
  21265. 'uniform sampler2D uImage;\n' +
  21266. 'uniform vec4 uColor;\n' +
  21267. 'varying vec2 vTexCoord;\n' +
  21268. 'varying vec2 vTexCoord2;\n' +
  21269. 'void main() {\n' +
  21270. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21271. 'vec4 color2 = texture2D(uImage, vTexCoord2);\n' +
  21272. 'color.a = color2.a;\n' +
  21273. 'gl_FragColor = color;\n' +
  21274. '}',
  21275. },
  21276. /**
  21277. * Retrieves the cached shader.
  21278. * @param {Object} options
  21279. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21280. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21281. */
  21282. retrieveShader: function(options) {
  21283. var cacheKey = this.type + '_' + this.mode;
  21284. var shaderSource = this.fragmentSource[this.mode];
  21285. if (!options.programCache.hasOwnProperty(cacheKey)) {
  21286. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  21287. }
  21288. return options.programCache[cacheKey];
  21289. },
  21290. applyToWebGL: function(options) {
  21291. // load texture to blend.
  21292. var gl = options.context,
  21293. texture = this.createTexture(options.filterBackend, this.image);
  21294. this.bindAdditionalTexture(gl, texture, gl.TEXTURE1);
  21295. this.callSuper('applyToWebGL', options);
  21296. this.unbindAdditionalTexture(gl, gl.TEXTURE1);
  21297. },
  21298. createTexture: function(backend, image) {
  21299. return backend.getCachedTexture(image.cacheKey, image._element);
  21300. },
  21301. /**
  21302. * Calculate a transformMatrix to adapt the image to blend over
  21303. * @param {Object} options
  21304. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21305. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21306. */
  21307. calculateMatrix: function() {
  21308. var image = this.image,
  21309. width = image._element.width,
  21310. height = image._element.height;
  21311. return [
  21312. 1 / image.scaleX, 0, 0,
  21313. 0, 1 / image.scaleY, 0,
  21314. -image.left / width, -image.top / height, 1
  21315. ];
  21316. },
  21317. /**
  21318. * Apply the Blend operation to a Uint8ClampedArray representing the pixels of an image.
  21319. *
  21320. * @param {Object} options
  21321. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  21322. */
  21323. applyTo2d: function(options) {
  21324. var imageData = options.imageData,
  21325. resources = options.filterBackend.resources,
  21326. data = imageData.data, iLen = data.length,
  21327. width = options.imageData.width,
  21328. height = options.imageData.height,
  21329. tr, tg, tb, ta,
  21330. r, g, b, a,
  21331. canvas1, context, image = this.image, blendData;
  21332. if (!resources.blendImage) {
  21333. resources.blendImage = document.createElement('canvas');
  21334. }
  21335. canvas1 = resources.blendImage;
  21336. if (canvas1.width !== width || canvas1.height !== height) {
  21337. canvas1.width = width;
  21338. canvas1.height = height;
  21339. }
  21340. context = canvas1.getContext('2d');
  21341. context.setTransform(image.scaleX, 0, 0, image.scaleY, image.left, image.top);
  21342. context.drawImage(image._element, 0, 0, width, height);
  21343. blendData = context.getImageData(0, 0, width, height).data;
  21344. for (var i = 0; i < iLen; i += 4) {
  21345. r = data[i];
  21346. g = data[i + 1];
  21347. b = data[i + 2];
  21348. a = data[i + 3];
  21349. tr = blendData[i];
  21350. tg = blendData[i + 1];
  21351. tb = blendData[i + 2];
  21352. ta = blendData[i + 3];
  21353. switch (this.mode) {
  21354. case 'multiply':
  21355. data[i] = r * tr / 255;
  21356. data[i + 1] = g * tg / 255;
  21357. data[i + 2] = b * tb / 255;
  21358. data[i + 3] = a * ta / 255;
  21359. break;
  21360. case 'mask':
  21361. data[i + 3] = ta;
  21362. break;
  21363. }
  21364. }
  21365. },
  21366. /**
  21367. * Return WebGL uniform locations for this filter's shader.
  21368. *
  21369. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21370. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21371. */
  21372. getUniformLocations: function(gl, program) {
  21373. return {
  21374. uTransformMatrix: gl.getUniformLocation(program, 'uTransformMatrix'),
  21375. uImage: gl.getUniformLocation(program, 'uImage'),
  21376. };
  21377. },
  21378. /**
  21379. * Send data from this filter to its shader program's uniforms.
  21380. *
  21381. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21382. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21383. */
  21384. sendUniformData: function(gl, uniformLocations) {
  21385. var matrix = this.calculateMatrix();
  21386. gl.uniform1i(uniformLocations.uImage, 1); // texture unit 1.
  21387. gl.uniformMatrix3fv(uniformLocations.uTransformMatrix, false, matrix);
  21388. },
  21389. /**
  21390. * Returns object representation of an instance
  21391. * @return {Object} Object representation of an instance
  21392. */
  21393. toObject: function() {
  21394. return {
  21395. type: this.type,
  21396. image: this.image && this.image.toObject(),
  21397. mode: this.mode,
  21398. alpha: this.alpha
  21399. };
  21400. }
  21401. });
  21402. /**
  21403. * Returns filter instance from an object representation
  21404. * @static
  21405. * @param {Object} object Object to create an instance from
  21406. * @param {function} callback to be invoked after filter creation
  21407. * @return {fabric.Image.filters.BlendImage} Instance of fabric.Image.filters.BlendImage
  21408. */
  21409. fabric.Image.filters.BlendImage.fromObject = function(object, callback) {
  21410. fabric.Image.fromObject(object.image, function(image) {
  21411. var options = fabric.util.object.clone(object);
  21412. options.image = image;
  21413. callback(new fabric.Image.filters.BlendImage(options));
  21414. });
  21415. };
  21416. })(typeof exports !== 'undefined' ? exports : this);
  21417. (function(global) {
  21418. 'use strict';
  21419. var fabric = global.fabric || (global.fabric = { }), pow = Math.pow, floor = Math.floor,
  21420. sqrt = Math.sqrt, abs = Math.abs, round = Math.round, sin = Math.sin,
  21421. ceil = Math.ceil,
  21422. filters = fabric.Image.filters,
  21423. createClass = fabric.util.createClass;
  21424. /**
  21425. * Resize image filter class
  21426. * @class fabric.Image.filters.Resize
  21427. * @memberOf fabric.Image.filters
  21428. * @extends fabric.Image.filters.BaseFilter
  21429. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21430. * @example
  21431. * var filter = new fabric.Image.filters.Resize();
  21432. * object.filters.push(filter);
  21433. * object.applyFilters(canvas.renderAll.bind(canvas));
  21434. */
  21435. filters.Resize = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Resize.prototype */ {
  21436. /**
  21437. * Filter type
  21438. * @param {String} type
  21439. * @default
  21440. */
  21441. type: 'Resize',
  21442. /**
  21443. * Resize type
  21444. * @param {String} resizeType
  21445. * @default
  21446. */
  21447. resizeType: 'hermite',
  21448. /**
  21449. * Scale factor for resizing, x axis
  21450. * @param {Number} scaleX
  21451. * @default
  21452. */
  21453. scaleX: 0,
  21454. /**
  21455. * Scale factor for resizing, y axis
  21456. * @param {Number} scaleY
  21457. * @default
  21458. */
  21459. scaleY: 0,
  21460. /**
  21461. * LanczosLobes parameter for lanczos filter
  21462. * @param {Number} lanczosLobes
  21463. * @default
  21464. */
  21465. lanczosLobes: 3,
  21466. /**
  21467. * Return WebGL uniform locations for this filter's shader.
  21468. *
  21469. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21470. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21471. */
  21472. getUniformLocations: function(gl, program) {
  21473. return {
  21474. uDelta: gl.getUniformLocation(program, 'uDelta'),
  21475. uTaps: gl.getUniformLocation(program, 'uTaps'),
  21476. };
  21477. },
  21478. /**
  21479. * Send data from this filter to its shader program's uniforms.
  21480. *
  21481. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21482. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21483. */
  21484. sendUniformData: function(gl, uniformLocations) {
  21485. gl.uniform2fv(uniformLocations.uDelta, this.horizontal ? [1 / this.width, 0] : [0, 1 / this.height]);
  21486. gl.uniform1fv(uniformLocations.uTaps, this.taps);
  21487. },
  21488. /**
  21489. * Retrieves the cached shader.
  21490. * @param {Object} options
  21491. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21492. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21493. */
  21494. retrieveShader: function(options) {
  21495. var filterWindow = this.getFilterWindow(), cacheKey = this.type + '_' + filterWindow;
  21496. if (!options.programCache.hasOwnProperty(cacheKey)) {
  21497. var fragmentShader = this.generateShader(filterWindow);
  21498. options.programCache[cacheKey] = this.createProgram(options.context, fragmentShader);
  21499. }
  21500. return options.programCache[cacheKey];
  21501. },
  21502. getFilterWindow: function() {
  21503. var scale = this.tempScale;
  21504. return Math.ceil(this.lanczosLobes / scale);
  21505. },
  21506. getTaps: function() {
  21507. var lobeFunction = this.lanczosCreate(this.lanczosLobes), scale = this.tempScale,
  21508. filterWindow = this.getFilterWindow(), taps = new Array(filterWindow);
  21509. for (var i = 1; i <= filterWindow; i++) {
  21510. taps[i - 1] = lobeFunction(i * scale);
  21511. }
  21512. return taps;
  21513. },
  21514. /**
  21515. * Generate vertex and shader sources from the necessary steps numbers
  21516. * @param {Number} filterWindow
  21517. */
  21518. generateShader: function(filterWindow) {
  21519. var offsets = new Array(filterWindow),
  21520. fragmentShader = this.fragmentSourceTOP, filterWindow;
  21521. for (var i = 1; i <= filterWindow; i++) {
  21522. offsets[i - 1] = i + '.0 * uDelta';
  21523. }
  21524. fragmentShader += 'uniform float uTaps[' + filterWindow + '];\n';
  21525. fragmentShader += 'void main() {\n';
  21526. fragmentShader += ' vec4 color = texture2D(uTexture, vTexCoord);\n';
  21527. fragmentShader += ' float sum = 1.0;\n';
  21528. offsets.forEach(function(offset, i) {
  21529. fragmentShader += ' color += texture2D(uTexture, vTexCoord + ' + offset + ') * uTaps[' + i + '];\n';
  21530. fragmentShader += ' color += texture2D(uTexture, vTexCoord - ' + offset + ') * uTaps[' + i + '];\n';
  21531. fragmentShader += ' sum += 2.0 * uTaps[' + i + '];\n';
  21532. });
  21533. fragmentShader += ' gl_FragColor = color / sum;\n';
  21534. fragmentShader += '}';
  21535. return fragmentShader;
  21536. },
  21537. fragmentSourceTOP: 'precision highp float;\n' +
  21538. 'uniform sampler2D uTexture;\n' +
  21539. 'uniform vec2 uDelta;\n' +
  21540. 'varying vec2 vTexCoord;\n',
  21541. /**
  21542. * Apply the resize filter to the image
  21543. * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
  21544. *
  21545. * @param {Object} options
  21546. * @param {Number} options.passes The number of filters remaining to be executed
  21547. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  21548. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  21549. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  21550. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21551. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21552. */
  21553. applyTo: function(options) {
  21554. if (options.webgl) {
  21555. if (options.passes > 1 && this.isNeutralState(options)) {
  21556. // avoid doing something that we do not need
  21557. return;
  21558. }
  21559. options.passes++;
  21560. this.width = options.sourceWidth;
  21561. this.horizontal = true;
  21562. this.dW = Math.round(this.width * this.scaleX);
  21563. this.dH = options.sourceHeight;
  21564. this.tempScale = this.dW / this.width;
  21565. this.taps = this.getTaps();
  21566. options.destinationWidth = this.dW;
  21567. this._setupFrameBuffer(options);
  21568. this.applyToWebGL(options);
  21569. this._swapTextures(options);
  21570. options.sourceWidth = options.destinationWidth;
  21571. this.height = options.sourceHeight;
  21572. this.horizontal = false;
  21573. this.dH = Math.round(this.height * this.scaleY);
  21574. this.tempScale = this.dH / this.height;
  21575. this.taps = this.getTaps();
  21576. options.destinationHeight = this.dH;
  21577. this._setupFrameBuffer(options);
  21578. this.applyToWebGL(options);
  21579. this._swapTextures(options);
  21580. options.sourceHeight = options.destinationHeight;
  21581. }
  21582. else if (!this.isNeutralState(options)) {
  21583. this.applyTo2d(options);
  21584. }
  21585. },
  21586. isNeutralState: function(options) {
  21587. var scaleX = options.scaleX || this.scaleX,
  21588. scaleY = options.scaleY || this.scaleY;
  21589. return scaleX === 1 && scaleY === 1;
  21590. },
  21591. lanczosCreate: function(lobes) {
  21592. return function(x) {
  21593. if (x >= lobes || x <= -lobes) {
  21594. return 0.0;
  21595. }
  21596. if (x < 1.19209290E-07 && x > -1.19209290E-07) {
  21597. return 1.0;
  21598. }
  21599. x *= Math.PI;
  21600. var xx = x / lobes;
  21601. return (sin(x) / x) * sin(xx) / xx;
  21602. };
  21603. },
  21604. /**
  21605. * Applies filter to canvas element
  21606. * @memberOf fabric.Image.filters.Resize.prototype
  21607. * @param {Object} canvasEl Canvas element to apply filter to
  21608. * @param {Number} scaleX
  21609. * @param {Number} scaleY
  21610. */
  21611. applyTo2d: function(options) {
  21612. var imageData = options.imageData,
  21613. scaleX = this.scaleX,
  21614. scaleY = this.scaleY;
  21615. this.rcpScaleX = 1 / scaleX;
  21616. this.rcpScaleY = 1 / scaleY;
  21617. var oW = imageData.width, oH = imageData.height,
  21618. dW = round(oW * scaleX), dH = round(oH * scaleY),
  21619. newData;
  21620. if (this.resizeType === 'sliceHack') {
  21621. newData = this.sliceByTwo(options, oW, oH, dW, dH);
  21622. }
  21623. else if (this.resizeType === 'hermite') {
  21624. newData = this.hermiteFastResize(options, oW, oH, dW, dH);
  21625. }
  21626. else if (this.resizeType === 'bilinear') {
  21627. newData = this.bilinearFiltering(options, oW, oH, dW, dH);
  21628. }
  21629. else if (this.resizeType === 'lanczos') {
  21630. newData = this.lanczosResize(options, oW, oH, dW, dH);
  21631. }
  21632. options.imageData = newData;
  21633. },
  21634. /**
  21635. * Filter sliceByTwo
  21636. * @param {Object} canvasEl Canvas element to apply filter to
  21637. * @param {Number} oW Original Width
  21638. * @param {Number} oH Original Height
  21639. * @param {Number} dW Destination Width
  21640. * @param {Number} dH Destination Height
  21641. * @returns {ImageData}
  21642. */
  21643. sliceByTwo: function(options, oW, oH, dW, dH) {
  21644. var imageData = options.imageData,
  21645. mult = 0.5, doneW = false, doneH = false, stepW = oW * mult,
  21646. stepH = oH * mult, resources = fabric.filterBackend.resources,
  21647. tmpCanvas, ctx, sX = 0, sY = 0, dX = oW, dY = 0;
  21648. if (!resources.sliceByTwo) {
  21649. resources.sliceByTwo = document.createElement('canvas');
  21650. }
  21651. tmpCanvas = resources.sliceByTwo;
  21652. if (tmpCanvas.width < oW * 1.5 || tmpCanvas.height < oH) {
  21653. tmpCanvas.width = oW * 1.5;
  21654. tmpCanvas.height = oH;
  21655. }
  21656. ctx = tmpCanvas.getContext('2d');
  21657. ctx.clearRect(0, 0, oW * 1.5, oH);
  21658. ctx.putImageData(imageData, 0, 0);
  21659. dW = floor(dW);
  21660. dH = floor(dH);
  21661. while (!doneW || !doneH) {
  21662. oW = stepW;
  21663. oH = stepH;
  21664. if (dW < floor(stepW * mult)) {
  21665. stepW = floor(stepW * mult);
  21666. }
  21667. else {
  21668. stepW = dW;
  21669. doneW = true;
  21670. }
  21671. if (dH < floor(stepH * mult)) {
  21672. stepH = floor(stepH * mult);
  21673. }
  21674. else {
  21675. stepH = dH;
  21676. doneH = true;
  21677. }
  21678. ctx.drawImage(tmpCanvas, sX, sY, oW, oH, dX, dY, stepW, stepH);
  21679. sX = dX;
  21680. sY = dY;
  21681. dY += stepH;
  21682. }
  21683. return ctx.getImageData(sX, sY, dW, dH);
  21684. },
  21685. /**
  21686. * Filter lanczosResize
  21687. * @param {Object} canvasEl Canvas element to apply filter to
  21688. * @param {Number} oW Original Width
  21689. * @param {Number} oH Original Height
  21690. * @param {Number} dW Destination Width
  21691. * @param {Number} dH Destination Height
  21692. * @returns {ImageData}
  21693. */
  21694. lanczosResize: function(options, oW, oH, dW, dH) {
  21695. function process(u) {
  21696. var v, i, weight, idx, a, red, green,
  21697. blue, alpha, fX, fY;
  21698. center.x = (u + 0.5) * ratioX;
  21699. icenter.x = floor(center.x);
  21700. for (v = 0; v < dH; v++) {
  21701. center.y = (v + 0.5) * ratioY;
  21702. icenter.y = floor(center.y);
  21703. a = 0; red = 0; green = 0; blue = 0; alpha = 0;
  21704. for (i = icenter.x - range2X; i <= icenter.x + range2X; i++) {
  21705. if (i < 0 || i >= oW) {
  21706. continue;
  21707. }
  21708. fX = floor(1000 * abs(i - center.x));
  21709. if (!cacheLanc[fX]) {
  21710. cacheLanc[fX] = { };
  21711. }
  21712. for (var j = icenter.y - range2Y; j <= icenter.y + range2Y; j++) {
  21713. if (j < 0 || j >= oH) {
  21714. continue;
  21715. }
  21716. fY = floor(1000 * abs(j - center.y));
  21717. if (!cacheLanc[fX][fY]) {
  21718. cacheLanc[fX][fY] = lanczos(sqrt(pow(fX * rcpRatioX, 2) + pow(fY * rcpRatioY, 2)) / 1000);
  21719. }
  21720. weight = cacheLanc[fX][fY];
  21721. if (weight > 0) {
  21722. idx = (j * oW + i) * 4;
  21723. a += weight;
  21724. red += weight * srcData[idx];
  21725. green += weight * srcData[idx + 1];
  21726. blue += weight * srcData[idx + 2];
  21727. alpha += weight * srcData[idx + 3];
  21728. }
  21729. }
  21730. }
  21731. idx = (v * dW + u) * 4;
  21732. destData[idx] = red / a;
  21733. destData[idx + 1] = green / a;
  21734. destData[idx + 2] = blue / a;
  21735. destData[idx + 3] = alpha / a;
  21736. }
  21737. if (++u < dW) {
  21738. return process(u);
  21739. }
  21740. else {
  21741. return destImg;
  21742. }
  21743. }
  21744. var srcData = options.imageData.data,
  21745. destImg = options.ctx.createImageData(dW, dH),
  21746. destData = destImg.data,
  21747. lanczos = this.lanczosCreate(this.lanczosLobes),
  21748. ratioX = this.rcpScaleX, ratioY = this.rcpScaleY,
  21749. rcpRatioX = 2 / this.rcpScaleX, rcpRatioY = 2 / this.rcpScaleY,
  21750. range2X = ceil(ratioX * this.lanczosLobes / 2),
  21751. range2Y = ceil(ratioY * this.lanczosLobes / 2),
  21752. cacheLanc = { }, center = { }, icenter = { };
  21753. return process(0);
  21754. },
  21755. /**
  21756. * bilinearFiltering
  21757. * @param {Object} canvasEl Canvas element to apply filter to
  21758. * @param {Number} oW Original Width
  21759. * @param {Number} oH Original Height
  21760. * @param {Number} dW Destination Width
  21761. * @param {Number} dH Destination Height
  21762. * @returns {ImageData}
  21763. */
  21764. bilinearFiltering: function(options, oW, oH, dW, dH) {
  21765. var a, b, c, d, x, y, i, j, xDiff, yDiff, chnl,
  21766. color, offset = 0, origPix, ratioX = this.rcpScaleX,
  21767. ratioY = this.rcpScaleY,
  21768. w4 = 4 * (oW - 1), img = options.imageData,
  21769. pixels = img.data, destImage = options.ctx.createImageData(dW, dH),
  21770. destPixels = destImage.data;
  21771. for (i = 0; i < dH; i++) {
  21772. for (j = 0; j < dW; j++) {
  21773. x = floor(ratioX * j);
  21774. y = floor(ratioY * i);
  21775. xDiff = ratioX * j - x;
  21776. yDiff = ratioY * i - y;
  21777. origPix = 4 * (y * oW + x);
  21778. for (chnl = 0; chnl < 4; chnl++) {
  21779. a = pixels[origPix + chnl];
  21780. b = pixels[origPix + 4 + chnl];
  21781. c = pixels[origPix + w4 + chnl];
  21782. d = pixels[origPix + w4 + 4 + chnl];
  21783. color = a * (1 - xDiff) * (1 - yDiff) + b * xDiff * (1 - yDiff) +
  21784. c * yDiff * (1 - xDiff) + d * xDiff * yDiff;
  21785. destPixels[offset++] = color;
  21786. }
  21787. }
  21788. }
  21789. return destImage;
  21790. },
  21791. /**
  21792. * hermiteFastResize
  21793. * @param {Object} canvasEl Canvas element to apply filter to
  21794. * @param {Number} oW Original Width
  21795. * @param {Number} oH Original Height
  21796. * @param {Number} dW Destination Width
  21797. * @param {Number} dH Destination Height
  21798. * @returns {ImageData}
  21799. */
  21800. hermiteFastResize: function(options, oW, oH, dW, dH) {
  21801. var ratioW = this.rcpScaleX, ratioH = this.rcpScaleY,
  21802. ratioWHalf = ceil(ratioW / 2),
  21803. ratioHHalf = ceil(ratioH / 2),
  21804. img = options.imageData, data = img.data,
  21805. img2 = options.ctx.createImageData(dW, dH), data2 = img2.data;
  21806. for (var j = 0; j < dH; j++) {
  21807. for (var i = 0; i < dW; i++) {
  21808. var x2 = (i + j * dW) * 4, weight = 0, weights = 0, weightsAlpha = 0,
  21809. gxR = 0, gxG = 0, gxB = 0, gxA = 0, centerY = (j + 0.5) * ratioH;
  21810. for (var yy = floor(j * ratioH); yy < (j + 1) * ratioH; yy++) {
  21811. var dy = abs(centerY - (yy + 0.5)) / ratioHHalf,
  21812. centerX = (i + 0.5) * ratioW, w0 = dy * dy;
  21813. for (var xx = floor(i * ratioW); xx < (i + 1) * ratioW; xx++) {
  21814. var dx = abs(centerX - (xx + 0.5)) / ratioWHalf,
  21815. w = sqrt(w0 + dx * dx);
  21816. /* eslint-disable max-depth */
  21817. if (w > 1 && w < -1) {
  21818. continue;
  21819. }
  21820. //hermite filter
  21821. weight = 2 * w * w * w - 3 * w * w + 1;
  21822. if (weight > 0) {
  21823. dx = 4 * (xx + yy * oW);
  21824. //alpha
  21825. gxA += weight * data[dx + 3];
  21826. weightsAlpha += weight;
  21827. //colors
  21828. if (data[dx + 3] < 255) {
  21829. weight = weight * data[dx + 3] / 250;
  21830. }
  21831. gxR += weight * data[dx];
  21832. gxG += weight * data[dx + 1];
  21833. gxB += weight * data[dx + 2];
  21834. weights += weight;
  21835. }
  21836. /* eslint-enable max-depth */
  21837. }
  21838. }
  21839. data2[x2] = gxR / weights;
  21840. data2[x2 + 1] = gxG / weights;
  21841. data2[x2 + 2] = gxB / weights;
  21842. data2[x2 + 3] = gxA / weightsAlpha;
  21843. }
  21844. }
  21845. return img2;
  21846. },
  21847. /**
  21848. * Returns object representation of an instance
  21849. * @return {Object} Object representation of an instance
  21850. */
  21851. toObject: function() {
  21852. return {
  21853. type: this.type,
  21854. scaleX: this.scaleX,
  21855. scaleY: this.scaleY,
  21856. resizeType: this.resizeType,
  21857. lanczosLobes: this.lanczosLobes
  21858. };
  21859. }
  21860. });
  21861. /**
  21862. * Returns filter instance from an object representation
  21863. * @static
  21864. * @param {Object} object Object to create an instance from
  21865. * @param {Function} [callback] to be invoked after filter creation
  21866. * @return {fabric.Image.filters.Resize} Instance of fabric.Image.filters.Resize
  21867. */
  21868. fabric.Image.filters.Resize.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21869. })(typeof exports !== 'undefined' ? exports : this);
  21870. (function(global) {
  21871. 'use strict';
  21872. var fabric = global.fabric || (global.fabric = { }),
  21873. filters = fabric.Image.filters,
  21874. createClass = fabric.util.createClass;
  21875. /**
  21876. * Contrast filter class
  21877. * @class fabric.Image.filters.Contrast
  21878. * @memberOf fabric.Image.filters
  21879. * @extends fabric.Image.filters.BaseFilter
  21880. * @see {@link fabric.Image.filters.Contrast#initialize} for constructor definition
  21881. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21882. * @example
  21883. * var filter = new fabric.Image.filters.Contrast({
  21884. * contrast: 40
  21885. * });
  21886. * object.filters.push(filter);
  21887. * object.applyFilters();
  21888. */
  21889. filters.Contrast = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Contrast.prototype */ {
  21890. /**
  21891. * Filter type
  21892. * @param {String} type
  21893. * @default
  21894. */
  21895. type: 'Contrast',
  21896. fragmentSource: 'precision highp float;\n' +
  21897. 'uniform sampler2D uTexture;\n' +
  21898. 'uniform float uContrast;\n' +
  21899. 'varying vec2 vTexCoord;\n' +
  21900. 'void main() {\n' +
  21901. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21902. 'float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\n' +
  21903. 'color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\n' +
  21904. 'gl_FragColor = color;\n' +
  21905. '}',
  21906. contrast: 0,
  21907. mainParameter: 'contrast',
  21908. /**
  21909. * Constructor
  21910. * @memberOf fabric.Image.filters.Contrast.prototype
  21911. * @param {Object} [options] Options object
  21912. * @param {Number} [options.contrast=0] Value to contrast the image up (-1...1)
  21913. */
  21914. /**
  21915. * Apply the Contrast operation to a Uint8Array representing the pixels of an image.
  21916. *
  21917. * @param {Object} options
  21918. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  21919. */
  21920. applyTo2d: function(options) {
  21921. if (this.contrast === 0) {
  21922. return;
  21923. }
  21924. var imageData = options.imageData, i, len,
  21925. data = imageData.data, len = data.length,
  21926. contrast = Math.floor(this.contrast * 255),
  21927. contrastF = 259 * (contrast + 255) / (255 * (259 - contrast));
  21928. for (i = 0; i < len; i += 4) {
  21929. data[i] = contrastF * (data[i] - 128) + 128;
  21930. data[i + 1] = contrastF * (data[i + 1] - 128) + 128;
  21931. data[i + 2] = contrastF * (data[i + 2] - 128) + 128;
  21932. }
  21933. },
  21934. /**
  21935. * Return WebGL uniform locations for this filter's shader.
  21936. *
  21937. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21938. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21939. */
  21940. getUniformLocations: function(gl, program) {
  21941. return {
  21942. uContrast: gl.getUniformLocation(program, 'uContrast'),
  21943. };
  21944. },
  21945. /**
  21946. * Send data from this filter to its shader program's uniforms.
  21947. *
  21948. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21949. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21950. */
  21951. sendUniformData: function(gl, uniformLocations) {
  21952. gl.uniform1f(uniformLocations.uContrast, this.contrast);
  21953. },
  21954. });
  21955. /**
  21956. * Returns filter instance from an object representation
  21957. * @static
  21958. * @param {Object} object Object to create an instance from
  21959. * @param {function} [callback] to be invoked after filter creation
  21960. * @return {fabric.Image.filters.Contrast} Instance of fabric.Image.filters.Contrast
  21961. */
  21962. fabric.Image.filters.Contrast.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21963. })(typeof exports !== 'undefined' ? exports : this);
  21964. (function(global) {
  21965. 'use strict';
  21966. var fabric = global.fabric || (global.fabric = { }),
  21967. filters = fabric.Image.filters,
  21968. createClass = fabric.util.createClass;
  21969. /**
  21970. * Saturate filter class
  21971. * @class fabric.Image.filters.Saturation
  21972. * @memberOf fabric.Image.filters
  21973. * @extends fabric.Image.filters.BaseFilter
  21974. * @see {@link fabric.Image.filters.Saturation#initialize} for constructor definition
  21975. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21976. * @example
  21977. * var filter = new fabric.Image.filters.Saturation({
  21978. * saturation: 100
  21979. * });
  21980. * object.filters.push(filter);
  21981. * object.applyFilters();
  21982. */
  21983. filters.Saturation = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Saturation.prototype */ {
  21984. /**
  21985. * Filter type
  21986. * @param {String} type
  21987. * @default
  21988. */
  21989. type: 'Saturation',
  21990. fragmentSource: 'precision highp float;\n' +
  21991. 'uniform sampler2D uTexture;\n' +
  21992. 'uniform float uSaturation;\n' +
  21993. 'varying vec2 vTexCoord;\n' +
  21994. 'void main() {\n' +
  21995. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21996. 'float rgMax = max(color.r, color.g);\n' +
  21997. 'float rgbMax = max(rgMax, color.b);\n' +
  21998. 'color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\n' +
  21999. 'color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\n' +
  22000. 'color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\n' +
  22001. 'gl_FragColor = color;\n' +
  22002. '}',
  22003. saturation: 0,
  22004. mainParameter: 'saturation',
  22005. /**
  22006. * Constructor
  22007. * @memberOf fabric.Image.filters.Saturate.prototype
  22008. * @param {Object} [options] Options object
  22009. * @param {Number} [options.saturate=0] Value to saturate the image (-1...1)
  22010. */
  22011. /**
  22012. * Apply the Saturation operation to a Uint8ClampedArray representing the pixels of an image.
  22013. *
  22014. * @param {Object} options
  22015. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  22016. */
  22017. applyTo2d: function(options) {
  22018. if (this.saturation === 0) {
  22019. return;
  22020. }
  22021. var imageData = options.imageData,
  22022. data = imageData.data, len = data.length,
  22023. adjust = -this.saturation, i, max;
  22024. for (i = 0; i < len; i += 4) {
  22025. max = Math.max(data[i], data[i + 1], data[i + 2]);
  22026. data[i] += max !== data[i] ? (max - data[i]) * adjust : 0;
  22027. data[i + 1] += max !== data[i + 1] ? (max - data[i + 1]) * adjust : 0;
  22028. data[i + 2] += max !== data[i + 2] ? (max - data[i + 2]) * adjust : 0;
  22029. }
  22030. },
  22031. /**
  22032. * Return WebGL uniform locations for this filter's shader.
  22033. *
  22034. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22035. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22036. */
  22037. getUniformLocations: function(gl, program) {
  22038. return {
  22039. uSaturation: gl.getUniformLocation(program, 'uSaturation'),
  22040. };
  22041. },
  22042. /**
  22043. * Send data from this filter to its shader program's uniforms.
  22044. *
  22045. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22046. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  22047. */
  22048. sendUniformData: function(gl, uniformLocations) {
  22049. gl.uniform1f(uniformLocations.uSaturation, -this.saturation);
  22050. },
  22051. });
  22052. /**
  22053. * Returns filter instance from an object representation
  22054. * @static
  22055. * @param {Object} object Object to create an instance from
  22056. * @param {Function} [callback] to be invoked after filter creation
  22057. * @return {fabric.Image.filters.Saturation} Instance of fabric.Image.filters.Saturate
  22058. */
  22059. fabric.Image.filters.Saturation.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22060. })(typeof exports !== 'undefined' ? exports : this);
  22061. (function(global) {
  22062. 'use strict';
  22063. var fabric = global.fabric || (global.fabric = { }),
  22064. filters = fabric.Image.filters,
  22065. createClass = fabric.util.createClass;
  22066. /**
  22067. * Blur filter class
  22068. * @class fabric.Image.filters.Blur
  22069. * @memberOf fabric.Image.filters
  22070. * @extends fabric.Image.filters.BaseFilter
  22071. * @see {@link fabric.Image.filters.Blur#initialize} for constructor definition
  22072. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  22073. * @example
  22074. * var filter = new fabric.Image.filters.Blur({
  22075. * blur: 0.5
  22076. * });
  22077. * object.filters.push(filter);
  22078. * object.applyFilters();
  22079. * canvas.renderAll();
  22080. */
  22081. filters.Blur = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Blur.prototype */ {
  22082. type: 'Blur',
  22083. /*
  22084. 'gl_FragColor = vec4(0.0);',
  22085. 'gl_FragColor += texture2D(texture, vTexCoord + -7 * uDelta)*0.0044299121055113265;',
  22086. 'gl_FragColor += texture2D(texture, vTexCoord + -6 * uDelta)*0.00895781211794;',
  22087. 'gl_FragColor += texture2D(texture, vTexCoord + -5 * uDelta)*0.0215963866053;',
  22088. 'gl_FragColor += texture2D(texture, vTexCoord + -4 * uDelta)*0.0443683338718;',
  22089. 'gl_FragColor += texture2D(texture, vTexCoord + -3 * uDelta)*0.0776744219933;',
  22090. 'gl_FragColor += texture2D(texture, vTexCoord + -2 * uDelta)*0.115876621105;',
  22091. 'gl_FragColor += texture2D(texture, vTexCoord + -1 * uDelta)*0.147308056121;',
  22092. 'gl_FragColor += texture2D(texture, vTexCoord )*0.159576912161;',
  22093. 'gl_FragColor += texture2D(texture, vTexCoord + 1 * uDelta)*0.147308056121;',
  22094. 'gl_FragColor += texture2D(texture, vTexCoord + 2 * uDelta)*0.115876621105;',
  22095. 'gl_FragColor += texture2D(texture, vTexCoord + 3 * uDelta)*0.0776744219933;',
  22096. 'gl_FragColor += texture2D(texture, vTexCoord + 4 * uDelta)*0.0443683338718;',
  22097. 'gl_FragColor += texture2D(texture, vTexCoord + 5 * uDelta)*0.0215963866053;',
  22098. 'gl_FragColor += texture2D(texture, vTexCoord + 6 * uDelta)*0.00895781211794;',
  22099. 'gl_FragColor += texture2D(texture, vTexCoord + 7 * uDelta)*0.0044299121055113265;',
  22100. */
  22101. /* eslint-disable max-len */
  22102. fragmentSource: 'precision highp float;\n' +
  22103. 'uniform sampler2D uTexture;\n' +
  22104. 'uniform vec2 uDelta;\n' +
  22105. 'varying vec2 vTexCoord;\n' +
  22106. 'const float nSamples = 15.0;\n' +
  22107. 'vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\n' +
  22108. 'float random(vec3 scale) {\n' +
  22109. /* use the fragment position for a different seed per-pixel */
  22110. 'return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n' +
  22111. '}\n' +
  22112. 'void main() {\n' +
  22113. 'vec4 color = vec4(0.0);\n' +
  22114. 'float total = 0.0;\n' +
  22115. 'float offset = random(v3offset);\n' +
  22116. 'for (float t = -nSamples; t <= nSamples; t++) {\n' +
  22117. 'float percent = (t + offset - 0.5) / nSamples;\n' +
  22118. 'float weight = 1.0 - abs(percent);\n' +
  22119. 'color += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\n' +
  22120. 'total += weight;\n' +
  22121. '}\n' +
  22122. 'gl_FragColor = color / total;\n' +
  22123. '}',
  22124. /* eslint-enable max-len */
  22125. /**
  22126. * blur value, in percentage of image dimensions.
  22127. * specific to keep the image blur constant at different resolutions
  22128. * range bewteen 0 and 1.
  22129. */
  22130. blur: 0,
  22131. mainParameter: 'blur',
  22132. applyTo: function(options) {
  22133. if (options.webgl) {
  22134. // this aspectRatio is used to give the same blur to vertical and horizontal
  22135. this.aspectRatio = options.sourceWidth / options.sourceHeight;
  22136. options.passes++;
  22137. this._setupFrameBuffer(options);
  22138. this.horizontal = true;
  22139. this.applyToWebGL(options);
  22140. this._swapTextures(options);
  22141. this._setupFrameBuffer(options);
  22142. this.horizontal = false;
  22143. this.applyToWebGL(options);
  22144. this._swapTextures(options);
  22145. }
  22146. else {
  22147. this.applyTo2d(options);
  22148. }
  22149. },
  22150. applyTo2d: function(options) {
  22151. // paint canvasEl with current image data.
  22152. //options.ctx.putImageData(options.imageData, 0, 0);
  22153. options.imageData = this.simpleBlur(options);
  22154. },
  22155. simpleBlur: function(options) {
  22156. var resources = options.filterBackend.resources, canvas1, canvas2,
  22157. width = options.imageData.width,
  22158. height = options.imageData.height;
  22159. if (!resources.blurLayer1) {
  22160. resources.blurLayer1 = fabric.util.createCanvasElement();
  22161. resources.blurLayer2 = fabric.util.createCanvasElement();
  22162. }
  22163. canvas1 = resources.blurLayer1;
  22164. canvas2 = resources.blurLayer2;
  22165. if (canvas1.width !== width || canvas1.height !== height) {
  22166. canvas2.width = canvas1.width = width;
  22167. canvas2.height = canvas1.height = height;
  22168. }
  22169. var ctx1 = canvas1.getContext('2d'),
  22170. ctx2 = canvas2.getContext('2d'),
  22171. nSamples = 15,
  22172. random, percent, j, i,
  22173. blur = this.blur * 0.06 * 0.5;
  22174. // load first canvas
  22175. ctx1.putImageData(options.imageData, 0, 0);
  22176. ctx2.clearRect(0, 0, width, height);
  22177. for (i = -nSamples; i <= nSamples; i++) {
  22178. random = (Math.random() - 0.5) / 4;
  22179. percent = i / nSamples;
  22180. j = blur * percent * width + random;
  22181. ctx2.globalAlpha = 1 - Math.abs(percent);
  22182. ctx2.drawImage(canvas1, j, random);
  22183. ctx1.drawImage(canvas2, 0, 0);
  22184. ctx2.globalAlpha = 1;
  22185. ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  22186. }
  22187. for (i = -nSamples; i <= nSamples; i++) {
  22188. random = (Math.random() - 0.5) / 4;
  22189. percent = i / nSamples;
  22190. j = blur * percent * height + random;
  22191. ctx2.globalAlpha = 1 - Math.abs(percent);
  22192. ctx2.drawImage(canvas1, random, j);
  22193. ctx1.drawImage(canvas2, 0, 0);
  22194. ctx2.globalAlpha = 1;
  22195. ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  22196. }
  22197. options.ctx.drawImage(canvas1, 0, 0);
  22198. var newImageData = options.ctx.getImageData(0, 0, canvas1.width, canvas1.height);
  22199. ctx1.globalAlpha = 1;
  22200. ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
  22201. return newImageData;
  22202. },
  22203. /**
  22204. * Return WebGL uniform locations for this filter's shader.
  22205. *
  22206. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22207. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22208. */
  22209. getUniformLocations: function(gl, program) {
  22210. return {
  22211. delta: gl.getUniformLocation(program, 'uDelta'),
  22212. };
  22213. },
  22214. /**
  22215. * Send data from this filter to its shader program's uniforms.
  22216. *
  22217. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22218. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  22219. */
  22220. sendUniformData: function(gl, uniformLocations) {
  22221. var delta = this.chooseRightDelta();
  22222. gl.uniform2fv(uniformLocations.delta, delta);
  22223. },
  22224. /**
  22225. * choose right value of image percentage to blur with
  22226. * @returns {Array} a numeric array with delta values
  22227. */
  22228. chooseRightDelta: function() {
  22229. var blurScale = 1, delta = [0, 0], blur;
  22230. if (this.horizontal) {
  22231. if (this.aspectRatio > 1) {
  22232. // image is wide, i want to shrink radius horizontal
  22233. blurScale = 1 / this.aspectRatio;
  22234. }
  22235. }
  22236. else {
  22237. if (this.aspectRatio < 1) {
  22238. // image is tall, i want to shrink radius vertical
  22239. blurScale = this.aspectRatio;
  22240. }
  22241. }
  22242. blur = blurScale * this.blur * 0.12;
  22243. if (this.horizontal) {
  22244. delta[0] = blur;
  22245. }
  22246. else {
  22247. delta[1] = blur;
  22248. }
  22249. return delta;
  22250. },
  22251. });
  22252. /**
  22253. * Deserialize a JSON definition of a BlurFilter into a concrete instance.
  22254. */
  22255. filters.Blur.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22256. })(typeof exports !== 'undefined' ? exports : this);
  22257. (function(global) {
  22258. 'use strict';
  22259. var fabric = global.fabric || (global.fabric = { }),
  22260. filters = fabric.Image.filters,
  22261. createClass = fabric.util.createClass;
  22262. /**
  22263. * Gamma filter class
  22264. * @class fabric.Image.filters.Gamma
  22265. * @memberOf fabric.Image.filters
  22266. * @extends fabric.Image.filters.BaseFilter
  22267. * @see {@link fabric.Image.filters.Gamma#initialize} for constructor definition
  22268. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  22269. * @example
  22270. * var filter = new fabric.Image.filters.Gamma({
  22271. * brightness: 200
  22272. * });
  22273. * object.filters.push(filter);
  22274. * object.applyFilters();
  22275. */
  22276. filters.Gamma = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Gamma.prototype */ {
  22277. /**
  22278. * Filter type
  22279. * @param {String} type
  22280. * @default
  22281. */
  22282. type: 'Gamma',
  22283. fragmentSource: 'precision highp float;\n' +
  22284. 'uniform sampler2D uTexture;\n' +
  22285. 'uniform vec3 uGamma;\n' +
  22286. 'varying vec2 vTexCoord;\n' +
  22287. 'void main() {\n' +
  22288. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  22289. 'vec3 correction = (1.0 / uGamma);\n' +
  22290. 'color.r = pow(color.r, correction.r);\n' +
  22291. 'color.g = pow(color.g, correction.g);\n' +
  22292. 'color.b = pow(color.b, correction.b);\n' +
  22293. 'gl_FragColor = color;\n' +
  22294. 'gl_FragColor.rgb *= color.a;\n' +
  22295. '}',
  22296. /**
  22297. * Gamma array value, from 0.01 to 2.2.
  22298. * @param {Array} gamma
  22299. * @default
  22300. */
  22301. gamma: [1, 1, 1],
  22302. /**
  22303. * Describe the property that is the filter parameter
  22304. * @param {String} m
  22305. * @default
  22306. */
  22307. mainParameter: 'gamma',
  22308. /**
  22309. * Apply the Gamma operation to a Uint8Array representing the pixels of an image.
  22310. *
  22311. * @param {Object} options
  22312. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  22313. */
  22314. applyTo2d: function(options) {
  22315. var imageData = options.imageData, data = imageData.data,
  22316. gamma = this.gamma, len = data.length,
  22317. rInv = 1 / gamma[0], gInv = 1 / gamma[1],
  22318. bInv = 1 / gamma[2], i;
  22319. if (!this.rVals) {
  22320. // eslint-disable-next-line
  22321. this.rVals = new Uint8Array(256);
  22322. // eslint-disable-next-line
  22323. this.gVals = new Uint8Array(256);
  22324. // eslint-disable-next-line
  22325. this.bVals = new Uint8Array(256);
  22326. }
  22327. // This is an optimization - pre-compute a look-up table for each color channel
  22328. // instead of performing these pow calls for each pixel in the image.
  22329. for (i = 0, len = 256; i < len; i++) {
  22330. this.rVals[i] = Math.pow(i / 255, rInv) * 255;
  22331. this.gVals[i] = Math.pow(i / 255, gInv) * 255;
  22332. this.bVals[i] = Math.pow(i / 255, bInv) * 255;
  22333. }
  22334. for (i = 0, len = data.length; i < len; i += 4) {
  22335. data[i] = this.rVals[data[i]];
  22336. data[i + 1] = this.gVals[data[i + 1]];
  22337. data[i + 2] = this.bVals[data[i + 2]];
  22338. }
  22339. },
  22340. /**
  22341. * Return WebGL uniform locations for this filter's shader.
  22342. *
  22343. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22344. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22345. */
  22346. getUniformLocations: function(gl, program) {
  22347. return {
  22348. uGamma: gl.getUniformLocation(program, 'uGamma'),
  22349. };
  22350. },
  22351. /**
  22352. * Send data from this filter to its shader program's uniforms.
  22353. *
  22354. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22355. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  22356. */
  22357. sendUniformData: function(gl, uniformLocations) {
  22358. gl.uniform3fv(uniformLocations.uGamma, this.gamma);
  22359. },
  22360. });
  22361. /**
  22362. * Returns filter instance from an object representation
  22363. * @static
  22364. * @param {Object} object Object to create an instance from
  22365. * @param {function} [callback] to be invoked after filter creation
  22366. * @return {fabric.Image.filters.Gamma} Instance of fabric.Image.filters.Gamma
  22367. */
  22368. fabric.Image.filters.Gamma.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22369. })(typeof exports !== 'undefined' ? exports : this);
  22370. (function(global) {
  22371. 'use strict';
  22372. var fabric = global.fabric || (global.fabric = { }),
  22373. filters = fabric.Image.filters,
  22374. createClass = fabric.util.createClass;
  22375. /**
  22376. * A container class that knows how to apply a sequence of filters to an input image.
  22377. */
  22378. filters.Composed = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Composed.prototype */ {
  22379. type: 'Composed',
  22380. /**
  22381. * A non sparse array of filters to apply
  22382. */
  22383. subFilters: [],
  22384. /**
  22385. * Constructor
  22386. * @param {Object} [options] Options object
  22387. */
  22388. initialize: function(options) {
  22389. this.callSuper('initialize', options);
  22390. // create a new array instead mutating the prototype with push
  22391. this.subFilters = this.subFilters.slice(0);
  22392. },
  22393. /**
  22394. * Apply this container's filters to the input image provided.
  22395. *
  22396. * @param {Object} options
  22397. * @param {Number} options.passes The number of filters remaining to be applied.
  22398. */
  22399. applyTo: function(options) {
  22400. options.passes += this.subFilters.length - 1;
  22401. this.subFilters.forEach(function(filter) {
  22402. filter.applyTo(options);
  22403. });
  22404. },
  22405. /**
  22406. * Serialize this filter into JSON.
  22407. *
  22408. * @returns {Object} A JSON representation of this filter.
  22409. */
  22410. toObject: function() {
  22411. return fabric.util.object.extend(this.callSuper('toObject'), {
  22412. subFilters: this.subFilters.map(function(filter) { return filter.toObject(); }),
  22413. });
  22414. },
  22415. });
  22416. /**
  22417. * Deserialize a JSON definition of a ComposedFilter into a concrete instance.
  22418. */
  22419. fabric.Image.filters.Composed.fromObject = function(object, callback) {
  22420. var filters = object.subFilters || [],
  22421. subFilters = filters.map(function(filter) {
  22422. return new fabric.Image.filters[filter.type](filter);
  22423. }),
  22424. instance = new fabric.Image.filters.Composed({ subFilters: subFilters });
  22425. callback && callback(instance);
  22426. return instance;
  22427. };
  22428. })(typeof exports !== 'undefined' ? exports : this);
  22429. (function(global) {
  22430. 'use strict';
  22431. var fabric = global.fabric || (global.fabric = { }),
  22432. filters = fabric.Image.filters,
  22433. createClass = fabric.util.createClass;
  22434. /**
  22435. * HueRotation filter class
  22436. * @class fabric.Image.filters.HueRotation
  22437. * @memberOf fabric.Image.filters
  22438. * @extends fabric.Image.filters.BaseFilter
  22439. * @see {@link fabric.Image.filters.HueRotation#initialize} for constructor definition
  22440. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  22441. * @example
  22442. * var filter = new fabric.Image.filters.HueRotation({
  22443. * rotation: -0.5
  22444. * });
  22445. * object.filters.push(filter);
  22446. * object.applyFilters();
  22447. */
  22448. filters.HueRotation = createClass(filters.ColorMatrix, /** @lends fabric.Image.filters.HueRotation.prototype */ {
  22449. /**
  22450. * Filter type
  22451. * @param {String} type
  22452. * @default
  22453. */
  22454. type: 'HueRotation',
  22455. /**
  22456. * HueRotation value, from -1 to 1.
  22457. * the unit is radians
  22458. * @param {Number} myParameter
  22459. * @default
  22460. */
  22461. rotation: 0,
  22462. /**
  22463. * Describe the property that is the filter parameter
  22464. * @param {String} m
  22465. * @default
  22466. */
  22467. mainParameter: 'rotation',
  22468. calculateMatrix: function() {
  22469. var rad = this.rotation * Math.PI, cos = fabric.util.cos(rad), sin = fabric.util.sin(rad),
  22470. aThird = 1 / 3, aThirdSqtSin = Math.sqrt(aThird) * sin, OneMinusCos = 1 - cos;
  22471. this.matrix = [
  22472. 1, 0, 0, 0, 0,
  22473. 0, 1, 0, 0, 0,
  22474. 0, 0, 1, 0, 0,
  22475. 0, 0, 0, 1, 0
  22476. ];
  22477. this.matrix[0] = cos + OneMinusCos / 3;
  22478. this.matrix[1] = aThird * OneMinusCos - aThirdSqtSin;
  22479. this.matrix[2] = aThird * OneMinusCos + aThirdSqtSin;
  22480. this.matrix[5] = aThird * OneMinusCos + aThirdSqtSin;
  22481. this.matrix[6] = cos + aThird * OneMinusCos;
  22482. this.matrix[7] = aThird * OneMinusCos - aThirdSqtSin;
  22483. this.matrix[10] = aThird * OneMinusCos - aThirdSqtSin;
  22484. this.matrix[11] = aThird * OneMinusCos + aThirdSqtSin;
  22485. this.matrix[12] = cos + aThird * OneMinusCos;
  22486. },
  22487. /**
  22488. * Apply this filter to the input image data provided.
  22489. *
  22490. * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
  22491. *
  22492. * @param {Object} options
  22493. * @param {Number} options.passes The number of filters remaining to be executed
  22494. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  22495. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  22496. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  22497. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  22498. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  22499. */
  22500. applyTo: function(options) {
  22501. this.calculateMatrix();
  22502. fabric.Image.filters.BaseFilter.prototype.applyTo.call(this, options);
  22503. },
  22504. });
  22505. /**
  22506. * Returns filter instance from an object representation
  22507. * @static
  22508. * @param {Object} object Object to create an instance from
  22509. * @param {function} [callback] to be invoked after filter creation
  22510. * @return {fabric.Image.filters.HueRotation} Instance of fabric.Image.filters.HueRotation
  22511. */
  22512. fabric.Image.filters.HueRotation.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22513. })(typeof exports !== 'undefined' ? exports : this);
  22514. (function(global) {
  22515. 'use strict';
  22516. var fabric = global.fabric || (global.fabric = { }),
  22517. clone = fabric.util.object.clone;
  22518. if (fabric.Text) {
  22519. fabric.warn('fabric.Text is already defined');
  22520. return;
  22521. }
  22522. /**
  22523. * Text class
  22524. * @class fabric.Text
  22525. * @extends fabric.Object
  22526. * @return {fabric.Text} thisArg
  22527. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#text}
  22528. * @see {@link fabric.Text#initialize} for constructor definition
  22529. */
  22530. fabric.Text = fabric.util.createClass(fabric.Object, /** @lends fabric.Text.prototype */ {
  22531. /**
  22532. * Properties which when set cause object to change dimensions
  22533. * @type Array
  22534. * @private
  22535. */
  22536. _dimensionAffectingProps: [
  22537. 'fontSize',
  22538. 'fontWeight',
  22539. 'fontFamily',
  22540. 'fontStyle',
  22541. 'lineHeight',
  22542. 'text',
  22543. 'charSpacing',
  22544. 'textAlign',
  22545. 'styles',
  22546. ],
  22547. /**
  22548. * @private
  22549. */
  22550. _reNewline: /\r?\n/,
  22551. /**
  22552. * Use this regular expression to filter for whitespaces that is not a new line.
  22553. * Mostly used when text is 'justify' aligned.
  22554. * @private
  22555. */
  22556. _reSpacesAndTabs: /[ \t\r]/g,
  22557. /**
  22558. * Use this regular expression to filter for whitespace that is not a new line.
  22559. * Mostly used when text is 'justify' aligned.
  22560. * @private
  22561. */
  22562. _reSpaceAndTab: /[ \t\r]/,
  22563. /**
  22564. * Use this regular expression to filter consecutive groups of non spaces.
  22565. * Mostly used when text is 'justify' aligned.
  22566. * @private
  22567. */
  22568. _reWords: /\S+/g,
  22569. /**
  22570. * Type of an object
  22571. * @type String
  22572. * @default
  22573. */
  22574. type: 'text',
  22575. /**
  22576. * Font size (in pixels)
  22577. * @type Number
  22578. * @default
  22579. */
  22580. fontSize: 40,
  22581. /**
  22582. * Font weight (e.g. bold, normal, 400, 600, 800)
  22583. * @type {(Number|String)}
  22584. * @default
  22585. */
  22586. fontWeight: 'normal',
  22587. /**
  22588. * Font family
  22589. * @type String
  22590. * @default
  22591. */
  22592. fontFamily: 'Times New Roman',
  22593. /**
  22594. * Text decoration underline.
  22595. * @type String
  22596. * @default
  22597. */
  22598. underline: false,
  22599. /**
  22600. * Text decoration overline.
  22601. * @type String
  22602. * @default
  22603. */
  22604. overline: false,
  22605. /**
  22606. * Text decoration linethrough.
  22607. * @type String
  22608. * @default
  22609. */
  22610. linethrough: false,
  22611. /**
  22612. * Text alignment. Possible values: "left", "center", "right", "justify",
  22613. * "justify-left", "justify-center" or "justify-right".
  22614. * @type String
  22615. * @default
  22616. */
  22617. textAlign: 'left',
  22618. /**
  22619. * Font style . Possible values: "", "normal", "italic" or "oblique".
  22620. * @type String
  22621. * @default
  22622. */
  22623. fontStyle: 'normal',
  22624. /**
  22625. * Line height
  22626. * @type Number
  22627. * @default
  22628. */
  22629. lineHeight: 1.16,
  22630. /**
  22631. * Superscript schema object (minimum overlap)
  22632. * @type {Object}
  22633. * @default
  22634. */
  22635. superscript: {
  22636. size: 0.60, // fontSize factor
  22637. baseline: -0.35 // baseline-shift factor (upwards)
  22638. },
  22639. /**
  22640. * Subscript schema object (minimum overlap)
  22641. * @type {Object}
  22642. * @default
  22643. */
  22644. subscript: {
  22645. size: 0.60, // fontSize factor
  22646. baseline: 0.11 // baseline-shift factor (downwards)
  22647. },
  22648. /**
  22649. * Background color of text lines
  22650. * @type String
  22651. * @default
  22652. */
  22653. textBackgroundColor: '',
  22654. /**
  22655. * List of properties to consider when checking if
  22656. * state of an object is changed ({@link fabric.Object#hasStateChanged})
  22657. * as well as for history (undo/redo) purposes
  22658. * @type Array
  22659. */
  22660. stateProperties: fabric.Object.prototype.stateProperties.concat('fontFamily',
  22661. 'fontWeight',
  22662. 'fontSize',
  22663. 'text',
  22664. 'underline',
  22665. 'overline',
  22666. 'linethrough',
  22667. 'textAlign',
  22668. 'fontStyle',
  22669. 'lineHeight',
  22670. 'textBackgroundColor',
  22671. 'charSpacing',
  22672. 'styles'),
  22673. /**
  22674. * List of properties to consider when checking if cache needs refresh
  22675. * @type Array
  22676. */
  22677. cacheProperties: fabric.Object.prototype.cacheProperties.concat('fontFamily',
  22678. 'fontWeight',
  22679. 'fontSize',
  22680. 'text',
  22681. 'underline',
  22682. 'overline',
  22683. 'linethrough',
  22684. 'textAlign',
  22685. 'fontStyle',
  22686. 'lineHeight',
  22687. 'textBackgroundColor',
  22688. 'charSpacing',
  22689. 'styles'),
  22690. /**
  22691. * When defined, an object is rendered via stroke and this property specifies its color.
  22692. * <b>Backwards incompatibility note:</b> This property was named "strokeStyle" until v1.1.6
  22693. * @type String
  22694. * @default
  22695. */
  22696. stroke: null,
  22697. /**
  22698. * Shadow object representing shadow of this shape.
  22699. * <b>Backwards incompatibility note:</b> This property was named "textShadow" (String) until v1.2.11
  22700. * @type fabric.Shadow
  22701. * @default
  22702. */
  22703. shadow: null,
  22704. /**
  22705. * @private
  22706. */
  22707. _fontSizeFraction: 0.222,
  22708. /**
  22709. * @private
  22710. */
  22711. offsets: {
  22712. underline: 0.10,
  22713. linethrough: -0.315,
  22714. overline: -0.88
  22715. },
  22716. /**
  22717. * Text Line proportion to font Size (in pixels)
  22718. * @type Number
  22719. * @default
  22720. */
  22721. _fontSizeMult: 1.13,
  22722. /**
  22723. * additional space between characters
  22724. * expressed in thousands of em unit
  22725. * @type Number
  22726. * @default
  22727. */
  22728. charSpacing: 0,
  22729. /**
  22730. * Object containing character styles - top-level properties -> line numbers,
  22731. * 2nd-level properties - charater numbers
  22732. * @type Object
  22733. * @default
  22734. */
  22735. styles: null,
  22736. /**
  22737. * Reference to a context to measure text char or couple of chars
  22738. * the cacheContext of the canvas will be used or a freshly created one if the object is not on canvas
  22739. * once created it will be referenced on fabric._measuringContext to avoide creating a canvas for every
  22740. * text object created.
  22741. * @type {CanvasRenderingContext2D}
  22742. * @default
  22743. */
  22744. _measuringContext: null,
  22745. /**
  22746. * Baseline shift, stlyes only, keep at 0 for the main text object
  22747. * @type {Number}
  22748. * @default
  22749. */
  22750. deltaY: 0,
  22751. /**
  22752. * Array of properties that define a style unit (of 'styles').
  22753. * @type {Array}
  22754. * @default
  22755. */
  22756. _styleProperties: [
  22757. 'stroke',
  22758. 'strokeWidth',
  22759. 'fill',
  22760. 'fontFamily',
  22761. 'fontSize',
  22762. 'fontWeight',
  22763. 'fontStyle',
  22764. 'underline',
  22765. 'overline',
  22766. 'linethrough',
  22767. 'deltaY',
  22768. 'textBackgroundColor',
  22769. ],
  22770. /**
  22771. * contains characters bounding boxes
  22772. */
  22773. __charBounds: [],
  22774. /**
  22775. * use this size when measuring text. To avoid IE11 rounding errors
  22776. * @type {Number}
  22777. * @default
  22778. * @readonly
  22779. * @private
  22780. */
  22781. CACHE_FONT_SIZE: 400,
  22782. /**
  22783. * contains the min text width to avoid getting 0
  22784. * @type {Number}
  22785. * @default
  22786. */
  22787. MIN_TEXT_WIDTH: 2,
  22788. /**
  22789. * Constructor
  22790. * @param {String} text Text string
  22791. * @param {Object} [options] Options object
  22792. * @return {fabric.Text} thisArg
  22793. */
  22794. initialize: function(text, options) {
  22795. this.styles = options ? (options.styles || { }) : { };
  22796. this.text = text;
  22797. this.__skipDimension = true;
  22798. this.callSuper('initialize', options);
  22799. this.__skipDimension = false;
  22800. this.initDimensions();
  22801. this.setCoords();
  22802. this.setupState({ propertySet: '_dimensionAffectingProps' });
  22803. },
  22804. /**
  22805. * Return a contex for measurement of text string.
  22806. * if created it gets stored for reuse
  22807. * @param {String} text Text string
  22808. * @param {Object} [options] Options object
  22809. * @return {fabric.Text} thisArg
  22810. */
  22811. getMeasuringContext: function() {
  22812. // if we did not return we have to measure something.
  22813. if (!fabric._measuringContext) {
  22814. fabric._measuringContext = this.canvas && this.canvas.contextCache ||
  22815. fabric.util.createCanvasElement().getContext('2d');
  22816. }
  22817. return fabric._measuringContext;
  22818. },
  22819. /**
  22820. * @private
  22821. * Divides text into lines of text and lines of graphemes.
  22822. */
  22823. _splitText: function() {
  22824. var newLines = this._splitTextIntoLines(this.text);
  22825. this.textLines = newLines.lines;
  22826. this._textLines = newLines.graphemeLines;
  22827. this._unwrappedTextLines = newLines._unwrappedLines;
  22828. this._text = newLines.graphemeText;
  22829. return newLines;
  22830. },
  22831. /**
  22832. * Initialize or update text dimensions.
  22833. * Updates this.width and this.height with the proper values.
  22834. * Does not return dimensions.
  22835. */
  22836. initDimensions: function() {
  22837. if (this.__skipDimension) {
  22838. return;
  22839. }
  22840. this._splitText();
  22841. this._clearCache();
  22842. this.width = this.calcTextWidth() || this.cursorWidth || this.MIN_TEXT_WIDTH;
  22843. if (this.textAlign.indexOf('justify') !== -1) {
  22844. // once text is measured we need to make space fatter to make justified text.
  22845. this.enlargeSpaces();
  22846. }
  22847. this.height = this.calcTextHeight();
  22848. this.saveState({ propertySet: '_dimensionAffectingProps' });
  22849. },
  22850. /**
  22851. * Enlarge space boxes and shift the others
  22852. */
  22853. enlargeSpaces: function() {
  22854. var diffSpace, currentLineWidth, numberOfSpaces, accumulatedSpace, line, charBound, spaces;
  22855. for (var i = 0, len = this._textLines.length; i < len; i++) {
  22856. if (this.textAlign !== 'justify' && (i === len - 1 || this.isEndOfWrapping(i))) {
  22857. continue;
  22858. }
  22859. accumulatedSpace = 0;
  22860. line = this._textLines[i];
  22861. currentLineWidth = this.getLineWidth(i);
  22862. if (currentLineWidth < this.width && (spaces = this.textLines[i].match(this._reSpacesAndTabs))) {
  22863. numberOfSpaces = spaces.length;
  22864. diffSpace = (this.width - currentLineWidth) / numberOfSpaces;
  22865. for (var j = 0, jlen = line.length; j <= jlen; j++) {
  22866. charBound = this.__charBounds[i][j];
  22867. if (this._reSpaceAndTab.test(line[j])) {
  22868. charBound.width += diffSpace;
  22869. charBound.kernedWidth += diffSpace;
  22870. charBound.left += accumulatedSpace;
  22871. accumulatedSpace += diffSpace;
  22872. }
  22873. else {
  22874. charBound.left += accumulatedSpace;
  22875. }
  22876. }
  22877. }
  22878. }
  22879. },
  22880. /**
  22881. * Detect if the text line is ended with an hard break
  22882. * text and itext do not have wrapping, return false
  22883. * @return {Boolean}
  22884. */
  22885. isEndOfWrapping: function(lineIndex) {
  22886. return lineIndex === this._textLines.length - 1;
  22887. },
  22888. /**
  22889. * Returns string representation of an instance
  22890. * @return {String} String representation of text object
  22891. */
  22892. toString: function() {
  22893. return '#<fabric.Text (' + this.complexity() +
  22894. '): { "text": "' + this.text + '", "fontFamily": "' + this.fontFamily + '" }>';
  22895. },
  22896. /**
  22897. * Return the dimension and the zoom level needed to create a cache canvas
  22898. * big enough to host the object to be cached.
  22899. * @private
  22900. * @param {Object} dim.x width of object to be cached
  22901. * @param {Object} dim.y height of object to be cached
  22902. * @return {Object}.width width of canvas
  22903. * @return {Object}.height height of canvas
  22904. * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache
  22905. * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
  22906. */
  22907. _getCacheCanvasDimensions: function() {
  22908. var dims = this.callSuper('_getCacheCanvasDimensions');
  22909. var fontSize = this.fontSize;
  22910. dims.width += fontSize * dims.zoomX;
  22911. dims.height += fontSize * dims.zoomY;
  22912. return dims;
  22913. },
  22914. /**
  22915. * @private
  22916. * @param {CanvasRenderingContext2D} ctx Context to render on
  22917. */
  22918. _render: function(ctx) {
  22919. this._setTextStyles(ctx);
  22920. this._renderTextLinesBackground(ctx);
  22921. this._renderTextDecoration(ctx, 'underline');
  22922. this._renderText(ctx);
  22923. this._renderTextDecoration(ctx, 'overline');
  22924. this._renderTextDecoration(ctx, 'linethrough');
  22925. },
  22926. /**
  22927. * @private
  22928. * @param {CanvasRenderingContext2D} ctx Context to render on
  22929. */
  22930. _renderText: function(ctx) {
  22931. if (this.paintFirst === 'stroke') {
  22932. this._renderTextStroke(ctx);
  22933. this._renderTextFill(ctx);
  22934. }
  22935. else {
  22936. this._renderTextFill(ctx);
  22937. this._renderTextStroke(ctx);
  22938. }
  22939. },
  22940. /**
  22941. * Set the font parameter of the context with the object properties or with charStyle
  22942. * @private
  22943. * @param {CanvasRenderingContext2D} ctx Context to render on
  22944. * @param {Object} [charStyle] object with font style properties
  22945. * @param {String} [charStyle.fontFamily] Font Family
  22946. * @param {Number} [charStyle.fontSize] Font size in pixels. ( without px suffix )
  22947. * @param {String} [charStyle.fontWeight] Font weight
  22948. * @param {String} [charStyle.fontStyle] Font style (italic|normal)
  22949. */
  22950. _setTextStyles: function(ctx, charStyle, forMeasuring) {
  22951. ctx.textBaseline = 'alphabetic';
  22952. ctx.font = this._getFontDeclaration(charStyle, forMeasuring);
  22953. },
  22954. /**
  22955. * calculate and return the text Width measuring each line.
  22956. * @private
  22957. * @param {CanvasRenderingContext2D} ctx Context to render on
  22958. * @return {Number} Maximum width of fabric.Text object
  22959. */
  22960. calcTextWidth: function() {
  22961. var maxWidth = this.getLineWidth(0);
  22962. for (var i = 1, len = this._textLines.length; i < len; i++) {
  22963. var currentLineWidth = this.getLineWidth(i);
  22964. if (currentLineWidth > maxWidth) {
  22965. maxWidth = currentLineWidth;
  22966. }
  22967. }
  22968. return maxWidth;
  22969. },
  22970. /**
  22971. * @private
  22972. * @param {String} method Method name ("fillText" or "strokeText")
  22973. * @param {CanvasRenderingContext2D} ctx Context to render on
  22974. * @param {String} line Text to render
  22975. * @param {Number} left Left position of text
  22976. * @param {Number} top Top position of text
  22977. * @param {Number} lineIndex Index of a line in a text
  22978. */
  22979. _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
  22980. this._renderChars(method, ctx, line, left, top, lineIndex);
  22981. },
  22982. /**
  22983. * Renders the text background for lines, taking care of style
  22984. * @private
  22985. * @param {CanvasRenderingContext2D} ctx Context to render on
  22986. */
  22987. _renderTextLinesBackground: function(ctx) {
  22988. if (!this.textBackgroundColor && !this.styleHas('textBackgroundColor')) {
  22989. return;
  22990. }
  22991. var lineTopOffset = 0, heightOfLine,
  22992. lineLeftOffset, originalFill = ctx.fillStyle,
  22993. line, lastColor,
  22994. leftOffset = this._getLeftOffset(),
  22995. topOffset = this._getTopOffset(),
  22996. boxStart = 0, boxWidth = 0, charBox, currentColor;
  22997. for (var i = 0, len = this._textLines.length; i < len; i++) {
  22998. heightOfLine = this.getHeightOfLine(i);
  22999. if (!this.textBackgroundColor && !this.styleHas('textBackgroundColor', i)) {
  23000. lineTopOffset += heightOfLine;
  23001. continue;
  23002. }
  23003. line = this._textLines[i];
  23004. lineLeftOffset = this._getLineLeftOffset(i);
  23005. boxWidth = 0;
  23006. boxStart = 0;
  23007. lastColor = this.getValueOfPropertyAt(i, 0, 'textBackgroundColor');
  23008. for (var j = 0, jlen = line.length; j < jlen; j++) {
  23009. charBox = this.__charBounds[i][j];
  23010. currentColor = this.getValueOfPropertyAt(i, j, 'textBackgroundColor');
  23011. if (currentColor !== lastColor) {
  23012. ctx.fillStyle = lastColor;
  23013. lastColor && ctx.fillRect(
  23014. leftOffset + lineLeftOffset + boxStart,
  23015. topOffset + lineTopOffset,
  23016. boxWidth,
  23017. heightOfLine / this.lineHeight
  23018. );
  23019. boxStart = charBox.left;
  23020. boxWidth = charBox.width;
  23021. lastColor = currentColor;
  23022. }
  23023. else {
  23024. boxWidth += charBox.kernedWidth;
  23025. }
  23026. }
  23027. if (currentColor) {
  23028. ctx.fillStyle = currentColor;
  23029. ctx.fillRect(
  23030. leftOffset + lineLeftOffset + boxStart,
  23031. topOffset + lineTopOffset,
  23032. boxWidth,
  23033. heightOfLine / this.lineHeight
  23034. );
  23035. }
  23036. lineTopOffset += heightOfLine;
  23037. }
  23038. ctx.fillStyle = originalFill;
  23039. // if there is text background color no
  23040. // other shadows should be casted
  23041. this._removeShadow(ctx);
  23042. },
  23043. /**
  23044. * @private
  23045. * @param {Object} decl style declaration for cache
  23046. * @param {String} decl.fontFamily fontFamily
  23047. * @param {String} decl.fontStyle fontStyle
  23048. * @param {String} decl.fontWeight fontWeight
  23049. * @return {Object} reference to cache
  23050. */
  23051. getFontCache: function(decl) {
  23052. var fontFamily = decl.fontFamily.toLowerCase();
  23053. if (!fabric.charWidthsCache[fontFamily]) {
  23054. fabric.charWidthsCache[fontFamily] = { };
  23055. }
  23056. var cache = fabric.charWidthsCache[fontFamily],
  23057. cacheProp = decl.fontStyle.toLowerCase() + '_' + (decl.fontWeight + '').toLowerCase();
  23058. if (!cache[cacheProp]) {
  23059. cache[cacheProp] = { };
  23060. }
  23061. return cache[cacheProp];
  23062. },
  23063. /**
  23064. * apply all the character style to canvas for rendering
  23065. * @private
  23066. * @param {String} _char
  23067. * @param {Number} lineIndex
  23068. * @param {Number} charIndex
  23069. * @param {Object} [decl]
  23070. */
  23071. _applyCharStyles: function(method, ctx, lineIndex, charIndex, styleDeclaration) {
  23072. this._setFillStyles(ctx, styleDeclaration);
  23073. this._setStrokeStyles(ctx, styleDeclaration);
  23074. ctx.font = this._getFontDeclaration(styleDeclaration);
  23075. },
  23076. /**
  23077. * measure and return the width of a single character.
  23078. * possibly overridden to accommodate different measure logic or
  23079. * to hook some external lib for character measurement
  23080. * @private
  23081. * @param {String} char to be measured
  23082. * @param {Object} charStyle style of char to be measured
  23083. * @param {String} [previousChar] previous char
  23084. * @param {Object} [prevCharStyle] style of previous char
  23085. */
  23086. _measureChar: function(_char, charStyle, previousChar, prevCharStyle) {
  23087. // first i try to return from cache
  23088. var fontCache = this.getFontCache(charStyle), fontDeclaration = this._getFontDeclaration(charStyle),
  23089. previousFontDeclaration = this._getFontDeclaration(prevCharStyle), couple = previousChar + _char,
  23090. stylesAreEqual = fontDeclaration === previousFontDeclaration, width, coupleWidth, previousWidth,
  23091. fontMultiplier = charStyle.fontSize / this.CACHE_FONT_SIZE, kernedWidth;
  23092. if (previousChar && fontCache[previousChar] !== undefined) {
  23093. previousWidth = fontCache[previousChar];
  23094. }
  23095. if (fontCache[_char] !== undefined) {
  23096. kernedWidth = width = fontCache[_char];
  23097. }
  23098. if (stylesAreEqual && fontCache[couple] !== undefined) {
  23099. coupleWidth = fontCache[couple];
  23100. kernedWidth = coupleWidth - previousWidth;
  23101. }
  23102. if (width === undefined || previousWidth === undefined || coupleWidth === undefined) {
  23103. var ctx = this.getMeasuringContext();
  23104. // send a TRUE to specify measuring font size CACHE_FONT_SIZE
  23105. this._setTextStyles(ctx, charStyle, true);
  23106. }
  23107. if (width === undefined) {
  23108. kernedWidth = width = ctx.measureText(_char).width;
  23109. fontCache[_char] = width;
  23110. }
  23111. if (previousWidth === undefined && stylesAreEqual && previousChar) {
  23112. previousWidth = ctx.measureText(previousChar).width;
  23113. fontCache[previousChar] = previousWidth;
  23114. }
  23115. if (stylesAreEqual && coupleWidth === undefined) {
  23116. // we can measure the kerning couple and subtract the width of the previous character
  23117. coupleWidth = ctx.measureText(couple).width;
  23118. fontCache[couple] = coupleWidth;
  23119. kernedWidth = coupleWidth - previousWidth;
  23120. }
  23121. return { width: width * fontMultiplier, kernedWidth: kernedWidth * fontMultiplier };
  23122. },
  23123. /**
  23124. * Computes height of character at given position
  23125. * @param {Number} line the line number
  23126. * @param {Number} char the character number
  23127. * @return {Number} fontSize of the character
  23128. */
  23129. getHeightOfChar: function(line, char) {
  23130. return this.getValueOfPropertyAt(line, char, 'fontSize');
  23131. },
  23132. /**
  23133. * measure a text line measuring all characters.
  23134. * @param {Number} lineIndex line number
  23135. * @return {Number} Line width
  23136. */
  23137. measureLine: function(lineIndex) {
  23138. var lineInfo = this._measureLine(lineIndex);
  23139. if (this.charSpacing !== 0) {
  23140. lineInfo.width -= this._getWidthOfCharSpacing();
  23141. }
  23142. if (lineInfo.width < 0) {
  23143. lineInfo.width = 0;
  23144. }
  23145. return lineInfo;
  23146. },
  23147. /**
  23148. * measure every grapheme of a line, populating __charBounds
  23149. * @param {Number} lineIndex
  23150. * @return {Object} object.width total width of characters
  23151. * @return {Object} object.widthOfSpaces length of chars that match this._reSpacesAndTabs
  23152. */
  23153. _measureLine: function(lineIndex) {
  23154. var width = 0, i, grapheme, line = this._textLines[lineIndex], prevGrapheme,
  23155. graphemeInfo, numOfSpaces = 0, lineBounds = new Array(line.length);
  23156. this.__charBounds[lineIndex] = lineBounds;
  23157. for (i = 0; i < line.length; i++) {
  23158. grapheme = line[i];
  23159. graphemeInfo = this._getGraphemeBox(grapheme, lineIndex, i, prevGrapheme);
  23160. lineBounds[i] = graphemeInfo;
  23161. width += graphemeInfo.kernedWidth;
  23162. prevGrapheme = grapheme;
  23163. }
  23164. // this latest bound box represent the last character of the line
  23165. // to simplify cursor handling in interactive mode.
  23166. lineBounds[i] = {
  23167. left: graphemeInfo ? graphemeInfo.left + graphemeInfo.width : 0,
  23168. width: 0,
  23169. kernedWidth: 0,
  23170. height: this.fontSize
  23171. };
  23172. return { width: width, numOfSpaces: numOfSpaces };
  23173. },
  23174. /**
  23175. * Measure and return the info of a single grapheme.
  23176. * needs the the info of previous graphemes already filled
  23177. * @private
  23178. * @param {String} grapheme to be measured
  23179. * @param {Number} lineIndex index of the line where the char is
  23180. * @param {Number} charIndex position in the line
  23181. * @param {String} [prevGrapheme] character preceding the one to be measured
  23182. */
  23183. _getGraphemeBox: function(grapheme, lineIndex, charIndex, prevGrapheme, skipLeft) {
  23184. var style = this.getCompleteStyleDeclaration(lineIndex, charIndex),
  23185. prevStyle = prevGrapheme ? this.getCompleteStyleDeclaration(lineIndex, charIndex - 1) : { },
  23186. info = this._measureChar(grapheme, style, prevGrapheme, prevStyle),
  23187. kernedWidth = info.kernedWidth,
  23188. width = info.width, charSpacing;
  23189. if (this.charSpacing !== 0) {
  23190. charSpacing = this._getWidthOfCharSpacing();
  23191. width += charSpacing;
  23192. kernedWidth += charSpacing;
  23193. }
  23194. var box = {
  23195. width: width,
  23196. left: 0,
  23197. height: style.fontSize,
  23198. kernedWidth: kernedWidth,
  23199. deltaY: style.deltaY,
  23200. };
  23201. if (charIndex > 0 && !skipLeft) {
  23202. var previousBox = this.__charBounds[lineIndex][charIndex - 1];
  23203. box.left = previousBox.left + previousBox.width + info.kernedWidth - info.width;
  23204. }
  23205. return box;
  23206. },
  23207. /**
  23208. * Calculate height of line at 'lineIndex'
  23209. * @param {Number} lineIndex index of line to calculate
  23210. * @return {Number}
  23211. */
  23212. getHeightOfLine: function(lineIndex) {
  23213. if (this.__lineHeights[lineIndex]) {
  23214. return this.__lineHeights[lineIndex];
  23215. }
  23216. var line = this._textLines[lineIndex],
  23217. // char 0 is measured before the line cycle because it nneds to char
  23218. // emptylines
  23219. maxHeight = this.getHeightOfChar(lineIndex, 0);
  23220. for (var i = 1, len = line.length; i < len; i++) {
  23221. maxHeight = Math.max(this.getHeightOfChar(lineIndex, i), maxHeight);
  23222. }
  23223. return this.__lineHeights[lineIndex] = maxHeight * this.lineHeight * this._fontSizeMult;
  23224. },
  23225. /**
  23226. * Calculate text box height
  23227. */
  23228. calcTextHeight: function() {
  23229. var lineHeight, height = 0;
  23230. for (var i = 0, len = this._textLines.length; i < len; i++) {
  23231. lineHeight = this.getHeightOfLine(i);
  23232. height += (i === len - 1 ? lineHeight / this.lineHeight : lineHeight);
  23233. }
  23234. return height;
  23235. },
  23236. /**
  23237. * @private
  23238. * @return {Number} Left offset
  23239. */
  23240. _getLeftOffset: function() {
  23241. return -this.width / 2;
  23242. },
  23243. /**
  23244. * @private
  23245. * @return {Number} Top offset
  23246. */
  23247. _getTopOffset: function() {
  23248. return -this.height / 2;
  23249. },
  23250. /**
  23251. * @private
  23252. * @param {CanvasRenderingContext2D} ctx Context to render on
  23253. * @param {String} method Method name ("fillText" or "strokeText")
  23254. */
  23255. _renderTextCommon: function(ctx, method) {
  23256. ctx.save();
  23257. var lineHeights = 0, left = this._getLeftOffset(), top = this._getTopOffset(),
  23258. offsets = this._applyPatternGradientTransform(ctx, method === 'fillText' ? this.fill : this.stroke);
  23259. for (var i = 0, len = this._textLines.length; i < len; i++) {
  23260. var heightOfLine = this.getHeightOfLine(i),
  23261. maxHeight = heightOfLine / this.lineHeight,
  23262. leftOffset = this._getLineLeftOffset(i);
  23263. this._renderTextLine(
  23264. method,
  23265. ctx,
  23266. this._textLines[i],
  23267. left + leftOffset - offsets.offsetX,
  23268. top + lineHeights + maxHeight - offsets.offsetY,
  23269. i
  23270. );
  23271. lineHeights += heightOfLine;
  23272. }
  23273. ctx.restore();
  23274. },
  23275. /**
  23276. * @private
  23277. * @param {CanvasRenderingContext2D} ctx Context to render on
  23278. */
  23279. _renderTextFill: function(ctx) {
  23280. if (!this.fill && !this.styleHas('fill')) {
  23281. return;
  23282. }
  23283. this._renderTextCommon(ctx, 'fillText');
  23284. },
  23285. /**
  23286. * @private
  23287. * @param {CanvasRenderingContext2D} ctx Context to render on
  23288. */
  23289. _renderTextStroke: function(ctx) {
  23290. if ((!this.stroke || this.strokeWidth === 0) && this.isEmptyStyles()) {
  23291. return;
  23292. }
  23293. if (this.shadow && !this.shadow.affectStroke) {
  23294. this._removeShadow(ctx);
  23295. }
  23296. ctx.save();
  23297. this._setLineDash(ctx, this.strokeDashArray);
  23298. ctx.beginPath();
  23299. this._renderTextCommon(ctx, 'strokeText');
  23300. ctx.closePath();
  23301. ctx.restore();
  23302. },
  23303. /**
  23304. * @private
  23305. * @param {String} method
  23306. * @param {CanvasRenderingContext2D} ctx Context to render on
  23307. * @param {String} line Content of the line
  23308. * @param {Number} left
  23309. * @param {Number} top
  23310. * @param {Number} lineIndex
  23311. * @param {Number} charOffset
  23312. */
  23313. _renderChars: function(method, ctx, line, left, top, lineIndex) {
  23314. // set proper line offset
  23315. var lineHeight = this.getHeightOfLine(lineIndex),
  23316. isJustify = this.textAlign.indexOf('justify') !== -1,
  23317. actualStyle,
  23318. nextStyle,
  23319. charsToRender = '',
  23320. charBox,
  23321. boxWidth = 0,
  23322. timeToRender,
  23323. shortCut = !isJustify && this.charSpacing === 0 && this.isEmptyStyles(lineIndex);
  23324. ctx.save();
  23325. top -= lineHeight * this._fontSizeFraction / this.lineHeight;
  23326. if (shortCut) {
  23327. // render all the line in one pass without checking
  23328. this._renderChar(method, ctx, lineIndex, 0, this.textLines[lineIndex], left, top, lineHeight);
  23329. ctx.restore();
  23330. return;
  23331. }
  23332. for (var i = 0, len = line.length - 1; i <= len; i++) {
  23333. timeToRender = i === len || this.charSpacing;
  23334. charsToRender += line[i];
  23335. charBox = this.__charBounds[lineIndex][i];
  23336. if (boxWidth === 0) {
  23337. left += charBox.kernedWidth - charBox.width;
  23338. boxWidth += charBox.width;
  23339. }
  23340. else {
  23341. boxWidth += charBox.kernedWidth;
  23342. }
  23343. if (isJustify && !timeToRender) {
  23344. if (this._reSpaceAndTab.test(line[i])) {
  23345. timeToRender = true;
  23346. }
  23347. }
  23348. if (!timeToRender) {
  23349. // if we have charSpacing, we render char by char
  23350. actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i);
  23351. nextStyle = this.getCompleteStyleDeclaration(lineIndex, i + 1);
  23352. timeToRender = this._hasStyleChanged(actualStyle, nextStyle);
  23353. }
  23354. if (timeToRender) {
  23355. this._renderChar(method, ctx, lineIndex, i, charsToRender, left, top, lineHeight);
  23356. charsToRender = '';
  23357. actualStyle = nextStyle;
  23358. left += boxWidth;
  23359. boxWidth = 0;
  23360. }
  23361. }
  23362. ctx.restore();
  23363. },
  23364. /**
  23365. * @private
  23366. * @param {String} method
  23367. * @param {CanvasRenderingContext2D} ctx Context to render on
  23368. * @param {Number} lineIndex
  23369. * @param {Number} charIndex
  23370. * @param {String} _char
  23371. * @param {Number} left Left coordinate
  23372. * @param {Number} top Top coordinate
  23373. * @param {Number} lineHeight Height of the line
  23374. */
  23375. _renderChar: function(method, ctx, lineIndex, charIndex, _char, left, top) {
  23376. var decl = this._getStyleDeclaration(lineIndex, charIndex),
  23377. fullDecl = this.getCompleteStyleDeclaration(lineIndex, charIndex),
  23378. shouldFill = method === 'fillText' && fullDecl.fill,
  23379. shouldStroke = method === 'strokeText' && fullDecl.stroke && fullDecl.strokeWidth;
  23380. if (!shouldStroke && !shouldFill) {
  23381. return;
  23382. }
  23383. decl && ctx.save();
  23384. this._applyCharStyles(method, ctx, lineIndex, charIndex, fullDecl);
  23385. if (decl && decl.textBackgroundColor) {
  23386. this._removeShadow(ctx);
  23387. }
  23388. if (decl && decl.deltaY) {
  23389. top += decl.deltaY;
  23390. }
  23391. shouldFill && ctx.fillText(_char, left, top);
  23392. shouldStroke && ctx.strokeText(_char, left, top);
  23393. decl && ctx.restore();
  23394. },
  23395. /**
  23396. * Turns the character into a 'superior figure' (i.e. 'superscript')
  23397. * @param {Number} start selection start
  23398. * @param {Number} end selection end
  23399. * @returns {fabric.Text} thisArg
  23400. * @chainable
  23401. */
  23402. setSuperscript: function(start, end) {
  23403. return this._setScript(start, end, this.superscript);
  23404. },
  23405. /**
  23406. * Turns the character into an 'inferior figure' (i.e. 'subscript')
  23407. * @param {Number} start selection start
  23408. * @param {Number} end selection end
  23409. * @returns {fabric.Text} thisArg
  23410. * @chainable
  23411. */
  23412. setSubscript: function(start, end) {
  23413. return this._setScript(start, end, this.subscript);
  23414. },
  23415. /**
  23416. * Applies 'schema' at given position
  23417. * @private
  23418. * @param {Number} start selection start
  23419. * @param {Number} end selection end
  23420. * @param {Number} schema
  23421. * @returns {fabric.Text} thisArg
  23422. * @chainable
  23423. */
  23424. _setScript: function(start, end, schema) {
  23425. var loc = this.get2DCursorLocation(start, true),
  23426. fontSize = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, 'fontSize'),
  23427. dy = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, 'deltaY'),
  23428. style = { fontSize: fontSize * schema.size, deltaY: dy + fontSize * schema.baseline };
  23429. this.setSelectionStyles(style, start, end);
  23430. return this;
  23431. },
  23432. /**
  23433. * @private
  23434. * @param {Object} prevStyle
  23435. * @param {Object} thisStyle
  23436. */
  23437. _hasStyleChanged: function(prevStyle, thisStyle) {
  23438. return prevStyle.fill !== thisStyle.fill ||
  23439. prevStyle.stroke !== thisStyle.stroke ||
  23440. prevStyle.strokeWidth !== thisStyle.strokeWidth ||
  23441. prevStyle.fontSize !== thisStyle.fontSize ||
  23442. prevStyle.fontFamily !== thisStyle.fontFamily ||
  23443. prevStyle.fontWeight !== thisStyle.fontWeight ||
  23444. prevStyle.fontStyle !== thisStyle.fontStyle ||
  23445. prevStyle.deltaY !== thisStyle.deltaY;
  23446. },
  23447. /**
  23448. * @private
  23449. * @param {Object} prevStyle
  23450. * @param {Object} thisStyle
  23451. */
  23452. _hasStyleChangedForSvg: function(prevStyle, thisStyle) {
  23453. return this._hasStyleChanged(prevStyle, thisStyle) ||
  23454. prevStyle.overline !== thisStyle.overline ||
  23455. prevStyle.underline !== thisStyle.underline ||
  23456. prevStyle.linethrough !== thisStyle.linethrough;
  23457. },
  23458. /**
  23459. * @private
  23460. * @param {Number} lineIndex index text line
  23461. * @return {Number} Line left offset
  23462. */
  23463. _getLineLeftOffset: function(lineIndex) {
  23464. var lineWidth = this.getLineWidth(lineIndex);
  23465. if (this.textAlign === 'center') {
  23466. return (this.width - lineWidth) / 2;
  23467. }
  23468. if (this.textAlign === 'right') {
  23469. return this.width - lineWidth;
  23470. }
  23471. if (this.textAlign === 'justify-center' && this.isEndOfWrapping(lineIndex)) {
  23472. return (this.width - lineWidth) / 2;
  23473. }
  23474. if (this.textAlign === 'justify-right' && this.isEndOfWrapping(lineIndex)) {
  23475. return this.width - lineWidth;
  23476. }
  23477. return 0;
  23478. },
  23479. /**
  23480. * @private
  23481. */
  23482. _clearCache: function() {
  23483. this.__lineWidths = [];
  23484. this.__lineHeights = [];
  23485. this.__charBounds = [];
  23486. },
  23487. /**
  23488. * @private
  23489. */
  23490. _shouldClearDimensionCache: function() {
  23491. var shouldClear = this._forceClearCache;
  23492. shouldClear || (shouldClear = this.hasStateChanged('_dimensionAffectingProps'));
  23493. if (shouldClear) {
  23494. this.dirty = true;
  23495. this._forceClearCache = false;
  23496. }
  23497. return shouldClear;
  23498. },
  23499. /**
  23500. * Measure a single line given its index. Used to calculate the initial
  23501. * text bounding box. The values are calculated and stored in __lineWidths cache.
  23502. * @private
  23503. * @param {Number} lineIndex line number
  23504. * @return {Number} Line width
  23505. */
  23506. getLineWidth: function(lineIndex) {
  23507. if (this.__lineWidths[lineIndex]) {
  23508. return this.__lineWidths[lineIndex];
  23509. }
  23510. var width, line = this._textLines[lineIndex], lineInfo;
  23511. if (line === '') {
  23512. width = 0;
  23513. }
  23514. else {
  23515. lineInfo = this.measureLine(lineIndex);
  23516. width = lineInfo.width;
  23517. }
  23518. this.__lineWidths[lineIndex] = width;
  23519. return width;
  23520. },
  23521. _getWidthOfCharSpacing: function() {
  23522. if (this.charSpacing !== 0) {
  23523. return this.fontSize * this.charSpacing / 1000;
  23524. }
  23525. return 0;
  23526. },
  23527. /**
  23528. * Retrieves the value of property at given character position
  23529. * @param {Number} lineIndex the line number
  23530. * @param {Number} charIndex the charater number
  23531. * @param {String} property the property name
  23532. * @returns the value of 'property'
  23533. */
  23534. getValueOfPropertyAt: function(lineIndex, charIndex, property) {
  23535. var charStyle = this._getStyleDeclaration(lineIndex, charIndex);
  23536. if (charStyle && typeof charStyle[property] !== 'undefined') {
  23537. return charStyle[property];
  23538. }
  23539. return this[property];
  23540. },
  23541. /**
  23542. * @private
  23543. * @param {CanvasRenderingContext2D} ctx Context to render on
  23544. */
  23545. _renderTextDecoration: function(ctx, type) {
  23546. if (!this[type] && !this.styleHas(type)) {
  23547. return;
  23548. }
  23549. var heightOfLine, size, _size,
  23550. lineLeftOffset, dy, _dy,
  23551. line, lastDecoration,
  23552. leftOffset = this._getLeftOffset(),
  23553. topOffset = this._getTopOffset(), top,
  23554. boxStart, boxWidth, charBox, currentDecoration,
  23555. maxHeight, currentFill, lastFill,
  23556. charSpacing = this._getWidthOfCharSpacing();
  23557. for (var i = 0, len = this._textLines.length; i < len; i++) {
  23558. heightOfLine = this.getHeightOfLine(i);
  23559. if (!this[type] && !this.styleHas(type, i)) {
  23560. topOffset += heightOfLine;
  23561. continue;
  23562. }
  23563. line = this._textLines[i];
  23564. maxHeight = heightOfLine / this.lineHeight;
  23565. lineLeftOffset = this._getLineLeftOffset(i);
  23566. boxStart = 0;
  23567. boxWidth = 0;
  23568. lastDecoration = this.getValueOfPropertyAt(i, 0, type);
  23569. lastFill = this.getValueOfPropertyAt(i, 0, 'fill');
  23570. top = topOffset + maxHeight * (1 - this._fontSizeFraction);
  23571. size = this.getHeightOfChar(i, 0);
  23572. dy = this.getValueOfPropertyAt(i, 0, 'deltaY');
  23573. for (var j = 0, jlen = line.length; j < jlen; j++) {
  23574. charBox = this.__charBounds[i][j];
  23575. currentDecoration = this.getValueOfPropertyAt(i, j, type);
  23576. currentFill = this.getValueOfPropertyAt(i, j, 'fill');
  23577. _size = this.getHeightOfChar(i, j);
  23578. _dy = this.getValueOfPropertyAt(i, j, 'deltaY');
  23579. if ((currentDecoration !== lastDecoration || currentFill !== lastFill || _size !== size || _dy !== dy) &&
  23580. boxWidth > 0) {
  23581. ctx.fillStyle = lastFill;
  23582. lastDecoration && lastFill && ctx.fillRect(
  23583. leftOffset + lineLeftOffset + boxStart,
  23584. top + this.offsets[type] * size + dy,
  23585. boxWidth,
  23586. this.fontSize / 15
  23587. );
  23588. boxStart = charBox.left;
  23589. boxWidth = charBox.width;
  23590. lastDecoration = currentDecoration;
  23591. lastFill = currentFill;
  23592. size = _size;
  23593. dy = _dy;
  23594. }
  23595. else {
  23596. boxWidth += charBox.kernedWidth;
  23597. }
  23598. }
  23599. ctx.fillStyle = currentFill;
  23600. currentDecoration && currentFill && ctx.fillRect(
  23601. leftOffset + lineLeftOffset + boxStart,
  23602. top + this.offsets[type] * size + dy,
  23603. boxWidth - charSpacing,
  23604. this.fontSize / 15
  23605. );
  23606. topOffset += heightOfLine;
  23607. }
  23608. // if there is text background color no
  23609. // other shadows should be casted
  23610. this._removeShadow(ctx);
  23611. },
  23612. /**
  23613. * return font declaration string for canvas context
  23614. * @param {Object} [styleObject] object
  23615. * @returns {String} font declaration formatted for canvas context.
  23616. */
  23617. _getFontDeclaration: function(styleObject, forMeasuring) {
  23618. var style = styleObject || this, family = this.fontFamily,
  23619. fontIsGeneric = fabric.Text.genericFonts.indexOf(family.toLowerCase()) > -1;
  23620. var fontFamily = family === undefined ||
  23621. family.indexOf('\'') > -1 ||
  23622. family.indexOf('"') > -1 || fontIsGeneric
  23623. ? style.fontFamily : '"' + style.fontFamily + '"';
  23624. return [
  23625. // node-canvas needs "weight style", while browsers need "style weight"
  23626. (fabric.isLikelyNode ? style.fontWeight : style.fontStyle),
  23627. (fabric.isLikelyNode ? style.fontStyle : style.fontWeight),
  23628. forMeasuring ? this.CACHE_FONT_SIZE + 'px' : style.fontSize + 'px',
  23629. fontFamily
  23630. ].join(' ');
  23631. },
  23632. /**
  23633. * Renders text instance on a specified context
  23634. * @param {CanvasRenderingContext2D} ctx Context to render on
  23635. */
  23636. render: function(ctx) {
  23637. // do not render if object is not visible
  23638. if (!this.visible) {
  23639. return;
  23640. }
  23641. if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {
  23642. return;
  23643. }
  23644. if (this._shouldClearDimensionCache()) {
  23645. this.initDimensions();
  23646. }
  23647. this.callSuper('render', ctx);
  23648. },
  23649. /**
  23650. * Returns the text as an array of lines.
  23651. * @param {String} text text to split
  23652. * @returns {Array} Lines in the text
  23653. */
  23654. _splitTextIntoLines: function(text) {
  23655. var lines = text.split(this._reNewline),
  23656. newLines = new Array(lines.length),
  23657. newLine = ['\n'],
  23658. newText = [];
  23659. for (var i = 0; i < lines.length; i++) {
  23660. newLines[i] = fabric.util.string.graphemeSplit(lines[i]);
  23661. newText = newText.concat(newLines[i], newLine);
  23662. }
  23663. newText.pop();
  23664. return { _unwrappedLines: newLines, lines: lines, graphemeText: newText, graphemeLines: newLines };
  23665. },
  23666. /**
  23667. * Returns object representation of an instance
  23668. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  23669. * @return {Object} Object representation of an instance
  23670. */
  23671. toObject: function(propertiesToInclude) {
  23672. var additionalProperties = [
  23673. 'text',
  23674. 'fontSize',
  23675. 'fontWeight',
  23676. 'fontFamily',
  23677. 'fontStyle',
  23678. 'lineHeight',
  23679. 'underline',
  23680. 'overline',
  23681. 'linethrough',
  23682. 'textAlign',
  23683. 'textBackgroundColor',
  23684. 'charSpacing',
  23685. ].concat(propertiesToInclude);
  23686. var obj = this.callSuper('toObject', additionalProperties);
  23687. obj.styles = clone(this.styles, true);
  23688. return obj;
  23689. },
  23690. /**
  23691. * Sets property to a given value. When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. If you need to update those, call `setCoords()`.
  23692. * @param {String|Object} key Property name or object (if object, iterate over the object properties)
  23693. * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
  23694. * @return {fabric.Object} thisArg
  23695. * @chainable
  23696. */
  23697. set: function(key, value) {
  23698. this.callSuper('set', key, value);
  23699. var needsDims = false;
  23700. if (typeof key === 'object') {
  23701. for (var _key in key) {
  23702. needsDims = needsDims || this._dimensionAffectingProps.indexOf(_key) !== -1;
  23703. }
  23704. }
  23705. else {
  23706. needsDims = this._dimensionAffectingProps.indexOf(key) !== -1;
  23707. }
  23708. if (needsDims) {
  23709. this.initDimensions();
  23710. this.setCoords();
  23711. }
  23712. return this;
  23713. },
  23714. /**
  23715. * Returns complexity of an instance
  23716. * @return {Number} complexity
  23717. */
  23718. complexity: function() {
  23719. return 1;
  23720. }
  23721. });
  23722. /**
  23723. * Returns fabric.Text instance from an object representation
  23724. * @static
  23725. * @memberOf fabric.Text
  23726. * @param {Object} object Object to create an instance from
  23727. * @param {Function} [callback] Callback to invoke when an fabric.Text instance is created
  23728. */
  23729. fabric.Text.fromObject = function(object, callback) {
  23730. return fabric.Object._fromObject('Text', object, callback, 'text');
  23731. };
  23732. fabric.Text.genericFonts = ['sans-serif', 'serif', 'cursive', 'fantasy', 'monospace'];
  23733. fabric.util.createAccessors && fabric.util.createAccessors(fabric.Text);
  23734. })(typeof exports !== 'undefined' ? exports : this);
  23735. (function() {
  23736. fabric.util.object.extend(fabric.Text.prototype, /** @lends fabric.Text.prototype */ {
  23737. /**
  23738. * Returns true if object has no styling or no styling in a line
  23739. * @param {Number} lineIndex , lineIndex is on wrapped lines.
  23740. * @return {Boolean}
  23741. */
  23742. isEmptyStyles: function(lineIndex) {
  23743. if (!this.styles) {
  23744. return true;
  23745. }
  23746. if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {
  23747. return true;
  23748. }
  23749. var obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };
  23750. for (var p1 in obj) {
  23751. for (var p2 in obj[p1]) {
  23752. // eslint-disable-next-line no-unused-vars
  23753. for (var p3 in obj[p1][p2]) {
  23754. return false;
  23755. }
  23756. }
  23757. }
  23758. return true;
  23759. },
  23760. /**
  23761. * Returns true if object has a style property or has it ina specified line
  23762. * @param {Number} lineIndex
  23763. * @return {Boolean}
  23764. */
  23765. styleHas: function(property, lineIndex) {
  23766. if (!this.styles || !property || property === '') {
  23767. return false;
  23768. }
  23769. if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {
  23770. return false;
  23771. }
  23772. var obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };
  23773. // eslint-disable-next-line
  23774. for (var p1 in obj) {
  23775. // eslint-disable-next-line
  23776. for (var p2 in obj[p1]) {
  23777. if (typeof obj[p1][p2][property] !== 'undefined') {
  23778. return true;
  23779. }
  23780. }
  23781. }
  23782. return false;
  23783. },
  23784. /**
  23785. * Check if characters in a text have a value for a property
  23786. * whose value matches the textbox's value for that property. If so,
  23787. * the character-level property is deleted. If the character
  23788. * has no other properties, then it is also deleted. Finally,
  23789. * if the line containing that character has no other characters
  23790. * then it also is deleted.
  23791. *
  23792. * @param {string} property The property to compare between characters and text.
  23793. */
  23794. cleanStyle: function(property) {
  23795. if (!this.styles || !property || property === '') {
  23796. return false;
  23797. }
  23798. var obj = this.styles, stylesCount = 0, letterCount, stylePropertyValue,
  23799. allStyleObjectPropertiesMatch = true, graphemeCount = 0, styleObject;
  23800. // eslint-disable-next-line
  23801. for (var p1 in obj) {
  23802. letterCount = 0;
  23803. // eslint-disable-next-line
  23804. for (var p2 in obj[p1]) {
  23805. var styleObject = obj[p1][p2],
  23806. stylePropertyHasBeenSet = styleObject.hasOwnProperty(property);
  23807. stylesCount++;
  23808. if (stylePropertyHasBeenSet) {
  23809. if (!stylePropertyValue) {
  23810. stylePropertyValue = styleObject[property];
  23811. }
  23812. else if (styleObject[property] !== stylePropertyValue) {
  23813. allStyleObjectPropertiesMatch = false;
  23814. }
  23815. if (styleObject[property] === this[property]) {
  23816. delete styleObject[property];
  23817. }
  23818. }
  23819. else {
  23820. allStyleObjectPropertiesMatch = false;
  23821. }
  23822. if (Object.keys(styleObject).length !== 0) {
  23823. letterCount++;
  23824. }
  23825. else {
  23826. delete obj[p1][p2];
  23827. }
  23828. }
  23829. if (letterCount === 0) {
  23830. delete obj[p1];
  23831. }
  23832. }
  23833. // if every grapheme has the same style set then
  23834. // delete those styles and set it on the parent
  23835. for (var i = 0; i < this._textLines.length; i++) {
  23836. graphemeCount += this._textLines[i].length;
  23837. }
  23838. if (allStyleObjectPropertiesMatch && stylesCount === graphemeCount) {
  23839. this[property] = stylePropertyValue;
  23840. this.removeStyle(property);
  23841. }
  23842. },
  23843. /**
  23844. * Remove a style property or properties from all individual character styles
  23845. * in a text object. Deletes the character style object if it contains no other style
  23846. * props. Deletes a line style object if it contains no other character styles.
  23847. *
  23848. * @param {String} props The property to remove from character styles.
  23849. */
  23850. removeStyle: function(property) {
  23851. if (!this.styles || !property || property === '') {
  23852. return;
  23853. }
  23854. var obj = this.styles, line, lineNum, charNum;
  23855. for (lineNum in obj) {
  23856. line = obj[lineNum];
  23857. for (charNum in line) {
  23858. delete line[charNum][property];
  23859. if (Object.keys(line[charNum]).length === 0) {
  23860. delete line[charNum];
  23861. }
  23862. }
  23863. if (Object.keys(line).length === 0) {
  23864. delete obj[lineNum];
  23865. }
  23866. }
  23867. },
  23868. /**
  23869. * @private
  23870. */
  23871. _extendStyles: function(index, styles) {
  23872. var loc = this.get2DCursorLocation(index);
  23873. if (!this._getLineStyle(loc.lineIndex)) {
  23874. this._setLineStyle(loc.lineIndex, {});
  23875. }
  23876. if (!this._getStyleDeclaration(loc.lineIndex, loc.charIndex)) {
  23877. this._setStyleDeclaration(loc.lineIndex, loc.charIndex, {});
  23878. }
  23879. fabric.util.object.extend(this._getStyleDeclaration(loc.lineIndex, loc.charIndex), styles);
  23880. },
  23881. /**
  23882. * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start)
  23883. * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used.
  23884. * @param {Boolean} [skipWrapping] consider the location for unwrapped lines. usefull to manage styles.
  23885. */
  23886. get2DCursorLocation: function(selectionStart, skipWrapping) {
  23887. if (typeof selectionStart === 'undefined') {
  23888. selectionStart = this.selectionStart;
  23889. }
  23890. var lines = skipWrapping ? this._unwrappedTextLines : this._textLines;
  23891. var len = lines.length;
  23892. for (var i = 0; i < len; i++) {
  23893. if (selectionStart <= lines[i].length) {
  23894. return {
  23895. lineIndex: i,
  23896. charIndex: selectionStart
  23897. };
  23898. }
  23899. selectionStart -= lines[i].length + 1;
  23900. }
  23901. return {
  23902. lineIndex: i - 1,
  23903. charIndex: lines[i - 1].length < selectionStart ? lines[i - 1].length : selectionStart
  23904. };
  23905. },
  23906. /**
  23907. * Gets style of a current selection/cursor (at the start position)
  23908. * if startIndex or endIndex are not provided, slectionStart or selectionEnd will be used.
  23909. * @param {Number} [startIndex] Start index to get styles at
  23910. * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1
  23911. * @param {Boolean} [complete] get full style or not
  23912. * @return {Array} styles an array with one, zero or more Style objects
  23913. */
  23914. getSelectionStyles: function(startIndex, endIndex, complete) {
  23915. if (typeof startIndex === 'undefined') {
  23916. startIndex = this.selectionStart || 0;
  23917. }
  23918. if (typeof endIndex === 'undefined') {
  23919. endIndex = this.selectionEnd || startIndex;
  23920. }
  23921. var styles = [];
  23922. for (var i = startIndex; i < endIndex; i++) {
  23923. styles.push(this.getStyleAtPosition(i, complete));
  23924. }
  23925. return styles;
  23926. },
  23927. /**
  23928. * Gets style of a current selection/cursor position
  23929. * @param {Number} position to get styles at
  23930. * @param {Boolean} [complete] full style if true
  23931. * @return {Object} style Style object at a specified index
  23932. * @private
  23933. */
  23934. getStyleAtPosition: function(position, complete) {
  23935. var loc = this.get2DCursorLocation(position),
  23936. style = complete ? this.getCompleteStyleDeclaration(loc.lineIndex, loc.charIndex) :
  23937. this._getStyleDeclaration(loc.lineIndex, loc.charIndex);
  23938. return style || {};
  23939. },
  23940. /**
  23941. * Sets style of a current selection, if no selection exist, do not set anything.
  23942. * @param {Object} [styles] Styles object
  23943. * @param {Number} [startIndex] Start index to get styles at
  23944. * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1
  23945. * @return {fabric.IText} thisArg
  23946. * @chainable
  23947. */
  23948. setSelectionStyles: function(styles, startIndex, endIndex) {
  23949. if (typeof startIndex === 'undefined') {
  23950. startIndex = this.selectionStart || 0;
  23951. }
  23952. if (typeof endIndex === 'undefined') {
  23953. endIndex = this.selectionEnd || startIndex;
  23954. }
  23955. for (var i = startIndex; i < endIndex; i++) {
  23956. this._extendStyles(i, styles);
  23957. }
  23958. /* not included in _extendStyles to avoid clearing cache more than once */
  23959. this._forceClearCache = true;
  23960. return this;
  23961. },
  23962. /**
  23963. * get the reference, not a clone, of the style object for a given character
  23964. * @param {Number} lineIndex
  23965. * @param {Number} charIndex
  23966. * @return {Object} style object
  23967. */
  23968. _getStyleDeclaration: function(lineIndex, charIndex) {
  23969. var lineStyle = this.styles && this.styles[lineIndex];
  23970. if (!lineStyle) {
  23971. return null;
  23972. }
  23973. return lineStyle[charIndex];
  23974. },
  23975. /**
  23976. * return a new object that contains all the style property for a character
  23977. * the object returned is newly created
  23978. * @param {Number} lineIndex of the line where the character is
  23979. * @param {Number} charIndex position of the character on the line
  23980. * @return {Object} style object
  23981. */
  23982. getCompleteStyleDeclaration: function(lineIndex, charIndex) {
  23983. var style = this._getStyleDeclaration(lineIndex, charIndex) || { },
  23984. styleObject = { }, prop;
  23985. for (var i = 0; i < this._styleProperties.length; i++) {
  23986. prop = this._styleProperties[i];
  23987. styleObject[prop] = typeof style[prop] === 'undefined' ? this[prop] : style[prop];
  23988. }
  23989. return styleObject;
  23990. },
  23991. /**
  23992. * @param {Number} lineIndex
  23993. * @param {Number} charIndex
  23994. * @param {Object} style
  23995. * @private
  23996. */
  23997. _setStyleDeclaration: function(lineIndex, charIndex, style) {
  23998. this.styles[lineIndex][charIndex] = style;
  23999. },
  24000. /**
  24001. *
  24002. * @param {Number} lineIndex
  24003. * @param {Number} charIndex
  24004. * @private
  24005. */
  24006. _deleteStyleDeclaration: function(lineIndex, charIndex) {
  24007. delete this.styles[lineIndex][charIndex];
  24008. },
  24009. /**
  24010. * @param {Number} lineIndex
  24011. * @private
  24012. */
  24013. _getLineStyle: function(lineIndex) {
  24014. return this.styles[lineIndex];
  24015. },
  24016. /**
  24017. * @param {Number} lineIndex
  24018. * @param {Object} style
  24019. * @private
  24020. */
  24021. _setLineStyle: function(lineIndex, style) {
  24022. this.styles[lineIndex] = style;
  24023. },
  24024. /**
  24025. * @param {Number} lineIndex
  24026. * @private
  24027. */
  24028. _deleteLineStyle: function(lineIndex) {
  24029. delete this.styles[lineIndex];
  24030. }
  24031. });
  24032. })();
  24033. (function() {
  24034. function parseDecoration(object) {
  24035. if (object.textDecoration) {
  24036. object.textDecoration.indexOf('underline') > -1 && (object.underline = true);
  24037. object.textDecoration.indexOf('line-through') > -1 && (object.linethrough = true);
  24038. object.textDecoration.indexOf('overline') > -1 && (object.overline = true);
  24039. delete object.textDecoration;
  24040. }
  24041. }
  24042. /**
  24043. * IText class (introduced in <b>v1.4</b>) Events are also fired with "text:"
  24044. * prefix when observing canvas.
  24045. * @class fabric.IText
  24046. * @extends fabric.Text
  24047. * @mixes fabric.Observable
  24048. *
  24049. * @fires changed
  24050. * @fires selection:changed
  24051. * @fires editing:entered
  24052. * @fires editing:exited
  24053. *
  24054. * @return {fabric.IText} thisArg
  24055. * @see {@link fabric.IText#initialize} for constructor definition
  24056. *
  24057. * <p>Supported key combinations:</p>
  24058. * <pre>
  24059. * Move cursor: left, right, up, down
  24060. * Select character: shift + left, shift + right
  24061. * Select text vertically: shift + up, shift + down
  24062. * Move cursor by word: alt + left, alt + right
  24063. * Select words: shift + alt + left, shift + alt + right
  24064. * Move cursor to line start/end: cmd + left, cmd + right or home, end
  24065. * Select till start/end of line: cmd + shift + left, cmd + shift + right or shift + home, shift + end
  24066. * Jump to start/end of text: cmd + up, cmd + down
  24067. * Select till start/end of text: cmd + shift + up, cmd + shift + down or shift + pgUp, shift + pgDown
  24068. * Delete character: backspace
  24069. * Delete word: alt + backspace
  24070. * Delete line: cmd + backspace
  24071. * Forward delete: delete
  24072. * Copy text: ctrl/cmd + c
  24073. * Paste text: ctrl/cmd + v
  24074. * Cut text: ctrl/cmd + x
  24075. * Select entire text: ctrl/cmd + a
  24076. * Quit editing tab or esc
  24077. * </pre>
  24078. *
  24079. * <p>Supported mouse/touch combination</p>
  24080. * <pre>
  24081. * Position cursor: click/touch
  24082. * Create selection: click/touch & drag
  24083. * Create selection: click & shift + click
  24084. * Select word: double click
  24085. * Select line: triple click
  24086. * </pre>
  24087. */
  24088. fabric.IText = fabric.util.createClass(fabric.Text, fabric.Observable, /** @lends fabric.IText.prototype */ {
  24089. /**
  24090. * Type of an object
  24091. * @type String
  24092. * @default
  24093. */
  24094. type: 'i-text',
  24095. /**
  24096. * Index where text selection starts (or where cursor is when there is no selection)
  24097. * @type Number
  24098. * @default
  24099. */
  24100. selectionStart: 0,
  24101. /**
  24102. * Index where text selection ends
  24103. * @type Number
  24104. * @default
  24105. */
  24106. selectionEnd: 0,
  24107. /**
  24108. * Color of text selection
  24109. * @type String
  24110. * @default
  24111. */
  24112. selectionColor: 'rgba(17,119,255,0.3)',
  24113. /**
  24114. * Indicates whether text is in editing mode
  24115. * @type Boolean
  24116. * @default
  24117. */
  24118. isEditing: false,
  24119. /**
  24120. * Indicates whether a text can be edited
  24121. * @type Boolean
  24122. * @default
  24123. */
  24124. editable: true,
  24125. /**
  24126. * Border color of text object while it's in editing mode
  24127. * @type String
  24128. * @default
  24129. */
  24130. editingBorderColor: 'rgba(102,153,255,0.25)',
  24131. /**
  24132. * Width of cursor (in px)
  24133. * @type Number
  24134. * @default
  24135. */
  24136. cursorWidth: 2,
  24137. /**
  24138. * Color of default cursor (when not overwritten by character style)
  24139. * @type String
  24140. * @default
  24141. */
  24142. cursorColor: '#333',
  24143. /**
  24144. * Delay between cursor blink (in ms)
  24145. * @type Number
  24146. * @default
  24147. */
  24148. cursorDelay: 1000,
  24149. /**
  24150. * Duration of cursor fadein (in ms)
  24151. * @type Number
  24152. * @default
  24153. */
  24154. cursorDuration: 600,
  24155. /**
  24156. * Indicates whether internal text char widths can be cached
  24157. * @type Boolean
  24158. * @default
  24159. */
  24160. caching: true,
  24161. /**
  24162. * @private
  24163. */
  24164. _reSpace: /\s|\n/,
  24165. /**
  24166. * @private
  24167. */
  24168. _currentCursorOpacity: 0,
  24169. /**
  24170. * @private
  24171. */
  24172. _selectionDirection: null,
  24173. /**
  24174. * @private
  24175. */
  24176. _abortCursorAnimation: false,
  24177. /**
  24178. * @private
  24179. */
  24180. __widthOfSpace: [],
  24181. /**
  24182. * Helps determining when the text is in composition, so that the cursor
  24183. * rendering is altered.
  24184. */
  24185. inCompositionMode: false,
  24186. /**
  24187. * Constructor
  24188. * @param {String} text Text string
  24189. * @param {Object} [options] Options object
  24190. * @return {fabric.IText} thisArg
  24191. */
  24192. initialize: function(text, options) {
  24193. this.callSuper('initialize', text, options);
  24194. this.initBehavior();
  24195. },
  24196. /**
  24197. * Sets selection start (left boundary of a selection)
  24198. * @param {Number} index Index to set selection start to
  24199. */
  24200. setSelectionStart: function(index) {
  24201. index = Math.max(index, 0);
  24202. this._updateAndFire('selectionStart', index);
  24203. },
  24204. /**
  24205. * Sets selection end (right boundary of a selection)
  24206. * @param {Number} index Index to set selection end to
  24207. */
  24208. setSelectionEnd: function(index) {
  24209. index = Math.min(index, this.text.length);
  24210. this._updateAndFire('selectionEnd', index);
  24211. },
  24212. /**
  24213. * @private
  24214. * @param {String} property 'selectionStart' or 'selectionEnd'
  24215. * @param {Number} index new position of property
  24216. */
  24217. _updateAndFire: function(property, index) {
  24218. if (this[property] !== index) {
  24219. this._fireSelectionChanged();
  24220. this[property] = index;
  24221. }
  24222. this._updateTextarea();
  24223. },
  24224. /**
  24225. * Fires the even of selection changed
  24226. * @private
  24227. */
  24228. _fireSelectionChanged: function() {
  24229. this.fire('selection:changed');
  24230. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  24231. },
  24232. /**
  24233. * Initialize text dimensions. Render all text on given context
  24234. * or on a offscreen canvas to get the text width with measureText.
  24235. * Updates this.width and this.height with the proper values.
  24236. * Does not return dimensions.
  24237. * @private
  24238. */
  24239. initDimensions: function() {
  24240. this.isEditing && this.initDelayedCursor();
  24241. this.clearContextTop();
  24242. this.callSuper('initDimensions');
  24243. },
  24244. /**
  24245. * @private
  24246. * @param {CanvasRenderingContext2D} ctx Context to render on
  24247. */
  24248. render: function(ctx) {
  24249. this.clearContextTop();
  24250. this.callSuper('render', ctx);
  24251. // clear the cursorOffsetCache, so we ensure to calculate once per renderCursor
  24252. // the correct position but not at every cursor animation.
  24253. this.cursorOffsetCache = { };
  24254. this.renderCursorOrSelection();
  24255. },
  24256. /**
  24257. * @private
  24258. * @param {CanvasRenderingContext2D} ctx Context to render on
  24259. */
  24260. _render: function(ctx) {
  24261. this.callSuper('_render', ctx);
  24262. },
  24263. /**
  24264. * Prepare and clean the contextTop
  24265. */
  24266. clearContextTop: function(skipRestore) {
  24267. if (!this.isEditing) {
  24268. return;
  24269. }
  24270. if (this.canvas && this.canvas.contextTop) {
  24271. var ctx = this.canvas.contextTop, v = this.canvas.viewportTransform;
  24272. ctx.save();
  24273. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  24274. this.transform(ctx);
  24275. this.transformMatrix && ctx.transform.apply(ctx, this.transformMatrix);
  24276. this._clearTextArea(ctx);
  24277. skipRestore || ctx.restore();
  24278. }
  24279. },
  24280. /**
  24281. * Renders cursor or selection (depending on what exists)
  24282. */
  24283. renderCursorOrSelection: function() {
  24284. if (!this.isEditing || !this.canvas) {
  24285. return;
  24286. }
  24287. var boundaries = this._getCursorBoundaries(), ctx;
  24288. if (this.canvas && this.canvas.contextTop) {
  24289. ctx = this.canvas.contextTop;
  24290. this.clearContextTop(true);
  24291. }
  24292. else {
  24293. ctx = this.canvas.contextContainer;
  24294. ctx.save();
  24295. }
  24296. if (this.selectionStart === this.selectionEnd) {
  24297. this.renderCursor(boundaries, ctx);
  24298. }
  24299. else {
  24300. this.renderSelection(boundaries, ctx);
  24301. }
  24302. ctx.restore();
  24303. },
  24304. _clearTextArea: function(ctx) {
  24305. // we add 4 pixel, to be sure to do not leave any pixel out
  24306. var width = this.width + 4, height = this.height + 4;
  24307. ctx.clearRect(-width / 2, -height / 2, width, height);
  24308. },
  24309. /**
  24310. * Returns cursor boundaries (left, top, leftOffset, topOffset)
  24311. * @private
  24312. * @param {Array} chars Array of characters
  24313. * @param {String} typeOfBoundaries
  24314. */
  24315. _getCursorBoundaries: function(position) {
  24316. // left/top are left/top of entire text box
  24317. // leftOffset/topOffset are offset from that left/top point of a text box
  24318. if (typeof position === 'undefined') {
  24319. position = this.selectionStart;
  24320. }
  24321. var left = this._getLeftOffset(),
  24322. top = this._getTopOffset(),
  24323. offsets = this._getCursorBoundariesOffsets(position);
  24324. return {
  24325. left: left,
  24326. top: top,
  24327. leftOffset: offsets.left,
  24328. topOffset: offsets.top
  24329. };
  24330. },
  24331. /**
  24332. * @private
  24333. */
  24334. _getCursorBoundariesOffsets: function(position) {
  24335. if (this.cursorOffsetCache && 'top' in this.cursorOffsetCache) {
  24336. return this.cursorOffsetCache;
  24337. }
  24338. var lineLeftOffset,
  24339. lineIndex,
  24340. charIndex,
  24341. topOffset = 0,
  24342. leftOffset = 0,
  24343. boundaries,
  24344. cursorPosition = this.get2DCursorLocation(position);
  24345. charIndex = cursorPosition.charIndex;
  24346. lineIndex = cursorPosition.lineIndex;
  24347. for (var i = 0; i < lineIndex; i++) {
  24348. topOffset += this.getHeightOfLine(i);
  24349. }
  24350. lineLeftOffset = this._getLineLeftOffset(lineIndex);
  24351. var bound = this.__charBounds[lineIndex][charIndex];
  24352. bound && (leftOffset = bound.left);
  24353. if (this.charSpacing !== 0 && charIndex === this._textLines[lineIndex].length) {
  24354. leftOffset -= this._getWidthOfCharSpacing();
  24355. }
  24356. boundaries = {
  24357. top: topOffset,
  24358. left: lineLeftOffset + (leftOffset > 0 ? leftOffset : 0),
  24359. };
  24360. this.cursorOffsetCache = boundaries;
  24361. return this.cursorOffsetCache;
  24362. },
  24363. /**
  24364. * Renders cursor
  24365. * @param {Object} boundaries
  24366. * @param {CanvasRenderingContext2D} ctx transformed context to draw on
  24367. */
  24368. renderCursor: function(boundaries, ctx) {
  24369. var cursorLocation = this.get2DCursorLocation(),
  24370. lineIndex = cursorLocation.lineIndex,
  24371. charIndex = cursorLocation.charIndex > 0 ? cursorLocation.charIndex - 1 : 0,
  24372. charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, 'fontSize'),
  24373. multiplier = this.scaleX * this.canvas.getZoom(),
  24374. cursorWidth = this.cursorWidth / multiplier,
  24375. topOffset = boundaries.topOffset,
  24376. dy = this.getValueOfPropertyAt(lineIndex, charIndex, 'deltaY');
  24377. topOffset += (1 - this._fontSizeFraction) * this.getHeightOfLine(lineIndex) / this.lineHeight
  24378. - charHeight * (1 - this._fontSizeFraction);
  24379. if (this.inCompositionMode) {
  24380. this.renderSelection(boundaries, ctx);
  24381. }
  24382. ctx.fillStyle = this.getValueOfPropertyAt(lineIndex, charIndex, 'fill');
  24383. ctx.globalAlpha = this.__isMousedown ? 1 : this._currentCursorOpacity;
  24384. ctx.fillRect(
  24385. boundaries.left + boundaries.leftOffset - cursorWidth / 2,
  24386. topOffset + boundaries.top + dy,
  24387. cursorWidth,
  24388. charHeight);
  24389. },
  24390. /**
  24391. * Renders text selection
  24392. * @param {Object} boundaries Object with left/top/leftOffset/topOffset
  24393. * @param {CanvasRenderingContext2D} ctx transformed context to draw on
  24394. */
  24395. renderSelection: function(boundaries, ctx) {
  24396. var selectionStart = this.inCompositionMode ? this.hiddenTextarea.selectionStart : this.selectionStart,
  24397. selectionEnd = this.inCompositionMode ? this.hiddenTextarea.selectionEnd : this.selectionEnd,
  24398. isJustify = this.textAlign.indexOf('justify') !== -1,
  24399. start = this.get2DCursorLocation(selectionStart),
  24400. end = this.get2DCursorLocation(selectionEnd),
  24401. startLine = start.lineIndex,
  24402. endLine = end.lineIndex,
  24403. startChar = start.charIndex < 0 ? 0 : start.charIndex,
  24404. endChar = end.charIndex < 0 ? 0 : end.charIndex;
  24405. for (var i = startLine; i <= endLine; i++) {
  24406. var lineOffset = this._getLineLeftOffset(i) || 0,
  24407. lineHeight = this.getHeightOfLine(i),
  24408. realLineHeight = 0, boxStart = 0, boxEnd = 0;
  24409. if (i === startLine) {
  24410. boxStart = this.__charBounds[startLine][startChar].left;
  24411. }
  24412. if (i >= startLine && i < endLine) {
  24413. boxEnd = isJustify && !this.isEndOfWrapping(i) ? this.width : this.getLineWidth(i) || 5; // WTF is this 5?
  24414. }
  24415. else if (i === endLine) {
  24416. if (endChar === 0) {
  24417. boxEnd = this.__charBounds[endLine][endChar].left;
  24418. }
  24419. else {
  24420. var charSpacing = this._getWidthOfCharSpacing();
  24421. boxEnd = this.__charBounds[endLine][endChar - 1].left
  24422. + this.__charBounds[endLine][endChar - 1].width - charSpacing;
  24423. }
  24424. }
  24425. realLineHeight = lineHeight;
  24426. if (this.lineHeight < 1 || (i === endLine && this.lineHeight > 1)) {
  24427. lineHeight /= this.lineHeight;
  24428. }
  24429. if (this.inCompositionMode) {
  24430. ctx.fillStyle = this.compositionColor || 'black';
  24431. ctx.fillRect(
  24432. boundaries.left + lineOffset + boxStart,
  24433. boundaries.top + boundaries.topOffset + lineHeight,
  24434. boxEnd - boxStart,
  24435. 1);
  24436. }
  24437. else {
  24438. ctx.fillStyle = this.selectionColor;
  24439. ctx.fillRect(
  24440. boundaries.left + lineOffset + boxStart,
  24441. boundaries.top + boundaries.topOffset,
  24442. boxEnd - boxStart,
  24443. lineHeight);
  24444. }
  24445. boundaries.topOffset += realLineHeight;
  24446. }
  24447. },
  24448. /**
  24449. * High level function to know the height of the cursor.
  24450. * the currentChar is the one that precedes the cursor
  24451. * Returns fontSize of char at the current cursor
  24452. * @return {Number} Character font size
  24453. */
  24454. getCurrentCharFontSize: function() {
  24455. var cp = this._getCurrentCharIndex();
  24456. return this.getValueOfPropertyAt(cp.l, cp.c, 'fontSize');
  24457. },
  24458. /**
  24459. * High level function to know the color of the cursor.
  24460. * the currentChar is the one that precedes the cursor
  24461. * Returns color (fill) of char at the current cursor
  24462. * @return {String} Character color (fill)
  24463. */
  24464. getCurrentCharColor: function() {
  24465. var cp = this._getCurrentCharIndex();
  24466. return this.getValueOfPropertyAt(cp.l, cp.c, 'fill');
  24467. },
  24468. /**
  24469. * Returns the cursor position for the getCurrent.. functions
  24470. * @private
  24471. */
  24472. _getCurrentCharIndex: function() {
  24473. var cursorPosition = this.get2DCursorLocation(this.selectionStart, true),
  24474. charIndex = cursorPosition.charIndex > 0 ? cursorPosition.charIndex - 1 : 0;
  24475. return { l: cursorPosition.lineIndex, c: charIndex };
  24476. }
  24477. });
  24478. /**
  24479. * Returns fabric.IText instance from an object representation
  24480. * @static
  24481. * @memberOf fabric.IText
  24482. * @param {Object} object Object to create an instance from
  24483. * @param {function} [callback] invoked with new instance as argument
  24484. */
  24485. fabric.IText.fromObject = function(object, callback) {
  24486. parseDecoration(object);
  24487. if (object.styles) {
  24488. for (var i in object.styles) {
  24489. for (var j in object.styles[i]) {
  24490. parseDecoration(object.styles[i][j]);
  24491. }
  24492. }
  24493. }
  24494. fabric.Object._fromObject('IText', object, callback, 'text');
  24495. };
  24496. })();
  24497. (function() {
  24498. var clone = fabric.util.object.clone;
  24499. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  24500. /**
  24501. * Initializes all the interactive behavior of IText
  24502. */
  24503. initBehavior: function() {
  24504. this.initAddedHandler();
  24505. this.initRemovedHandler();
  24506. this.initCursorSelectionHandlers();
  24507. this.initDoubleClickSimulation();
  24508. this.mouseMoveHandler = this.mouseMoveHandler.bind(this);
  24509. },
  24510. onDeselect: function() {
  24511. this.isEditing && this.exitEditing();
  24512. this.selected = false;
  24513. },
  24514. /**
  24515. * Initializes "added" event handler
  24516. */
  24517. initAddedHandler: function() {
  24518. var _this = this;
  24519. this.on('added', function() {
  24520. var canvas = _this.canvas;
  24521. if (canvas) {
  24522. if (!canvas._hasITextHandlers) {
  24523. canvas._hasITextHandlers = true;
  24524. _this._initCanvasHandlers(canvas);
  24525. }
  24526. canvas._iTextInstances = canvas._iTextInstances || [];
  24527. canvas._iTextInstances.push(_this);
  24528. }
  24529. });
  24530. },
  24531. initRemovedHandler: function() {
  24532. var _this = this;
  24533. this.on('removed', function() {
  24534. var canvas = _this.canvas;
  24535. if (canvas) {
  24536. canvas._iTextInstances = canvas._iTextInstances || [];
  24537. fabric.util.removeFromArray(canvas._iTextInstances, _this);
  24538. if (canvas._iTextInstances.length === 0) {
  24539. canvas._hasITextHandlers = false;
  24540. _this._removeCanvasHandlers(canvas);
  24541. }
  24542. }
  24543. });
  24544. },
  24545. /**
  24546. * register canvas event to manage exiting on other instances
  24547. * @private
  24548. */
  24549. _initCanvasHandlers: function(canvas) {
  24550. canvas._mouseUpITextHandler = function() {
  24551. if (canvas._iTextInstances) {
  24552. canvas._iTextInstances.forEach(function(obj) {
  24553. obj.__isMousedown = false;
  24554. });
  24555. }
  24556. };
  24557. canvas.on('mouse:up', canvas._mouseUpITextHandler);
  24558. },
  24559. /**
  24560. * remove canvas event to manage exiting on other instances
  24561. * @private
  24562. */
  24563. _removeCanvasHandlers: function(canvas) {
  24564. canvas.off('mouse:up', canvas._mouseUpITextHandler);
  24565. },
  24566. /**
  24567. * @private
  24568. */
  24569. _tick: function() {
  24570. this._currentTickState = this._animateCursor(this, 1, this.cursorDuration, '_onTickComplete');
  24571. },
  24572. /**
  24573. * @private
  24574. */
  24575. _animateCursor: function(obj, targetOpacity, duration, completeMethod) {
  24576. var tickState;
  24577. tickState = {
  24578. isAborted: false,
  24579. abort: function() {
  24580. this.isAborted = true;
  24581. },
  24582. };
  24583. obj.animate('_currentCursorOpacity', targetOpacity, {
  24584. duration: duration,
  24585. onComplete: function() {
  24586. if (!tickState.isAborted) {
  24587. obj[completeMethod]();
  24588. }
  24589. },
  24590. onChange: function() {
  24591. // we do not want to animate a selection, only cursor
  24592. if (obj.canvas && obj.selectionStart === obj.selectionEnd) {
  24593. obj.renderCursorOrSelection();
  24594. }
  24595. },
  24596. abort: function() {
  24597. return tickState.isAborted;
  24598. }
  24599. });
  24600. return tickState;
  24601. },
  24602. /**
  24603. * @private
  24604. */
  24605. _onTickComplete: function() {
  24606. var _this = this;
  24607. if (this._cursorTimeout1) {
  24608. clearTimeout(this._cursorTimeout1);
  24609. }
  24610. this._cursorTimeout1 = setTimeout(function() {
  24611. _this._currentTickCompleteState = _this._animateCursor(_this, 0, this.cursorDuration / 2, '_tick');
  24612. }, 100);
  24613. },
  24614. /**
  24615. * Initializes delayed cursor
  24616. */
  24617. initDelayedCursor: function(restart) {
  24618. var _this = this,
  24619. delay = restart ? 0 : this.cursorDelay;
  24620. this.abortCursorAnimation();
  24621. this._currentCursorOpacity = 1;
  24622. this._cursorTimeout2 = setTimeout(function() {
  24623. _this._tick();
  24624. }, delay);
  24625. },
  24626. /**
  24627. * Aborts cursor animation and clears all timeouts
  24628. */
  24629. abortCursorAnimation: function() {
  24630. var shouldClear = this._currentTickState || this._currentTickCompleteState,
  24631. canvas = this.canvas;
  24632. this._currentTickState && this._currentTickState.abort();
  24633. this._currentTickCompleteState && this._currentTickCompleteState.abort();
  24634. clearTimeout(this._cursorTimeout1);
  24635. clearTimeout(this._cursorTimeout2);
  24636. this._currentCursorOpacity = 0;
  24637. // to clear just itext area we need to transform the context
  24638. // it may not be worth it
  24639. if (shouldClear && canvas) {
  24640. canvas.clearContext(canvas.contextTop || canvas.contextContainer);
  24641. }
  24642. },
  24643. /**
  24644. * Selects entire text
  24645. * @return {fabric.IText} thisArg
  24646. * @chainable
  24647. */
  24648. selectAll: function() {
  24649. this.selectionStart = 0;
  24650. this.selectionEnd = this._text.length;
  24651. this._fireSelectionChanged();
  24652. this._updateTextarea();
  24653. return this;
  24654. },
  24655. /**
  24656. * Returns selected text
  24657. * @return {String}
  24658. */
  24659. getSelectedText: function() {
  24660. return this._text.slice(this.selectionStart, this.selectionEnd).join('');
  24661. },
  24662. /**
  24663. * Find new selection index representing start of current word according to current selection index
  24664. * @param {Number} startFrom Surrent selection index
  24665. * @return {Number} New selection index
  24666. */
  24667. findWordBoundaryLeft: function(startFrom) {
  24668. var offset = 0, index = startFrom - 1;
  24669. // remove space before cursor first
  24670. if (this._reSpace.test(this._text[index])) {
  24671. while (this._reSpace.test(this._text[index])) {
  24672. offset++;
  24673. index--;
  24674. }
  24675. }
  24676. while (/\S/.test(this._text[index]) && index > -1) {
  24677. offset++;
  24678. index--;
  24679. }
  24680. return startFrom - offset;
  24681. },
  24682. /**
  24683. * Find new selection index representing end of current word according to current selection index
  24684. * @param {Number} startFrom Current selection index
  24685. * @return {Number} New selection index
  24686. */
  24687. findWordBoundaryRight: function(startFrom) {
  24688. var offset = 0, index = startFrom;
  24689. // remove space after cursor first
  24690. if (this._reSpace.test(this._text[index])) {
  24691. while (this._reSpace.test(this._text[index])) {
  24692. offset++;
  24693. index++;
  24694. }
  24695. }
  24696. while (/\S/.test(this._text[index]) && index < this.text.length) {
  24697. offset++;
  24698. index++;
  24699. }
  24700. return startFrom + offset;
  24701. },
  24702. /**
  24703. * Find new selection index representing start of current line according to current selection index
  24704. * @param {Number} startFrom Current selection index
  24705. * @return {Number} New selection index
  24706. */
  24707. findLineBoundaryLeft: function(startFrom) {
  24708. var offset = 0, index = startFrom - 1;
  24709. while (!/\n/.test(this._text[index]) && index > -1) {
  24710. offset++;
  24711. index--;
  24712. }
  24713. return startFrom - offset;
  24714. },
  24715. /**
  24716. * Find new selection index representing end of current line according to current selection index
  24717. * @param {Number} startFrom Current selection index
  24718. * @return {Number} New selection index
  24719. */
  24720. findLineBoundaryRight: function(startFrom) {
  24721. var offset = 0, index = startFrom;
  24722. while (!/\n/.test(this._text[index]) && index < this.text.length) {
  24723. offset++;
  24724. index++;
  24725. }
  24726. return startFrom + offset;
  24727. },
  24728. /**
  24729. * Finds index corresponding to beginning or end of a word
  24730. * @param {Number} selectionStart Index of a character
  24731. * @param {Number} direction 1 or -1
  24732. * @return {Number} Index of the beginning or end of a word
  24733. */
  24734. searchWordBoundary: function(selectionStart, direction) {
  24735. var index = this._reSpace.test(this.text.charAt(selectionStart)) ? selectionStart - 1 : selectionStart,
  24736. _char = this.text.charAt(index),
  24737. reNonWord = /[ \n\.,;!\?\-]/;
  24738. while (!reNonWord.test(_char) && index > 0 && index < this.text.length) {
  24739. index += direction;
  24740. _char = this.text.charAt(index);
  24741. }
  24742. if (reNonWord.test(_char) && _char !== '\n') {
  24743. index += direction === 1 ? 0 : 1;
  24744. }
  24745. return index;
  24746. },
  24747. /**
  24748. * Selects a word based on the index
  24749. * @param {Number} selectionStart Index of a character
  24750. */
  24751. selectWord: function(selectionStart) {
  24752. selectionStart = selectionStart || this.selectionStart;
  24753. var newSelectionStart = this.searchWordBoundary(selectionStart, -1), /* search backwards */
  24754. newSelectionEnd = this.searchWordBoundary(selectionStart, 1); /* search forward */
  24755. this.selectionStart = newSelectionStart;
  24756. this.selectionEnd = newSelectionEnd;
  24757. this._fireSelectionChanged();
  24758. this._updateTextarea();
  24759. this.renderCursorOrSelection();
  24760. },
  24761. /**
  24762. * Selects a line based on the index
  24763. * @param {Number} selectionStart Index of a character
  24764. * @return {fabric.IText} thisArg
  24765. * @chainable
  24766. */
  24767. selectLine: function(selectionStart) {
  24768. selectionStart = selectionStart || this.selectionStart;
  24769. var newSelectionStart = this.findLineBoundaryLeft(selectionStart),
  24770. newSelectionEnd = this.findLineBoundaryRight(selectionStart);
  24771. this.selectionStart = newSelectionStart;
  24772. this.selectionEnd = newSelectionEnd;
  24773. this._fireSelectionChanged();
  24774. this._updateTextarea();
  24775. return this;
  24776. },
  24777. /**
  24778. * Enters editing state
  24779. * @return {fabric.IText} thisArg
  24780. * @chainable
  24781. */
  24782. enterEditing: function(e) {
  24783. if (this.isEditing || !this.editable) {
  24784. return;
  24785. }
  24786. if (this.canvas) {
  24787. this.canvas.calcOffset();
  24788. this.exitEditingOnOthers(this.canvas);
  24789. }
  24790. this.isEditing = true;
  24791. this.initHiddenTextarea(e);
  24792. this.hiddenTextarea.focus();
  24793. this.hiddenTextarea.value = this.text;
  24794. this._updateTextarea();
  24795. this._saveEditingProps();
  24796. this._setEditingProps();
  24797. this._textBeforeEdit = this.text;
  24798. this._tick();
  24799. this.fire('editing:entered');
  24800. this._fireSelectionChanged();
  24801. if (!this.canvas) {
  24802. return this;
  24803. }
  24804. this.canvas.fire('text:editing:entered', { target: this });
  24805. this.initMouseMoveHandler();
  24806. this.canvas.requestRenderAll();
  24807. return this;
  24808. },
  24809. exitEditingOnOthers: function(canvas) {
  24810. if (canvas._iTextInstances) {
  24811. canvas._iTextInstances.forEach(function(obj) {
  24812. obj.selected = false;
  24813. if (obj.isEditing) {
  24814. obj.exitEditing();
  24815. }
  24816. });
  24817. }
  24818. },
  24819. /**
  24820. * Initializes "mousemove" event handler
  24821. */
  24822. initMouseMoveHandler: function() {
  24823. this.canvas.on('mouse:move', this.mouseMoveHandler);
  24824. },
  24825. /**
  24826. * @private
  24827. */
  24828. mouseMoveHandler: function(options) {
  24829. if (!this.__isMousedown || !this.isEditing) {
  24830. return;
  24831. }
  24832. var newSelectionStart = this.getSelectionStartFromPointer(options.e),
  24833. currentStart = this.selectionStart,
  24834. currentEnd = this.selectionEnd;
  24835. if (
  24836. (newSelectionStart !== this.__selectionStartOnMouseDown || currentStart === currentEnd)
  24837. &&
  24838. (currentStart === newSelectionStart || currentEnd === newSelectionStart)
  24839. ) {
  24840. return;
  24841. }
  24842. if (newSelectionStart > this.__selectionStartOnMouseDown) {
  24843. this.selectionStart = this.__selectionStartOnMouseDown;
  24844. this.selectionEnd = newSelectionStart;
  24845. }
  24846. else {
  24847. this.selectionStart = newSelectionStart;
  24848. this.selectionEnd = this.__selectionStartOnMouseDown;
  24849. }
  24850. if (this.selectionStart !== currentStart || this.selectionEnd !== currentEnd) {
  24851. this.restartCursorIfNeeded();
  24852. this._fireSelectionChanged();
  24853. this._updateTextarea();
  24854. this.renderCursorOrSelection();
  24855. }
  24856. },
  24857. /**
  24858. * @private
  24859. */
  24860. _setEditingProps: function() {
  24861. this.hoverCursor = 'text';
  24862. if (this.canvas) {
  24863. this.canvas.defaultCursor = this.canvas.moveCursor = 'text';
  24864. }
  24865. this.borderColor = this.editingBorderColor;
  24866. this.hasControls = this.selectable = false;
  24867. this.lockMovementX = this.lockMovementY = true;
  24868. },
  24869. /**
  24870. * convert from textarea to grapheme indexes
  24871. */
  24872. fromStringToGraphemeSelection: function(start, end, text) {
  24873. var smallerTextStart = text.slice(0, start),
  24874. graphemeStart = fabric.util.string.graphemeSplit(smallerTextStart).length;
  24875. if (start === end) {
  24876. return { selectionStart: graphemeStart, selectionEnd: graphemeStart };
  24877. }
  24878. var smallerTextEnd = text.slice(start, end),
  24879. graphemeEnd = fabric.util.string.graphemeSplit(smallerTextEnd).length;
  24880. return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };
  24881. },
  24882. /**
  24883. * convert from fabric to textarea values
  24884. */
  24885. fromGraphemeToStringSelection: function(start, end, _text) {
  24886. var smallerTextStart = _text.slice(0, start),
  24887. graphemeStart = smallerTextStart.join('').length;
  24888. if (start === end) {
  24889. return { selectionStart: graphemeStart, selectionEnd: graphemeStart };
  24890. }
  24891. var smallerTextEnd = _text.slice(start, end),
  24892. graphemeEnd = smallerTextEnd.join('').length;
  24893. return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };
  24894. },
  24895. /**
  24896. * @private
  24897. */
  24898. _updateTextarea: function() {
  24899. this.cursorOffsetCache = { };
  24900. if (!this.hiddenTextarea) {
  24901. return;
  24902. }
  24903. if (!this.inCompositionMode) {
  24904. var newSelection = this.fromGraphemeToStringSelection(this.selectionStart, this.selectionEnd, this._text);
  24905. this.hiddenTextarea.selectionStart = newSelection.selectionStart;
  24906. this.hiddenTextarea.selectionEnd = newSelection.selectionEnd;
  24907. }
  24908. this.updateTextareaPosition();
  24909. },
  24910. /**
  24911. * @private
  24912. */
  24913. updateFromTextArea: function() {
  24914. if (!this.hiddenTextarea) {
  24915. return;
  24916. }
  24917. this.cursorOffsetCache = { };
  24918. this.text = this.hiddenTextarea.value;
  24919. if (this._shouldClearDimensionCache()) {
  24920. this.initDimensions();
  24921. this.setCoords();
  24922. }
  24923. var newSelection = this.fromStringToGraphemeSelection(
  24924. this.hiddenTextarea.selectionStart, this.hiddenTextarea.selectionEnd, this.hiddenTextarea.value);
  24925. this.selectionEnd = this.selectionStart = newSelection.selectionEnd;
  24926. if (!this.inCompositionMode) {
  24927. this.selectionStart = newSelection.selectionStart;
  24928. }
  24929. this.updateTextareaPosition();
  24930. },
  24931. /**
  24932. * @private
  24933. */
  24934. updateTextareaPosition: function() {
  24935. if (this.selectionStart === this.selectionEnd) {
  24936. var style = this._calcTextareaPosition();
  24937. this.hiddenTextarea.style.left = style.left;
  24938. this.hiddenTextarea.style.top = style.top;
  24939. }
  24940. },
  24941. /**
  24942. * @private
  24943. * @return {Object} style contains style for hiddenTextarea
  24944. */
  24945. _calcTextareaPosition: function() {
  24946. if (!this.canvas) {
  24947. return { x: 1, y: 1 };
  24948. }
  24949. var desiredPostion = this.inCompositionMode ? this.compositionStart : this.selectionStart,
  24950. boundaries = this._getCursorBoundaries(desiredPostion),
  24951. cursorLocation = this.get2DCursorLocation(desiredPostion),
  24952. lineIndex = cursorLocation.lineIndex,
  24953. charIndex = cursorLocation.charIndex,
  24954. charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, 'fontSize') * this.lineHeight,
  24955. leftOffset = boundaries.leftOffset,
  24956. m = this.calcTransformMatrix(),
  24957. p = {
  24958. x: boundaries.left + leftOffset,
  24959. y: boundaries.top + boundaries.topOffset + charHeight
  24960. },
  24961. upperCanvas = this.canvas.upperCanvasEl,
  24962. upperCanvasWidth = upperCanvas.width,
  24963. upperCanvasHeight = upperCanvas.height,
  24964. maxWidth = upperCanvasWidth - charHeight,
  24965. maxHeight = upperCanvasHeight - charHeight,
  24966. scaleX = upperCanvas.clientWidth / upperCanvasWidth,
  24967. scaleY = upperCanvas.clientHeight / upperCanvasHeight;
  24968. p = fabric.util.transformPoint(p, m);
  24969. p = fabric.util.transformPoint(p, this.canvas.viewportTransform);
  24970. p.x *= scaleX;
  24971. p.y *= scaleY;
  24972. if (p.x < 0) {
  24973. p.x = 0;
  24974. }
  24975. if (p.x > maxWidth) {
  24976. p.x = maxWidth;
  24977. }
  24978. if (p.y < 0) {
  24979. p.y = 0;
  24980. }
  24981. if (p.y > maxHeight) {
  24982. p.y = maxHeight;
  24983. }
  24984. // add canvas offset on document
  24985. p.x += this.canvas._offset.left;
  24986. p.y += this.canvas._offset.top;
  24987. return { left: p.x + 'px', top: p.y + 'px', fontSize: charHeight + 'px', charHeight: charHeight };
  24988. },
  24989. /**
  24990. * @private
  24991. */
  24992. _saveEditingProps: function() {
  24993. this._savedProps = {
  24994. hasControls: this.hasControls,
  24995. borderColor: this.borderColor,
  24996. lockMovementX: this.lockMovementX,
  24997. lockMovementY: this.lockMovementY,
  24998. hoverCursor: this.hoverCursor,
  24999. defaultCursor: this.canvas && this.canvas.defaultCursor,
  25000. moveCursor: this.canvas && this.canvas.moveCursor
  25001. };
  25002. },
  25003. /**
  25004. * @private
  25005. */
  25006. _restoreEditingProps: function() {
  25007. if (!this._savedProps) {
  25008. return;
  25009. }
  25010. this.hoverCursor = this._savedProps.hoverCursor;
  25011. this.hasControls = this._savedProps.hasControls;
  25012. this.borderColor = this._savedProps.borderColor;
  25013. this.lockMovementX = this._savedProps.lockMovementX;
  25014. this.lockMovementY = this._savedProps.lockMovementY;
  25015. if (this.canvas) {
  25016. this.canvas.defaultCursor = this._savedProps.defaultCursor;
  25017. this.canvas.moveCursor = this._savedProps.moveCursor;
  25018. }
  25019. },
  25020. /**
  25021. * Exits from editing state
  25022. * @return {fabric.IText} thisArg
  25023. * @chainable
  25024. */
  25025. exitEditing: function() {
  25026. var isTextChanged = (this._textBeforeEdit !== this.text);
  25027. this.selected = false;
  25028. this.isEditing = false;
  25029. this.selectable = true;
  25030. this.selectionEnd = this.selectionStart;
  25031. if (this.hiddenTextarea) {
  25032. this.hiddenTextarea.blur && this.hiddenTextarea.blur();
  25033. this.canvas && this.hiddenTextarea.parentNode.removeChild(this.hiddenTextarea);
  25034. this.hiddenTextarea = null;
  25035. }
  25036. this.abortCursorAnimation();
  25037. this._restoreEditingProps();
  25038. this._currentCursorOpacity = 0;
  25039. if (this._shouldClearDimensionCache()) {
  25040. this.initDimensions();
  25041. this.setCoords();
  25042. }
  25043. this.fire('editing:exited');
  25044. isTextChanged && this.fire('modified');
  25045. if (this.canvas) {
  25046. this.canvas.off('mouse:move', this.mouseMoveHandler);
  25047. this.canvas.fire('text:editing:exited', { target: this });
  25048. isTextChanged && this.canvas.fire('object:modified', { target: this });
  25049. }
  25050. return this;
  25051. },
  25052. /**
  25053. * @private
  25054. */
  25055. _removeExtraneousStyles: function() {
  25056. for (var prop in this.styles) {
  25057. if (!this._textLines[prop]) {
  25058. delete this.styles[prop];
  25059. }
  25060. }
  25061. },
  25062. /**
  25063. * remove and reflow a style block from start to end.
  25064. * @param {Number} start linear start position for removal (included in removal)
  25065. * @param {Number} end linear end position for removal ( excluded from removal )
  25066. */
  25067. removeStyleFromTo: function(start, end) {
  25068. var cursorStart = this.get2DCursorLocation(start, true),
  25069. cursorEnd = this.get2DCursorLocation(end, true),
  25070. lineStart = cursorStart.lineIndex,
  25071. charStart = cursorStart.charIndex,
  25072. lineEnd = cursorEnd.lineIndex,
  25073. charEnd = cursorEnd.charIndex,
  25074. i, styleObj;
  25075. if (lineStart !== lineEnd) {
  25076. // step1 remove the trailing of lineStart
  25077. if (this.styles[lineStart]) {
  25078. for (i = charStart; i < this._unwrappedTextLines[lineStart].length; i++) {
  25079. delete this.styles[lineStart][i];
  25080. }
  25081. }
  25082. // step2 move the trailing of lineEnd to lineStart if needed
  25083. if (this.styles[lineEnd]) {
  25084. for (i = charEnd; i < this._unwrappedTextLines[lineEnd].length; i++) {
  25085. styleObj = this.styles[lineEnd][i];
  25086. if (styleObj) {
  25087. this.styles[lineStart] || (this.styles[lineStart] = { });
  25088. this.styles[lineStart][charStart + i - charEnd] = styleObj;
  25089. }
  25090. }
  25091. }
  25092. // step3 detects lines will be completely removed.
  25093. for (i = lineStart + 1; i <= lineEnd; i++) {
  25094. delete this.styles[i];
  25095. }
  25096. // step4 shift remaining lines.
  25097. this.shiftLineStyles(lineEnd, lineStart - lineEnd);
  25098. }
  25099. else {
  25100. // remove and shift left on the same line
  25101. if (this.styles[lineStart]) {
  25102. styleObj = this.styles[lineStart];
  25103. var diff = charEnd - charStart, numericChar, _char;
  25104. for (i = charStart; i < charEnd; i++) {
  25105. delete styleObj[i];
  25106. }
  25107. for (_char in this.styles[lineStart]) {
  25108. numericChar = parseInt(_char, 10);
  25109. if (numericChar >= charEnd) {
  25110. styleObj[numericChar - diff] = styleObj[_char];
  25111. delete styleObj[_char];
  25112. }
  25113. }
  25114. }
  25115. }
  25116. },
  25117. /**
  25118. * Shifts line styles up or down
  25119. * @param {Number} lineIndex Index of a line
  25120. * @param {Number} offset Can any number?
  25121. */
  25122. shiftLineStyles: function(lineIndex, offset) {
  25123. // shift all line styles by offset upward or downward
  25124. // do not clone deep. we need new array, not new style objects
  25125. var clonedStyles = clone(this.styles);
  25126. for (var line in this.styles) {
  25127. var numericLine = parseInt(line, 10);
  25128. if (numericLine > lineIndex) {
  25129. this.styles[numericLine + offset] = clonedStyles[numericLine];
  25130. if (!clonedStyles[numericLine - offset]) {
  25131. delete this.styles[numericLine];
  25132. }
  25133. }
  25134. }
  25135. },
  25136. restartCursorIfNeeded: function() {
  25137. if (!this._currentTickState || this._currentTickState.isAborted
  25138. || !this._currentTickCompleteState || this._currentTickCompleteState.isAborted
  25139. ) {
  25140. this.initDelayedCursor();
  25141. }
  25142. },
  25143. /**
  25144. * Inserts new style object
  25145. * @param {Number} lineIndex Index of a line
  25146. * @param {Number} charIndex Index of a char
  25147. * @param {Number} qty number of lines to add
  25148. * @param {Array} copiedStyle Array of objects styles
  25149. */
  25150. insertNewlineStyleObject: function(lineIndex, charIndex, qty, copiedStyle) {
  25151. var currentCharStyle,
  25152. newLineStyles = {},
  25153. somethingAdded = false;
  25154. qty || (qty = 1);
  25155. this.shiftLineStyles(lineIndex, qty);
  25156. if (this.styles[lineIndex]) {
  25157. currentCharStyle = this.styles[lineIndex][charIndex === 0 ? charIndex : charIndex - 1];
  25158. }
  25159. // we clone styles of all chars
  25160. // after cursor onto the current line
  25161. for (var index in this.styles[lineIndex]) {
  25162. var numIndex = parseInt(index, 10);
  25163. if (numIndex >= charIndex) {
  25164. somethingAdded = true;
  25165. newLineStyles[numIndex - charIndex] = this.styles[lineIndex][index];
  25166. // remove lines from the previous line since they're on a new line now
  25167. delete this.styles[lineIndex][index];
  25168. }
  25169. }
  25170. if (somethingAdded) {
  25171. this.styles[lineIndex + qty] = newLineStyles;
  25172. }
  25173. else {
  25174. delete this.styles[lineIndex + qty];
  25175. }
  25176. // for the other lines
  25177. // we clone current char style onto the next (otherwise empty) line
  25178. while (qty > 1) {
  25179. qty--;
  25180. if (copiedStyle && copiedStyle[qty]) {
  25181. this.styles[lineIndex + qty] = { 0: clone(copiedStyle[qty]) };
  25182. }
  25183. else if (currentCharStyle) {
  25184. this.styles[lineIndex + qty] = { 0: clone(currentCharStyle) };
  25185. }
  25186. else {
  25187. delete this.styles[lineIndex + qty];
  25188. }
  25189. }
  25190. this._forceClearCache = true;
  25191. },
  25192. /**
  25193. * Inserts style object for a given line/char index
  25194. * @param {Number} lineIndex Index of a line
  25195. * @param {Number} charIndex Index of a char
  25196. * @param {Number} quantity number Style object to insert, if given
  25197. * @param {Array} copiedStyle array of style objecs
  25198. */
  25199. insertCharStyleObject: function(lineIndex, charIndex, quantity, copiedStyle) {
  25200. if (!this.styles) {
  25201. this.styles = {};
  25202. }
  25203. var currentLineStyles = this.styles[lineIndex],
  25204. currentLineStylesCloned = currentLineStyles ? clone(currentLineStyles) : {};
  25205. quantity || (quantity = 1);
  25206. // shift all char styles by quantity forward
  25207. // 0,1,2,3 -> (charIndex=2) -> 0,1,3,4 -> (insert 2) -> 0,1,2,3,4
  25208. for (var index in currentLineStylesCloned) {
  25209. var numericIndex = parseInt(index, 10);
  25210. if (numericIndex >= charIndex) {
  25211. currentLineStyles[numericIndex + quantity] = currentLineStylesCloned[numericIndex];
  25212. // only delete the style if there was nothing moved there
  25213. if (!currentLineStylesCloned[numericIndex - quantity]) {
  25214. delete currentLineStyles[numericIndex];
  25215. }
  25216. }
  25217. }
  25218. this._forceClearCache = true;
  25219. if (copiedStyle) {
  25220. while (quantity--) {
  25221. if (!Object.keys(copiedStyle[quantity]).length) {
  25222. continue;
  25223. }
  25224. if (!this.styles[lineIndex]) {
  25225. this.styles[lineIndex] = {};
  25226. }
  25227. this.styles[lineIndex][charIndex + quantity] = clone(copiedStyle[quantity]);
  25228. }
  25229. return;
  25230. }
  25231. if (!currentLineStyles) {
  25232. return;
  25233. }
  25234. var newStyle = currentLineStyles[charIndex ? charIndex - 1 : 1];
  25235. while (newStyle && quantity--) {
  25236. this.styles[lineIndex][charIndex + quantity] = clone(newStyle);
  25237. }
  25238. },
  25239. /**
  25240. * Inserts style object(s)
  25241. * @param {Array} insertedText Characters at the location where style is inserted
  25242. * @param {Number} start cursor index for inserting style
  25243. * @param {Array} [copiedStyle] array of style objects to insert.
  25244. */
  25245. insertNewStyleBlock: function(insertedText, start, copiedStyle) {
  25246. var cursorLoc = this.get2DCursorLocation(start, true),
  25247. addedLines = [0], linesLenght = 0;
  25248. for (var i = 0; i < insertedText.length; i++) {
  25249. if (insertedText[i] === '\n') {
  25250. linesLenght++;
  25251. addedLines[linesLenght] = 0;
  25252. }
  25253. else {
  25254. addedLines[linesLenght]++;
  25255. }
  25256. }
  25257. if (addedLines[0] > 0) {
  25258. this.insertCharStyleObject(cursorLoc.lineIndex, cursorLoc.charIndex, addedLines[0], copiedStyle);
  25259. copiedStyle = copiedStyle && copiedStyle.slice(addedLines[0] + 1);
  25260. }
  25261. linesLenght && this.insertNewlineStyleObject(
  25262. cursorLoc.lineIndex, cursorLoc.charIndex + addedLines[0], linesLenght);
  25263. for (var i = 1; i < linesLenght; i++) {
  25264. if (addedLines[i] > 0) {
  25265. this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);
  25266. }
  25267. else if (copiedStyle) {
  25268. this.styles[cursorLoc.lineIndex + i][0] = copiedStyle[0];
  25269. }
  25270. copiedStyle = copiedStyle && copiedStyle.slice(addedLines[i] + 1);
  25271. }
  25272. // we use i outside the loop to get it like linesLength
  25273. if (addedLines[i] > 0) {
  25274. this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);
  25275. }
  25276. },
  25277. /**
  25278. * Set the selectionStart and selectionEnd according to the ne postion of cursor
  25279. * mimic the key - mouse navigation when shift is pressed.
  25280. */
  25281. setSelectionStartEndWithShift: function(start, end, newSelection) {
  25282. if (newSelection <= start) {
  25283. if (end === start) {
  25284. this._selectionDirection = 'left';
  25285. }
  25286. else if (this._selectionDirection === 'right') {
  25287. this._selectionDirection = 'left';
  25288. this.selectionEnd = start;
  25289. }
  25290. this.selectionStart = newSelection;
  25291. }
  25292. else if (newSelection > start && newSelection < end) {
  25293. if (this._selectionDirection === 'right') {
  25294. this.selectionEnd = newSelection;
  25295. }
  25296. else {
  25297. this.selectionStart = newSelection;
  25298. }
  25299. }
  25300. else {
  25301. // newSelection is > selection start and end
  25302. if (end === start) {
  25303. this._selectionDirection = 'right';
  25304. }
  25305. else if (this._selectionDirection === 'left') {
  25306. this._selectionDirection = 'right';
  25307. this.selectionStart = end;
  25308. }
  25309. this.selectionEnd = newSelection;
  25310. }
  25311. },
  25312. setSelectionInBoundaries: function() {
  25313. var length = this.text.length;
  25314. if (this.selectionStart > length) {
  25315. this.selectionStart = length;
  25316. }
  25317. else if (this.selectionStart < 0) {
  25318. this.selectionStart = 0;
  25319. }
  25320. if (this.selectionEnd > length) {
  25321. this.selectionEnd = length;
  25322. }
  25323. else if (this.selectionEnd < 0) {
  25324. this.selectionEnd = 0;
  25325. }
  25326. }
  25327. });
  25328. })();
  25329. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  25330. /**
  25331. * Initializes "dbclick" event handler
  25332. */
  25333. initDoubleClickSimulation: function() {
  25334. // for double click
  25335. this.__lastClickTime = +new Date();
  25336. // for triple click
  25337. this.__lastLastClickTime = +new Date();
  25338. this.__lastPointer = { };
  25339. this.on('mousedown', this.onMouseDown);
  25340. },
  25341. /**
  25342. * Default event handler to simulate triple click
  25343. * @private
  25344. */
  25345. onMouseDown: function(options) {
  25346. if (!this.canvas) {
  25347. return;
  25348. }
  25349. this.__newClickTime = +new Date();
  25350. var newPointer = options.pointer;
  25351. if (this.isTripleClick(newPointer)) {
  25352. this.fire('tripleclick', options);
  25353. this._stopEvent(options.e);
  25354. }
  25355. this.__lastLastClickTime = this.__lastClickTime;
  25356. this.__lastClickTime = this.__newClickTime;
  25357. this.__lastPointer = newPointer;
  25358. this.__lastIsEditing = this.isEditing;
  25359. this.__lastSelected = this.selected;
  25360. },
  25361. isTripleClick: function(newPointer) {
  25362. return this.__newClickTime - this.__lastClickTime < 500 &&
  25363. this.__lastClickTime - this.__lastLastClickTime < 500 &&
  25364. this.__lastPointer.x === newPointer.x &&
  25365. this.__lastPointer.y === newPointer.y;
  25366. },
  25367. /**
  25368. * @private
  25369. */
  25370. _stopEvent: function(e) {
  25371. e.preventDefault && e.preventDefault();
  25372. e.stopPropagation && e.stopPropagation();
  25373. },
  25374. /**
  25375. * Initializes event handlers related to cursor or selection
  25376. */
  25377. initCursorSelectionHandlers: function() {
  25378. this.initMousedownHandler();
  25379. this.initMouseupHandler();
  25380. this.initClicks();
  25381. },
  25382. /**
  25383. * Initializes double and triple click event handlers
  25384. */
  25385. initClicks: function() {
  25386. this.on('mousedblclick', function(options) {
  25387. this.selectWord(this.getSelectionStartFromPointer(options.e));
  25388. });
  25389. this.on('tripleclick', function(options) {
  25390. this.selectLine(this.getSelectionStartFromPointer(options.e));
  25391. });
  25392. },
  25393. /**
  25394. * Default event handler for the basic functionalities needed on _mouseDown
  25395. * can be overridden to do something different.
  25396. * Scope of this implementation is: find the click position, set selectionStart
  25397. * find selectionEnd, initialize the drawing of either cursor or selection area
  25398. */
  25399. _mouseDownHandler: function(options) {
  25400. if (!this.canvas || !this.editable || (options.e.button && options.e.button !== 1)) {
  25401. return;
  25402. }
  25403. this.__isMousedown = true;
  25404. if (this.selected) {
  25405. this.setCursorByClick(options.e);
  25406. }
  25407. if (this.isEditing) {
  25408. this.__selectionStartOnMouseDown = this.selectionStart;
  25409. if (this.selectionStart === this.selectionEnd) {
  25410. this.abortCursorAnimation();
  25411. }
  25412. this.renderCursorOrSelection();
  25413. }
  25414. },
  25415. /**
  25416. * Default event handler for the basic functionalities needed on mousedown:before
  25417. * can be overridden to do something different.
  25418. * Scope of this implementation is: verify the object is already selected when mousing down
  25419. */
  25420. _mouseDownHandlerBefore: function(options) {
  25421. if (!this.canvas || !this.editable || (options.e.button && options.e.button !== 1)) {
  25422. return;
  25423. }
  25424. if (this === this.canvas._activeObject) {
  25425. this.selected = true;
  25426. }
  25427. },
  25428. /**
  25429. * Initializes "mousedown" event handler
  25430. */
  25431. initMousedownHandler: function() {
  25432. this.on('mousedown', this._mouseDownHandler);
  25433. this.on('mousedown:before', this._mouseDownHandlerBefore);
  25434. },
  25435. /**
  25436. * Initializes "mouseup" event handler
  25437. */
  25438. initMouseupHandler: function() {
  25439. this.on('mouseup', this.mouseUpHandler);
  25440. },
  25441. /**
  25442. * standard hander for mouse up, overridable
  25443. * @private
  25444. */
  25445. mouseUpHandler: function(options) {
  25446. this.__isMousedown = false;
  25447. if (!this.editable ||
  25448. (options.transform && options.transform.actionPerformed) ||
  25449. (options.e.button && options.e.button !== 1)) {
  25450. return;
  25451. }
  25452. if (this.__lastSelected && !this.__corner) {
  25453. this.enterEditing(options.e);
  25454. if (this.selectionStart === this.selectionEnd) {
  25455. this.initDelayedCursor(true);
  25456. }
  25457. else {
  25458. this.renderCursorOrSelection();
  25459. }
  25460. }
  25461. this.selected = true;
  25462. },
  25463. /**
  25464. * Changes cursor location in a text depending on passed pointer (x/y) object
  25465. * @param {Event} e Event object
  25466. */
  25467. setCursorByClick: function(e) {
  25468. var newSelection = this.getSelectionStartFromPointer(e),
  25469. start = this.selectionStart, end = this.selectionEnd;
  25470. if (e.shiftKey) {
  25471. this.setSelectionStartEndWithShift(start, end, newSelection);
  25472. }
  25473. else {
  25474. this.selectionStart = newSelection;
  25475. this.selectionEnd = newSelection;
  25476. }
  25477. if (this.isEditing) {
  25478. this._fireSelectionChanged();
  25479. this._updateTextarea();
  25480. }
  25481. },
  25482. /**
  25483. * Returns index of a character corresponding to where an object was clicked
  25484. * @param {Event} e Event object
  25485. * @return {Number} Index of a character
  25486. */
  25487. getSelectionStartFromPointer: function(e) {
  25488. var mouseOffset = this.getLocalPointer(e),
  25489. prevWidth = 0,
  25490. width = 0,
  25491. height = 0,
  25492. charIndex = 0,
  25493. lineIndex = 0,
  25494. lineLeftOffset,
  25495. line;
  25496. for (var i = 0, len = this._textLines.length; i < len; i++) {
  25497. if (height <= mouseOffset.y) {
  25498. height += this.getHeightOfLine(i) * this.scaleY;
  25499. lineIndex = i;
  25500. if (i > 0) {
  25501. charIndex += this._textLines[i - 1].length + 1;
  25502. }
  25503. }
  25504. else {
  25505. break;
  25506. }
  25507. }
  25508. lineLeftOffset = this._getLineLeftOffset(lineIndex);
  25509. width = lineLeftOffset * this.scaleX;
  25510. line = this._textLines[lineIndex];
  25511. for (var j = 0, jlen = line.length; j < jlen; j++) {
  25512. prevWidth = width;
  25513. // i removed something about flipX here, check.
  25514. width += this.__charBounds[lineIndex][j].kernedWidth * this.scaleX;
  25515. if (width <= mouseOffset.x) {
  25516. charIndex++;
  25517. }
  25518. else {
  25519. break;
  25520. }
  25521. }
  25522. return this._getNewSelectionStartFromOffset(mouseOffset, prevWidth, width, charIndex, jlen);
  25523. },
  25524. /**
  25525. * @private
  25526. */
  25527. _getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index, jlen) {
  25528. // we need Math.abs because when width is after the last char, the offset is given as 1, while is 0
  25529. var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth,
  25530. distanceBtwNextCharAndCursor = width - mouseOffset.x,
  25531. offset = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor ||
  25532. distanceBtwNextCharAndCursor < 0 ? 0 : 1,
  25533. newSelectionStart = index + offset;
  25534. // if object is horizontally flipped, mirror cursor location from the end
  25535. if (this.flipX) {
  25536. newSelectionStart = jlen - newSelectionStart;
  25537. }
  25538. if (newSelectionStart > this._text.length) {
  25539. newSelectionStart = this._text.length;
  25540. }
  25541. return newSelectionStart;
  25542. }
  25543. });
  25544. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  25545. /**
  25546. * Initializes hidden textarea (needed to bring up keyboard in iOS)
  25547. */
  25548. initHiddenTextarea: function() {
  25549. this.hiddenTextarea = fabric.document.createElement('textarea');
  25550. this.hiddenTextarea.setAttribute('autocapitalize', 'off');
  25551. this.hiddenTextarea.setAttribute('autocorrect', 'off');
  25552. this.hiddenTextarea.setAttribute('autocomplete', 'off');
  25553. this.hiddenTextarea.setAttribute('spellcheck', 'false');
  25554. this.hiddenTextarea.setAttribute('data-fabric-hiddentextarea', '');
  25555. this.hiddenTextarea.setAttribute('wrap', 'off');
  25556. var style = this._calcTextareaPosition();
  25557. this.hiddenTextarea.style.cssText = 'position: absolute; top: ' + style.top +
  25558. '; left: ' + style.left + '; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px;' +
  25559. ' line-height: 1px; paddingーtop: ' + style.fontSize + ';';
  25560. fabric.document.body.appendChild(this.hiddenTextarea);
  25561. fabric.util.addListener(this.hiddenTextarea, 'keydown', this.onKeyDown.bind(this));
  25562. fabric.util.addListener(this.hiddenTextarea, 'keyup', this.onKeyUp.bind(this));
  25563. fabric.util.addListener(this.hiddenTextarea, 'input', this.onInput.bind(this));
  25564. fabric.util.addListener(this.hiddenTextarea, 'copy', this.copy.bind(this));
  25565. fabric.util.addListener(this.hiddenTextarea, 'cut', this.copy.bind(this));
  25566. fabric.util.addListener(this.hiddenTextarea, 'paste', this.paste.bind(this));
  25567. fabric.util.addListener(this.hiddenTextarea, 'compositionstart', this.onCompositionStart.bind(this));
  25568. fabric.util.addListener(this.hiddenTextarea, 'compositionupdate', this.onCompositionUpdate.bind(this));
  25569. fabric.util.addListener(this.hiddenTextarea, 'compositionend', this.onCompositionEnd.bind(this));
  25570. if (!this._clickHandlerInitialized && this.canvas) {
  25571. fabric.util.addListener(this.canvas.upperCanvasEl, 'click', this.onClick.bind(this));
  25572. this._clickHandlerInitialized = true;
  25573. }
  25574. },
  25575. /**
  25576. * For functionalities on keyDown
  25577. * Map a special key to a function of the instance/prototype
  25578. * If you need different behaviour for ESC or TAB or arrows, you have to change
  25579. * this map setting the name of a function that you build on the fabric.Itext or
  25580. * your prototype.
  25581. * the map change will affect all Instances unless you need for only some text Instances
  25582. * in that case you have to clone this object and assign your Instance.
  25583. * this.keysMap = fabric.util.object.clone(this.keysMap);
  25584. * The function must be in fabric.Itext.prototype.myFunction And will receive event as args[0]
  25585. */
  25586. keysMap: {
  25587. 9: 'exitEditing',
  25588. 27: 'exitEditing',
  25589. 33: 'moveCursorUp',
  25590. 34: 'moveCursorDown',
  25591. 35: 'moveCursorRight',
  25592. 36: 'moveCursorLeft',
  25593. 37: 'moveCursorLeft',
  25594. 38: 'moveCursorUp',
  25595. 39: 'moveCursorRight',
  25596. 40: 'moveCursorDown',
  25597. },
  25598. /**
  25599. * For functionalities on keyUp + ctrl || cmd
  25600. */
  25601. ctrlKeysMapUp: {
  25602. 67: 'copy',
  25603. 88: 'cut'
  25604. },
  25605. /**
  25606. * For functionalities on keyDown + ctrl || cmd
  25607. */
  25608. ctrlKeysMapDown: {
  25609. 65: 'selectAll'
  25610. },
  25611. onClick: function() {
  25612. // No need to trigger click event here, focus is enough to have the keyboard appear on Android
  25613. this.hiddenTextarea && this.hiddenTextarea.focus();
  25614. },
  25615. /**
  25616. * Handles keyup event
  25617. * @param {Event} e Event object
  25618. */
  25619. onKeyDown: function(e) {
  25620. if (!this.isEditing || this.inCompositionMode) {
  25621. return;
  25622. }
  25623. if (e.keyCode in this.keysMap) {
  25624. this[this.keysMap[e.keyCode]](e);
  25625. }
  25626. else if ((e.keyCode in this.ctrlKeysMapDown) && (e.ctrlKey || e.metaKey)) {
  25627. this[this.ctrlKeysMapDown[e.keyCode]](e);
  25628. }
  25629. else {
  25630. return;
  25631. }
  25632. e.stopImmediatePropagation();
  25633. e.preventDefault();
  25634. if (e.keyCode >= 33 && e.keyCode <= 40) {
  25635. // if i press an arrow key just update selection
  25636. this.clearContextTop();
  25637. this.renderCursorOrSelection();
  25638. }
  25639. else {
  25640. this.canvas && this.canvas.requestRenderAll();
  25641. }
  25642. },
  25643. /**
  25644. * Handles keyup event
  25645. * We handle KeyUp because ie11 and edge have difficulties copy/pasting
  25646. * if a copy/cut event fired, keyup is dismissed
  25647. * @param {Event} e Event object
  25648. */
  25649. onKeyUp: function(e) {
  25650. if (!this.isEditing || this._copyDone || this.inCompositionMode) {
  25651. this._copyDone = false;
  25652. return;
  25653. }
  25654. if ((e.keyCode in this.ctrlKeysMapUp) && (e.ctrlKey || e.metaKey)) {
  25655. this[this.ctrlKeysMapUp[e.keyCode]](e);
  25656. }
  25657. else {
  25658. return;
  25659. }
  25660. e.stopImmediatePropagation();
  25661. e.preventDefault();
  25662. this.canvas && this.canvas.requestRenderAll();
  25663. },
  25664. /**
  25665. * Handles onInput event
  25666. * @param {Event} e Event object
  25667. */
  25668. onInput: function(e) {
  25669. var fromPaste = this.fromPaste;
  25670. this.fromPaste = false;
  25671. e && e.stopPropagation();
  25672. if (!this.isEditing) {
  25673. return;
  25674. }
  25675. // decisions about style changes.
  25676. var nextText = this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,
  25677. charCount = this._text.length,
  25678. nextCharCount = nextText.length,
  25679. removedText, insertedText,
  25680. charDiff = nextCharCount - charCount;
  25681. if (this.hiddenTextarea.value === '') {
  25682. this.styles = { };
  25683. this.updateFromTextArea();
  25684. this.fire('changed');
  25685. if (this.canvas) {
  25686. this.canvas.fire('text:changed', { target: this });
  25687. this.canvas.requestRenderAll();
  25688. }
  25689. return;
  25690. }
  25691. var textareaSelection = this.fromStringToGraphemeSelection(
  25692. this.hiddenTextarea.selectionStart,
  25693. this.hiddenTextarea.selectionEnd,
  25694. this.hiddenTextarea.value
  25695. );
  25696. var backDelete = this.selectionStart > textareaSelection.selectionStart;
  25697. if (this.selectionStart !== this.selectionEnd) {
  25698. removedText = this._text.slice(this.selectionStart, this.selectionEnd);
  25699. charDiff += this.selectionEnd - this.selectionStart;
  25700. }
  25701. else if (nextCharCount < charCount) {
  25702. if (backDelete) {
  25703. removedText = this._text.slice(this.selectionEnd + charDiff, this.selectionEnd);
  25704. }
  25705. else {
  25706. removedText = this._text.slice(this.selectionStart, this.selectionStart - charDiff);
  25707. }
  25708. }
  25709. insertedText = nextText.slice(textareaSelection.selectionEnd - charDiff, textareaSelection.selectionEnd);
  25710. if (removedText && removedText.length) {
  25711. if (this.selectionStart !== this.selectionEnd) {
  25712. this.removeStyleFromTo(this.selectionStart, this.selectionEnd);
  25713. }
  25714. else if (backDelete) {
  25715. // detect differencies between forwardDelete and backDelete
  25716. this.removeStyleFromTo(this.selectionEnd - removedText.length, this.selectionEnd);
  25717. }
  25718. else {
  25719. this.removeStyleFromTo(this.selectionEnd, this.selectionEnd + removedText.length);
  25720. }
  25721. }
  25722. if (insertedText.length) {
  25723. if (fromPaste && insertedText.join('') === fabric.copiedText) {
  25724. this.insertNewStyleBlock(insertedText, this.selectionStart, fabric.copiedTextStyle);
  25725. }
  25726. else {
  25727. this.insertNewStyleBlock(insertedText, this.selectionStart);
  25728. }
  25729. }
  25730. this.updateFromTextArea();
  25731. this.fire('changed');
  25732. if (this.canvas) {
  25733. this.canvas.fire('text:changed', { target: this });
  25734. this.canvas.requestRenderAll();
  25735. }
  25736. },
  25737. /**
  25738. * Composition start
  25739. */
  25740. onCompositionStart: function() {
  25741. this.inCompositionMode = true;
  25742. },
  25743. /**
  25744. * Composition end
  25745. */
  25746. onCompositionEnd: function() {
  25747. this.inCompositionMode = false;
  25748. },
  25749. // /**
  25750. // * Composition update
  25751. // */
  25752. onCompositionUpdate: function(e) {
  25753. this.compositionStart = e.target.selectionStart;
  25754. this.compositionEnd = e.target.selectionEnd;
  25755. this.updateTextareaPosition();
  25756. },
  25757. /**
  25758. * Copies selected text
  25759. * @param {Event} e Event object
  25760. */
  25761. copy: function() {
  25762. if (this.selectionStart === this.selectionEnd) {
  25763. //do not cut-copy if no selection
  25764. return;
  25765. }
  25766. fabric.copiedText = this.getSelectedText();
  25767. fabric.copiedTextStyle = this.getSelectionStyles(this.selectionStart, this.selectionEnd, true);
  25768. this._copyDone = true;
  25769. },
  25770. /**
  25771. * Pastes text
  25772. * @param {Event} e Event object
  25773. */
  25774. paste: function() {
  25775. this.fromPaste = true;
  25776. },
  25777. /**
  25778. * @private
  25779. * @param {Event} e Event object
  25780. * @return {Object} Clipboard data object
  25781. */
  25782. _getClipboardData: function(e) {
  25783. return (e && e.clipboardData) || fabric.window.clipboardData;
  25784. },
  25785. /**
  25786. * Finds the width in pixels before the cursor on the same line
  25787. * @private
  25788. * @param {Number} lineIndex
  25789. * @param {Number} charIndex
  25790. * @return {Number} widthBeforeCursor width before cursor
  25791. */
  25792. _getWidthBeforeCursor: function(lineIndex, charIndex) {
  25793. var widthBeforeCursor = this._getLineLeftOffset(lineIndex), bound;
  25794. if (charIndex > 0) {
  25795. bound = this.__charBounds[lineIndex][charIndex - 1];
  25796. widthBeforeCursor += bound.left + bound.width;
  25797. }
  25798. return widthBeforeCursor;
  25799. },
  25800. /**
  25801. * Gets start offset of a selection
  25802. * @param {Event} e Event object
  25803. * @param {Boolean} isRight
  25804. * @return {Number}
  25805. */
  25806. getDownCursorOffset: function(e, isRight) {
  25807. var selectionProp = this._getSelectionForOffset(e, isRight),
  25808. cursorLocation = this.get2DCursorLocation(selectionProp),
  25809. lineIndex = cursorLocation.lineIndex;
  25810. // if on last line, down cursor goes to end of line
  25811. if (lineIndex === this._textLines.length - 1 || e.metaKey || e.keyCode === 34) {
  25812. // move to the end of a text
  25813. return this._text.length - selectionProp;
  25814. }
  25815. var charIndex = cursorLocation.charIndex,
  25816. widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex),
  25817. indexOnOtherLine = this._getIndexOnLine(lineIndex + 1, widthBeforeCursor),
  25818. textAfterCursor = this._textLines[lineIndex].slice(charIndex);
  25819. return textAfterCursor.length + indexOnOtherLine + 2;
  25820. },
  25821. /**
  25822. * private
  25823. * Helps finding if the offset should be counted from Start or End
  25824. * @param {Event} e Event object
  25825. * @param {Boolean} isRight
  25826. * @return {Number}
  25827. */
  25828. _getSelectionForOffset: function(e, isRight) {
  25829. if (e.shiftKey && this.selectionStart !== this.selectionEnd && isRight) {
  25830. return this.selectionEnd;
  25831. }
  25832. else {
  25833. return this.selectionStart;
  25834. }
  25835. },
  25836. /**
  25837. * @param {Event} e Event object
  25838. * @param {Boolean} isRight
  25839. * @return {Number}
  25840. */
  25841. getUpCursorOffset: function(e, isRight) {
  25842. var selectionProp = this._getSelectionForOffset(e, isRight),
  25843. cursorLocation = this.get2DCursorLocation(selectionProp),
  25844. lineIndex = cursorLocation.lineIndex;
  25845. if (lineIndex === 0 || e.metaKey || e.keyCode === 33) {
  25846. // if on first line, up cursor goes to start of line
  25847. return -selectionProp;
  25848. }
  25849. var charIndex = cursorLocation.charIndex,
  25850. widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex),
  25851. indexOnOtherLine = this._getIndexOnLine(lineIndex - 1, widthBeforeCursor),
  25852. textBeforeCursor = this._textLines[lineIndex].slice(0, charIndex);
  25853. // return a negative offset
  25854. return -this._textLines[lineIndex - 1].length + indexOnOtherLine - textBeforeCursor.length;
  25855. },
  25856. /**
  25857. * for a given width it founds the matching character.
  25858. * @private
  25859. */
  25860. _getIndexOnLine: function(lineIndex, width) {
  25861. var line = this._textLines[lineIndex],
  25862. lineLeftOffset = this._getLineLeftOffset(lineIndex),
  25863. widthOfCharsOnLine = lineLeftOffset,
  25864. indexOnLine = 0, charWidth, foundMatch;
  25865. for (var j = 0, jlen = line.length; j < jlen; j++) {
  25866. charWidth = this.__charBounds[lineIndex][j].width;
  25867. widthOfCharsOnLine += charWidth;
  25868. if (widthOfCharsOnLine > width) {
  25869. foundMatch = true;
  25870. var leftEdge = widthOfCharsOnLine - charWidth,
  25871. rightEdge = widthOfCharsOnLine,
  25872. offsetFromLeftEdge = Math.abs(leftEdge - width),
  25873. offsetFromRightEdge = Math.abs(rightEdge - width);
  25874. indexOnLine = offsetFromRightEdge < offsetFromLeftEdge ? j : (j - 1);
  25875. break;
  25876. }
  25877. }
  25878. // reached end
  25879. if (!foundMatch) {
  25880. indexOnLine = line.length - 1;
  25881. }
  25882. return indexOnLine;
  25883. },
  25884. /**
  25885. * Moves cursor down
  25886. * @param {Event} e Event object
  25887. */
  25888. moveCursorDown: function(e) {
  25889. if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {
  25890. return;
  25891. }
  25892. this._moveCursorUpOrDown('Down', e);
  25893. },
  25894. /**
  25895. * Moves cursor up
  25896. * @param {Event} e Event object
  25897. */
  25898. moveCursorUp: function(e) {
  25899. if (this.selectionStart === 0 && this.selectionEnd === 0) {
  25900. return;
  25901. }
  25902. this._moveCursorUpOrDown('Up', e);
  25903. },
  25904. /**
  25905. * Moves cursor up or down, fires the events
  25906. * @param {String} direction 'Up' or 'Down'
  25907. * @param {Event} e Event object
  25908. */
  25909. _moveCursorUpOrDown: function(direction, e) {
  25910. // getUpCursorOffset
  25911. // getDownCursorOffset
  25912. var action = 'get' + direction + 'CursorOffset',
  25913. offset = this[action](e, this._selectionDirection === 'right');
  25914. if (e.shiftKey) {
  25915. this.moveCursorWithShift(offset);
  25916. }
  25917. else {
  25918. this.moveCursorWithoutShift(offset);
  25919. }
  25920. if (offset !== 0) {
  25921. this.setSelectionInBoundaries();
  25922. this.abortCursorAnimation();
  25923. this._currentCursorOpacity = 1;
  25924. this.initDelayedCursor();
  25925. this._fireSelectionChanged();
  25926. this._updateTextarea();
  25927. }
  25928. },
  25929. /**
  25930. * Moves cursor with shift
  25931. * @param {Number} offset
  25932. */
  25933. moveCursorWithShift: function(offset) {
  25934. var newSelection = this._selectionDirection === 'left'
  25935. ? this.selectionStart + offset
  25936. : this.selectionEnd + offset;
  25937. this.setSelectionStartEndWithShift(this.selectionStart, this.selectionEnd, newSelection);
  25938. return offset !== 0;
  25939. },
  25940. /**
  25941. * Moves cursor up without shift
  25942. * @param {Number} offset
  25943. */
  25944. moveCursorWithoutShift: function(offset) {
  25945. if (offset < 0) {
  25946. this.selectionStart += offset;
  25947. this.selectionEnd = this.selectionStart;
  25948. }
  25949. else {
  25950. this.selectionEnd += offset;
  25951. this.selectionStart = this.selectionEnd;
  25952. }
  25953. return offset !== 0;
  25954. },
  25955. /**
  25956. * Moves cursor left
  25957. * @param {Event} e Event object
  25958. */
  25959. moveCursorLeft: function(e) {
  25960. if (this.selectionStart === 0 && this.selectionEnd === 0) {
  25961. return;
  25962. }
  25963. this._moveCursorLeftOrRight('Left', e);
  25964. },
  25965. /**
  25966. * @private
  25967. * @return {Boolean} true if a change happened
  25968. */
  25969. _move: function(e, prop, direction) {
  25970. var newValue;
  25971. if (e.altKey) {
  25972. newValue = this['findWordBoundary' + direction](this[prop]);
  25973. }
  25974. else if (e.metaKey || e.keyCode === 35 || e.keyCode === 36 ) {
  25975. newValue = this['findLineBoundary' + direction](this[prop]);
  25976. }
  25977. else {
  25978. this[prop] += direction === 'Left' ? -1 : 1;
  25979. return true;
  25980. }
  25981. if (typeof newValue !== undefined && this[prop] !== newValue) {
  25982. this[prop] = newValue;
  25983. return true;
  25984. }
  25985. },
  25986. /**
  25987. * @private
  25988. */
  25989. _moveLeft: function(e, prop) {
  25990. return this._move(e, prop, 'Left');
  25991. },
  25992. /**
  25993. * @private
  25994. */
  25995. _moveRight: function(e, prop) {
  25996. return this._move(e, prop, 'Right');
  25997. },
  25998. /**
  25999. * Moves cursor left without keeping selection
  26000. * @param {Event} e
  26001. */
  26002. moveCursorLeftWithoutShift: function(e) {
  26003. var change = true;
  26004. this._selectionDirection = 'left';
  26005. // only move cursor when there is no selection,
  26006. // otherwise we discard it, and leave cursor on same place
  26007. if (this.selectionEnd === this.selectionStart && this.selectionStart !== 0) {
  26008. change = this._moveLeft(e, 'selectionStart');
  26009. }
  26010. this.selectionEnd = this.selectionStart;
  26011. return change;
  26012. },
  26013. /**
  26014. * Moves cursor left while keeping selection
  26015. * @param {Event} e
  26016. */
  26017. moveCursorLeftWithShift: function(e) {
  26018. if (this._selectionDirection === 'right' && this.selectionStart !== this.selectionEnd) {
  26019. return this._moveLeft(e, 'selectionEnd');
  26020. }
  26021. else if (this.selectionStart !== 0){
  26022. this._selectionDirection = 'left';
  26023. return this._moveLeft(e, 'selectionStart');
  26024. }
  26025. },
  26026. /**
  26027. * Moves cursor right
  26028. * @param {Event} e Event object
  26029. */
  26030. moveCursorRight: function(e) {
  26031. if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {
  26032. return;
  26033. }
  26034. this._moveCursorLeftOrRight('Right', e);
  26035. },
  26036. /**
  26037. * Moves cursor right or Left, fires event
  26038. * @param {String} direction 'Left', 'Right'
  26039. * @param {Event} e Event object
  26040. */
  26041. _moveCursorLeftOrRight: function(direction, e) {
  26042. var actionName = 'moveCursor' + direction + 'With';
  26043. this._currentCursorOpacity = 1;
  26044. if (e.shiftKey) {
  26045. actionName += 'Shift';
  26046. }
  26047. else {
  26048. actionName += 'outShift';
  26049. }
  26050. if (this[actionName](e)) {
  26051. this.abortCursorAnimation();
  26052. this.initDelayedCursor();
  26053. this._fireSelectionChanged();
  26054. this._updateTextarea();
  26055. }
  26056. },
  26057. /**
  26058. * Moves cursor right while keeping selection
  26059. * @param {Event} e
  26060. */
  26061. moveCursorRightWithShift: function(e) {
  26062. if (this._selectionDirection === 'left' && this.selectionStart !== this.selectionEnd) {
  26063. return this._moveRight(e, 'selectionStart');
  26064. }
  26065. else if (this.selectionEnd !== this._text.length) {
  26066. this._selectionDirection = 'right';
  26067. return this._moveRight(e, 'selectionEnd');
  26068. }
  26069. },
  26070. /**
  26071. * Moves cursor right without keeping selection
  26072. * @param {Event} e Event object
  26073. */
  26074. moveCursorRightWithoutShift: function(e) {
  26075. var changed = true;
  26076. this._selectionDirection = 'right';
  26077. if (this.selectionStart === this.selectionEnd) {
  26078. changed = this._moveRight(e, 'selectionStart');
  26079. this.selectionEnd = this.selectionStart;
  26080. }
  26081. else {
  26082. this.selectionStart = this.selectionEnd;
  26083. }
  26084. return changed;
  26085. },
  26086. /**
  26087. * Removes characters from start/end
  26088. * start/end ar per grapheme position in _text array.
  26089. *
  26090. * @param {Number} start
  26091. * @param {Number} end default to start + 1
  26092. */
  26093. removeChars: function(start, end) {
  26094. if (typeof end === 'undefined') {
  26095. end = start + 1;
  26096. }
  26097. this.removeStyleFromTo(start, end);
  26098. this._text.splice(start, end - start);
  26099. this.text = this._text.join('');
  26100. this.set('dirty', true);
  26101. if (this._shouldClearDimensionCache()) {
  26102. this.initDimensions();
  26103. this.setCoords();
  26104. }
  26105. this._removeExtraneousStyles();
  26106. },
  26107. /**
  26108. * insert characters at start position, before start position.
  26109. * start equal 1 it means the text get inserted between actual grapheme 0 and 1
  26110. * if style array is provided, it must be as the same length of text in graphemes
  26111. * if end is provided and is bigger than start, old text is replaced.
  26112. * start/end ar per grapheme position in _text array.
  26113. *
  26114. * @param {String} text text to insert
  26115. * @param {Array} style array of style objects
  26116. * @param {Number} start
  26117. * @param {Number} end default to start + 1
  26118. */
  26119. insertChars: function(text, style, start, end) {
  26120. if (typeof end === 'undefined') {
  26121. end = start;
  26122. }
  26123. if (end > start) {
  26124. this.removeStyleFromTo(start, end);
  26125. }
  26126. var graphemes = fabric.util.string.graphemeSplit(text);
  26127. this.insertNewStyleBlock(graphemes, start, style);
  26128. this._text = [].concat(this._text.slice(0, start), graphemes, this._text.slice(end));
  26129. this.text = this._text.join('');
  26130. this.set('dirty', true);
  26131. if (this._shouldClearDimensionCache()) {
  26132. this.initDimensions();
  26133. this.setCoords();
  26134. }
  26135. this._removeExtraneousStyles();
  26136. },
  26137. });
  26138. (function(global) {
  26139. 'use strict';
  26140. var fabric = global.fabric || (global.fabric = {});
  26141. /**
  26142. * Textbox class, based on IText, allows the user to resize the text rectangle
  26143. * and wraps lines automatically. Textboxes have their Y scaling locked, the
  26144. * user can only change width. Height is adjusted automatically based on the
  26145. * wrapping of lines.
  26146. * @class fabric.Textbox
  26147. * @extends fabric.IText
  26148. * @mixes fabric.Observable
  26149. * @return {fabric.Textbox} thisArg
  26150. * @see {@link fabric.Textbox#initialize} for constructor definition
  26151. */
  26152. fabric.Textbox = fabric.util.createClass(fabric.IText, fabric.Observable, {
  26153. /**
  26154. * Type of an object
  26155. * @type String
  26156. * @default
  26157. */
  26158. type: 'textbox',
  26159. /**
  26160. * Minimum width of textbox, in pixels.
  26161. * @type Number
  26162. * @default
  26163. */
  26164. minWidth: 20,
  26165. /**
  26166. * Minimum calculated width of a textbox, in pixels.
  26167. * fixed to 2 so that an empty textbox cannot go to 0
  26168. * and is still selectable without text.
  26169. * @type Number
  26170. * @default
  26171. */
  26172. dynamicMinWidth: 2,
  26173. /**
  26174. * Cached array of text wrapping.
  26175. * @type Array
  26176. */
  26177. __cachedLines: null,
  26178. /**
  26179. * Override standard Object class values
  26180. */
  26181. lockScalingFlip: true,
  26182. /**
  26183. * Override standard Object class values
  26184. * Textbox needs this on false
  26185. */
  26186. noScaleCache: false,
  26187. /**
  26188. * Properties which when set cause object to change dimensions
  26189. * @type Object
  26190. * @private
  26191. */
  26192. _dimensionAffectingProps: fabric.Text.prototype._dimensionAffectingProps.concat('width'),
  26193. /**
  26194. * Unlike superclass's version of this function, Textbox does not update
  26195. * its width.
  26196. * @private
  26197. * @override
  26198. */
  26199. initDimensions: function() {
  26200. if (this.__skipDimension) {
  26201. return;
  26202. }
  26203. this.isEditing && this.initDelayedCursor();
  26204. this.clearContextTop();
  26205. this._clearCache();
  26206. // clear dynamicMinWidth as it will be different after we re-wrap line
  26207. this.dynamicMinWidth = 0;
  26208. // wrap lines
  26209. this._styleMap = this._generateStyleMap(this._splitText());
  26210. // if after wrapping, the width is smaller than dynamicMinWidth, change the width and re-wrap
  26211. if (this.dynamicMinWidth > this.width) {
  26212. this._set('width', this.dynamicMinWidth);
  26213. }
  26214. if (this.textAlign.indexOf('justify') !== -1) {
  26215. // once text is measured we need to make space fatter to make justified text.
  26216. this.enlargeSpaces();
  26217. }
  26218. // clear cache and re-calculate height
  26219. this.height = this.calcTextHeight();
  26220. this.saveState({ propertySet: '_dimensionAffectingProps' });
  26221. },
  26222. /**
  26223. * Generate an object that translates the style object so that it is
  26224. * broken up by visual lines (new lines and automatic wrapping).
  26225. * The original text styles object is broken up by actual lines (new lines only),
  26226. * which is only sufficient for Text / IText
  26227. * @private
  26228. */
  26229. _generateStyleMap: function(textInfo) {
  26230. var realLineCount = 0,
  26231. realLineCharCount = 0,
  26232. charCount = 0,
  26233. map = {};
  26234. for (var i = 0; i < textInfo.graphemeLines.length; i++) {
  26235. if (textInfo.graphemeText[charCount] === '\n' && i > 0) {
  26236. realLineCharCount = 0;
  26237. charCount++;
  26238. realLineCount++;
  26239. }
  26240. else if (this._reSpaceAndTab.test(textInfo.graphemeText[charCount]) && i > 0) {
  26241. // this case deals with space's that are removed from end of lines when wrapping
  26242. realLineCharCount++;
  26243. charCount++;
  26244. }
  26245. map[i] = { line: realLineCount, offset: realLineCharCount };
  26246. charCount += textInfo.graphemeLines[i].length;
  26247. realLineCharCount += textInfo.graphemeLines[i].length;
  26248. }
  26249. return map;
  26250. },
  26251. /**
  26252. * Returns true if object has a style property or has it ina specified line
  26253. * @param {Number} lineIndex
  26254. * @return {Boolean}
  26255. */
  26256. styleHas: function(property, lineIndex) {
  26257. if (this._styleMap && !this.isWrapping) {
  26258. var map = this._styleMap[lineIndex];
  26259. if (map) {
  26260. lineIndex = map.line;
  26261. }
  26262. }
  26263. return fabric.Text.prototype.styleHas.call(this, property, lineIndex);
  26264. },
  26265. /**
  26266. * Returns true if object has no styling or no styling in a line
  26267. * @param {Number} lineIndex , lineIndex is on wrapped lines.
  26268. * @return {Boolean}
  26269. */
  26270. isEmptyStyles: function(lineIndex) {
  26271. var offset = 0, nextLineIndex = lineIndex + 1, nextOffset, obj, shouldLimit = false;
  26272. var map = this._styleMap[lineIndex];
  26273. var mapNextLine = this._styleMap[lineIndex + 1];
  26274. if (map) {
  26275. lineIndex = map.line;
  26276. offset = map.offset;
  26277. }
  26278. if (mapNextLine) {
  26279. nextLineIndex = mapNextLine.line;
  26280. shouldLimit = nextLineIndex === lineIndex;
  26281. nextOffset = mapNextLine.offset;
  26282. }
  26283. obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };
  26284. for (var p1 in obj) {
  26285. for (var p2 in obj[p1]) {
  26286. if (p2 >= offset && (!shouldLimit || p2 < nextOffset)) {
  26287. // eslint-disable-next-line no-unused-vars
  26288. for (var p3 in obj[p1][p2]) {
  26289. return false;
  26290. }
  26291. }
  26292. }
  26293. }
  26294. return true;
  26295. },
  26296. /**
  26297. * @param {Number} lineIndex
  26298. * @param {Number} charIndex
  26299. * @private
  26300. */
  26301. _getStyleDeclaration: function(lineIndex, charIndex) {
  26302. if (this._styleMap && !this.isWrapping) {
  26303. var map = this._styleMap[lineIndex];
  26304. if (!map) {
  26305. return null;
  26306. }
  26307. lineIndex = map.line;
  26308. charIndex = map.offset + charIndex;
  26309. }
  26310. return this.callSuper('_getStyleDeclaration', lineIndex, charIndex);
  26311. },
  26312. /**
  26313. * @param {Number} lineIndex
  26314. * @param {Number} charIndex
  26315. * @param {Object} style
  26316. * @private
  26317. */
  26318. _setStyleDeclaration: function(lineIndex, charIndex, style) {
  26319. var map = this._styleMap[lineIndex];
  26320. lineIndex = map.line;
  26321. charIndex = map.offset + charIndex;
  26322. this.styles[lineIndex][charIndex] = style;
  26323. },
  26324. /**
  26325. * @param {Number} lineIndex
  26326. * @param {Number} charIndex
  26327. * @private
  26328. */
  26329. _deleteStyleDeclaration: function(lineIndex, charIndex) {
  26330. var map = this._styleMap[lineIndex];
  26331. lineIndex = map.line;
  26332. charIndex = map.offset + charIndex;
  26333. delete this.styles[lineIndex][charIndex];
  26334. },
  26335. /**
  26336. * probably broken need a fix
  26337. * @param {Number} lineIndex
  26338. * @private
  26339. */
  26340. _getLineStyle: function(lineIndex) {
  26341. var map = this._styleMap[lineIndex];
  26342. return this.styles[map.line];
  26343. },
  26344. /**
  26345. * probably broken need a fix
  26346. * @param {Number} lineIndex
  26347. * @param {Object} style
  26348. * @private
  26349. */
  26350. _setLineStyle: function(lineIndex, style) {
  26351. var map = this._styleMap[lineIndex];
  26352. this.styles[map.line] = style;
  26353. },
  26354. /**
  26355. * probably broken need a fix
  26356. * @param {Number} lineIndex
  26357. * @private
  26358. */
  26359. _deleteLineStyle: function(lineIndex) {
  26360. var map = this._styleMap[lineIndex];
  26361. delete this.styles[map.line];
  26362. },
  26363. /**
  26364. * Wraps text using the 'width' property of Textbox. First this function
  26365. * splits text on newlines, so we preserve newlines entered by the user.
  26366. * Then it wraps each line using the width of the Textbox by calling
  26367. * _wrapLine().
  26368. * @param {Array} lines The string array of text that is split into lines
  26369. * @param {Number} desiredWidth width you want to wrap to
  26370. * @returns {Array} Array of lines
  26371. */
  26372. _wrapText: function(lines, desiredWidth) {
  26373. var wrapped = [], i;
  26374. this.isWrapping = true;
  26375. for (i = 0; i < lines.length; i++) {
  26376. wrapped = wrapped.concat(this._wrapLine(lines[i], i, desiredWidth));
  26377. }
  26378. this.isWrapping = false;
  26379. return wrapped;
  26380. },
  26381. /**
  26382. * Helper function to measure a string of text, given its lineIndex and charIndex offset
  26383. * it gets called when charBounds are not available yet.
  26384. * @param {CanvasRenderingContext2D} ctx
  26385. * @param {String} text
  26386. * @param {number} lineIndex
  26387. * @param {number} charOffset
  26388. * @returns {number}
  26389. * @private
  26390. */
  26391. _measureWord: function(word, lineIndex, charOffset) {
  26392. var width = 0, prevGrapheme, skipLeft = true;
  26393. charOffset = charOffset || 0;
  26394. for (var i = 0, len = word.length; i < len; i++) {
  26395. var box = this._getGraphemeBox(word[i], lineIndex, i + charOffset, prevGrapheme, skipLeft);
  26396. width += box.kernedWidth;
  26397. prevGrapheme = word[i];
  26398. }
  26399. return width;
  26400. },
  26401. /**
  26402. * Wraps a line of text using the width of the Textbox and a context.
  26403. * @param {Array} line The grapheme array that represent the line
  26404. * @param {Number} lineIndex
  26405. * @param {Number} desiredWidth width you want to wrap the line to
  26406. * @param {Number} reservedSpace space to remove from wrapping for custom functionalities
  26407. * @returns {Array} Array of line(s) into which the given text is wrapped
  26408. * to.
  26409. */
  26410. _wrapLine: function(_line, lineIndex, desiredWidth, reservedSpace) {
  26411. var lineWidth = 0,
  26412. graphemeLines = [],
  26413. line = [],
  26414. // spaces in different languges?
  26415. words = _line.split(this._reSpaceAndTab),
  26416. word = '',
  26417. offset = 0,
  26418. infix = ' ',
  26419. wordWidth = 0,
  26420. infixWidth = 0,
  26421. largestWordWidth = 0,
  26422. lineJustStarted = true,
  26423. additionalSpace = this._getWidthOfCharSpacing(),
  26424. reservedSpace = reservedSpace || 0;
  26425. desiredWidth -= reservedSpace;
  26426. for (var i = 0; i < words.length; i++) {
  26427. // i would avoid resplitting the graphemes
  26428. word = fabric.util.string.graphemeSplit(words[i]);
  26429. wordWidth = this._measureWord(word, lineIndex, offset);
  26430. offset += word.length;
  26431. lineWidth += infixWidth + wordWidth - additionalSpace;
  26432. if (lineWidth >= desiredWidth && !lineJustStarted) {
  26433. graphemeLines.push(line);
  26434. line = [];
  26435. lineWidth = wordWidth;
  26436. lineJustStarted = true;
  26437. }
  26438. else {
  26439. lineWidth += additionalSpace;
  26440. }
  26441. if (!lineJustStarted) {
  26442. line.push(infix);
  26443. }
  26444. line = line.concat(word);
  26445. infixWidth = this._measureWord([infix], lineIndex, offset);
  26446. offset++;
  26447. lineJustStarted = false;
  26448. // keep track of largest word
  26449. if (wordWidth > largestWordWidth) {
  26450. largestWordWidth = wordWidth;
  26451. }
  26452. }
  26453. i && graphemeLines.push(line);
  26454. if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
  26455. this.dynamicMinWidth = largestWordWidth - additionalSpace + reservedSpace;
  26456. }
  26457. return graphemeLines;
  26458. },
  26459. /**
  26460. * Detect if the text line is ended with an hard break
  26461. * text and itext do not have wrapping, return false
  26462. * @param {Number} lineIndex text to split
  26463. * @return {Boolean}
  26464. */
  26465. isEndOfWrapping: function(lineIndex) {
  26466. if (!this._styleMap[lineIndex + 1]) {
  26467. // is last line, return true;
  26468. return true;
  26469. }
  26470. if (this._styleMap[lineIndex + 1].line !== this._styleMap[lineIndex].line) {
  26471. // this is last line before a line break, return true;
  26472. return true;
  26473. }
  26474. return false;
  26475. },
  26476. /**
  26477. * Gets lines of text to render in the Textbox. This function calculates
  26478. * text wrapping on the fly every time it is called.
  26479. * @param {String} text text to split
  26480. * @returns {Array} Array of lines in the Textbox.
  26481. * @override
  26482. */
  26483. _splitTextIntoLines: function(text) {
  26484. var newText = fabric.Text.prototype._splitTextIntoLines.call(this, text),
  26485. graphemeLines = this._wrapText(newText.lines, this.width),
  26486. lines = new Array(graphemeLines.length);
  26487. for (var i = 0; i < graphemeLines.length; i++) {
  26488. lines[i] = graphemeLines[i].join('');
  26489. }
  26490. newText.lines = lines;
  26491. newText.graphemeLines = graphemeLines;
  26492. return newText;
  26493. },
  26494. getMinWidth: function() {
  26495. return Math.max(this.minWidth, this.dynamicMinWidth);
  26496. },
  26497. /**
  26498. * Returns object representation of an instance
  26499. * @method toObject
  26500. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  26501. * @return {Object} object representation of an instance
  26502. */
  26503. toObject: function(propertiesToInclude) {
  26504. return this.callSuper('toObject', ['minWidth'].concat(propertiesToInclude));
  26505. }
  26506. });
  26507. /**
  26508. * Returns fabric.Textbox instance from an object representation
  26509. * @static
  26510. * @memberOf fabric.Textbox
  26511. * @param {Object} object Object to create an instance from
  26512. * @param {Function} [callback] Callback to invoke when an fabric.Textbox instance is created
  26513. */
  26514. fabric.Textbox.fromObject = function(object, callback) {
  26515. return fabric.Object._fromObject('Textbox', object, callback, 'text');
  26516. };
  26517. })(typeof exports !== 'undefined' ? exports : this);
  26518. (function() {
  26519. /**
  26520. * Override _setObjectScale and add Textbox specific resizing behavior. Resizing
  26521. * a Textbox doesn't scale text, it only changes width and makes text wrap automatically.
  26522. */
  26523. var setObjectScaleOverridden = fabric.Canvas.prototype._setObjectScale;
  26524. fabric.Canvas.prototype._setObjectScale = function(localMouse, transform,
  26525. lockScalingX, lockScalingY, by, lockScalingFlip, _dim) {
  26526. var t = transform.target;
  26527. if (by === 'x' && t instanceof fabric.Textbox) {
  26528. var tw = t._getTransformedDimensions().x;
  26529. var w = t.width * (localMouse.x / tw);
  26530. if (w >= t.getMinWidth()) {
  26531. t.set('width', w);
  26532. return true;
  26533. }
  26534. }
  26535. else {
  26536. return setObjectScaleOverridden.call(fabric.Canvas.prototype, localMouse, transform,
  26537. lockScalingX, lockScalingY, by, lockScalingFlip, _dim);
  26538. }
  26539. };
  26540. fabric.util.object.extend(fabric.Textbox.prototype, /** @lends fabric.IText.prototype */ {
  26541. /**
  26542. * @private
  26543. */
  26544. _removeExtraneousStyles: function() {
  26545. for (var prop in this._styleMap) {
  26546. if (!this._textLines[prop]) {
  26547. delete this.styles[this._styleMap[prop].line];
  26548. }
  26549. }
  26550. },
  26551. });
  26552. })();