fabric.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057
  1. /*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */
  2. var fabric = fabric || { version: '5.2.1' };
  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. if (document instanceof (typeof HTMLDocument !== 'undefined' ? HTMLDocument : Document)) {
  13. fabric.document = document;
  14. }
  15. else {
  16. fabric.document = document.implementation.createHTMLDocument('');
  17. }
  18. fabric.window = window;
  19. }
  20. else {
  21. // assume we're running under node.js when document/window are not present
  22. var jsdom = require('jsdom');
  23. var virtualWindow = new jsdom.JSDOM(
  24. decodeURIComponent('%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E'),
  25. {
  26. features: {
  27. FetchExternalResources: ['img']
  28. },
  29. resources: 'usable'
  30. }).window;
  31. fabric.document = virtualWindow.document;
  32. fabric.jsdomImplForWrapper = require('jsdom/lib/jsdom/living/generated/utils').implForWrapper;
  33. fabric.nodeCanvas = require('jsdom/lib/jsdom/utils').Canvas;
  34. fabric.window = virtualWindow;
  35. DOMParser = fabric.window.DOMParser;
  36. }
  37. /**
  38. * True when in environment that supports touch events
  39. * @type boolean
  40. */
  41. fabric.isTouchSupported = 'ontouchstart' in fabric.window || 'ontouchstart' in fabric.document ||
  42. (fabric.window && fabric.window.navigator && fabric.window.navigator.maxTouchPoints > 0);
  43. /**
  44. * True when in environment that's probably Node.js
  45. * @type boolean
  46. */
  47. fabric.isLikelyNode = typeof Buffer !== 'undefined' &&
  48. typeof window === 'undefined';
  49. /* _FROM_SVG_START_ */
  50. /**
  51. * Attributes parsed from all SVG elements
  52. * @type array
  53. */
  54. fabric.SHARED_ATTRIBUTES = [
  55. 'display',
  56. 'transform',
  57. 'fill', 'fill-opacity', 'fill-rule',
  58. 'opacity',
  59. 'stroke', 'stroke-dasharray', 'stroke-linecap', 'stroke-dashoffset',
  60. 'stroke-linejoin', 'stroke-miterlimit',
  61. 'stroke-opacity', 'stroke-width',
  62. 'id', 'paint-order', 'vector-effect',
  63. 'instantiated_by_use', 'clip-path',
  64. ];
  65. /* _FROM_SVG_END_ */
  66. /**
  67. * Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
  68. */
  69. fabric.DPI = 96;
  70. fabric.reNum = '(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)';
  71. fabric.commaWsp = '(?:\\s+,?\\s*|,\\s*)';
  72. fabric.rePathCommand = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/ig;
  73. fabric.reNonWord = /[ \n\.,;!\?\-]/;
  74. fabric.fontPaths = { };
  75. fabric.iMatrix = [1, 0, 0, 1, 0, 0];
  76. fabric.svgNS = 'http://www.w3.org/2000/svg';
  77. /**
  78. * Pixel limit for cache canvases. 1Mpx , 4Mpx should be fine.
  79. * @since 1.7.14
  80. * @type Number
  81. * @default
  82. */
  83. fabric.perfLimitSizeTotal = 2097152;
  84. /**
  85. * Pixel limit for cache canvases width or height. IE fixes the maximum at 5000
  86. * @since 1.7.14
  87. * @type Number
  88. * @default
  89. */
  90. fabric.maxCacheSideLimit = 4096;
  91. /**
  92. * Lowest pixel limit for cache canvases, set at 256PX
  93. * @since 1.7.14
  94. * @type Number
  95. * @default
  96. */
  97. fabric.minCacheSideLimit = 256;
  98. /**
  99. * Cache Object for widths of chars in text rendering.
  100. */
  101. fabric.charWidthsCache = { };
  102. /**
  103. * if webgl is enabled and available, textureSize will determine the size
  104. * of the canvas backend
  105. * @since 2.0.0
  106. * @type Number
  107. * @default
  108. */
  109. fabric.textureSize = 2048;
  110. /**
  111. * When 'true', style information is not retained when copy/pasting text, making
  112. * pasted text use destination style.
  113. * Defaults to 'false'.
  114. * @type Boolean
  115. * @default
  116. */
  117. fabric.disableStyleCopyPaste = false;
  118. /**
  119. * Enable webgl for filtering picture is available
  120. * A filtering backend will be initialized, this will both take memory and
  121. * time since a default 2048x2048 canvas will be created for the gl context
  122. * @since 2.0.0
  123. * @type Boolean
  124. * @default
  125. */
  126. fabric.enableGLFiltering = true;
  127. /**
  128. * Device Pixel Ratio
  129. * @see https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/SettingUptheCanvas/SettingUptheCanvas.html
  130. */
  131. fabric.devicePixelRatio = fabric.window.devicePixelRatio ||
  132. fabric.window.webkitDevicePixelRatio ||
  133. fabric.window.mozDevicePixelRatio ||
  134. 1;
  135. /**
  136. * Browser-specific constant to adjust CanvasRenderingContext2D.shadowBlur value,
  137. * which is unitless and not rendered equally across browsers.
  138. *
  139. * Values that work quite well (as of October 2017) are:
  140. * - Chrome: 1.5
  141. * - Edge: 1.75
  142. * - Firefox: 0.9
  143. * - Safari: 0.95
  144. *
  145. * @since 2.0.0
  146. * @type Number
  147. * @default 1
  148. */
  149. fabric.browserShadowBlurConstant = 1;
  150. /**
  151. * This object contains the result of arc to bezier conversion for faster retrieving if the same arc needs to be converted again.
  152. * It was an internal variable, is accessible since version 2.3.4
  153. */
  154. fabric.arcToSegmentsCache = { };
  155. /**
  156. * This object keeps the results of the boundsOfCurve calculation mapped by the joined arguments necessary to calculate it.
  157. * It does speed up calculation, if you parse and add always the same paths, but in case of heavy usage of freedrawing
  158. * you do not get any speed benefit and you get a big object in memory.
  159. * The object was a private variable before, while now is appended to the lib so that you have access to it and you
  160. * can eventually clear it.
  161. * It was an internal variable, is accessible since version 2.3.4
  162. */
  163. fabric.boundsOfCurveCache = { };
  164. /**
  165. * If disabled boundsOfCurveCache is not used. For apps that make heavy usage of pencil drawing probably disabling it is better
  166. * @default true
  167. */
  168. fabric.cachesBoundsOfCurve = true;
  169. /**
  170. * Skip performance testing of setupGLContext and force the use of putImageData that seems to be the one that works best on
  171. * Chrome + old hardware. if your users are experiencing empty images after filtering you may try to force this to true
  172. * this has to be set before instantiating the filtering backend ( before filtering the first image )
  173. * @type Boolean
  174. * @default false
  175. */
  176. fabric.forceGLPutImageData = false;
  177. fabric.initFilterBackend = function() {
  178. if (fabric.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(fabric.textureSize)) {
  179. console.log('max texture size: ' + fabric.maxTextureSize);
  180. return (new fabric.WebglFilterBackend({ tileSize: fabric.textureSize }));
  181. }
  182. else if (fabric.Canvas2dFilterBackend) {
  183. return (new fabric.Canvas2dFilterBackend());
  184. }
  185. };
  186. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  187. // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)
  188. window.fabric = fabric;
  189. }
  190. (function() {
  191. /**
  192. * @private
  193. * @param {String} eventName
  194. * @param {Function} handler
  195. */
  196. function _removeEventListener(eventName, handler) {
  197. if (!this.__eventListeners[eventName]) {
  198. return;
  199. }
  200. var eventListener = this.__eventListeners[eventName];
  201. if (handler) {
  202. eventListener[eventListener.indexOf(handler)] = false;
  203. }
  204. else {
  205. fabric.util.array.fill(eventListener, false);
  206. }
  207. }
  208. /**
  209. * Observes specified event
  210. * @memberOf fabric.Observable
  211. * @alias on
  212. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  213. * @param {Function} handler Function that receives a notification when an event of the specified type occurs
  214. * @return {Self} thisArg
  215. * @chainable
  216. */
  217. function on(eventName, handler) {
  218. if (!this.__eventListeners) {
  219. this.__eventListeners = { };
  220. }
  221. // one object with key/value pairs was passed
  222. if (arguments.length === 1) {
  223. for (var prop in eventName) {
  224. this.on(prop, eventName[prop]);
  225. }
  226. }
  227. else {
  228. if (!this.__eventListeners[eventName]) {
  229. this.__eventListeners[eventName] = [];
  230. }
  231. this.__eventListeners[eventName].push(handler);
  232. }
  233. return this;
  234. }
  235. function _once(eventName, handler) {
  236. var _handler = function () {
  237. handler.apply(this, arguments);
  238. this.off(eventName, _handler);
  239. }.bind(this);
  240. this.on(eventName, _handler);
  241. }
  242. function once(eventName, handler) {
  243. // one object with key/value pairs was passed
  244. if (arguments.length === 1) {
  245. for (var prop in eventName) {
  246. _once.call(this, prop, eventName[prop]);
  247. }
  248. }
  249. else {
  250. _once.call(this, eventName, handler);
  251. }
  252. return this;
  253. }
  254. /**
  255. * Stops event observing for a particular event handler. Calling this method
  256. * without arguments removes all handlers for all events
  257. * @memberOf fabric.Observable
  258. * @alias off
  259. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  260. * @param {Function} handler Function to be deleted from EventListeners
  261. * @return {Self} thisArg
  262. * @chainable
  263. */
  264. function off(eventName, handler) {
  265. if (!this.__eventListeners) {
  266. return this;
  267. }
  268. // remove all key/value pairs (event name -> event handler)
  269. if (arguments.length === 0) {
  270. for (eventName in this.__eventListeners) {
  271. _removeEventListener.call(this, eventName);
  272. }
  273. }
  274. // one object with key/value pairs was passed
  275. else if (arguments.length === 1 && typeof arguments[0] === 'object') {
  276. for (var prop in eventName) {
  277. _removeEventListener.call(this, prop, eventName[prop]);
  278. }
  279. }
  280. else {
  281. _removeEventListener.call(this, eventName, handler);
  282. }
  283. return this;
  284. }
  285. /**
  286. * Fires event with an optional options object
  287. * @memberOf fabric.Observable
  288. * @param {String} eventName Event name to fire
  289. * @param {Object} [options] Options object
  290. * @return {Self} thisArg
  291. * @chainable
  292. */
  293. function fire(eventName, options) {
  294. if (!this.__eventListeners) {
  295. return this;
  296. }
  297. var listenersForEvent = this.__eventListeners[eventName];
  298. if (!listenersForEvent) {
  299. return this;
  300. }
  301. for (var i = 0, len = listenersForEvent.length; i < len; i++) {
  302. listenersForEvent[i] && listenersForEvent[i].call(this, options || { });
  303. }
  304. this.__eventListeners[eventName] = listenersForEvent.filter(function(value) {
  305. return value !== false;
  306. });
  307. return this;
  308. }
  309. /**
  310. * @namespace fabric.Observable
  311. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#events}
  312. * @see {@link http://fabricjs.com/events|Events demo}
  313. */
  314. fabric.Observable = {
  315. fire: fire,
  316. on: on,
  317. once: once,
  318. off: off,
  319. };
  320. })();
  321. /**
  322. * @namespace fabric.Collection
  323. */
  324. fabric.Collection = {
  325. _objects: [],
  326. /**
  327. * Adds objects to collection, Canvas or Group, then renders canvas
  328. * (if `renderOnAddRemove` is not `false`).
  329. * in case of Group no changes to bounding box are made.
  330. * Objects should be instances of (or inherit from) fabric.Object
  331. * Use of this function is highly discouraged for groups.
  332. * you can add a bunch of objects with the add method but then you NEED
  333. * to run a addWithUpdate call for the Group class or position/bbox will be wrong.
  334. * @param {...fabric.Object} object Zero or more fabric instances
  335. * @return {Self} thisArg
  336. * @chainable
  337. */
  338. add: function () {
  339. this._objects.push.apply(this._objects, arguments);
  340. if (this._onObjectAdded) {
  341. for (var i = 0, length = arguments.length; i < length; i++) {
  342. this._onObjectAdded(arguments[i]);
  343. }
  344. }
  345. this.renderOnAddRemove && this.requestRenderAll();
  346. return this;
  347. },
  348. /**
  349. * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
  350. * An object should be an instance of (or inherit from) fabric.Object
  351. * Use of this function is highly discouraged for groups.
  352. * you can add a bunch of objects with the insertAt method but then you NEED
  353. * to run a addWithUpdate call for the Group class or position/bbox will be wrong.
  354. * @param {Object} object Object to insert
  355. * @param {Number} index Index to insert object at
  356. * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
  357. * @return {Self} thisArg
  358. * @chainable
  359. */
  360. insertAt: function (object, index, nonSplicing) {
  361. var objects = this._objects;
  362. if (nonSplicing) {
  363. objects[index] = object;
  364. }
  365. else {
  366. objects.splice(index, 0, object);
  367. }
  368. this._onObjectAdded && this._onObjectAdded(object);
  369. this.renderOnAddRemove && this.requestRenderAll();
  370. return this;
  371. },
  372. /**
  373. * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
  374. * @param {...fabric.Object} object Zero or more fabric instances
  375. * @return {Self} thisArg
  376. * @chainable
  377. */
  378. remove: function() {
  379. var objects = this._objects,
  380. index, somethingRemoved = false;
  381. for (var i = 0, length = arguments.length; i < length; i++) {
  382. index = objects.indexOf(arguments[i]);
  383. // only call onObjectRemoved if an object was actually removed
  384. if (index !== -1) {
  385. somethingRemoved = true;
  386. objects.splice(index, 1);
  387. this._onObjectRemoved && this._onObjectRemoved(arguments[i]);
  388. }
  389. }
  390. this.renderOnAddRemove && somethingRemoved && this.requestRenderAll();
  391. return this;
  392. },
  393. /**
  394. * Executes given function for each object in this group
  395. * @param {Function} callback
  396. * Callback invoked with current object as first argument,
  397. * index - as second and an array of all objects - as third.
  398. * Callback is invoked in a context of Global Object (e.g. `window`)
  399. * when no `context` argument is given
  400. *
  401. * @param {Object} context Context (aka thisObject)
  402. * @return {Self} thisArg
  403. * @chainable
  404. */
  405. forEachObject: function(callback, context) {
  406. var objects = this.getObjects();
  407. for (var i = 0, len = objects.length; i < len; i++) {
  408. callback.call(context, objects[i], i, objects);
  409. }
  410. return this;
  411. },
  412. /**
  413. * Returns an array of children objects of this instance
  414. * Type parameter introduced in 1.3.10
  415. * since 2.3.5 this method return always a COPY of the array;
  416. * @param {String} [type] When specified, only objects of this type are returned
  417. * @return {Array}
  418. */
  419. getObjects: function(type) {
  420. if (typeof type === 'undefined') {
  421. return this._objects.concat();
  422. }
  423. return this._objects.filter(function(o) {
  424. return o.type === type;
  425. });
  426. },
  427. /**
  428. * Returns object at specified index
  429. * @param {Number} index
  430. * @return {Self} thisArg
  431. */
  432. item: function (index) {
  433. return this._objects[index];
  434. },
  435. /**
  436. * Returns true if collection contains no objects
  437. * @return {Boolean} true if collection is empty
  438. */
  439. isEmpty: function () {
  440. return this._objects.length === 0;
  441. },
  442. /**
  443. * Returns a size of a collection (i.e: length of an array containing its objects)
  444. * @return {Number} Collection size
  445. */
  446. size: function() {
  447. return this._objects.length;
  448. },
  449. /**
  450. * Returns true if collection contains an object
  451. * @param {Object} object Object to check against
  452. * @param {Boolean} [deep=false] `true` to check all descendants, `false` to check only `_objects`
  453. * @return {Boolean} `true` if collection contains an object
  454. */
  455. contains: function (object, deep) {
  456. if (this._objects.indexOf(object) > -1) {
  457. return true;
  458. }
  459. else if (deep) {
  460. return this._objects.some(function (obj) {
  461. return typeof obj.contains === 'function' && obj.contains(object, true);
  462. });
  463. }
  464. return false;
  465. },
  466. /**
  467. * Returns number representation of a collection complexity
  468. * @return {Number} complexity
  469. */
  470. complexity: function () {
  471. return this._objects.reduce(function (memo, current) {
  472. memo += current.complexity ? current.complexity() : 0;
  473. return memo;
  474. }, 0);
  475. }
  476. };
  477. /**
  478. * @namespace fabric.CommonMethods
  479. */
  480. fabric.CommonMethods = {
  481. /**
  482. * Sets object's properties from options
  483. * @param {Object} [options] Options object
  484. */
  485. _setOptions: function(options) {
  486. for (var prop in options) {
  487. this.set(prop, options[prop]);
  488. }
  489. },
  490. /**
  491. * @private
  492. * @param {Object} [filler] Options object
  493. * @param {String} [property] property to set the Gradient to
  494. */
  495. _initGradient: function(filler, property) {
  496. if (filler && filler.colorStops && !(filler instanceof fabric.Gradient)) {
  497. this.set(property, new fabric.Gradient(filler));
  498. }
  499. },
  500. /**
  501. * @private
  502. * @param {Object} [filler] Options object
  503. * @param {String} [property] property to set the Pattern to
  504. * @param {Function} [callback] callback to invoke after pattern load
  505. */
  506. _initPattern: function(filler, property, callback) {
  507. if (filler && filler.source && !(filler instanceof fabric.Pattern)) {
  508. this.set(property, new fabric.Pattern(filler, callback));
  509. }
  510. else {
  511. callback && callback();
  512. }
  513. },
  514. /**
  515. * @private
  516. */
  517. _setObject: function(obj) {
  518. for (var prop in obj) {
  519. this._set(prop, obj[prop]);
  520. }
  521. },
  522. /**
  523. * 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()`.
  524. * @param {String|Object} key Property name or object (if object, iterate over the object properties)
  525. * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
  526. * @return {fabric.Object} thisArg
  527. * @chainable
  528. */
  529. set: function(key, value) {
  530. if (typeof key === 'object') {
  531. this._setObject(key);
  532. }
  533. else {
  534. this._set(key, value);
  535. }
  536. return this;
  537. },
  538. _set: function(key, value) {
  539. this[key] = value;
  540. },
  541. /**
  542. * Toggles specified property from `true` to `false` or from `false` to `true`
  543. * @param {String} property Property to toggle
  544. * @return {fabric.Object} thisArg
  545. * @chainable
  546. */
  547. toggle: function(property) {
  548. var value = this.get(property);
  549. if (typeof value === 'boolean') {
  550. this.set(property, !value);
  551. }
  552. return this;
  553. },
  554. /**
  555. * Basic getter
  556. * @param {String} property Property name
  557. * @return {*} value of a property
  558. */
  559. get: function(property) {
  560. return this[property];
  561. }
  562. };
  563. (function(global) {
  564. var sqrt = Math.sqrt,
  565. atan2 = Math.atan2,
  566. pow = Math.pow,
  567. PiBy180 = Math.PI / 180,
  568. PiBy2 = Math.PI / 2;
  569. /**
  570. * @namespace fabric.util
  571. */
  572. fabric.util = {
  573. /**
  574. * Calculate the cos of an angle, avoiding returning floats for known results
  575. * @static
  576. * @memberOf fabric.util
  577. * @param {Number} angle the angle in radians or in degree
  578. * @return {Number}
  579. */
  580. cos: function(angle) {
  581. if (angle === 0) { return 1; }
  582. if (angle < 0) {
  583. // cos(a) = cos(-a)
  584. angle = -angle;
  585. }
  586. var angleSlice = angle / PiBy2;
  587. switch (angleSlice) {
  588. case 1: case 3: return 0;
  589. case 2: return -1;
  590. }
  591. return Math.cos(angle);
  592. },
  593. /**
  594. * Calculate the sin of an angle, avoiding returning floats for known results
  595. * @static
  596. * @memberOf fabric.util
  597. * @param {Number} angle the angle in radians or in degree
  598. * @return {Number}
  599. */
  600. sin: function(angle) {
  601. if (angle === 0) { return 0; }
  602. var angleSlice = angle / PiBy2, sign = 1;
  603. if (angle < 0) {
  604. // sin(-a) = -sin(a)
  605. sign = -1;
  606. }
  607. switch (angleSlice) {
  608. case 1: return sign;
  609. case 2: return 0;
  610. case 3: return -sign;
  611. }
  612. return Math.sin(angle);
  613. },
  614. /**
  615. * Removes value from an array.
  616. * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
  617. * @static
  618. * @memberOf fabric.util
  619. * @param {Array} array
  620. * @param {*} value
  621. * @return {Array} original array
  622. */
  623. removeFromArray: function(array, value) {
  624. var idx = array.indexOf(value);
  625. if (idx !== -1) {
  626. array.splice(idx, 1);
  627. }
  628. return array;
  629. },
  630. /**
  631. * Returns random number between 2 specified ones.
  632. * @static
  633. * @memberOf fabric.util
  634. * @param {Number} min lower limit
  635. * @param {Number} max upper limit
  636. * @return {Number} random value (between min and max)
  637. */
  638. getRandomInt: function(min, max) {
  639. return Math.floor(Math.random() * (max - min + 1)) + min;
  640. },
  641. /**
  642. * Transforms degrees to radians.
  643. * @static
  644. * @memberOf fabric.util
  645. * @param {Number} degrees value in degrees
  646. * @return {Number} value in radians
  647. */
  648. degreesToRadians: function(degrees) {
  649. return degrees * PiBy180;
  650. },
  651. /**
  652. * Transforms radians to degrees.
  653. * @static
  654. * @memberOf fabric.util
  655. * @param {Number} radians value in radians
  656. * @return {Number} value in degrees
  657. */
  658. radiansToDegrees: function(radians) {
  659. return radians / PiBy180;
  660. },
  661. /**
  662. * Rotates `point` around `origin` with `radians`
  663. * @static
  664. * @memberOf fabric.util
  665. * @param {fabric.Point} point The point to rotate
  666. * @param {fabric.Point} origin The origin of the rotation
  667. * @param {Number} radians The radians of the angle for the rotation
  668. * @return {fabric.Point} The new rotated point
  669. */
  670. rotatePoint: function(point, origin, radians) {
  671. var newPoint = new fabric.Point(point.x - origin.x, point.y - origin.y),
  672. v = fabric.util.rotateVector(newPoint, radians);
  673. return new fabric.Point(v.x, v.y).addEquals(origin);
  674. },
  675. /**
  676. * Rotates `vector` with `radians`
  677. * @static
  678. * @memberOf fabric.util
  679. * @param {Object} vector The vector to rotate (x and y)
  680. * @param {Number} radians The radians of the angle for the rotation
  681. * @return {Object} The new rotated point
  682. */
  683. rotateVector: function(vector, radians) {
  684. var sin = fabric.util.sin(radians),
  685. cos = fabric.util.cos(radians),
  686. rx = vector.x * cos - vector.y * sin,
  687. ry = vector.x * sin + vector.y * cos;
  688. return {
  689. x: rx,
  690. y: ry
  691. };
  692. },
  693. /**
  694. * Creates a vetor from points represented as a point
  695. * @static
  696. * @memberOf fabric.util
  697. *
  698. * @typedef {Object} Point
  699. * @property {number} x
  700. * @property {number} y
  701. *
  702. * @param {Point} from
  703. * @param {Point} to
  704. * @returns {Point} vector
  705. */
  706. createVector: function (from, to) {
  707. return new fabric.Point(to.x - from.x, to.y - from.y);
  708. },
  709. /**
  710. * Calculates angle between 2 vectors using dot product
  711. * @static
  712. * @memberOf fabric.util
  713. * @param {Point} a
  714. * @param {Point} b
  715. * @returns the angle in radian between the vectors
  716. */
  717. calcAngleBetweenVectors: function (a, b) {
  718. return Math.acos((a.x * b.x + a.y * b.y) / (Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y)));
  719. },
  720. /**
  721. * @static
  722. * @memberOf fabric.util
  723. * @param {Point} v
  724. * @returns {Point} vector representing the unit vector of pointing to the direction of `v`
  725. */
  726. getHatVector: function (v) {
  727. return new fabric.Point(v.x, v.y).multiply(1 / Math.hypot(v.x, v.y));
  728. },
  729. /**
  730. * @static
  731. * @memberOf fabric.util
  732. * @param {Point} A
  733. * @param {Point} B
  734. * @param {Point} C
  735. * @returns {{ vector: Point, angle: number }} vector representing the bisector of A and A's angle
  736. */
  737. getBisector: function (A, B, C) {
  738. var AB = fabric.util.createVector(A, B), AC = fabric.util.createVector(A, C);
  739. var alpha = fabric.util.calcAngleBetweenVectors(AB, AC);
  740. // check if alpha is relative to AB->BC
  741. var ro = fabric.util.calcAngleBetweenVectors(fabric.util.rotateVector(AB, alpha), AC);
  742. var phi = alpha * (ro === 0 ? 1 : -1) / 2;
  743. return {
  744. vector: fabric.util.getHatVector(fabric.util.rotateVector(AB, phi)),
  745. angle: alpha
  746. };
  747. },
  748. /**
  749. * Project stroke width on points returning 2 projections for each point as follows:
  750. * - `miter`: 2 points corresponding to the outer boundary and the inner boundary of stroke.
  751. * - `bevel`: 2 points corresponding to the bevel boundaries, tangent to the bisector.
  752. * - `round`: same as `bevel`
  753. * Used to calculate object's bounding box
  754. * @static
  755. * @memberOf fabric.util
  756. * @param {Point[]} points
  757. * @param {Object} options
  758. * @param {number} options.strokeWidth
  759. * @param {'miter'|'bevel'|'round'} options.strokeLineJoin
  760. * @param {number} options.strokeMiterLimit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
  761. * @param {boolean} options.strokeUniform
  762. * @param {number} options.scaleX
  763. * @param {number} options.scaleY
  764. * @param {boolean} [openPath] whether the shape is open or not, affects the calculations of the first and last points
  765. * @returns {fabric.Point[]} array of size 2n/4n of all suspected points
  766. */
  767. projectStrokeOnPoints: function (points, options, openPath) {
  768. var coords = [], s = options.strokeWidth / 2,
  769. strokeUniformScalar = options.strokeUniform ?
  770. new fabric.Point(1 / options.scaleX, 1 / options.scaleY) : new fabric.Point(1, 1),
  771. getStrokeHatVector = function (v) {
  772. var scalar = s / (Math.hypot(v.x, v.y));
  773. return new fabric.Point(v.x * scalar * strokeUniformScalar.x, v.y * scalar * strokeUniformScalar.y);
  774. };
  775. if (points.length <= 1) {return coords;}
  776. points.forEach(function (p, index) {
  777. var A = new fabric.Point(p.x, p.y), B, C;
  778. if (index === 0) {
  779. C = points[index + 1];
  780. B = openPath ? getStrokeHatVector(fabric.util.createVector(C, A)).addEquals(A) : points[points.length - 1];
  781. }
  782. else if (index === points.length - 1) {
  783. B = points[index - 1];
  784. C = openPath ? getStrokeHatVector(fabric.util.createVector(B, A)).addEquals(A) : points[0];
  785. }
  786. else {
  787. B = points[index - 1];
  788. C = points[index + 1];
  789. }
  790. var bisector = fabric.util.getBisector(A, B, C),
  791. bisectorVector = bisector.vector,
  792. alpha = bisector.angle,
  793. scalar,
  794. miterVector;
  795. if (options.strokeLineJoin === 'miter') {
  796. scalar = -s / Math.sin(alpha / 2);
  797. miterVector = new fabric.Point(
  798. bisectorVector.x * scalar * strokeUniformScalar.x,
  799. bisectorVector.y * scalar * strokeUniformScalar.y
  800. );
  801. if (Math.hypot(miterVector.x, miterVector.y) / s <= options.strokeMiterLimit) {
  802. coords.push(A.add(miterVector));
  803. coords.push(A.subtract(miterVector));
  804. return;
  805. }
  806. }
  807. scalar = -s * Math.SQRT2;
  808. miterVector = new fabric.Point(
  809. bisectorVector.x * scalar * strokeUniformScalar.x,
  810. bisectorVector.y * scalar * strokeUniformScalar.y
  811. );
  812. coords.push(A.add(miterVector));
  813. coords.push(A.subtract(miterVector));
  814. });
  815. return coords;
  816. },
  817. /**
  818. * Apply transform t to point p
  819. * @static
  820. * @memberOf fabric.util
  821. * @param {fabric.Point} p The point to transform
  822. * @param {Array} t The transform
  823. * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied
  824. * @return {fabric.Point} The transformed point
  825. */
  826. transformPoint: function(p, t, ignoreOffset) {
  827. if (ignoreOffset) {
  828. return new fabric.Point(
  829. t[0] * p.x + t[2] * p.y,
  830. t[1] * p.x + t[3] * p.y
  831. );
  832. }
  833. return new fabric.Point(
  834. t[0] * p.x + t[2] * p.y + t[4],
  835. t[1] * p.x + t[3] * p.y + t[5]
  836. );
  837. },
  838. /**
  839. * Returns coordinates of points's bounding rectangle (left, top, width, height)
  840. * @param {Array} points 4 points array
  841. * @param {Array} [transform] an array of 6 numbers representing a 2x3 transform matrix
  842. * @return {Object} Object with left, top, width, height properties
  843. */
  844. makeBoundingBoxFromPoints: function(points, transform) {
  845. if (transform) {
  846. for (var i = 0; i < points.length; i++) {
  847. points[i] = fabric.util.transformPoint(points[i], transform);
  848. }
  849. }
  850. var xPoints = [points[0].x, points[1].x, points[2].x, points[3].x],
  851. minX = fabric.util.array.min(xPoints),
  852. maxX = fabric.util.array.max(xPoints),
  853. width = maxX - minX,
  854. yPoints = [points[0].y, points[1].y, points[2].y, points[3].y],
  855. minY = fabric.util.array.min(yPoints),
  856. maxY = fabric.util.array.max(yPoints),
  857. height = maxY - minY;
  858. return {
  859. left: minX,
  860. top: minY,
  861. width: width,
  862. height: height
  863. };
  864. },
  865. /**
  866. * Invert transformation t
  867. * @static
  868. * @memberOf fabric.util
  869. * @param {Array} t The transform
  870. * @return {Array} The inverted transform
  871. */
  872. invertTransform: function(t) {
  873. var a = 1 / (t[0] * t[3] - t[1] * t[2]),
  874. r = [a * t[3], -a * t[1], -a * t[2], a * t[0]],
  875. o = fabric.util.transformPoint({ x: t[4], y: t[5] }, r, true);
  876. r[4] = -o.x;
  877. r[5] = -o.y;
  878. return r;
  879. },
  880. /**
  881. * A wrapper around Number#toFixed, which contrary to native method returns number, not string.
  882. * @static
  883. * @memberOf fabric.util
  884. * @param {Number|String} number number to operate on
  885. * @param {Number} fractionDigits number of fraction digits to "leave"
  886. * @return {Number}
  887. */
  888. toFixed: function(number, fractionDigits) {
  889. return parseFloat(Number(number).toFixed(fractionDigits));
  890. },
  891. /**
  892. * Converts from attribute value to pixel value if applicable.
  893. * Returns converted pixels or original value not converted.
  894. * @param {Number|String} value number to operate on
  895. * @param {Number} fontSize
  896. * @return {Number|String}
  897. */
  898. parseUnit: function(value, fontSize) {
  899. var unit = /\D{0,2}$/.exec(value),
  900. number = parseFloat(value);
  901. if (!fontSize) {
  902. fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
  903. }
  904. switch (unit[0]) {
  905. case 'mm':
  906. return number * fabric.DPI / 25.4;
  907. case 'cm':
  908. return number * fabric.DPI / 2.54;
  909. case 'in':
  910. return number * fabric.DPI;
  911. case 'pt':
  912. return number * fabric.DPI / 72; // or * 4 / 3
  913. case 'pc':
  914. return number * fabric.DPI / 72 * 12; // or * 16
  915. case 'em':
  916. return number * fontSize;
  917. default:
  918. return number;
  919. }
  920. },
  921. /**
  922. * Function which always returns `false`.
  923. * @static
  924. * @memberOf fabric.util
  925. * @return {Boolean}
  926. */
  927. falseFunction: function() {
  928. return false;
  929. },
  930. /**
  931. * Returns klass "Class" object of given namespace
  932. * @memberOf fabric.util
  933. * @param {String} type Type of object (eg. 'circle')
  934. * @param {String} namespace Namespace to get klass "Class" object from
  935. * @return {Object} klass "Class"
  936. */
  937. getKlass: function(type, namespace) {
  938. // capitalize first letter only
  939. type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
  940. return fabric.util.resolveNamespace(namespace)[type];
  941. },
  942. /**
  943. * Returns array of attributes for given svg that fabric parses
  944. * @memberOf fabric.util
  945. * @param {String} type Type of svg element (eg. 'circle')
  946. * @return {Array} string names of supported attributes
  947. */
  948. getSvgAttributes: function(type) {
  949. var attributes = [
  950. 'instantiated_by_use',
  951. 'style',
  952. 'id',
  953. 'class'
  954. ];
  955. switch (type) {
  956. case 'linearGradient':
  957. attributes = attributes.concat(['x1', 'y1', 'x2', 'y2', 'gradientUnits', 'gradientTransform']);
  958. break;
  959. case 'radialGradient':
  960. attributes = attributes.concat(['gradientUnits', 'gradientTransform', 'cx', 'cy', 'r', 'fx', 'fy', 'fr']);
  961. break;
  962. case 'stop':
  963. attributes = attributes.concat(['offset', 'stop-color', 'stop-opacity']);
  964. break;
  965. }
  966. return attributes;
  967. },
  968. /**
  969. * Returns object of given namespace
  970. * @memberOf fabric.util
  971. * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'
  972. * @return {Object} Object for given namespace (default fabric)
  973. */
  974. resolveNamespace: function(namespace) {
  975. if (!namespace) {
  976. return fabric;
  977. }
  978. var parts = namespace.split('.'),
  979. len = parts.length, i,
  980. obj = global || fabric.window;
  981. for (i = 0; i < len; ++i) {
  982. obj = obj[parts[i]];
  983. }
  984. return obj;
  985. },
  986. /**
  987. * Loads image element from given url and passes it to a callback
  988. * @memberOf fabric.util
  989. * @param {String} url URL representing an image
  990. * @param {Function} callback Callback; invoked with loaded image
  991. * @param {*} [context] Context to invoke callback in
  992. * @param {Object} [crossOrigin] crossOrigin value to set image element to
  993. */
  994. loadImage: function(url, callback, context, crossOrigin) {
  995. if (!url) {
  996. callback && callback.call(context, url);
  997. return;
  998. }
  999. var img = fabric.util.createImage();
  1000. /** @ignore */
  1001. var onLoadCallback = function () {
  1002. callback && callback.call(context, img, false);
  1003. img = img.onload = img.onerror = null;
  1004. };
  1005. img.onload = onLoadCallback;
  1006. /** @ignore */
  1007. img.onerror = function() {
  1008. fabric.log('Error loading ' + img.src);
  1009. callback && callback.call(context, null, true);
  1010. img = img.onload = img.onerror = null;
  1011. };
  1012. // data-urls appear to be buggy with crossOrigin
  1013. // https://github.com/kangax/fabric.js/commit/d0abb90f1cd5c5ef9d2a94d3fb21a22330da3e0a#commitcomment-4513767
  1014. // see https://code.google.com/p/chromium/issues/detail?id=315152
  1015. // https://bugzilla.mozilla.org/show_bug.cgi?id=935069
  1016. // crossOrigin null is the same as not set.
  1017. if (url.indexOf('data') !== 0 &&
  1018. crossOrigin !== undefined &&
  1019. crossOrigin !== null) {
  1020. img.crossOrigin = crossOrigin;
  1021. }
  1022. // IE10 / IE11-Fix: SVG contents from data: URI
  1023. // will only be available if the IMG is present
  1024. // in the DOM (and visible)
  1025. if (url.substring(0,14) === 'data:image/svg') {
  1026. img.onload = null;
  1027. fabric.util.loadImageInDom(img, onLoadCallback);
  1028. }
  1029. img.src = url;
  1030. },
  1031. /**
  1032. * Attaches SVG image with data: URL to the dom
  1033. * @memberOf fabric.util
  1034. * @param {Object} img Image object with data:image/svg src
  1035. * @param {Function} callback Callback; invoked with loaded image
  1036. * @return {Object} DOM element (div containing the SVG image)
  1037. */
  1038. loadImageInDom: function(img, onLoadCallback) {
  1039. var div = fabric.document.createElement('div');
  1040. div.style.width = div.style.height = '1px';
  1041. div.style.left = div.style.top = '-100%';
  1042. div.style.position = 'absolute';
  1043. div.appendChild(img);
  1044. fabric.document.querySelector('body').appendChild(div);
  1045. /**
  1046. * Wrap in function to:
  1047. * 1. Call existing callback
  1048. * 2. Cleanup DOM
  1049. */
  1050. img.onload = function () {
  1051. onLoadCallback();
  1052. div.parentNode.removeChild(div);
  1053. div = null;
  1054. };
  1055. },
  1056. /**
  1057. * Creates corresponding fabric instances from their object representations
  1058. * @static
  1059. * @memberOf fabric.util
  1060. * @param {Array} objects Objects to enliven
  1061. * @param {Function} callback Callback to invoke when all objects are created
  1062. * @param {String} namespace Namespace to get klass "Class" object from
  1063. * @param {Function} reviver Method for further parsing of object elements,
  1064. * called after each fabric object created.
  1065. */
  1066. enlivenObjects: function(objects, callback, namespace, reviver) {
  1067. objects = objects || [];
  1068. var enlivenedObjects = [],
  1069. numLoadedObjects = 0,
  1070. numTotalObjects = objects.length;
  1071. function onLoaded() {
  1072. if (++numLoadedObjects === numTotalObjects) {
  1073. callback && callback(enlivenedObjects.filter(function(obj) {
  1074. // filter out undefined objects (objects that gave error)
  1075. return obj;
  1076. }));
  1077. }
  1078. }
  1079. if (!numTotalObjects) {
  1080. callback && callback(enlivenedObjects);
  1081. return;
  1082. }
  1083. objects.forEach(function (o, index) {
  1084. // if sparse array
  1085. if (!o || !o.type) {
  1086. onLoaded();
  1087. return;
  1088. }
  1089. var klass = fabric.util.getKlass(o.type, namespace);
  1090. klass.fromObject(o, function (obj, error) {
  1091. error || (enlivenedObjects[index] = obj);
  1092. reviver && reviver(o, obj, error);
  1093. onLoaded();
  1094. });
  1095. });
  1096. },
  1097. /**
  1098. * Creates corresponding fabric instances residing in an object, e.g. `clipPath`
  1099. * @see {@link fabric.Object.ENLIVEN_PROPS}
  1100. * @param {Object} object
  1101. * @param {Object} [context] assign enlived props to this object (pass null to skip this)
  1102. * @param {(objects:fabric.Object[]) => void} callback
  1103. */
  1104. enlivenObjectEnlivables: function (object, context, callback) {
  1105. var enlivenProps = fabric.Object.ENLIVEN_PROPS.filter(function (key) { return !!object[key]; });
  1106. fabric.util.enlivenObjects(enlivenProps.map(function (key) { return object[key]; }), function (enlivedProps) {
  1107. var objects = {};
  1108. enlivenProps.forEach(function (key, index) {
  1109. objects[key] = enlivedProps[index];
  1110. context && (context[key] = enlivedProps[index]);
  1111. });
  1112. callback && callback(objects);
  1113. });
  1114. },
  1115. /**
  1116. * Create and wait for loading of patterns
  1117. * @static
  1118. * @memberOf fabric.util
  1119. * @param {Array} patterns Objects to enliven
  1120. * @param {Function} callback Callback to invoke when all objects are created
  1121. * called after each fabric object created.
  1122. */
  1123. enlivenPatterns: function(patterns, callback) {
  1124. patterns = patterns || [];
  1125. function onLoaded() {
  1126. if (++numLoadedPatterns === numPatterns) {
  1127. callback && callback(enlivenedPatterns);
  1128. }
  1129. }
  1130. var enlivenedPatterns = [],
  1131. numLoadedPatterns = 0,
  1132. numPatterns = patterns.length;
  1133. if (!numPatterns) {
  1134. callback && callback(enlivenedPatterns);
  1135. return;
  1136. }
  1137. patterns.forEach(function (p, index) {
  1138. if (p && p.source) {
  1139. new fabric.Pattern(p, function(pattern) {
  1140. enlivenedPatterns[index] = pattern;
  1141. onLoaded();
  1142. });
  1143. }
  1144. else {
  1145. enlivenedPatterns[index] = p;
  1146. onLoaded();
  1147. }
  1148. });
  1149. },
  1150. /**
  1151. * Groups SVG elements (usually those retrieved from SVG document)
  1152. * @static
  1153. * @memberOf fabric.util
  1154. * @param {Array} elements SVG elements to group
  1155. * @param {Object} [options] Options object
  1156. * @param {String} path Value to set sourcePath to
  1157. * @return {fabric.Object|fabric.Group}
  1158. */
  1159. groupSVGElements: function(elements, options, path) {
  1160. var object;
  1161. if (elements && elements.length === 1) {
  1162. return elements[0];
  1163. }
  1164. if (options) {
  1165. if (options.width && options.height) {
  1166. options.centerPoint = {
  1167. x: options.width / 2,
  1168. y: options.height / 2
  1169. };
  1170. }
  1171. else {
  1172. delete options.width;
  1173. delete options.height;
  1174. }
  1175. }
  1176. object = new fabric.Group(elements, options);
  1177. if (typeof path !== 'undefined') {
  1178. object.sourcePath = path;
  1179. }
  1180. return object;
  1181. },
  1182. /**
  1183. * Populates an object with properties of another object
  1184. * @static
  1185. * @memberOf fabric.util
  1186. * @param {Object} source Source object
  1187. * @param {Object} destination Destination object
  1188. * @return {Array} properties Properties names to include
  1189. */
  1190. populateWithProperties: function(source, destination, properties) {
  1191. if (properties && Array.isArray(properties)) {
  1192. for (var i = 0, len = properties.length; i < len; i++) {
  1193. if (properties[i] in source) {
  1194. destination[properties[i]] = source[properties[i]];
  1195. }
  1196. }
  1197. }
  1198. },
  1199. /**
  1200. * Creates canvas element
  1201. * @static
  1202. * @memberOf fabric.util
  1203. * @return {CanvasElement} initialized canvas element
  1204. */
  1205. createCanvasElement: function() {
  1206. return fabric.document.createElement('canvas');
  1207. },
  1208. /**
  1209. * Creates a canvas element that is a copy of another and is also painted
  1210. * @param {CanvasElement} canvas to copy size and content of
  1211. * @static
  1212. * @memberOf fabric.util
  1213. * @return {CanvasElement} initialized canvas element
  1214. */
  1215. copyCanvasElement: function(canvas) {
  1216. var newCanvas = fabric.util.createCanvasElement();
  1217. newCanvas.width = canvas.width;
  1218. newCanvas.height = canvas.height;
  1219. newCanvas.getContext('2d').drawImage(canvas, 0, 0);
  1220. return newCanvas;
  1221. },
  1222. /**
  1223. * since 2.6.0 moved from canvas instance to utility.
  1224. * @param {CanvasElement} canvasEl to copy size and content of
  1225. * @param {String} format 'jpeg' or 'png', in some browsers 'webp' is ok too
  1226. * @param {Number} quality <= 1 and > 0
  1227. * @static
  1228. * @memberOf fabric.util
  1229. * @return {String} data url
  1230. */
  1231. toDataURL: function(canvasEl, format, quality) {
  1232. return canvasEl.toDataURL('image/' + format, quality);
  1233. },
  1234. /**
  1235. * Creates image element (works on client and node)
  1236. * @static
  1237. * @memberOf fabric.util
  1238. * @return {HTMLImageElement} HTML image element
  1239. */
  1240. createImage: function() {
  1241. return fabric.document.createElement('img');
  1242. },
  1243. /**
  1244. * Multiply matrix A by matrix B to nest transformations
  1245. * @static
  1246. * @memberOf fabric.util
  1247. * @param {Array} a First transformMatrix
  1248. * @param {Array} b Second transformMatrix
  1249. * @param {Boolean} is2x2 flag to multiply matrices as 2x2 matrices
  1250. * @return {Array} The product of the two transform matrices
  1251. */
  1252. multiplyTransformMatrices: function(a, b, is2x2) {
  1253. // Matrix multiply a * b
  1254. return [
  1255. a[0] * b[0] + a[2] * b[1],
  1256. a[1] * b[0] + a[3] * b[1],
  1257. a[0] * b[2] + a[2] * b[3],
  1258. a[1] * b[2] + a[3] * b[3],
  1259. is2x2 ? 0 : a[0] * b[4] + a[2] * b[5] + a[4],
  1260. is2x2 ? 0 : a[1] * b[4] + a[3] * b[5] + a[5]
  1261. ];
  1262. },
  1263. /**
  1264. * Decomposes standard 2x3 matrix into transform components
  1265. * @static
  1266. * @memberOf fabric.util
  1267. * @param {Array} a transformMatrix
  1268. * @return {Object} Components of transform
  1269. */
  1270. qrDecompose: function(a) {
  1271. var angle = atan2(a[1], a[0]),
  1272. denom = pow(a[0], 2) + pow(a[1], 2),
  1273. scaleX = sqrt(denom),
  1274. scaleY = (a[0] * a[3] - a[2] * a[1]) / scaleX,
  1275. skewX = atan2(a[0] * a[2] + a[1] * a [3], denom);
  1276. return {
  1277. angle: angle / PiBy180,
  1278. scaleX: scaleX,
  1279. scaleY: scaleY,
  1280. skewX: skewX / PiBy180,
  1281. skewY: 0,
  1282. translateX: a[4],
  1283. translateY: a[5]
  1284. };
  1285. },
  1286. /**
  1287. * Returns a transform matrix starting from an object of the same kind of
  1288. * the one returned from qrDecompose, useful also if you want to calculate some
  1289. * transformations from an object that is not enlived yet
  1290. * @static
  1291. * @memberOf fabric.util
  1292. * @param {Object} options
  1293. * @param {Number} [options.angle] angle in degrees
  1294. * @return {Number[]} transform matrix
  1295. */
  1296. calcRotateMatrix: function(options) {
  1297. if (!options.angle) {
  1298. return fabric.iMatrix.concat();
  1299. }
  1300. var theta = fabric.util.degreesToRadians(options.angle),
  1301. cos = fabric.util.cos(theta),
  1302. sin = fabric.util.sin(theta);
  1303. return [cos, sin, -sin, cos, 0, 0];
  1304. },
  1305. /**
  1306. * Returns a transform matrix starting from an object of the same kind of
  1307. * the one returned from qrDecompose, useful also if you want to calculate some
  1308. * transformations from an object that is not enlived yet.
  1309. * is called DimensionsTransformMatrix because those properties are the one that influence
  1310. * the size of the resulting box of the object.
  1311. * @static
  1312. * @memberOf fabric.util
  1313. * @param {Object} options
  1314. * @param {Number} [options.scaleX]
  1315. * @param {Number} [options.scaleY]
  1316. * @param {Boolean} [options.flipX]
  1317. * @param {Boolean} [options.flipY]
  1318. * @param {Number} [options.skewX]
  1319. * @param {Number} [options.skewY]
  1320. * @return {Number[]} transform matrix
  1321. */
  1322. calcDimensionsMatrix: function(options) {
  1323. var scaleX = typeof options.scaleX === 'undefined' ? 1 : options.scaleX,
  1324. scaleY = typeof options.scaleY === 'undefined' ? 1 : options.scaleY,
  1325. scaleMatrix = [
  1326. options.flipX ? -scaleX : scaleX,
  1327. 0,
  1328. 0,
  1329. options.flipY ? -scaleY : scaleY,
  1330. 0,
  1331. 0],
  1332. multiply = fabric.util.multiplyTransformMatrices,
  1333. degreesToRadians = fabric.util.degreesToRadians;
  1334. if (options.skewX) {
  1335. scaleMatrix = multiply(
  1336. scaleMatrix,
  1337. [1, 0, Math.tan(degreesToRadians(options.skewX)), 1],
  1338. true);
  1339. }
  1340. if (options.skewY) {
  1341. scaleMatrix = multiply(
  1342. scaleMatrix,
  1343. [1, Math.tan(degreesToRadians(options.skewY)), 0, 1],
  1344. true);
  1345. }
  1346. return scaleMatrix;
  1347. },
  1348. /**
  1349. * Returns a transform matrix starting from an object of the same kind of
  1350. * the one returned from qrDecompose, useful also if you want to calculate some
  1351. * transformations from an object that is not enlived yet
  1352. * @static
  1353. * @memberOf fabric.util
  1354. * @param {Object} options
  1355. * @param {Number} [options.angle]
  1356. * @param {Number} [options.scaleX]
  1357. * @param {Number} [options.scaleY]
  1358. * @param {Boolean} [options.flipX]
  1359. * @param {Boolean} [options.flipY]
  1360. * @param {Number} [options.skewX]
  1361. * @param {Number} [options.skewX]
  1362. * @param {Number} [options.translateX]
  1363. * @param {Number} [options.translateY]
  1364. * @return {Number[]} transform matrix
  1365. */
  1366. composeMatrix: function(options) {
  1367. var matrix = [1, 0, 0, 1, options.translateX || 0, options.translateY || 0],
  1368. multiply = fabric.util.multiplyTransformMatrices;
  1369. if (options.angle) {
  1370. matrix = multiply(matrix, fabric.util.calcRotateMatrix(options));
  1371. }
  1372. if (options.scaleX !== 1 || options.scaleY !== 1 ||
  1373. options.skewX || options.skewY || options.flipX || options.flipY) {
  1374. matrix = multiply(matrix, fabric.util.calcDimensionsMatrix(options));
  1375. }
  1376. return matrix;
  1377. },
  1378. /**
  1379. * reset an object transform state to neutral. Top and left are not accounted for
  1380. * @static
  1381. * @memberOf fabric.util
  1382. * @param {fabric.Object} target object to transform
  1383. */
  1384. resetObjectTransform: function (target) {
  1385. target.scaleX = 1;
  1386. target.scaleY = 1;
  1387. target.skewX = 0;
  1388. target.skewY = 0;
  1389. target.flipX = false;
  1390. target.flipY = false;
  1391. target.rotate(0);
  1392. },
  1393. /**
  1394. * Extract Object transform values
  1395. * @static
  1396. * @memberOf fabric.util
  1397. * @param {fabric.Object} target object to read from
  1398. * @return {Object} Components of transform
  1399. */
  1400. saveObjectTransform: function (target) {
  1401. return {
  1402. scaleX: target.scaleX,
  1403. scaleY: target.scaleY,
  1404. skewX: target.skewX,
  1405. skewY: target.skewY,
  1406. angle: target.angle,
  1407. left: target.left,
  1408. flipX: target.flipX,
  1409. flipY: target.flipY,
  1410. top: target.top
  1411. };
  1412. },
  1413. /**
  1414. * Returns true if context has transparent pixel
  1415. * at specified location (taking tolerance into account)
  1416. * @param {CanvasRenderingContext2D} ctx context
  1417. * @param {Number} x x coordinate
  1418. * @param {Number} y y coordinate
  1419. * @param {Number} tolerance Tolerance
  1420. */
  1421. isTransparent: function(ctx, x, y, tolerance) {
  1422. // If tolerance is > 0 adjust start coords to take into account.
  1423. // If moves off Canvas fix to 0
  1424. if (tolerance > 0) {
  1425. if (x > tolerance) {
  1426. x -= tolerance;
  1427. }
  1428. else {
  1429. x = 0;
  1430. }
  1431. if (y > tolerance) {
  1432. y -= tolerance;
  1433. }
  1434. else {
  1435. y = 0;
  1436. }
  1437. }
  1438. var _isTransparent = true, i, temp,
  1439. imageData = ctx.getImageData(x, y, (tolerance * 2) || 1, (tolerance * 2) || 1),
  1440. l = imageData.data.length;
  1441. // Split image data - for tolerance > 1, pixelDataSize = 4;
  1442. for (i = 3; i < l; i += 4) {
  1443. temp = imageData.data[i];
  1444. _isTransparent = temp <= 0;
  1445. if (_isTransparent === false) {
  1446. break; // Stop if colour found
  1447. }
  1448. }
  1449. imageData = null;
  1450. return _isTransparent;
  1451. },
  1452. /**
  1453. * Parse preserveAspectRatio attribute from element
  1454. * @param {string} attribute to be parsed
  1455. * @return {Object} an object containing align and meetOrSlice attribute
  1456. */
  1457. parsePreserveAspectRatioAttribute: function(attribute) {
  1458. var meetOrSlice = 'meet', alignX = 'Mid', alignY = 'Mid',
  1459. aspectRatioAttrs = attribute.split(' '), align;
  1460. if (aspectRatioAttrs && aspectRatioAttrs.length) {
  1461. meetOrSlice = aspectRatioAttrs.pop();
  1462. if (meetOrSlice !== 'meet' && meetOrSlice !== 'slice') {
  1463. align = meetOrSlice;
  1464. meetOrSlice = 'meet';
  1465. }
  1466. else if (aspectRatioAttrs.length) {
  1467. align = aspectRatioAttrs.pop();
  1468. }
  1469. }
  1470. //divide align in alignX and alignY
  1471. alignX = align !== 'none' ? align.slice(1, 4) : 'none';
  1472. alignY = align !== 'none' ? align.slice(5, 8) : 'none';
  1473. return {
  1474. meetOrSlice: meetOrSlice,
  1475. alignX: alignX,
  1476. alignY: alignY
  1477. };
  1478. },
  1479. /**
  1480. * Clear char widths cache for the given font family or all the cache if no
  1481. * fontFamily is specified.
  1482. * Use it if you know you are loading fonts in a lazy way and you are not waiting
  1483. * for custom fonts to load properly when adding text objects to the canvas.
  1484. * If a text object is added when its own font is not loaded yet, you will get wrong
  1485. * measurement and so wrong bounding boxes.
  1486. * After the font cache is cleared, either change the textObject text content or call
  1487. * initDimensions() to trigger a recalculation
  1488. * @memberOf fabric.util
  1489. * @param {String} [fontFamily] font family to clear
  1490. */
  1491. clearFabricFontCache: function(fontFamily) {
  1492. fontFamily = (fontFamily || '').toLowerCase();
  1493. if (!fontFamily) {
  1494. fabric.charWidthsCache = { };
  1495. }
  1496. else if (fabric.charWidthsCache[fontFamily]) {
  1497. delete fabric.charWidthsCache[fontFamily];
  1498. }
  1499. },
  1500. /**
  1501. * Given current aspect ratio, determines the max width and height that can
  1502. * respect the total allowed area for the cache.
  1503. * @memberOf fabric.util
  1504. * @param {Number} ar aspect ratio
  1505. * @param {Number} maximumArea Maximum area you want to achieve
  1506. * @return {Object.x} Limited dimensions by X
  1507. * @return {Object.y} Limited dimensions by Y
  1508. */
  1509. limitDimsByArea: function(ar, maximumArea) {
  1510. var roughWidth = Math.sqrt(maximumArea * ar),
  1511. perfLimitSizeY = Math.floor(maximumArea / roughWidth);
  1512. return { x: Math.floor(roughWidth), y: perfLimitSizeY };
  1513. },
  1514. capValue: function(min, value, max) {
  1515. return Math.max(min, Math.min(value, max));
  1516. },
  1517. /**
  1518. * Finds the scale for the object source to fit inside the object destination,
  1519. * keeping aspect ratio intact.
  1520. * respect the total allowed area for the cache.
  1521. * @memberOf fabric.util
  1522. * @param {Object | fabric.Object} source
  1523. * @param {Number} source.height natural unscaled height of the object
  1524. * @param {Number} source.width natural unscaled width of the object
  1525. * @param {Object | fabric.Object} destination
  1526. * @param {Number} destination.height natural unscaled height of the object
  1527. * @param {Number} destination.width natural unscaled width of the object
  1528. * @return {Number} scale factor to apply to source to fit into destination
  1529. */
  1530. findScaleToFit: function(source, destination) {
  1531. return Math.min(destination.width / source.width, destination.height / source.height);
  1532. },
  1533. /**
  1534. * Finds the scale for the object source to cover entirely the object destination,
  1535. * keeping aspect ratio intact.
  1536. * respect the total allowed area for the cache.
  1537. * @memberOf fabric.util
  1538. * @param {Object | fabric.Object} source
  1539. * @param {Number} source.height natural unscaled height of the object
  1540. * @param {Number} source.width natural unscaled width of the object
  1541. * @param {Object | fabric.Object} destination
  1542. * @param {Number} destination.height natural unscaled height of the object
  1543. * @param {Number} destination.width natural unscaled width of the object
  1544. * @return {Number} scale factor to apply to source to cover destination
  1545. */
  1546. findScaleToCover: function(source, destination) {
  1547. return Math.max(destination.width / source.width, destination.height / source.height);
  1548. },
  1549. /**
  1550. * given an array of 6 number returns something like `"matrix(...numbers)"`
  1551. * @memberOf fabric.util
  1552. * @param {Array} transform an array with 6 numbers
  1553. * @return {String} transform matrix for svg
  1554. * @return {Object.y} Limited dimensions by Y
  1555. */
  1556. matrixToSVG: function(transform) {
  1557. return 'matrix(' + transform.map(function(value) {
  1558. return fabric.util.toFixed(value, fabric.Object.NUM_FRACTION_DIGITS);
  1559. }).join(' ') + ')';
  1560. },
  1561. /**
  1562. * given an object and a transform, apply the inverse transform to the object,
  1563. * this is equivalent to remove from that object that transformation, so that
  1564. * added in a space with the removed transform, the object will be the same as before.
  1565. * Removing from an object a transform that scale by 2 is like scaling it by 1/2.
  1566. * Removing from an object a transfrom that rotate by 30deg is like rotating by 30deg
  1567. * in the opposite direction.
  1568. * This util is used to add objects inside transformed groups or nested groups.
  1569. * @memberOf fabric.util
  1570. * @param {fabric.Object} object the object you want to transform
  1571. * @param {Array} transform the destination transform
  1572. */
  1573. removeTransformFromObject: function(object, transform) {
  1574. var inverted = fabric.util.invertTransform(transform),
  1575. finalTransform = fabric.util.multiplyTransformMatrices(inverted, object.calcOwnMatrix());
  1576. fabric.util.applyTransformToObject(object, finalTransform);
  1577. },
  1578. /**
  1579. * given an object and a transform, apply the transform to the object.
  1580. * this is equivalent to change the space where the object is drawn.
  1581. * Adding to an object a transform that scale by 2 is like scaling it by 2.
  1582. * This is used when removing an object from an active selection for example.
  1583. * @memberOf fabric.util
  1584. * @param {fabric.Object} object the object you want to transform
  1585. * @param {Array} transform the destination transform
  1586. */
  1587. addTransformToObject: function(object, transform) {
  1588. fabric.util.applyTransformToObject(
  1589. object,
  1590. fabric.util.multiplyTransformMatrices(transform, object.calcOwnMatrix())
  1591. );
  1592. },
  1593. /**
  1594. * discard an object transform state and apply the one from the matrix.
  1595. * @memberOf fabric.util
  1596. * @param {fabric.Object} object the object you want to transform
  1597. * @param {Array} transform the destination transform
  1598. */
  1599. applyTransformToObject: function(object, transform) {
  1600. var options = fabric.util.qrDecompose(transform),
  1601. center = new fabric.Point(options.translateX, options.translateY);
  1602. object.flipX = false;
  1603. object.flipY = false;
  1604. object.set('scaleX', options.scaleX);
  1605. object.set('scaleY', options.scaleY);
  1606. object.skewX = options.skewX;
  1607. object.skewY = options.skewY;
  1608. object.angle = options.angle;
  1609. object.setPositionByOrigin(center, 'center', 'center');
  1610. },
  1611. /**
  1612. * given a width and height, return the size of the bounding box
  1613. * that can contains the box with width/height with applied transform
  1614. * described in options.
  1615. * Use to calculate the boxes around objects for controls.
  1616. * @memberOf fabric.util
  1617. * @param {Number} width
  1618. * @param {Number} height
  1619. * @param {Object} options
  1620. * @param {Number} options.scaleX
  1621. * @param {Number} options.scaleY
  1622. * @param {Number} options.skewX
  1623. * @param {Number} options.skewY
  1624. * @return {Object.x} width of containing
  1625. * @return {Object.y} height of containing
  1626. */
  1627. sizeAfterTransform: function(width, height, options) {
  1628. var dimX = width / 2, dimY = height / 2,
  1629. points = [
  1630. {
  1631. x: -dimX,
  1632. y: -dimY
  1633. },
  1634. {
  1635. x: dimX,
  1636. y: -dimY
  1637. },
  1638. {
  1639. x: -dimX,
  1640. y: dimY
  1641. },
  1642. {
  1643. x: dimX,
  1644. y: dimY
  1645. }],
  1646. transformMatrix = fabric.util.calcDimensionsMatrix(options),
  1647. bbox = fabric.util.makeBoundingBoxFromPoints(points, transformMatrix);
  1648. return {
  1649. x: bbox.width,
  1650. y: bbox.height,
  1651. };
  1652. },
  1653. /**
  1654. * Merges 2 clip paths into one visually equal clip path
  1655. *
  1656. * **IMPORTANT**:\
  1657. * Does **NOT** clone the arguments, clone them proir if necessary.
  1658. *
  1659. * Creates a wrapper (group) that contains one clip path and is clipped by the other so content is kept where both overlap.
  1660. * Use this method if both the clip paths may have nested clip paths of their own, so assigning one to the other's clip path property is not possible.
  1661. *
  1662. * In order to handle the `inverted` property we follow logic described in the following cases:\
  1663. * **(1)** both clip paths are inverted - the clip paths pass the inverted prop to the wrapper and loose it themselves.\
  1664. * **(2)** one is inverted and the other isn't - the wrapper shouldn't become inverted and the inverted clip path must clip the non inverted one to produce an identical visual effect.\
  1665. * **(3)** both clip paths are not inverted - wrapper and clip paths remain unchanged.
  1666. *
  1667. * @memberOf fabric.util
  1668. * @param {fabric.Object} c1
  1669. * @param {fabric.Object} c2
  1670. * @returns {fabric.Object} merged clip path
  1671. */
  1672. mergeClipPaths: function (c1, c2) {
  1673. var a = c1, b = c2;
  1674. if (a.inverted && !b.inverted) {
  1675. // case (2)
  1676. a = c2;
  1677. b = c1;
  1678. }
  1679. // `b` becomes `a`'s clip path so we transform `b` to `a` coordinate plane
  1680. fabric.util.applyTransformToObject(
  1681. b,
  1682. fabric.util.multiplyTransformMatrices(
  1683. fabric.util.invertTransform(a.calcTransformMatrix()),
  1684. b.calcTransformMatrix()
  1685. )
  1686. );
  1687. // assign the `inverted` prop to the wrapping group
  1688. var inverted = a.inverted && b.inverted;
  1689. if (inverted) {
  1690. // case (1)
  1691. a.inverted = b.inverted = false;
  1692. }
  1693. return new fabric.Group([a], { clipPath: b, inverted: inverted });
  1694. },
  1695. /**
  1696. * @memberOf fabric.util
  1697. * @param {Object} prevStyle first style to compare
  1698. * @param {Object} thisStyle second style to compare
  1699. * @param {boolean} forTextSpans whether to check overline, underline, and line-through properties
  1700. * @return {boolean} true if the style changed
  1701. */
  1702. hasStyleChanged: function(prevStyle, thisStyle, forTextSpans) {
  1703. forTextSpans = forTextSpans || false;
  1704. return (prevStyle.fill !== thisStyle.fill ||
  1705. prevStyle.stroke !== thisStyle.stroke ||
  1706. prevStyle.strokeWidth !== thisStyle.strokeWidth ||
  1707. prevStyle.fontSize !== thisStyle.fontSize ||
  1708. prevStyle.fontFamily !== thisStyle.fontFamily ||
  1709. prevStyle.fontWeight !== thisStyle.fontWeight ||
  1710. prevStyle.fontStyle !== thisStyle.fontStyle ||
  1711. prevStyle.deltaY !== thisStyle.deltaY) ||
  1712. (forTextSpans &&
  1713. (prevStyle.overline !== thisStyle.overline ||
  1714. prevStyle.underline !== thisStyle.underline ||
  1715. prevStyle.linethrough !== thisStyle.linethrough));
  1716. },
  1717. /**
  1718. * Returns the array form of a text object's inline styles property with styles grouped in ranges
  1719. * rather than per character. This format is less verbose, and is better suited for storage
  1720. * so it is used in serialization (not during runtime).
  1721. * @memberOf fabric.util
  1722. * @param {object} styles per character styles for a text object
  1723. * @param {String} text the text string that the styles are applied to
  1724. * @return {{start: number, end: number, style: object}[]}
  1725. */
  1726. stylesToArray: function(styles, text) {
  1727. // clone style structure to prevent mutation
  1728. var styles = fabric.util.object.clone(styles, true),
  1729. textLines = text.split('\n'),
  1730. charIndex = -1, prevStyle = {}, stylesArray = [];
  1731. //loop through each textLine
  1732. for (var i = 0; i < textLines.length; i++) {
  1733. if (!styles[i]) {
  1734. //no styles exist for this line, so add the line's length to the charIndex total
  1735. charIndex += textLines[i].length;
  1736. continue;
  1737. }
  1738. //loop through each character of the current line
  1739. for (var c = 0; c < textLines[i].length; c++) {
  1740. charIndex++;
  1741. var thisStyle = styles[i][c];
  1742. //check if style exists for this character
  1743. if (thisStyle) {
  1744. var styleChanged = fabric.util.hasStyleChanged(prevStyle, thisStyle, true);
  1745. if (styleChanged) {
  1746. stylesArray.push({
  1747. start: charIndex,
  1748. end: charIndex + 1,
  1749. style: thisStyle
  1750. });
  1751. }
  1752. else {
  1753. //if style is the same as previous character, increase end index
  1754. stylesArray[stylesArray.length - 1].end++;
  1755. }
  1756. }
  1757. prevStyle = thisStyle || {};
  1758. }
  1759. }
  1760. return stylesArray;
  1761. },
  1762. /**
  1763. * Returns the object form of the styles property with styles that are assigned per
  1764. * character rather than grouped by range. This format is more verbose, and is
  1765. * only used during runtime (not for serialization/storage)
  1766. * @memberOf fabric.util
  1767. * @param {Array} styles the serialized form of a text object's styles
  1768. * @param {String} text the text string that the styles are applied to
  1769. * @return {Object}
  1770. */
  1771. stylesFromArray: function(styles, text) {
  1772. if (!Array.isArray(styles)) {
  1773. return styles;
  1774. }
  1775. var textLines = text.split('\n'),
  1776. charIndex = -1, styleIndex = 0, stylesObject = {};
  1777. //loop through each textLine
  1778. for (var i = 0; i < textLines.length; i++) {
  1779. //loop through each character of the current line
  1780. for (var c = 0; c < textLines[i].length; c++) {
  1781. charIndex++;
  1782. //check if there's a style collection that includes the current character
  1783. if (styles[styleIndex]
  1784. && styles[styleIndex].start <= charIndex
  1785. && charIndex < styles[styleIndex].end) {
  1786. //create object for line index if it doesn't exist
  1787. stylesObject[i] = stylesObject[i] || {};
  1788. //assign a style at this character's index
  1789. stylesObject[i][c] = Object.assign({}, styles[styleIndex].style);
  1790. //if character is at the end of the current style collection, move to the next
  1791. if (charIndex === styles[styleIndex].end - 1) {
  1792. styleIndex++;
  1793. }
  1794. }
  1795. }
  1796. }
  1797. return stylesObject;
  1798. }
  1799. };
  1800. })(typeof exports !== 'undefined' ? exports : this);
  1801. (function() {
  1802. /**
  1803. * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array
  1804. * @static
  1805. * @memberOf fabric.util
  1806. * @param {Object} klass "Class" to create accessors for
  1807. */
  1808. fabric.util.createAccessors = function(klass) {
  1809. var proto = klass.prototype, i, propName,
  1810. capitalizedPropName, setterName, getterName;
  1811. for (i = proto.stateProperties.length; i--; ) {
  1812. propName = proto.stateProperties[i];
  1813. capitalizedPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  1814. setterName = 'set' + capitalizedPropName;
  1815. getterName = 'get' + capitalizedPropName;
  1816. // using `new Function` for better introspection
  1817. if (!proto[getterName]) {
  1818. proto[getterName] = (function(property) {
  1819. return new Function('return this.get("' + property + '")');
  1820. })(propName);
  1821. }
  1822. if (!proto[setterName]) {
  1823. proto[setterName] = (function(property) {
  1824. return new Function('value', 'return this.set("' + property + '", value)');
  1825. })(propName);
  1826. }
  1827. }
  1828. };
  1829. /** @lends fabric.Text.Prototype */
  1830. /**
  1831. * Retrieves object's fontSize
  1832. * @method getFontSize
  1833. * @memberOf fabric.Text.prototype
  1834. * @return {String} Font size (in pixels)
  1835. */
  1836. /**
  1837. * Sets object's fontSize
  1838. * Does not update the object .width and .height,
  1839. * call .initDimensions() to update the values.
  1840. * @method setFontSize
  1841. * @memberOf fabric.Text.prototype
  1842. * @param {Number} fontSize Font size (in pixels)
  1843. * @return {fabric.Text}
  1844. * @chainable
  1845. */
  1846. /**
  1847. * Retrieves object's fontWeight
  1848. * @method getFontWeight
  1849. * @memberOf fabric.Text.prototype
  1850. * @return {(String|Number)} Font weight
  1851. */
  1852. /**
  1853. * Sets object's fontWeight
  1854. * Does not update the object .width and .height,
  1855. * call .initDimensions() to update the values.
  1856. * @method setFontWeight
  1857. * @memberOf fabric.Text.prototype
  1858. * @param {(Number|String)} fontWeight Font weight
  1859. * @return {fabric.Text}
  1860. * @chainable
  1861. */
  1862. /**
  1863. * Retrieves object's fontFamily
  1864. * @method getFontFamily
  1865. * @memberOf fabric.Text.prototype
  1866. * @return {String} Font family
  1867. */
  1868. /**
  1869. * Sets object's fontFamily
  1870. * Does not update the object .width and .height,
  1871. * call .initDimensions() to update the values.
  1872. * @method setFontFamily
  1873. * @memberOf fabric.Text.prototype
  1874. * @param {String} fontFamily Font family
  1875. * @return {fabric.Text}
  1876. * @chainable
  1877. */
  1878. /**
  1879. * Retrieves object's text
  1880. * @method getText
  1881. * @memberOf fabric.Text.prototype
  1882. * @return {String} text
  1883. */
  1884. /**
  1885. * Sets object's text
  1886. * Does not update the object .width and .height,
  1887. * call .initDimensions() to update the values.
  1888. * @method setText
  1889. * @memberOf fabric.Text.prototype
  1890. * @param {String} text Text
  1891. * @return {fabric.Text}
  1892. * @chainable
  1893. */
  1894. /**
  1895. * Retrieves object's underline
  1896. * @method getUnderline
  1897. * @memberOf fabric.Text.prototype
  1898. * @return {Boolean} underline enabled or disabled
  1899. */
  1900. /**
  1901. * Sets object's underline
  1902. * @method setUnderline
  1903. * @memberOf fabric.Text.prototype
  1904. * @param {Boolean} underline Text decoration
  1905. * @return {fabric.Text}
  1906. * @chainable
  1907. */
  1908. /**
  1909. * Retrieves object's fontStyle
  1910. * @method getFontStyle
  1911. * @memberOf fabric.Text.prototype
  1912. * @return {String} Font style
  1913. */
  1914. /**
  1915. * Sets object's fontStyle
  1916. * Does not update the object .width and .height,
  1917. * call .initDimensions() to update the values.
  1918. * @method setFontStyle
  1919. * @memberOf fabric.Text.prototype
  1920. * @param {String} fontStyle Font style
  1921. * @return {fabric.Text}
  1922. * @chainable
  1923. */
  1924. /**
  1925. * Retrieves object's lineHeight
  1926. * @method getLineHeight
  1927. * @memberOf fabric.Text.prototype
  1928. * @return {Number} Line height
  1929. */
  1930. /**
  1931. * Sets object's lineHeight
  1932. * @method setLineHeight
  1933. * @memberOf fabric.Text.prototype
  1934. * @param {Number} lineHeight Line height
  1935. * @return {fabric.Text}
  1936. * @chainable
  1937. */
  1938. /**
  1939. * Retrieves object's textAlign
  1940. * @method getTextAlign
  1941. * @memberOf fabric.Text.prototype
  1942. * @return {String} Text alignment
  1943. */
  1944. /**
  1945. * Sets object's textAlign
  1946. * @method setTextAlign
  1947. * @memberOf fabric.Text.prototype
  1948. * @param {String} textAlign Text alignment
  1949. * @return {fabric.Text}
  1950. * @chainable
  1951. */
  1952. /**
  1953. * Retrieves object's textBackgroundColor
  1954. * @method getTextBackgroundColor
  1955. * @memberOf fabric.Text.prototype
  1956. * @return {String} Text background color
  1957. */
  1958. /**
  1959. * Sets object's textBackgroundColor
  1960. * @method setTextBackgroundColor
  1961. * @memberOf fabric.Text.prototype
  1962. * @param {String} textBackgroundColor Text background color
  1963. * @return {fabric.Text}
  1964. * @chainable
  1965. */
  1966. /** @lends fabric.Object.Prototype */
  1967. /**
  1968. * Retrieves object's {@link fabric.Object#transformMatrix|transformMatrix}
  1969. * @method getTransformMatrix
  1970. * @memberOf fabric.Object.prototype
  1971. * @return {Array} transformMatrix
  1972. */
  1973. /**
  1974. * Sets object's {@link fabric.Object#transformMatrix|transformMatrix}
  1975. * @method setTransformMatrix
  1976. * @memberOf fabric.Object.prototype
  1977. * @param {Array} transformMatrix
  1978. * @return {fabric.Object} thisArg
  1979. * @chainable
  1980. */
  1981. /**
  1982. * Retrieves object's {@link fabric.Object#visible|visible} state
  1983. * @method getVisible
  1984. * @memberOf fabric.Object.prototype
  1985. * @return {Boolean} True if visible
  1986. */
  1987. /**
  1988. * Sets object's {@link fabric.Object#visible|visible} state
  1989. * @method setVisible
  1990. * @memberOf fabric.Object.prototype
  1991. * @param {Boolean} value visible value
  1992. * @return {fabric.Object} thisArg
  1993. * @chainable
  1994. */
  1995. /**
  1996. * Retrieves object's {@link fabric.Object#shadow|shadow}
  1997. * @method getShadow
  1998. * @memberOf fabric.Object.prototype
  1999. * @return {Object} Shadow instance
  2000. */
  2001. /**
  2002. * Retrieves object's {@link fabric.Object#stroke|stroke}
  2003. * @method getStroke
  2004. * @memberOf fabric.Object.prototype
  2005. * @return {String} stroke value
  2006. */
  2007. /**
  2008. * Sets object's {@link fabric.Object#stroke|stroke}
  2009. * @method setStroke
  2010. * @memberOf fabric.Object.prototype
  2011. * @param {String} value stroke value
  2012. * @return {fabric.Object} thisArg
  2013. * @chainable
  2014. */
  2015. /**
  2016. * Retrieves object's {@link fabric.Object#strokeWidth|strokeWidth}
  2017. * @method getStrokeWidth
  2018. * @memberOf fabric.Object.prototype
  2019. * @return {Number} strokeWidth value
  2020. */
  2021. /**
  2022. * Sets object's {@link fabric.Object#strokeWidth|strokeWidth}
  2023. * @method setStrokeWidth
  2024. * @memberOf fabric.Object.prototype
  2025. * @param {Number} value strokeWidth value
  2026. * @return {fabric.Object} thisArg
  2027. * @chainable
  2028. */
  2029. /**
  2030. * Retrieves object's {@link fabric.Object#originX|originX}
  2031. * @method getOriginX
  2032. * @memberOf fabric.Object.prototype
  2033. * @return {String} originX value
  2034. */
  2035. /**
  2036. * Sets object's {@link fabric.Object#originX|originX}
  2037. * @method setOriginX
  2038. * @memberOf fabric.Object.prototype
  2039. * @param {String} value originX value
  2040. * @return {fabric.Object} thisArg
  2041. * @chainable
  2042. */
  2043. /**
  2044. * Retrieves object's {@link fabric.Object#originY|originY}
  2045. * @method getOriginY
  2046. * @memberOf fabric.Object.prototype
  2047. * @return {String} originY value
  2048. */
  2049. /**
  2050. * Sets object's {@link fabric.Object#originY|originY}
  2051. * @method setOriginY
  2052. * @memberOf fabric.Object.prototype
  2053. * @param {String} value originY value
  2054. * @return {fabric.Object} thisArg
  2055. * @chainable
  2056. */
  2057. /**
  2058. * Retrieves object's {@link fabric.Object#fill|fill}
  2059. * @method getFill
  2060. * @memberOf fabric.Object.prototype
  2061. * @return {String} Fill value
  2062. */
  2063. /**
  2064. * Sets object's {@link fabric.Object#fill|fill}
  2065. * @method setFill
  2066. * @memberOf fabric.Object.prototype
  2067. * @param {String} value Fill value
  2068. * @return {fabric.Object} thisArg
  2069. * @chainable
  2070. */
  2071. /**
  2072. * Retrieves object's {@link fabric.Object#opacity|opacity}
  2073. * @method getOpacity
  2074. * @memberOf fabric.Object.prototype
  2075. * @return {Number} Opacity value (0-1)
  2076. */
  2077. /**
  2078. * Sets object's {@link fabric.Object#opacity|opacity}
  2079. * @method setOpacity
  2080. * @memberOf fabric.Object.prototype
  2081. * @param {Number} value Opacity value (0-1)
  2082. * @return {fabric.Object} thisArg
  2083. * @chainable
  2084. */
  2085. /**
  2086. * Retrieves object's {@link fabric.Object#angle|angle} (in degrees)
  2087. * @method getAngle
  2088. * @memberOf fabric.Object.prototype
  2089. * @return {Number}
  2090. */
  2091. /**
  2092. * Retrieves object's {@link fabric.Object#top|top position}
  2093. * @method getTop
  2094. * @memberOf fabric.Object.prototype
  2095. * @return {Number} Top value (in pixels)
  2096. */
  2097. /**
  2098. * Sets object's {@link fabric.Object#top|top position}
  2099. * @method setTop
  2100. * @memberOf fabric.Object.prototype
  2101. * @param {Number} value Top value (in pixels)
  2102. * @return {fabric.Object} thisArg
  2103. * @chainable
  2104. */
  2105. /**
  2106. * Retrieves object's {@link fabric.Object#left|left position}
  2107. * @method getLeft
  2108. * @memberOf fabric.Object.prototype
  2109. * @return {Number} Left value (in pixels)
  2110. */
  2111. /**
  2112. * Sets object's {@link fabric.Object#left|left position}
  2113. * @method setLeft
  2114. * @memberOf fabric.Object.prototype
  2115. * @param {Number} value Left value (in pixels)
  2116. * @return {fabric.Object} thisArg
  2117. * @chainable
  2118. */
  2119. /**
  2120. * Retrieves object's {@link fabric.Object#scaleX|scaleX} value
  2121. * @method getScaleX
  2122. * @memberOf fabric.Object.prototype
  2123. * @return {Number} scaleX value
  2124. */
  2125. /**
  2126. * Sets object's {@link fabric.Object#scaleX|scaleX} value
  2127. * @method setScaleX
  2128. * @memberOf fabric.Object.prototype
  2129. * @param {Number} value scaleX value
  2130. * @return {fabric.Object} thisArg
  2131. * @chainable
  2132. */
  2133. /**
  2134. * Retrieves object's {@link fabric.Object#scaleY|scaleY} value
  2135. * @method getScaleY
  2136. * @memberOf fabric.Object.prototype
  2137. * @return {Number} scaleY value
  2138. */
  2139. /**
  2140. * Sets object's {@link fabric.Object#scaleY|scaleY} value
  2141. * @method setScaleY
  2142. * @memberOf fabric.Object.prototype
  2143. * @param {Number} value scaleY value
  2144. * @return {fabric.Object} thisArg
  2145. * @chainable
  2146. */
  2147. /**
  2148. * Retrieves object's {@link fabric.Object#flipX|flipX} value
  2149. * @method getFlipX
  2150. * @memberOf fabric.Object.prototype
  2151. * @return {Boolean} flipX value
  2152. */
  2153. /**
  2154. * Sets object's {@link fabric.Object#flipX|flipX} value
  2155. * @method setFlipX
  2156. * @memberOf fabric.Object.prototype
  2157. * @param {Boolean} value flipX value
  2158. * @return {fabric.Object} thisArg
  2159. * @chainable
  2160. */
  2161. /**
  2162. * Retrieves object's {@link fabric.Object#flipY|flipY} value
  2163. * @method getFlipY
  2164. * @memberOf fabric.Object.prototype
  2165. * @return {Boolean} flipY value
  2166. */
  2167. /**
  2168. * Sets object's {@link fabric.Object#flipY|flipY} value
  2169. * @method setFlipY
  2170. * @memberOf fabric.Object.prototype
  2171. * @param {Boolean} value flipY value
  2172. * @return {fabric.Object} thisArg
  2173. * @chainable
  2174. */
  2175. })(typeof exports !== 'undefined' ? exports : this);
  2176. (function() {
  2177. var _join = Array.prototype.join,
  2178. commandLengths = {
  2179. m: 2,
  2180. l: 2,
  2181. h: 1,
  2182. v: 1,
  2183. c: 6,
  2184. s: 4,
  2185. q: 4,
  2186. t: 2,
  2187. a: 7
  2188. },
  2189. repeatedCommands = {
  2190. m: 'l',
  2191. M: 'L'
  2192. };
  2193. function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {
  2194. var costh2 = fabric.util.cos(th2),
  2195. sinth2 = fabric.util.sin(th2),
  2196. costh3 = fabric.util.cos(th3),
  2197. sinth3 = fabric.util.sin(th3),
  2198. toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1,
  2199. toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1,
  2200. cp1X = fromX + mT * ( -cosTh * rx * sinth2 - sinTh * ry * costh2),
  2201. cp1Y = fromY + mT * ( -sinTh * rx * sinth2 + cosTh * ry * costh2),
  2202. cp2X = toX + mT * ( cosTh * rx * sinth3 + sinTh * ry * costh3),
  2203. cp2Y = toY + mT * ( sinTh * rx * sinth3 - cosTh * ry * costh3);
  2204. return ['C',
  2205. cp1X, cp1Y,
  2206. cp2X, cp2Y,
  2207. toX, toY
  2208. ];
  2209. }
  2210. /* Adapted from http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp
  2211. * by Andrea Bogazzi code is under MPL. if you don't have a copy of the license you can take it here
  2212. * http://mozilla.org/MPL/2.0/
  2213. */
  2214. function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {
  2215. var PI = Math.PI, th = rotateX * PI / 180,
  2216. sinTh = fabric.util.sin(th),
  2217. cosTh = fabric.util.cos(th),
  2218. fromX = 0, fromY = 0;
  2219. rx = Math.abs(rx);
  2220. ry = Math.abs(ry);
  2221. var px = -cosTh * toX * 0.5 - sinTh * toY * 0.5,
  2222. py = -cosTh * toY * 0.5 + sinTh * toX * 0.5,
  2223. rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px,
  2224. pl = rx2 * ry2 - rx2 * py2 - ry2 * px2,
  2225. root = 0;
  2226. if (pl < 0) {
  2227. var s = Math.sqrt(1 - pl / (rx2 * ry2));
  2228. rx *= s;
  2229. ry *= s;
  2230. }
  2231. else {
  2232. root = (large === sweep ? -1.0 : 1.0) *
  2233. Math.sqrt( pl / (rx2 * py2 + ry2 * px2));
  2234. }
  2235. var cx = root * rx * py / ry,
  2236. cy = -root * ry * px / rx,
  2237. cx1 = cosTh * cx - sinTh * cy + toX * 0.5,
  2238. cy1 = sinTh * cx + cosTh * cy + toY * 0.5,
  2239. mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry),
  2240. dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry);
  2241. if (sweep === 0 && dtheta > 0) {
  2242. dtheta -= 2 * PI;
  2243. }
  2244. else if (sweep === 1 && dtheta < 0) {
  2245. dtheta += 2 * PI;
  2246. }
  2247. // Convert into cubic bezier segments <= 90deg
  2248. var segments = Math.ceil(Math.abs(dtheta / PI * 2)),
  2249. result = [], mDelta = dtheta / segments,
  2250. mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2),
  2251. th3 = mTheta + mDelta;
  2252. for (var i = 0; i < segments; i++) {
  2253. result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);
  2254. fromX = result[i][5];
  2255. fromY = result[i][6];
  2256. mTheta = th3;
  2257. th3 += mDelta;
  2258. }
  2259. return result;
  2260. }
  2261. /*
  2262. * Private
  2263. */
  2264. function calcVectorAngle(ux, uy, vx, vy) {
  2265. var ta = Math.atan2(uy, ux),
  2266. tb = Math.atan2(vy, vx);
  2267. if (tb >= ta) {
  2268. return tb - ta;
  2269. }
  2270. else {
  2271. return 2 * Math.PI - (ta - tb);
  2272. }
  2273. }
  2274. /**
  2275. * Calculate bounding box of a beziercurve
  2276. * @param {Number} x0 starting point
  2277. * @param {Number} y0
  2278. * @param {Number} x1 first control point
  2279. * @param {Number} y1
  2280. * @param {Number} x2 secondo control point
  2281. * @param {Number} y2
  2282. * @param {Number} x3 end of bezier
  2283. * @param {Number} y3
  2284. */
  2285. // taken from http://jsbin.com/ivomiq/56/edit no credits available for that.
  2286. // TODO: can we normalize this with the starting points set at 0 and then translated the bbox?
  2287. function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {
  2288. var argsString;
  2289. if (fabric.cachesBoundsOfCurve) {
  2290. argsString = _join.call(arguments);
  2291. if (fabric.boundsOfCurveCache[argsString]) {
  2292. return fabric.boundsOfCurveCache[argsString];
  2293. }
  2294. }
  2295. var sqrt = Math.sqrt,
  2296. min = Math.min, max = Math.max,
  2297. abs = Math.abs, tvalues = [],
  2298. bounds = [[], []],
  2299. a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  2300. b = 6 * x0 - 12 * x1 + 6 * x2;
  2301. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  2302. c = 3 * x1 - 3 * x0;
  2303. for (var i = 0; i < 2; ++i) {
  2304. if (i > 0) {
  2305. b = 6 * y0 - 12 * y1 + 6 * y2;
  2306. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  2307. c = 3 * y1 - 3 * y0;
  2308. }
  2309. if (abs(a) < 1e-12) {
  2310. if (abs(b) < 1e-12) {
  2311. continue;
  2312. }
  2313. t = -c / b;
  2314. if (0 < t && t < 1) {
  2315. tvalues.push(t);
  2316. }
  2317. continue;
  2318. }
  2319. b2ac = b * b - 4 * c * a;
  2320. if (b2ac < 0) {
  2321. continue;
  2322. }
  2323. sqrtb2ac = sqrt(b2ac);
  2324. t1 = (-b + sqrtb2ac) / (2 * a);
  2325. if (0 < t1 && t1 < 1) {
  2326. tvalues.push(t1);
  2327. }
  2328. t2 = (-b - sqrtb2ac) / (2 * a);
  2329. if (0 < t2 && t2 < 1) {
  2330. tvalues.push(t2);
  2331. }
  2332. }
  2333. var x, y, j = tvalues.length, jlen = j, mt;
  2334. while (j--) {
  2335. t = tvalues[j];
  2336. mt = 1 - t;
  2337. x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
  2338. bounds[0][j] = x;
  2339. y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
  2340. bounds[1][j] = y;
  2341. }
  2342. bounds[0][jlen] = x0;
  2343. bounds[1][jlen] = y0;
  2344. bounds[0][jlen + 1] = x3;
  2345. bounds[1][jlen + 1] = y3;
  2346. var result = [
  2347. {
  2348. x: min.apply(null, bounds[0]),
  2349. y: min.apply(null, bounds[1])
  2350. },
  2351. {
  2352. x: max.apply(null, bounds[0]),
  2353. y: max.apply(null, bounds[1])
  2354. }
  2355. ];
  2356. if (fabric.cachesBoundsOfCurve) {
  2357. fabric.boundsOfCurveCache[argsString] = result;
  2358. }
  2359. return result;
  2360. }
  2361. /**
  2362. * Converts arc to a bunch of bezier curves
  2363. * @param {Number} fx starting point x
  2364. * @param {Number} fy starting point y
  2365. * @param {Array} coords Arc command
  2366. */
  2367. function fromArcToBeziers(fx, fy, coords) {
  2368. var rx = coords[1],
  2369. ry = coords[2],
  2370. rot = coords[3],
  2371. large = coords[4],
  2372. sweep = coords[5],
  2373. tx = coords[6],
  2374. ty = coords[7],
  2375. segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
  2376. for (var i = 0, len = segsNorm.length; i < len; i++) {
  2377. segsNorm[i][1] += fx;
  2378. segsNorm[i][2] += fy;
  2379. segsNorm[i][3] += fx;
  2380. segsNorm[i][4] += fy;
  2381. segsNorm[i][5] += fx;
  2382. segsNorm[i][6] += fy;
  2383. }
  2384. return segsNorm;
  2385. };
  2386. /**
  2387. * This function take a parsed SVG path and make it simpler for fabricJS logic.
  2388. * simplification consist of: only UPPERCASE absolute commands ( relative converted to absolute )
  2389. * S converted in C, T converted in Q, A converted in C.
  2390. * @param {Array} path the array of commands of a parsed svg path for fabric.Path
  2391. * @return {Array} the simplified array of commands of a parsed svg path for fabric.Path
  2392. */
  2393. function makePathSimpler(path) {
  2394. // x and y represent the last point of the path. the previous command point.
  2395. // we add them to each relative command to make it an absolute comment.
  2396. // we also swap the v V h H with L, because are easier to transform.
  2397. var x = 0, y = 0, len = path.length,
  2398. // x1 and y1 represent the last point of the subpath. the subpath is started with
  2399. // m or M command. When a z or Z command is drawn, x and y need to be resetted to
  2400. // the last x1 and y1.
  2401. x1 = 0, y1 = 0, current, i, converted,
  2402. // previous will host the letter of the previous command, to handle S and T.
  2403. // controlX and controlY will host the previous reflected control point
  2404. destinationPath = [], previous, controlX, controlY;
  2405. for (i = 0; i < len; ++i) {
  2406. converted = false;
  2407. current = path[i].slice(0);
  2408. switch (current[0]) { // first letter
  2409. case 'l': // lineto, relative
  2410. current[0] = 'L';
  2411. current[1] += x;
  2412. current[2] += y;
  2413. // falls through
  2414. case 'L':
  2415. x = current[1];
  2416. y = current[2];
  2417. break;
  2418. case 'h': // horizontal lineto, relative
  2419. current[1] += x;
  2420. // falls through
  2421. case 'H':
  2422. current[0] = 'L';
  2423. current[2] = y;
  2424. x = current[1];
  2425. break;
  2426. case 'v': // vertical lineto, relative
  2427. current[1] += y;
  2428. // falls through
  2429. case 'V':
  2430. current[0] = 'L';
  2431. y = current[1];
  2432. current[1] = x;
  2433. current[2] = y;
  2434. break;
  2435. case 'm': // moveTo, relative
  2436. current[0] = 'M';
  2437. current[1] += x;
  2438. current[2] += y;
  2439. // falls through
  2440. case 'M':
  2441. x = current[1];
  2442. y = current[2];
  2443. x1 = current[1];
  2444. y1 = current[2];
  2445. break;
  2446. case 'c': // bezierCurveTo, relative
  2447. current[0] = 'C';
  2448. current[1] += x;
  2449. current[2] += y;
  2450. current[3] += x;
  2451. current[4] += y;
  2452. current[5] += x;
  2453. current[6] += y;
  2454. // falls through
  2455. case 'C':
  2456. controlX = current[3];
  2457. controlY = current[4];
  2458. x = current[5];
  2459. y = current[6];
  2460. break;
  2461. case 's': // shorthand cubic bezierCurveTo, relative
  2462. current[0] = 'S';
  2463. current[1] += x;
  2464. current[2] += y;
  2465. current[3] += x;
  2466. current[4] += y;
  2467. // falls through
  2468. case 'S':
  2469. // would be sScC but since we are swapping sSc for C, we check just that.
  2470. if (previous === 'C') {
  2471. // calculate reflection of previous control points
  2472. controlX = 2 * x - controlX;
  2473. controlY = 2 * y - controlY;
  2474. }
  2475. else {
  2476. // If there is no previous command or if the previous command was not a C, c, S, or s,
  2477. // the control point is coincident with the current point
  2478. controlX = x;
  2479. controlY = y;
  2480. }
  2481. x = current[3];
  2482. y = current[4];
  2483. current[0] = 'C';
  2484. current[5] = current[3];
  2485. current[6] = current[4];
  2486. current[3] = current[1];
  2487. current[4] = current[2];
  2488. current[1] = controlX;
  2489. current[2] = controlY;
  2490. // current[3] and current[4] are NOW the second control point.
  2491. // we keep it for the next reflection.
  2492. controlX = current[3];
  2493. controlY = current[4];
  2494. break;
  2495. case 'q': // quadraticCurveTo, relative
  2496. current[0] = 'Q';
  2497. current[1] += x;
  2498. current[2] += y;
  2499. current[3] += x;
  2500. current[4] += y;
  2501. // falls through
  2502. case 'Q':
  2503. controlX = current[1];
  2504. controlY = current[2];
  2505. x = current[3];
  2506. y = current[4];
  2507. break;
  2508. case 't': // shorthand quadraticCurveTo, relative
  2509. current[0] = 'T';
  2510. current[1] += x;
  2511. current[2] += y;
  2512. // falls through
  2513. case 'T':
  2514. if (previous === 'Q') {
  2515. // calculate reflection of previous control point
  2516. controlX = 2 * x - controlX;
  2517. controlY = 2 * y - controlY;
  2518. }
  2519. else {
  2520. // If there is no previous command or if the previous command was not a Q, q, T or t,
  2521. // assume the control point is coincident with the current point
  2522. controlX = x;
  2523. controlY = y;
  2524. }
  2525. current[0] = 'Q';
  2526. x = current[1];
  2527. y = current[2];
  2528. current[1] = controlX;
  2529. current[2] = controlY;
  2530. current[3] = x;
  2531. current[4] = y;
  2532. break;
  2533. case 'a':
  2534. current[0] = 'A';
  2535. current[6] += x;
  2536. current[7] += y;
  2537. // falls through
  2538. case 'A':
  2539. converted = true;
  2540. destinationPath = destinationPath.concat(fromArcToBeziers(x, y, current));
  2541. x = current[6];
  2542. y = current[7];
  2543. break;
  2544. case 'z':
  2545. case 'Z':
  2546. x = x1;
  2547. y = y1;
  2548. break;
  2549. default:
  2550. }
  2551. if (!converted) {
  2552. destinationPath.push(current);
  2553. }
  2554. previous = current[0];
  2555. }
  2556. return destinationPath;
  2557. };
  2558. /**
  2559. * Calc length from point x1,y1 to x2,y2
  2560. * @param {Number} x1 starting point x
  2561. * @param {Number} y1 starting point y
  2562. * @param {Number} x2 starting point x
  2563. * @param {Number} y2 starting point y
  2564. * @return {Number} length of segment
  2565. */
  2566. function calcLineLength(x1, y1, x2, y2) {
  2567. return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  2568. }
  2569. // functions for the Cubic beizer
  2570. // taken from: https://github.com/konvajs/konva/blob/7.0.5/src/shapes/Path.ts#L350
  2571. function CB1(t) {
  2572. return t * t * t;
  2573. }
  2574. function CB2(t) {
  2575. return 3 * t * t * (1 - t);
  2576. }
  2577. function CB3(t) {
  2578. return 3 * t * (1 - t) * (1 - t);
  2579. }
  2580. function CB4(t) {
  2581. return (1 - t) * (1 - t) * (1 - t);
  2582. }
  2583. function getPointOnCubicBezierIterator(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) {
  2584. return function(pct) {
  2585. var c1 = CB1(pct), c2 = CB2(pct), c3 = CB3(pct), c4 = CB4(pct);
  2586. return {
  2587. x: p4x * c1 + p3x * c2 + p2x * c3 + p1x * c4,
  2588. y: p4y * c1 + p3y * c2 + p2y * c3 + p1y * c4
  2589. };
  2590. };
  2591. }
  2592. function getTangentCubicIterator(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) {
  2593. return function (pct) {
  2594. var invT = 1 - pct,
  2595. tangentX = (3 * invT * invT * (p2x - p1x)) + (6 * invT * pct * (p3x - p2x)) +
  2596. (3 * pct * pct * (p4x - p3x)),
  2597. tangentY = (3 * invT * invT * (p2y - p1y)) + (6 * invT * pct * (p3y - p2y)) +
  2598. (3 * pct * pct * (p4y - p3y));
  2599. return Math.atan2(tangentY, tangentX);
  2600. };
  2601. }
  2602. function QB1(t) {
  2603. return t * t;
  2604. }
  2605. function QB2(t) {
  2606. return 2 * t * (1 - t);
  2607. }
  2608. function QB3(t) {
  2609. return (1 - t) * (1 - t);
  2610. }
  2611. function getPointOnQuadraticBezierIterator(p1x, p1y, p2x, p2y, p3x, p3y) {
  2612. return function(pct) {
  2613. var c1 = QB1(pct), c2 = QB2(pct), c3 = QB3(pct);
  2614. return {
  2615. x: p3x * c1 + p2x * c2 + p1x * c3,
  2616. y: p3y * c1 + p2y * c2 + p1y * c3
  2617. };
  2618. };
  2619. }
  2620. function getTangentQuadraticIterator(p1x, p1y, p2x, p2y, p3x, p3y) {
  2621. return function (pct) {
  2622. var invT = 1 - pct,
  2623. tangentX = (2 * invT * (p2x - p1x)) + (2 * pct * (p3x - p2x)),
  2624. tangentY = (2 * invT * (p2y - p1y)) + (2 * pct * (p3y - p2y));
  2625. return Math.atan2(tangentY, tangentX);
  2626. };
  2627. }
  2628. // this will run over a path segment ( a cubic or quadratic segment) and approximate it
  2629. // with 100 segemnts. This will good enough to calculate the length of the curve
  2630. function pathIterator(iterator, x1, y1) {
  2631. var tempP = { x: x1, y: y1 }, p, tmpLen = 0, perc;
  2632. for (perc = 1; perc <= 100; perc += 1) {
  2633. p = iterator(perc / 100);
  2634. tmpLen += calcLineLength(tempP.x, tempP.y, p.x, p.y);
  2635. tempP = p;
  2636. }
  2637. return tmpLen;
  2638. }
  2639. /**
  2640. * Given a pathInfo, and a distance in pixels, find the percentage from 0 to 1
  2641. * that correspond to that pixels run over the path.
  2642. * The percentage will be then used to find the correct point on the canvas for the path.
  2643. * @param {Array} segInfo fabricJS collection of information on a parsed path
  2644. * @param {Number} distance from starting point, in pixels.
  2645. * @return {Object} info object with x and y ( the point on canvas ) and angle, the tangent on that point;
  2646. */
  2647. function findPercentageForDistance(segInfo, distance) {
  2648. var perc = 0, tmpLen = 0, iterator = segInfo.iterator, tempP = { x: segInfo.x, y: segInfo.y },
  2649. p, nextLen, nextStep = 0.01, angleFinder = segInfo.angleFinder, lastPerc;
  2650. // nextStep > 0.0001 covers 0.00015625 that 1/64th of 1/100
  2651. // the path
  2652. while (tmpLen < distance && nextStep > 0.0001) {
  2653. p = iterator(perc);
  2654. lastPerc = perc;
  2655. nextLen = calcLineLength(tempP.x, tempP.y, p.x, p.y);
  2656. // compare tmpLen each cycle with distance, decide next perc to test.
  2657. if ((nextLen + tmpLen) > distance) {
  2658. // we discard this step and we make smaller steps.
  2659. perc -= nextStep;
  2660. nextStep /= 2;
  2661. }
  2662. else {
  2663. tempP = p;
  2664. perc += nextStep;
  2665. tmpLen += nextLen;
  2666. }
  2667. }
  2668. p.angle = angleFinder(lastPerc);
  2669. return p;
  2670. }
  2671. /**
  2672. * Run over a parsed and simplifed path and extrac some informations.
  2673. * informations are length of each command and starting point
  2674. * @param {Array} path fabricJS parsed path commands
  2675. * @return {Array} path commands informations
  2676. */
  2677. function getPathSegmentsInfo(path) {
  2678. var totalLength = 0, len = path.length, current,
  2679. //x2 and y2 are the coords of segment start
  2680. //x1 and y1 are the coords of the current point
  2681. x1 = 0, y1 = 0, x2 = 0, y2 = 0, info = [], iterator, tempInfo, angleFinder;
  2682. for (var i = 0; i < len; i++) {
  2683. current = path[i];
  2684. tempInfo = {
  2685. x: x1,
  2686. y: y1,
  2687. command: current[0],
  2688. };
  2689. switch (current[0]) { //first letter
  2690. case 'M':
  2691. tempInfo.length = 0;
  2692. x2 = x1 = current[1];
  2693. y2 = y1 = current[2];
  2694. break;
  2695. case 'L':
  2696. tempInfo.length = calcLineLength(x1, y1, current[1], current[2]);
  2697. x1 = current[1];
  2698. y1 = current[2];
  2699. break;
  2700. case 'C':
  2701. iterator = getPointOnCubicBezierIterator(
  2702. x1,
  2703. y1,
  2704. current[1],
  2705. current[2],
  2706. current[3],
  2707. current[4],
  2708. current[5],
  2709. current[6]
  2710. );
  2711. angleFinder = getTangentCubicIterator(
  2712. x1,
  2713. y1,
  2714. current[1],
  2715. current[2],
  2716. current[3],
  2717. current[4],
  2718. current[5],
  2719. current[6]
  2720. );
  2721. tempInfo.iterator = iterator;
  2722. tempInfo.angleFinder = angleFinder;
  2723. tempInfo.length = pathIterator(iterator, x1, y1);
  2724. x1 = current[5];
  2725. y1 = current[6];
  2726. break;
  2727. case 'Q':
  2728. iterator = getPointOnQuadraticBezierIterator(
  2729. x1,
  2730. y1,
  2731. current[1],
  2732. current[2],
  2733. current[3],
  2734. current[4]
  2735. );
  2736. angleFinder = getTangentQuadraticIterator(
  2737. x1,
  2738. y1,
  2739. current[1],
  2740. current[2],
  2741. current[3],
  2742. current[4]
  2743. );
  2744. tempInfo.iterator = iterator;
  2745. tempInfo.angleFinder = angleFinder;
  2746. tempInfo.length = pathIterator(iterator, x1, y1);
  2747. x1 = current[3];
  2748. y1 = current[4];
  2749. break;
  2750. case 'Z':
  2751. case 'z':
  2752. // we add those in order to ease calculations later
  2753. tempInfo.destX = x2;
  2754. tempInfo.destY = y2;
  2755. tempInfo.length = calcLineLength(x1, y1, x2, y2);
  2756. x1 = x2;
  2757. y1 = y2;
  2758. break;
  2759. }
  2760. totalLength += tempInfo.length;
  2761. info.push(tempInfo);
  2762. }
  2763. info.push({ length: totalLength, x: x1, y: y1 });
  2764. return info;
  2765. }
  2766. function getPointOnPath(path, distance, infos) {
  2767. if (!infos) {
  2768. infos = getPathSegmentsInfo(path);
  2769. }
  2770. var i = 0;
  2771. while ((distance - infos[i].length > 0) && i < (infos.length - 2)) {
  2772. distance -= infos[i].length;
  2773. i++;
  2774. }
  2775. // var distance = infos[infos.length - 1] * perc;
  2776. var segInfo = infos[i], segPercent = distance / segInfo.length,
  2777. command = segInfo.command, segment = path[i], info;
  2778. switch (command) {
  2779. case 'M':
  2780. return { x: segInfo.x, y: segInfo.y, angle: 0 };
  2781. case 'Z':
  2782. case 'z':
  2783. info = new fabric.Point(segInfo.x, segInfo.y).lerp(
  2784. new fabric.Point(segInfo.destX, segInfo.destY),
  2785. segPercent
  2786. );
  2787. info.angle = Math.atan2(segInfo.destY - segInfo.y, segInfo.destX - segInfo.x);
  2788. return info;
  2789. case 'L':
  2790. info = new fabric.Point(segInfo.x, segInfo.y).lerp(
  2791. new fabric.Point(segment[1], segment[2]),
  2792. segPercent
  2793. );
  2794. info.angle = Math.atan2(segment[2] - segInfo.y, segment[1] - segInfo.x);
  2795. return info;
  2796. case 'C':
  2797. return findPercentageForDistance(segInfo, distance);
  2798. case 'Q':
  2799. return findPercentageForDistance(segInfo, distance);
  2800. }
  2801. }
  2802. /**
  2803. *
  2804. * @param {string} pathString
  2805. * @return {(string|number)[][]} An array of SVG path commands
  2806. * @example <caption>Usage</caption>
  2807. * parsePath('M 3 4 Q 3 5 2 1 4 0 Q 9 12 2 1 4 0') === [
  2808. * ['M', 3, 4],
  2809. * ['Q', 3, 5, 2, 1, 4, 0],
  2810. * ['Q', 9, 12, 2, 1, 4, 0],
  2811. * ];
  2812. *
  2813. */
  2814. function parsePath(pathString) {
  2815. var result = [],
  2816. coords = [],
  2817. currentPath,
  2818. parsed,
  2819. re = fabric.rePathCommand,
  2820. rNumber = '[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?\\s*',
  2821. rNumberCommaWsp = '(' + rNumber + ')' + fabric.commaWsp,
  2822. rFlagCommaWsp = '([01])' + fabric.commaWsp + '?',
  2823. rArcSeq = rNumberCommaWsp + '?' + rNumberCommaWsp + '?' + rNumberCommaWsp + rFlagCommaWsp + rFlagCommaWsp +
  2824. rNumberCommaWsp + '?(' + rNumber + ')',
  2825. regArcArgumentSequence = new RegExp(rArcSeq, 'g'),
  2826. match,
  2827. coordsStr,
  2828. // one of commands (m,M,l,L,q,Q,c,C,etc.) followed by non-command characters (i.e. command values)
  2829. path;
  2830. if (!pathString || !pathString.match) {
  2831. return result;
  2832. }
  2833. path = pathString.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);
  2834. for (var i = 0, coordsParsed, len = path.length; i < len; i++) {
  2835. currentPath = path[i];
  2836. coordsStr = currentPath.slice(1).trim();
  2837. coords.length = 0;
  2838. var command = currentPath.charAt(0);
  2839. coordsParsed = [command];
  2840. if (command.toLowerCase() === 'a') {
  2841. // arcs have special flags that apparently don't require spaces so handle special
  2842. for (var args; (args = regArcArgumentSequence.exec(coordsStr));) {
  2843. for (var j = 1; j < args.length; j++) {
  2844. coords.push(args[j]);
  2845. }
  2846. }
  2847. }
  2848. else {
  2849. while ((match = re.exec(coordsStr))) {
  2850. coords.push(match[0]);
  2851. }
  2852. }
  2853. for (var j = 0, jlen = coords.length; j < jlen; j++) {
  2854. parsed = parseFloat(coords[j]);
  2855. if (!isNaN(parsed)) {
  2856. coordsParsed.push(parsed);
  2857. }
  2858. }
  2859. var commandLength = commandLengths[command.toLowerCase()],
  2860. repeatedCommand = repeatedCommands[command] || command;
  2861. if (coordsParsed.length - 1 > commandLength) {
  2862. for (var k = 1, klen = coordsParsed.length; k < klen; k += commandLength) {
  2863. result.push([command].concat(coordsParsed.slice(k, k + commandLength)));
  2864. command = repeatedCommand;
  2865. }
  2866. }
  2867. else {
  2868. result.push(coordsParsed);
  2869. }
  2870. }
  2871. return result;
  2872. };
  2873. /**
  2874. *
  2875. * Converts points to a smooth SVG path
  2876. * @param {{ x: number,y: number }[]} points Array of points
  2877. * @param {number} [correction] Apply a correction to the path (usually we use `width / 1000`). If value is undefined 0 is used as the correction value.
  2878. * @return {(string|number)[][]} An array of SVG path commands
  2879. */
  2880. function getSmoothPathFromPoints(points, correction) {
  2881. var path = [], i,
  2882. p1 = new fabric.Point(points[0].x, points[0].y),
  2883. p2 = new fabric.Point(points[1].x, points[1].y),
  2884. len = points.length, multSignX = 1, multSignY = 0, manyPoints = len > 2;
  2885. correction = correction || 0;
  2886. if (manyPoints) {
  2887. multSignX = points[2].x < p2.x ? -1 : points[2].x === p2.x ? 0 : 1;
  2888. multSignY = points[2].y < p2.y ? -1 : points[2].y === p2.y ? 0 : 1;
  2889. }
  2890. path.push(['M', p1.x - multSignX * correction, p1.y - multSignY * correction]);
  2891. for (i = 1; i < len; i++) {
  2892. if (!p1.eq(p2)) {
  2893. var midPoint = p1.midPointFrom(p2);
  2894. // p1 is our bezier control point
  2895. // midpoint is our endpoint
  2896. // start point is p(i-1) value.
  2897. path.push(['Q', p1.x, p1.y, midPoint.x, midPoint.y]);
  2898. }
  2899. p1 = points[i];
  2900. if ((i + 1) < points.length) {
  2901. p2 = points[i + 1];
  2902. }
  2903. }
  2904. if (manyPoints) {
  2905. multSignX = p1.x > points[i - 2].x ? 1 : p1.x === points[i - 2].x ? 0 : -1;
  2906. multSignY = p1.y > points[i - 2].y ? 1 : p1.y === points[i - 2].y ? 0 : -1;
  2907. }
  2908. path.push(['L', p1.x + multSignX * correction, p1.y + multSignY * correction]);
  2909. return path;
  2910. }
  2911. /**
  2912. * Transform a path by transforming each segment.
  2913. * it has to be a simplified path or it won't work.
  2914. * WARNING: this depends from pathOffset for correct operation
  2915. * @param {Array} path fabricJS parsed and simplified path commands
  2916. * @param {Array} transform matrix that represent the transformation
  2917. * @param {Object} [pathOffset] the fabric.Path pathOffset
  2918. * @param {Number} pathOffset.x
  2919. * @param {Number} pathOffset.y
  2920. * @returns {Array} the transformed path
  2921. */
  2922. function transformPath(path, transform, pathOffset) {
  2923. if (pathOffset) {
  2924. transform = fabric.util.multiplyTransformMatrices(
  2925. transform,
  2926. [1, 0, 0, 1, -pathOffset.x, -pathOffset.y]
  2927. );
  2928. }
  2929. return path.map(function(pathSegment) {
  2930. var newSegment = pathSegment.slice(0), point = {};
  2931. for (var i = 1; i < pathSegment.length - 1; i += 2) {
  2932. point.x = pathSegment[i];
  2933. point.y = pathSegment[i + 1];
  2934. point = fabric.util.transformPoint(point, transform);
  2935. newSegment[i] = point.x;
  2936. newSegment[i + 1] = point.y;
  2937. }
  2938. return newSegment;
  2939. });
  2940. }
  2941. /**
  2942. * Join path commands to go back to svg format
  2943. * @param {Array} pathData fabricJS parsed path commands
  2944. * @return {String} joined path 'M 0 0 L 20 30'
  2945. */
  2946. fabric.util.joinPath = function(pathData) {
  2947. return pathData.map(function (segment) { return segment.join(' '); }).join(' ');
  2948. };
  2949. fabric.util.parsePath = parsePath;
  2950. fabric.util.makePathSimpler = makePathSimpler;
  2951. fabric.util.getSmoothPathFromPoints = getSmoothPathFromPoints;
  2952. fabric.util.getPathSegmentsInfo = getPathSegmentsInfo;
  2953. fabric.util.getBoundsOfCurve = getBoundsOfCurve;
  2954. fabric.util.getPointOnPath = getPointOnPath;
  2955. fabric.util.transformPath = transformPath;
  2956. })();
  2957. (function() {
  2958. var slice = Array.prototype.slice;
  2959. /**
  2960. * Invokes method on all items in a given array
  2961. * @memberOf fabric.util.array
  2962. * @param {Array} array Array to iterate over
  2963. * @param {String} method Name of a method to invoke
  2964. * @return {Array}
  2965. */
  2966. function invoke(array, method) {
  2967. var args = slice.call(arguments, 2), result = [];
  2968. for (var i = 0, len = array.length; i < len; i++) {
  2969. result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
  2970. }
  2971. return result;
  2972. }
  2973. /**
  2974. * Finds maximum value in array (not necessarily "first" one)
  2975. * @memberOf fabric.util.array
  2976. * @param {Array} array Array to iterate over
  2977. * @param {String} byProperty
  2978. * @return {*}
  2979. */
  2980. function max(array, byProperty) {
  2981. return find(array, byProperty, function(value1, value2) {
  2982. return value1 >= value2;
  2983. });
  2984. }
  2985. /**
  2986. * Finds minimum value in array (not necessarily "first" one)
  2987. * @memberOf fabric.util.array
  2988. * @param {Array} array Array to iterate over
  2989. * @param {String} byProperty
  2990. * @return {*}
  2991. */
  2992. function min(array, byProperty) {
  2993. return find(array, byProperty, function(value1, value2) {
  2994. return value1 < value2;
  2995. });
  2996. }
  2997. /**
  2998. * @private
  2999. */
  3000. function fill(array, value) {
  3001. var k = array.length;
  3002. while (k--) {
  3003. array[k] = value;
  3004. }
  3005. return array;
  3006. }
  3007. /**
  3008. * @private
  3009. */
  3010. function find(array, byProperty, condition) {
  3011. if (!array || array.length === 0) {
  3012. return;
  3013. }
  3014. var i = array.length - 1,
  3015. result = byProperty ? array[i][byProperty] : array[i];
  3016. if (byProperty) {
  3017. while (i--) {
  3018. if (condition(array[i][byProperty], result)) {
  3019. result = array[i][byProperty];
  3020. }
  3021. }
  3022. }
  3023. else {
  3024. while (i--) {
  3025. if (condition(array[i], result)) {
  3026. result = array[i];
  3027. }
  3028. }
  3029. }
  3030. return result;
  3031. }
  3032. /**
  3033. * @namespace fabric.util.array
  3034. */
  3035. fabric.util.array = {
  3036. fill: fill,
  3037. invoke: invoke,
  3038. min: min,
  3039. max: max
  3040. };
  3041. })();
  3042. (function() {
  3043. /**
  3044. * Copies all enumerable properties of one js object to another
  3045. * this does not and cannot compete with generic utils.
  3046. * Does not clone or extend fabric.Object subclasses.
  3047. * This is mostly for internal use and has extra handling for fabricJS objects
  3048. * it skips the canvas and group properties in deep cloning.
  3049. * @memberOf fabric.util.object
  3050. * @param {Object} destination Where to copy to
  3051. * @param {Object} source Where to copy from
  3052. * @param {Boolean} [deep] Whether to extend nested objects
  3053. * @return {Object}
  3054. */
  3055. function extend(destination, source, deep) {
  3056. // JScript DontEnum bug is not taken care of
  3057. // the deep clone is for internal use, is not meant to avoid
  3058. // javascript traps or cloning html element or self referenced objects.
  3059. if (deep) {
  3060. if (!fabric.isLikelyNode && source instanceof Element) {
  3061. // avoid cloning deep images, canvases,
  3062. destination = source;
  3063. }
  3064. else if (source instanceof Array) {
  3065. destination = [];
  3066. for (var i = 0, len = source.length; i < len; i++) {
  3067. destination[i] = extend({ }, source[i], deep);
  3068. }
  3069. }
  3070. else if (source && typeof source === 'object') {
  3071. for (var property in source) {
  3072. if (property === 'canvas' || property === 'group') {
  3073. // we do not want to clone this props at all.
  3074. // we want to keep the keys in the copy
  3075. destination[property] = null;
  3076. }
  3077. else if (source.hasOwnProperty(property)) {
  3078. destination[property] = extend({ }, source[property], deep);
  3079. }
  3080. }
  3081. }
  3082. else {
  3083. // this sounds odd for an extend but is ok for recursive use
  3084. destination = source;
  3085. }
  3086. }
  3087. else {
  3088. for (var property in source) {
  3089. destination[property] = source[property];
  3090. }
  3091. }
  3092. return destination;
  3093. }
  3094. /**
  3095. * Creates an empty object and copies all enumerable properties of another object to it
  3096. * This method is mostly for internal use, and not intended for duplicating shapes in canvas.
  3097. * @memberOf fabric.util.object
  3098. * @param {Object} object Object to clone
  3099. * @param {Boolean} [deep] Whether to clone nested objects
  3100. * @return {Object}
  3101. */
  3102. //TODO: this function return an empty object if you try to clone null
  3103. function clone(object, deep) {
  3104. return extend({ }, object, deep);
  3105. }
  3106. /** @namespace fabric.util.object */
  3107. fabric.util.object = {
  3108. extend: extend,
  3109. clone: clone
  3110. };
  3111. fabric.util.object.extend(fabric.util, fabric.Observable);
  3112. })();
  3113. (function() {
  3114. /**
  3115. * Camelizes a string
  3116. * @memberOf fabric.util.string
  3117. * @param {String} string String to camelize
  3118. * @return {String} Camelized version of a string
  3119. */
  3120. function camelize(string) {
  3121. return string.replace(/-+(.)?/g, function(match, character) {
  3122. return character ? character.toUpperCase() : '';
  3123. });
  3124. }
  3125. /**
  3126. * Capitalizes a string
  3127. * @memberOf fabric.util.string
  3128. * @param {String} string String to capitalize
  3129. * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized
  3130. * and other letters stay untouched, if false first letter is capitalized
  3131. * and other letters are converted to lowercase.
  3132. * @return {String} Capitalized version of a string
  3133. */
  3134. function capitalize(string, firstLetterOnly) {
  3135. return string.charAt(0).toUpperCase() +
  3136. (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());
  3137. }
  3138. /**
  3139. * Escapes XML in a string
  3140. * @memberOf fabric.util.string
  3141. * @param {String} string String to escape
  3142. * @return {String} Escaped version of a string
  3143. */
  3144. function escapeXml(string) {
  3145. return string.replace(/&/g, '&amp;')
  3146. .replace(/"/g, '&quot;')
  3147. .replace(/'/g, '&apos;')
  3148. .replace(/</g, '&lt;')
  3149. .replace(/>/g, '&gt;');
  3150. }
  3151. /**
  3152. * Divide a string in the user perceived single units
  3153. * @memberOf fabric.util.string
  3154. * @param {String} textstring String to escape
  3155. * @return {Array} array containing the graphemes
  3156. */
  3157. function graphemeSplit(textstring) {
  3158. var i = 0, chr, graphemes = [];
  3159. for (i = 0, chr; i < textstring.length; i++) {
  3160. if ((chr = getWholeChar(textstring, i)) === false) {
  3161. continue;
  3162. }
  3163. graphemes.push(chr);
  3164. }
  3165. return graphemes;
  3166. }
  3167. // taken from mdn in the charAt doc page.
  3168. function getWholeChar(str, i) {
  3169. var code = str.charCodeAt(i);
  3170. if (isNaN(code)) {
  3171. return ''; // Position not found
  3172. }
  3173. if (code < 0xD800 || code > 0xDFFF) {
  3174. return str.charAt(i);
  3175. }
  3176. // High surrogate (could change last hex to 0xDB7F to treat high private
  3177. // surrogates as single characters)
  3178. if (0xD800 <= code && code <= 0xDBFF) {
  3179. if (str.length <= (i + 1)) {
  3180. throw 'High surrogate without following low surrogate';
  3181. }
  3182. var next = str.charCodeAt(i + 1);
  3183. if (0xDC00 > next || next > 0xDFFF) {
  3184. throw 'High surrogate without following low surrogate';
  3185. }
  3186. return str.charAt(i) + str.charAt(i + 1);
  3187. }
  3188. // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  3189. if (i === 0) {
  3190. throw 'Low surrogate without preceding high surrogate';
  3191. }
  3192. var prev = str.charCodeAt(i - 1);
  3193. // (could change last hex to 0xDB7F to treat high private
  3194. // surrogates as single characters)
  3195. if (0xD800 > prev || prev > 0xDBFF) {
  3196. throw 'Low surrogate without preceding high surrogate';
  3197. }
  3198. // We can pass over low surrogates now as the second component
  3199. // in a pair which we have already processed
  3200. return false;
  3201. }
  3202. /**
  3203. * String utilities
  3204. * @namespace fabric.util.string
  3205. */
  3206. fabric.util.string = {
  3207. camelize: camelize,
  3208. capitalize: capitalize,
  3209. escapeXml: escapeXml,
  3210. graphemeSplit: graphemeSplit
  3211. };
  3212. })();
  3213. (function() {
  3214. var slice = Array.prototype.slice, emptyFunction = function() { },
  3215. IS_DONTENUM_BUGGY = (function() {
  3216. for (var p in { toString: 1 }) {
  3217. if (p === 'toString') {
  3218. return false;
  3219. }
  3220. }
  3221. return true;
  3222. })(),
  3223. /** @ignore */
  3224. addMethods = function(klass, source, parent) {
  3225. for (var property in source) {
  3226. if (property in klass.prototype &&
  3227. typeof klass.prototype[property] === 'function' &&
  3228. (source[property] + '').indexOf('callSuper') > -1) {
  3229. klass.prototype[property] = (function(property) {
  3230. return function() {
  3231. var superclass = this.constructor.superclass;
  3232. this.constructor.superclass = parent;
  3233. var returnValue = source[property].apply(this, arguments);
  3234. this.constructor.superclass = superclass;
  3235. if (property !== 'initialize') {
  3236. return returnValue;
  3237. }
  3238. };
  3239. })(property);
  3240. }
  3241. else {
  3242. klass.prototype[property] = source[property];
  3243. }
  3244. if (IS_DONTENUM_BUGGY) {
  3245. if (source.toString !== Object.prototype.toString) {
  3246. klass.prototype.toString = source.toString;
  3247. }
  3248. if (source.valueOf !== Object.prototype.valueOf) {
  3249. klass.prototype.valueOf = source.valueOf;
  3250. }
  3251. }
  3252. }
  3253. };
  3254. function Subclass() { }
  3255. function callSuper(methodName) {
  3256. var parentMethod = null,
  3257. _this = this;
  3258. // climb prototype chain to find method not equal to callee's method
  3259. while (_this.constructor.superclass) {
  3260. var superClassMethod = _this.constructor.superclass.prototype[methodName];
  3261. if (_this[methodName] !== superClassMethod) {
  3262. parentMethod = superClassMethod;
  3263. break;
  3264. }
  3265. // eslint-disable-next-line
  3266. _this = _this.constructor.superclass.prototype;
  3267. }
  3268. if (!parentMethod) {
  3269. return console.log('tried to callSuper ' + methodName + ', method not found in prototype chain', this);
  3270. }
  3271. return (arguments.length > 1)
  3272. ? parentMethod.apply(this, slice.call(arguments, 1))
  3273. : parentMethod.call(this);
  3274. }
  3275. /**
  3276. * Helper for creation of "classes".
  3277. * @memberOf fabric.util
  3278. * @param {Function} [parent] optional "Class" to inherit from
  3279. * @param {Object} [properties] Properties shared by all instances of this class
  3280. * (be careful modifying objects defined here as this would affect all instances)
  3281. */
  3282. function createClass() {
  3283. var parent = null,
  3284. properties = slice.call(arguments, 0);
  3285. if (typeof properties[0] === 'function') {
  3286. parent = properties.shift();
  3287. }
  3288. function klass() {
  3289. this.initialize.apply(this, arguments);
  3290. }
  3291. klass.superclass = parent;
  3292. klass.subclasses = [];
  3293. if (parent) {
  3294. Subclass.prototype = parent.prototype;
  3295. klass.prototype = new Subclass();
  3296. parent.subclasses.push(klass);
  3297. }
  3298. for (var i = 0, length = properties.length; i < length; i++) {
  3299. addMethods(klass, properties[i], parent);
  3300. }
  3301. if (!klass.prototype.initialize) {
  3302. klass.prototype.initialize = emptyFunction;
  3303. }
  3304. klass.prototype.constructor = klass;
  3305. klass.prototype.callSuper = callSuper;
  3306. return klass;
  3307. }
  3308. fabric.util.createClass = createClass;
  3309. })();
  3310. (function () {
  3311. // since ie11 can use addEventListener but they do not support options, i need to check
  3312. var couldUseAttachEvent = !!fabric.document.createElement('div').attachEvent,
  3313. touchEvents = ['touchstart', 'touchmove', 'touchend'];
  3314. /**
  3315. * Adds an event listener to an element
  3316. * @function
  3317. * @memberOf fabric.util
  3318. * @param {HTMLElement} element
  3319. * @param {String} eventName
  3320. * @param {Function} handler
  3321. */
  3322. fabric.util.addListener = function(element, eventName, handler, options) {
  3323. element && element.addEventListener(eventName, handler, couldUseAttachEvent ? false : options);
  3324. };
  3325. /**
  3326. * Removes an event listener from an element
  3327. * @function
  3328. * @memberOf fabric.util
  3329. * @param {HTMLElement} element
  3330. * @param {String} eventName
  3331. * @param {Function} handler
  3332. */
  3333. fabric.util.removeListener = function(element, eventName, handler, options) {
  3334. element && element.removeEventListener(eventName, handler, couldUseAttachEvent ? false : options);
  3335. };
  3336. function getTouchInfo(event) {
  3337. var touchProp = event.changedTouches;
  3338. if (touchProp && touchProp[0]) {
  3339. return touchProp[0];
  3340. }
  3341. return event;
  3342. }
  3343. fabric.util.getPointer = function(event) {
  3344. var element = event.target,
  3345. scroll = fabric.util.getScrollLeftTop(element),
  3346. _evt = getTouchInfo(event);
  3347. return {
  3348. x: _evt.clientX + scroll.left,
  3349. y: _evt.clientY + scroll.top
  3350. };
  3351. };
  3352. fabric.util.isTouchEvent = function(event) {
  3353. return touchEvents.indexOf(event.type) > -1 || event.pointerType === 'touch';
  3354. };
  3355. })();
  3356. (function () {
  3357. /**
  3358. * Cross-browser wrapper for setting element's style
  3359. * @memberOf fabric.util
  3360. * @param {HTMLElement} element
  3361. * @param {Object} styles
  3362. * @return {HTMLElement} Element that was passed as a first argument
  3363. */
  3364. function setStyle(element, styles) {
  3365. var elementStyle = element.style;
  3366. if (!elementStyle) {
  3367. return element;
  3368. }
  3369. if (typeof styles === 'string') {
  3370. element.style.cssText += ';' + styles;
  3371. return styles.indexOf('opacity') > -1
  3372. ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1])
  3373. : element;
  3374. }
  3375. for (var property in styles) {
  3376. if (property === 'opacity') {
  3377. setOpacity(element, styles[property]);
  3378. }
  3379. else {
  3380. var normalizedProperty = (property === 'float' || property === 'cssFloat')
  3381. ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')
  3382. : property;
  3383. elementStyle.setProperty(normalizedProperty, styles[property]);
  3384. }
  3385. }
  3386. return element;
  3387. }
  3388. var parseEl = fabric.document.createElement('div'),
  3389. supportsOpacity = typeof parseEl.style.opacity === 'string',
  3390. supportsFilters = typeof parseEl.style.filter === 'string',
  3391. reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
  3392. /** @ignore */
  3393. setOpacity = function (element) { return element; };
  3394. if (supportsOpacity) {
  3395. /** @ignore */
  3396. setOpacity = function(element, value) {
  3397. element.style.opacity = value;
  3398. return element;
  3399. };
  3400. }
  3401. else if (supportsFilters) {
  3402. /** @ignore */
  3403. setOpacity = function(element, value) {
  3404. var es = element.style;
  3405. if (element.currentStyle && !element.currentStyle.hasLayout) {
  3406. es.zoom = 1;
  3407. }
  3408. if (reOpacity.test(es.filter)) {
  3409. value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
  3410. es.filter = es.filter.replace(reOpacity, value);
  3411. }
  3412. else {
  3413. es.filter += ' alpha(opacity=' + (value * 100) + ')';
  3414. }
  3415. return element;
  3416. };
  3417. }
  3418. fabric.util.setStyle = setStyle;
  3419. })();
  3420. (function() {
  3421. var _slice = Array.prototype.slice;
  3422. /**
  3423. * Takes id and returns an element with that id (if one exists in a document)
  3424. * @memberOf fabric.util
  3425. * @param {String|HTMLElement} id
  3426. * @return {HTMLElement|null}
  3427. */
  3428. function getById(id) {
  3429. return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  3430. }
  3431. var sliceCanConvertNodelists,
  3432. /**
  3433. * Converts an array-like object (e.g. arguments or NodeList) to an array
  3434. * @memberOf fabric.util
  3435. * @param {Object} arrayLike
  3436. * @return {Array}
  3437. */
  3438. toArray = function(arrayLike) {
  3439. return _slice.call(arrayLike, 0);
  3440. };
  3441. try {
  3442. sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  3443. }
  3444. catch (err) { }
  3445. if (!sliceCanConvertNodelists) {
  3446. toArray = function(arrayLike) {
  3447. var arr = new Array(arrayLike.length), i = arrayLike.length;
  3448. while (i--) {
  3449. arr[i] = arrayLike[i];
  3450. }
  3451. return arr;
  3452. };
  3453. }
  3454. /**
  3455. * Creates specified element with specified attributes
  3456. * @memberOf fabric.util
  3457. * @param {String} tagName Type of an element to create
  3458. * @param {Object} [attributes] Attributes to set on an element
  3459. * @return {HTMLElement} Newly created element
  3460. */
  3461. function makeElement(tagName, attributes) {
  3462. var el = fabric.document.createElement(tagName);
  3463. for (var prop in attributes) {
  3464. if (prop === 'class') {
  3465. el.className = attributes[prop];
  3466. }
  3467. else if (prop === 'for') {
  3468. el.htmlFor = attributes[prop];
  3469. }
  3470. else {
  3471. el.setAttribute(prop, attributes[prop]);
  3472. }
  3473. }
  3474. return el;
  3475. }
  3476. /**
  3477. * Adds class to an element
  3478. * @memberOf fabric.util
  3479. * @param {HTMLElement} element Element to add class to
  3480. * @param {String} className Class to add to an element
  3481. */
  3482. function addClass(element, className) {
  3483. if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
  3484. element.className += (element.className ? ' ' : '') + className;
  3485. }
  3486. }
  3487. /**
  3488. * Wraps element with another element
  3489. * @memberOf fabric.util
  3490. * @param {HTMLElement} element Element to wrap
  3491. * @param {HTMLElement|String} wrapper Element to wrap with
  3492. * @param {Object} [attributes] Attributes to set on a wrapper
  3493. * @return {HTMLElement} wrapper
  3494. */
  3495. function wrapElement(element, wrapper, attributes) {
  3496. if (typeof wrapper === 'string') {
  3497. wrapper = makeElement(wrapper, attributes);
  3498. }
  3499. if (element.parentNode) {
  3500. element.parentNode.replaceChild(wrapper, element);
  3501. }
  3502. wrapper.appendChild(element);
  3503. return wrapper;
  3504. }
  3505. /**
  3506. * Returns element scroll offsets
  3507. * @memberOf fabric.util
  3508. * @param {HTMLElement} element Element to operate on
  3509. * @return {Object} Object with left/top values
  3510. */
  3511. function getScrollLeftTop(element) {
  3512. var left = 0,
  3513. top = 0,
  3514. docElement = fabric.document.documentElement,
  3515. body = fabric.document.body || {
  3516. scrollLeft: 0, scrollTop: 0
  3517. };
  3518. // While loop checks (and then sets element to) .parentNode OR .host
  3519. // to account for ShadowDOM. We still want to traverse up out of ShadowDOM,
  3520. // but the .parentNode of a root ShadowDOM node will always be null, instead
  3521. // it should be accessed through .host. See http://stackoverflow.com/a/24765528/4383938
  3522. while (element && (element.parentNode || element.host)) {
  3523. // Set element to element parent, or 'host' in case of ShadowDOM
  3524. element = element.parentNode || element.host;
  3525. if (element === fabric.document) {
  3526. left = body.scrollLeft || docElement.scrollLeft || 0;
  3527. top = body.scrollTop || docElement.scrollTop || 0;
  3528. }
  3529. else {
  3530. left += element.scrollLeft || 0;
  3531. top += element.scrollTop || 0;
  3532. }
  3533. if (element.nodeType === 1 && element.style.position === 'fixed') {
  3534. break;
  3535. }
  3536. }
  3537. return { left: left, top: top };
  3538. }
  3539. /**
  3540. * Returns offset for a given element
  3541. * @function
  3542. * @memberOf fabric.util
  3543. * @param {HTMLElement} element Element to get offset for
  3544. * @return {Object} Object with "left" and "top" properties
  3545. */
  3546. function getElementOffset(element) {
  3547. var docElem,
  3548. doc = element && element.ownerDocument,
  3549. box = { left: 0, top: 0 },
  3550. offset = { left: 0, top: 0 },
  3551. scrollLeftTop,
  3552. offsetAttributes = {
  3553. borderLeftWidth: 'left',
  3554. borderTopWidth: 'top',
  3555. paddingLeft: 'left',
  3556. paddingTop: 'top'
  3557. };
  3558. if (!doc) {
  3559. return offset;
  3560. }
  3561. for (var attr in offsetAttributes) {
  3562. offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
  3563. }
  3564. docElem = doc.documentElement;
  3565. if ( typeof element.getBoundingClientRect !== 'undefined' ) {
  3566. box = element.getBoundingClientRect();
  3567. }
  3568. scrollLeftTop = getScrollLeftTop(element);
  3569. return {
  3570. left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
  3571. top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top
  3572. };
  3573. }
  3574. /**
  3575. * Returns style attribute value of a given element
  3576. * @memberOf fabric.util
  3577. * @param {HTMLElement} element Element to get style attribute for
  3578. * @param {String} attr Style attribute to get for element
  3579. * @return {String} Style attribute value of the given element.
  3580. */
  3581. var getElementStyle;
  3582. if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
  3583. getElementStyle = function(element, attr) {
  3584. var style = fabric.document.defaultView.getComputedStyle(element, null);
  3585. return style ? style[attr] : undefined;
  3586. };
  3587. }
  3588. else {
  3589. getElementStyle = function(element, attr) {
  3590. var value = element.style[attr];
  3591. if (!value && element.currentStyle) {
  3592. value = element.currentStyle[attr];
  3593. }
  3594. return value;
  3595. };
  3596. }
  3597. (function () {
  3598. var style = fabric.document.documentElement.style,
  3599. selectProp = 'userSelect' in style
  3600. ? 'userSelect'
  3601. : 'MozUserSelect' in style
  3602. ? 'MozUserSelect'
  3603. : 'WebkitUserSelect' in style
  3604. ? 'WebkitUserSelect'
  3605. : 'KhtmlUserSelect' in style
  3606. ? 'KhtmlUserSelect'
  3607. : '';
  3608. /**
  3609. * Makes element unselectable
  3610. * @memberOf fabric.util
  3611. * @param {HTMLElement} element Element to make unselectable
  3612. * @return {HTMLElement} Element that was passed in
  3613. */
  3614. function makeElementUnselectable(element) {
  3615. if (typeof element.onselectstart !== 'undefined') {
  3616. element.onselectstart = fabric.util.falseFunction;
  3617. }
  3618. if (selectProp) {
  3619. element.style[selectProp] = 'none';
  3620. }
  3621. else if (typeof element.unselectable === 'string') {
  3622. element.unselectable = 'on';
  3623. }
  3624. return element;
  3625. }
  3626. /**
  3627. * Makes element selectable
  3628. * @memberOf fabric.util
  3629. * @param {HTMLElement} element Element to make selectable
  3630. * @return {HTMLElement} Element that was passed in
  3631. */
  3632. function makeElementSelectable(element) {
  3633. if (typeof element.onselectstart !== 'undefined') {
  3634. element.onselectstart = null;
  3635. }
  3636. if (selectProp) {
  3637. element.style[selectProp] = '';
  3638. }
  3639. else if (typeof element.unselectable === 'string') {
  3640. element.unselectable = '';
  3641. }
  3642. return element;
  3643. }
  3644. fabric.util.makeElementUnselectable = makeElementUnselectable;
  3645. fabric.util.makeElementSelectable = makeElementSelectable;
  3646. })();
  3647. function getNodeCanvas(element) {
  3648. var impl = fabric.jsdomImplForWrapper(element);
  3649. return impl._canvas || impl._image;
  3650. };
  3651. function cleanUpJsdomNode(element) {
  3652. if (!fabric.isLikelyNode) {
  3653. return;
  3654. }
  3655. var impl = fabric.jsdomImplForWrapper(element);
  3656. if (impl) {
  3657. impl._image = null;
  3658. impl._canvas = null;
  3659. // unsure if necessary
  3660. impl._currentSrc = null;
  3661. impl._attributes = null;
  3662. impl._classList = null;
  3663. }
  3664. }
  3665. function setImageSmoothing(ctx, value) {
  3666. ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled || ctx.webkitImageSmoothingEnabled
  3667. || ctx.mozImageSmoothingEnabled || ctx.msImageSmoothingEnabled || ctx.oImageSmoothingEnabled;
  3668. ctx.imageSmoothingEnabled = value;
  3669. }
  3670. /**
  3671. * setImageSmoothing sets the context imageSmoothingEnabled property.
  3672. * Used by canvas and by ImageObject.
  3673. * @memberOf fabric.util
  3674. * @since 4.0.0
  3675. * @param {HTMLRenderingContext2D} ctx to set on
  3676. * @param {Boolean} value true or false
  3677. */
  3678. fabric.util.setImageSmoothing = setImageSmoothing;
  3679. fabric.util.getById = getById;
  3680. fabric.util.toArray = toArray;
  3681. fabric.util.addClass = addClass;
  3682. fabric.util.makeElement = makeElement;
  3683. fabric.util.wrapElement = wrapElement;
  3684. fabric.util.getScrollLeftTop = getScrollLeftTop;
  3685. fabric.util.getElementOffset = getElementOffset;
  3686. fabric.util.getNodeCanvas = getNodeCanvas;
  3687. fabric.util.cleanUpJsdomNode = cleanUpJsdomNode;
  3688. })();
  3689. (function() {
  3690. function addParamToUrl(url, param) {
  3691. return url + (/\?/.test(url) ? '&' : '?') + param;
  3692. }
  3693. function emptyFn() { }
  3694. /**
  3695. * Cross-browser abstraction for sending XMLHttpRequest
  3696. * @memberOf fabric.util
  3697. * @param {String} url URL to send XMLHttpRequest to
  3698. * @param {Object} [options] Options object
  3699. * @param {String} [options.method="GET"]
  3700. * @param {String} [options.parameters] parameters to append to url in GET or in body
  3701. * @param {String} [options.body] body to send with POST or PUT request
  3702. * @param {Function} options.onComplete Callback to invoke when request is completed
  3703. * @return {XMLHttpRequest} request
  3704. */
  3705. function request(url, options) {
  3706. options || (options = { });
  3707. var method = options.method ? options.method.toUpperCase() : 'GET',
  3708. onComplete = options.onComplete || function() { },
  3709. xhr = new fabric.window.XMLHttpRequest(),
  3710. body = options.body || options.parameters;
  3711. /** @ignore */
  3712. xhr.onreadystatechange = function() {
  3713. if (xhr.readyState === 4) {
  3714. onComplete(xhr);
  3715. xhr.onreadystatechange = emptyFn;
  3716. }
  3717. };
  3718. if (method === 'GET') {
  3719. body = null;
  3720. if (typeof options.parameters === 'string') {
  3721. url = addParamToUrl(url, options.parameters);
  3722. }
  3723. }
  3724. xhr.open(method, url, true);
  3725. if (method === 'POST' || method === 'PUT') {
  3726. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  3727. }
  3728. xhr.send(body);
  3729. return xhr;
  3730. }
  3731. fabric.util.request = request;
  3732. })();
  3733. /**
  3734. * Wrapper around `console.log` (when available)
  3735. * @param {*} [values] Values to log
  3736. */
  3737. fabric.log = console.log;
  3738. /**
  3739. * Wrapper around `console.warn` (when available)
  3740. * @param {*} [values] Values to log as a warning
  3741. */
  3742. fabric.warn = console.warn;
  3743. (function () {
  3744. var extend = fabric.util.object.extend,
  3745. clone = fabric.util.object.clone;
  3746. /**
  3747. * @typedef {Object} AnimationOptions
  3748. * Animation of a value or list of values.
  3749. * When using lists, think of something like this:
  3750. * fabric.util.animate({
  3751. * startValue: [1, 2, 3],
  3752. * endValue: [2, 4, 6],
  3753. * onChange: function([a, b, c]) {
  3754. * canvas.zoomToPoint({x: b, y: c}, a)
  3755. * canvas.renderAll()
  3756. * }
  3757. * });
  3758. * @example
  3759. * @property {Function} [onChange] Callback; invoked on every value change
  3760. * @property {Function} [onComplete] Callback; invoked when value change is completed
  3761. * @example
  3762. * // Note: startValue, endValue, and byValue must match the type
  3763. * var animationOptions = { startValue: 0, endValue: 1, byValue: 0.25 }
  3764. * var animationOptions = { startValue: [0, 1], endValue: [1, 2], byValue: [0.25, 0.25] }
  3765. * @property {number | number[]} [startValue=0] Starting value
  3766. * @property {number | number[]} [endValue=100] Ending value
  3767. * @property {number | number[]} [byValue=100] Value to modify the property by
  3768. * @property {Function} [easing] Easing function
  3769. * @property {Number} [duration=500] Duration of change (in ms)
  3770. * @property {Function} [abort] Additional function with logic. If returns true, animation aborts.
  3771. *
  3772. * @typedef {() => void} CancelFunction
  3773. *
  3774. * @typedef {Object} AnimationCurrentState
  3775. * @property {number | number[]} currentValue value in range [`startValue`, `endValue`]
  3776. * @property {number} completionRate value in range [0, 1]
  3777. * @property {number} durationRate value in range [0, 1]
  3778. *
  3779. * @typedef {(AnimationOptions & AnimationCurrentState & { cancel: CancelFunction }} AnimationContext
  3780. */
  3781. /**
  3782. * Array holding all running animations
  3783. * @memberof fabric
  3784. * @type {AnimationContext[]}
  3785. */
  3786. var RUNNING_ANIMATIONS = [];
  3787. fabric.util.object.extend(RUNNING_ANIMATIONS, {
  3788. /**
  3789. * cancel all running animations at the next requestAnimFrame
  3790. * @returns {AnimationContext[]}
  3791. */
  3792. cancelAll: function () {
  3793. var animations = this.splice(0);
  3794. animations.forEach(function (animation) {
  3795. animation.cancel();
  3796. });
  3797. return animations;
  3798. },
  3799. /**
  3800. * cancel all running animations attached to canvas at the next requestAnimFrame
  3801. * @param {fabric.Canvas} canvas
  3802. * @returns {AnimationContext[]}
  3803. */
  3804. cancelByCanvas: function (canvas) {
  3805. if (!canvas) {
  3806. return [];
  3807. }
  3808. var cancelled = this.filter(function (animation) {
  3809. return typeof animation.target === 'object' && animation.target.canvas === canvas;
  3810. });
  3811. cancelled.forEach(function (animation) {
  3812. animation.cancel();
  3813. });
  3814. return cancelled;
  3815. },
  3816. /**
  3817. * cancel all running animations for target at the next requestAnimFrame
  3818. * @param {*} target
  3819. * @returns {AnimationContext[]}
  3820. */
  3821. cancelByTarget: function (target) {
  3822. var cancelled = this.findAnimationsByTarget(target);
  3823. cancelled.forEach(function (animation) {
  3824. animation.cancel();
  3825. });
  3826. return cancelled;
  3827. },
  3828. /**
  3829. *
  3830. * @param {CancelFunction} cancelFunc the function returned by animate
  3831. * @returns {number}
  3832. */
  3833. findAnimationIndex: function (cancelFunc) {
  3834. return this.indexOf(this.findAnimation(cancelFunc));
  3835. },
  3836. /**
  3837. *
  3838. * @param {CancelFunction} cancelFunc the function returned by animate
  3839. * @returns {AnimationContext | undefined} animation's options object
  3840. */
  3841. findAnimation: function (cancelFunc) {
  3842. return this.find(function (animation) {
  3843. return animation.cancel === cancelFunc;
  3844. });
  3845. },
  3846. /**
  3847. *
  3848. * @param {*} target the object that is assigned to the target property of the animation context
  3849. * @returns {AnimationContext[]} array of animation options object associated with target
  3850. */
  3851. findAnimationsByTarget: function (target) {
  3852. if (!target) {
  3853. return [];
  3854. }
  3855. return this.filter(function (animation) {
  3856. return animation.target === target;
  3857. });
  3858. }
  3859. });
  3860. function noop() {
  3861. return false;
  3862. }
  3863. function defaultEasing(t, b, c, d) {
  3864. return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
  3865. }
  3866. /**
  3867. * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
  3868. * @memberOf fabric.util
  3869. * @param {AnimationOptions} [options] Animation options
  3870. * @example
  3871. * // Note: startValue, endValue, and byValue must match the type
  3872. * fabric.util.animate({ startValue: 0, endValue: 1, byValue: 0.25 })
  3873. * fabric.util.animate({ startValue: [0, 1], endValue: [1, 2], byValue: [0.25, 0.25] })
  3874. * @returns {CancelFunction} cancel function
  3875. */
  3876. function animate(options) {
  3877. options || (options = {});
  3878. var cancel = false,
  3879. context,
  3880. removeFromRegistry = function () {
  3881. var index = fabric.runningAnimations.indexOf(context);
  3882. return index > -1 && fabric.runningAnimations.splice(index, 1)[0];
  3883. };
  3884. context = extend(clone(options), {
  3885. cancel: function () {
  3886. cancel = true;
  3887. return removeFromRegistry();
  3888. },
  3889. currentValue: 'startValue' in options ? options.startValue : 0,
  3890. completionRate: 0,
  3891. durationRate: 0
  3892. });
  3893. fabric.runningAnimations.push(context);
  3894. requestAnimFrame(function(timestamp) {
  3895. var start = timestamp || +new Date(),
  3896. duration = options.duration || 500,
  3897. finish = start + duration, time,
  3898. onChange = options.onChange || noop,
  3899. abort = options.abort || noop,
  3900. onComplete = options.onComplete || noop,
  3901. easing = options.easing || defaultEasing,
  3902. isMany = 'startValue' in options ? options.startValue.length > 0 : false,
  3903. startValue = 'startValue' in options ? options.startValue : 0,
  3904. endValue = 'endValue' in options ? options.endValue : 100,
  3905. byValue = options.byValue || (isMany ? startValue.map(function(value, i) {
  3906. return endValue[i] - startValue[i];
  3907. }) : endValue - startValue);
  3908. options.onStart && options.onStart();
  3909. (function tick(ticktime) {
  3910. time = ticktime || +new Date();
  3911. var currentTime = time > finish ? duration : (time - start),
  3912. timePerc = currentTime / duration,
  3913. current = isMany ? startValue.map(function(_value, i) {
  3914. return easing(currentTime, startValue[i], byValue[i], duration);
  3915. }) : easing(currentTime, startValue, byValue, duration),
  3916. valuePerc = isMany ? Math.abs((current[0] - startValue[0]) / byValue[0])
  3917. : Math.abs((current - startValue) / byValue);
  3918. // update context
  3919. context.currentValue = isMany ? current.slice() : current;
  3920. context.completionRate = valuePerc;
  3921. context.durationRate = timePerc;
  3922. if (cancel) {
  3923. return;
  3924. }
  3925. if (abort(current, valuePerc, timePerc)) {
  3926. removeFromRegistry();
  3927. return;
  3928. }
  3929. if (time > finish) {
  3930. // update context
  3931. context.currentValue = isMany ? endValue.slice() : endValue;
  3932. context.completionRate = 1;
  3933. context.durationRate = 1;
  3934. // execute callbacks
  3935. onChange(isMany ? endValue.slice() : endValue, 1, 1);
  3936. onComplete(endValue, 1, 1);
  3937. removeFromRegistry();
  3938. return;
  3939. }
  3940. else {
  3941. onChange(current, valuePerc, timePerc);
  3942. requestAnimFrame(tick);
  3943. }
  3944. })(start);
  3945. });
  3946. return context.cancel;
  3947. }
  3948. var _requestAnimFrame = fabric.window.requestAnimationFrame ||
  3949. fabric.window.webkitRequestAnimationFrame ||
  3950. fabric.window.mozRequestAnimationFrame ||
  3951. fabric.window.oRequestAnimationFrame ||
  3952. fabric.window.msRequestAnimationFrame ||
  3953. function(callback) {
  3954. return fabric.window.setTimeout(callback, 1000 / 60);
  3955. };
  3956. var _cancelAnimFrame = fabric.window.cancelAnimationFrame || fabric.window.clearTimeout;
  3957. /**
  3958. * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  3959. * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method
  3960. * @memberOf fabric.util
  3961. * @param {Function} callback Callback to invoke
  3962. * @param {DOMElement} element optional Element to associate with animation
  3963. */
  3964. function requestAnimFrame() {
  3965. return _requestAnimFrame.apply(fabric.window, arguments);
  3966. }
  3967. function cancelAnimFrame() {
  3968. return _cancelAnimFrame.apply(fabric.window, arguments);
  3969. }
  3970. fabric.util.animate = animate;
  3971. fabric.util.requestAnimFrame = requestAnimFrame;
  3972. fabric.util.cancelAnimFrame = cancelAnimFrame;
  3973. fabric.runningAnimations = RUNNING_ANIMATIONS;
  3974. })();
  3975. (function() {
  3976. // Calculate an in-between color. Returns a "rgba()" string.
  3977. // Credit: Edwin Martin <edwin@bitstorm.org>
  3978. // http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors.js
  3979. function calculateColor(begin, end, pos) {
  3980. var color = 'rgba('
  3981. + parseInt((begin[0] + pos * (end[0] - begin[0])), 10) + ','
  3982. + parseInt((begin[1] + pos * (end[1] - begin[1])), 10) + ','
  3983. + parseInt((begin[2] + pos * (end[2] - begin[2])), 10);
  3984. color += ',' + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);
  3985. color += ')';
  3986. return color;
  3987. }
  3988. /**
  3989. * Changes the color from one to another within certain period of time, invoking callbacks as value is being changed.
  3990. * @memberOf fabric.util
  3991. * @param {String} fromColor The starting color in hex or rgb(a) format.
  3992. * @param {String} toColor The starting color in hex or rgb(a) format.
  3993. * @param {Number} [duration] Duration of change (in ms).
  3994. * @param {Object} [options] Animation options
  3995. * @param {Function} [options.onChange] Callback; invoked on every value change
  3996. * @param {Function} [options.onComplete] Callback; invoked when value change is completed
  3997. * @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.
  3998. * @param {Function} [options.abort] Additional function with logic. If returns true, onComplete is called.
  3999. * @returns {Function} abort function
  4000. */
  4001. function animateColor(fromColor, toColor, duration, options) {
  4002. var startColor = new fabric.Color(fromColor).getSource(),
  4003. endColor = new fabric.Color(toColor).getSource(),
  4004. originalOnComplete = options.onComplete,
  4005. originalOnChange = options.onChange;
  4006. options = options || {};
  4007. return fabric.util.animate(fabric.util.object.extend(options, {
  4008. duration: duration || 500,
  4009. startValue: startColor,
  4010. endValue: endColor,
  4011. byValue: endColor,
  4012. easing: function (currentTime, startValue, byValue, duration) {
  4013. var posValue = options.colorEasing
  4014. ? options.colorEasing(currentTime, duration)
  4015. : 1 - Math.cos(currentTime / duration * (Math.PI / 2));
  4016. return calculateColor(startValue, byValue, posValue);
  4017. },
  4018. // has to take in account for color restoring;
  4019. onComplete: function(current, valuePerc, timePerc) {
  4020. if (originalOnComplete) {
  4021. return originalOnComplete(
  4022. calculateColor(endColor, endColor, 0),
  4023. valuePerc,
  4024. timePerc
  4025. );
  4026. }
  4027. },
  4028. onChange: function(current, valuePerc, timePerc) {
  4029. if (originalOnChange) {
  4030. if (Array.isArray(current)) {
  4031. return originalOnChange(
  4032. calculateColor(current, current, 0),
  4033. valuePerc,
  4034. timePerc
  4035. );
  4036. }
  4037. originalOnChange(current, valuePerc, timePerc);
  4038. }
  4039. }
  4040. }));
  4041. }
  4042. fabric.util.animateColor = animateColor;
  4043. })();
  4044. (function() {
  4045. function normalize(a, c, p, s) {
  4046. if (a < Math.abs(c)) {
  4047. a = c;
  4048. s = p / 4;
  4049. }
  4050. else {
  4051. //handle the 0/0 case:
  4052. if (c === 0 && a === 0) {
  4053. s = p / (2 * Math.PI) * Math.asin(1);
  4054. }
  4055. else {
  4056. s = p / (2 * Math.PI) * Math.asin(c / a);
  4057. }
  4058. }
  4059. return { a: a, c: c, p: p, s: s };
  4060. }
  4061. function elastic(opts, t, d) {
  4062. return opts.a *
  4063. Math.pow(2, 10 * (t -= 1)) *
  4064. Math.sin( (t * d - opts.s) * (2 * Math.PI) / opts.p );
  4065. }
  4066. /**
  4067. * Cubic easing out
  4068. * @memberOf fabric.util.ease
  4069. */
  4070. function easeOutCubic(t, b, c, d) {
  4071. return c * ((t = t / d - 1) * t * t + 1) + b;
  4072. }
  4073. /**
  4074. * Cubic easing in and out
  4075. * @memberOf fabric.util.ease
  4076. */
  4077. function easeInOutCubic(t, b, c, d) {
  4078. t /= d / 2;
  4079. if (t < 1) {
  4080. return c / 2 * t * t * t + b;
  4081. }
  4082. return c / 2 * ((t -= 2) * t * t + 2) + b;
  4083. }
  4084. /**
  4085. * Quartic easing in
  4086. * @memberOf fabric.util.ease
  4087. */
  4088. function easeInQuart(t, b, c, d) {
  4089. return c * (t /= d) * t * t * t + b;
  4090. }
  4091. /**
  4092. * Quartic easing out
  4093. * @memberOf fabric.util.ease
  4094. */
  4095. function easeOutQuart(t, b, c, d) {
  4096. return -c * ((t = t / d - 1) * t * t * t - 1) + b;
  4097. }
  4098. /**
  4099. * Quartic easing in and out
  4100. * @memberOf fabric.util.ease
  4101. */
  4102. function easeInOutQuart(t, b, c, d) {
  4103. t /= d / 2;
  4104. if (t < 1) {
  4105. return c / 2 * t * t * t * t + b;
  4106. }
  4107. return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
  4108. }
  4109. /**
  4110. * Quintic easing in
  4111. * @memberOf fabric.util.ease
  4112. */
  4113. function easeInQuint(t, b, c, d) {
  4114. return c * (t /= d) * t * t * t * t + b;
  4115. }
  4116. /**
  4117. * Quintic easing out
  4118. * @memberOf fabric.util.ease
  4119. */
  4120. function easeOutQuint(t, b, c, d) {
  4121. return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  4122. }
  4123. /**
  4124. * Quintic easing in and out
  4125. * @memberOf fabric.util.ease
  4126. */
  4127. function easeInOutQuint(t, b, c, d) {
  4128. t /= d / 2;
  4129. if (t < 1) {
  4130. return c / 2 * t * t * t * t * t + b;
  4131. }
  4132. return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
  4133. }
  4134. /**
  4135. * Sinusoidal easing in
  4136. * @memberOf fabric.util.ease
  4137. */
  4138. function easeInSine(t, b, c, d) {
  4139. return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
  4140. }
  4141. /**
  4142. * Sinusoidal easing out
  4143. * @memberOf fabric.util.ease
  4144. */
  4145. function easeOutSine(t, b, c, d) {
  4146. return c * Math.sin(t / d * (Math.PI / 2)) + b;
  4147. }
  4148. /**
  4149. * Sinusoidal easing in and out
  4150. * @memberOf fabric.util.ease
  4151. */
  4152. function easeInOutSine(t, b, c, d) {
  4153. return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
  4154. }
  4155. /**
  4156. * Exponential easing in
  4157. * @memberOf fabric.util.ease
  4158. */
  4159. function easeInExpo(t, b, c, d) {
  4160. return (t === 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
  4161. }
  4162. /**
  4163. * Exponential easing out
  4164. * @memberOf fabric.util.ease
  4165. */
  4166. function easeOutExpo(t, b, c, d) {
  4167. return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
  4168. }
  4169. /**
  4170. * Exponential easing in and out
  4171. * @memberOf fabric.util.ease
  4172. */
  4173. function easeInOutExpo(t, b, c, d) {
  4174. if (t === 0) {
  4175. return b;
  4176. }
  4177. if (t === d) {
  4178. return b + c;
  4179. }
  4180. t /= d / 2;
  4181. if (t < 1) {
  4182. return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
  4183. }
  4184. return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
  4185. }
  4186. /**
  4187. * Circular easing in
  4188. * @memberOf fabric.util.ease
  4189. */
  4190. function easeInCirc(t, b, c, d) {
  4191. return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
  4192. }
  4193. /**
  4194. * Circular easing out
  4195. * @memberOf fabric.util.ease
  4196. */
  4197. function easeOutCirc(t, b, c, d) {
  4198. return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
  4199. }
  4200. /**
  4201. * Circular easing in and out
  4202. * @memberOf fabric.util.ease
  4203. */
  4204. function easeInOutCirc(t, b, c, d) {
  4205. t /= d / 2;
  4206. if (t < 1) {
  4207. return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
  4208. }
  4209. return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
  4210. }
  4211. /**
  4212. * Elastic easing in
  4213. * @memberOf fabric.util.ease
  4214. */
  4215. function easeInElastic(t, b, c, d) {
  4216. var s = 1.70158, p = 0, a = c;
  4217. if (t === 0) {
  4218. return b;
  4219. }
  4220. t /= d;
  4221. if (t === 1) {
  4222. return b + c;
  4223. }
  4224. if (!p) {
  4225. p = d * 0.3;
  4226. }
  4227. var opts = normalize(a, c, p, s);
  4228. return -elastic(opts, t, d) + b;
  4229. }
  4230. /**
  4231. * Elastic easing out
  4232. * @memberOf fabric.util.ease
  4233. */
  4234. function easeOutElastic(t, b, c, d) {
  4235. var s = 1.70158, p = 0, a = c;
  4236. if (t === 0) {
  4237. return b;
  4238. }
  4239. t /= d;
  4240. if (t === 1) {
  4241. return b + c;
  4242. }
  4243. if (!p) {
  4244. p = d * 0.3;
  4245. }
  4246. var opts = normalize(a, c, p, s);
  4247. return opts.a * Math.pow(2, -10 * t) * Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) + opts.c + b;
  4248. }
  4249. /**
  4250. * Elastic easing in and out
  4251. * @memberOf fabric.util.ease
  4252. */
  4253. function easeInOutElastic(t, b, c, d) {
  4254. var s = 1.70158, p = 0, a = c;
  4255. if (t === 0) {
  4256. return b;
  4257. }
  4258. t /= d / 2;
  4259. if (t === 2) {
  4260. return b + c;
  4261. }
  4262. if (!p) {
  4263. p = d * (0.3 * 1.5);
  4264. }
  4265. var opts = normalize(a, c, p, s);
  4266. if (t < 1) {
  4267. return -0.5 * elastic(opts, t, d) + b;
  4268. }
  4269. return opts.a * Math.pow(2, -10 * (t -= 1)) *
  4270. Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) * 0.5 + opts.c + b;
  4271. }
  4272. /**
  4273. * Backwards easing in
  4274. * @memberOf fabric.util.ease
  4275. */
  4276. function easeInBack(t, b, c, d, s) {
  4277. if (s === undefined) {
  4278. s = 1.70158;
  4279. }
  4280. return c * (t /= d) * t * ((s + 1) * t - s) + b;
  4281. }
  4282. /**
  4283. * Backwards easing out
  4284. * @memberOf fabric.util.ease
  4285. */
  4286. function easeOutBack(t, b, c, d, s) {
  4287. if (s === undefined) {
  4288. s = 1.70158;
  4289. }
  4290. return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
  4291. }
  4292. /**
  4293. * Backwards easing in and out
  4294. * @memberOf fabric.util.ease
  4295. */
  4296. function easeInOutBack(t, b, c, d, s) {
  4297. if (s === undefined) {
  4298. s = 1.70158;
  4299. }
  4300. t /= d / 2;
  4301. if (t < 1) {
  4302. return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
  4303. }
  4304. return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
  4305. }
  4306. /**
  4307. * Bouncing easing in
  4308. * @memberOf fabric.util.ease
  4309. */
  4310. function easeInBounce(t, b, c, d) {
  4311. return c - easeOutBounce (d - t, 0, c, d) + b;
  4312. }
  4313. /**
  4314. * Bouncing easing out
  4315. * @memberOf fabric.util.ease
  4316. */
  4317. function easeOutBounce(t, b, c, d) {
  4318. if ((t /= d) < (1 / 2.75)) {
  4319. return c * (7.5625 * t * t) + b;
  4320. }
  4321. else if (t < (2 / 2.75)) {
  4322. return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
  4323. }
  4324. else if (t < (2.5 / 2.75)) {
  4325. return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
  4326. }
  4327. else {
  4328. return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
  4329. }
  4330. }
  4331. /**
  4332. * Bouncing easing in and out
  4333. * @memberOf fabric.util.ease
  4334. */
  4335. function easeInOutBounce(t, b, c, d) {
  4336. if (t < d / 2) {
  4337. return easeInBounce (t * 2, 0, c, d) * 0.5 + b;
  4338. }
  4339. return easeOutBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
  4340. }
  4341. /**
  4342. * Easing functions
  4343. * See <a href="http://gizma.com/easing/">Easing Equations by Robert Penner</a>
  4344. * @namespace fabric.util.ease
  4345. */
  4346. fabric.util.ease = {
  4347. /**
  4348. * Quadratic easing in
  4349. * @memberOf fabric.util.ease
  4350. */
  4351. easeInQuad: function(t, b, c, d) {
  4352. return c * (t /= d) * t + b;
  4353. },
  4354. /**
  4355. * Quadratic easing out
  4356. * @memberOf fabric.util.ease
  4357. */
  4358. easeOutQuad: function(t, b, c, d) {
  4359. return -c * (t /= d) * (t - 2) + b;
  4360. },
  4361. /**
  4362. * Quadratic easing in and out
  4363. * @memberOf fabric.util.ease
  4364. */
  4365. easeInOutQuad: function(t, b, c, d) {
  4366. t /= (d / 2);
  4367. if (t < 1) {
  4368. return c / 2 * t * t + b;
  4369. }
  4370. return -c / 2 * ((--t) * (t - 2) - 1) + b;
  4371. },
  4372. /**
  4373. * Cubic easing in
  4374. * @memberOf fabric.util.ease
  4375. */
  4376. easeInCubic: function(t, b, c, d) {
  4377. return c * (t /= d) * t * t + b;
  4378. },
  4379. easeOutCubic: easeOutCubic,
  4380. easeInOutCubic: easeInOutCubic,
  4381. easeInQuart: easeInQuart,
  4382. easeOutQuart: easeOutQuart,
  4383. easeInOutQuart: easeInOutQuart,
  4384. easeInQuint: easeInQuint,
  4385. easeOutQuint: easeOutQuint,
  4386. easeInOutQuint: easeInOutQuint,
  4387. easeInSine: easeInSine,
  4388. easeOutSine: easeOutSine,
  4389. easeInOutSine: easeInOutSine,
  4390. easeInExpo: easeInExpo,
  4391. easeOutExpo: easeOutExpo,
  4392. easeInOutExpo: easeInOutExpo,
  4393. easeInCirc: easeInCirc,
  4394. easeOutCirc: easeOutCirc,
  4395. easeInOutCirc: easeInOutCirc,
  4396. easeInElastic: easeInElastic,
  4397. easeOutElastic: easeOutElastic,
  4398. easeInOutElastic: easeInOutElastic,
  4399. easeInBack: easeInBack,
  4400. easeOutBack: easeOutBack,
  4401. easeInOutBack: easeInOutBack,
  4402. easeInBounce: easeInBounce,
  4403. easeOutBounce: easeOutBounce,
  4404. easeInOutBounce: easeInOutBounce
  4405. };
  4406. })();
  4407. (function(global) {
  4408. 'use strict';
  4409. /**
  4410. * @name fabric
  4411. * @namespace
  4412. */
  4413. var fabric = global.fabric || (global.fabric = { }),
  4414. extend = fabric.util.object.extend,
  4415. clone = fabric.util.object.clone,
  4416. toFixed = fabric.util.toFixed,
  4417. parseUnit = fabric.util.parseUnit,
  4418. multiplyTransformMatrices = fabric.util.multiplyTransformMatrices,
  4419. svgValidTagNames = ['path', 'circle', 'polygon', 'polyline', 'ellipse', 'rect', 'line',
  4420. 'image', 'text'],
  4421. svgViewBoxElements = ['symbol', 'image', 'marker', 'pattern', 'view', 'svg'],
  4422. svgInvalidAncestors = ['pattern', 'defs', 'symbol', 'metadata', 'clipPath', 'mask', 'desc'],
  4423. svgValidParents = ['symbol', 'g', 'a', 'svg', 'clipPath', 'defs'],
  4424. attributesMap = {
  4425. cx: 'left',
  4426. x: 'left',
  4427. r: 'radius',
  4428. cy: 'top',
  4429. y: 'top',
  4430. display: 'visible',
  4431. visibility: 'visible',
  4432. transform: 'transformMatrix',
  4433. 'fill-opacity': 'fillOpacity',
  4434. 'fill-rule': 'fillRule',
  4435. 'font-family': 'fontFamily',
  4436. 'font-size': 'fontSize',
  4437. 'font-style': 'fontStyle',
  4438. 'font-weight': 'fontWeight',
  4439. 'letter-spacing': 'charSpacing',
  4440. 'paint-order': 'paintFirst',
  4441. 'stroke-dasharray': 'strokeDashArray',
  4442. 'stroke-dashoffset': 'strokeDashOffset',
  4443. 'stroke-linecap': 'strokeLineCap',
  4444. 'stroke-linejoin': 'strokeLineJoin',
  4445. 'stroke-miterlimit': 'strokeMiterLimit',
  4446. 'stroke-opacity': 'strokeOpacity',
  4447. 'stroke-width': 'strokeWidth',
  4448. 'text-decoration': 'textDecoration',
  4449. 'text-anchor': 'textAnchor',
  4450. opacity: 'opacity',
  4451. 'clip-path': 'clipPath',
  4452. 'clip-rule': 'clipRule',
  4453. 'vector-effect': 'strokeUniform',
  4454. 'image-rendering': 'imageSmoothing',
  4455. },
  4456. colorAttributes = {
  4457. stroke: 'strokeOpacity',
  4458. fill: 'fillOpacity'
  4459. },
  4460. fSize = 'font-size', cPath = 'clip-path';
  4461. fabric.svgValidTagNamesRegEx = getSvgRegex(svgValidTagNames);
  4462. fabric.svgViewBoxElementsRegEx = getSvgRegex(svgViewBoxElements);
  4463. fabric.svgInvalidAncestorsRegEx = getSvgRegex(svgInvalidAncestors);
  4464. fabric.svgValidParentsRegEx = getSvgRegex(svgValidParents);
  4465. fabric.cssRules = { };
  4466. fabric.gradientDefs = { };
  4467. fabric.clipPaths = { };
  4468. function normalizeAttr(attr) {
  4469. // transform attribute names
  4470. if (attr in attributesMap) {
  4471. return attributesMap[attr];
  4472. }
  4473. return attr;
  4474. }
  4475. function normalizeValue(attr, value, parentAttributes, fontSize) {
  4476. var isArray = Array.isArray(value), parsed;
  4477. if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
  4478. value = '';
  4479. }
  4480. else if (attr === 'strokeUniform') {
  4481. return (value === 'non-scaling-stroke');
  4482. }
  4483. else if (attr === 'strokeDashArray') {
  4484. if (value === 'none') {
  4485. value = null;
  4486. }
  4487. else {
  4488. value = value.replace(/,/g, ' ').split(/\s+/).map(parseFloat);
  4489. }
  4490. }
  4491. else if (attr === 'transformMatrix') {
  4492. if (parentAttributes && parentAttributes.transformMatrix) {
  4493. value = multiplyTransformMatrices(
  4494. parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));
  4495. }
  4496. else {
  4497. value = fabric.parseTransformAttribute(value);
  4498. }
  4499. }
  4500. else if (attr === 'visible') {
  4501. value = value !== 'none' && value !== 'hidden';
  4502. // display=none on parent element always takes precedence over child element
  4503. if (parentAttributes && parentAttributes.visible === false) {
  4504. value = false;
  4505. }
  4506. }
  4507. else if (attr === 'opacity') {
  4508. value = parseFloat(value);
  4509. if (parentAttributes && typeof parentAttributes.opacity !== 'undefined') {
  4510. value *= parentAttributes.opacity;
  4511. }
  4512. }
  4513. else if (attr === 'textAnchor' /* text-anchor */) {
  4514. value = value === 'start' ? 'left' : value === 'end' ? 'right' : 'center';
  4515. }
  4516. else if (attr === 'charSpacing') {
  4517. // parseUnit returns px and we convert it to em
  4518. parsed = parseUnit(value, fontSize) / fontSize * 1000;
  4519. }
  4520. else if (attr === 'paintFirst') {
  4521. var fillIndex = value.indexOf('fill');
  4522. var strokeIndex = value.indexOf('stroke');
  4523. var value = 'fill';
  4524. if (fillIndex > -1 && strokeIndex > -1 && strokeIndex < fillIndex) {
  4525. value = 'stroke';
  4526. }
  4527. else if (fillIndex === -1 && strokeIndex > -1) {
  4528. value = 'stroke';
  4529. }
  4530. }
  4531. else if (attr === 'href' || attr === 'xlink:href' || attr === 'font') {
  4532. return value;
  4533. }
  4534. else if (attr === 'imageSmoothing') {
  4535. return (value === 'optimizeQuality');
  4536. }
  4537. else {
  4538. parsed = isArray ? value.map(parseUnit) : parseUnit(value, fontSize);
  4539. }
  4540. return (!isArray && isNaN(parsed) ? value : parsed);
  4541. }
  4542. /**
  4543. * @private
  4544. */
  4545. function getSvgRegex(arr) {
  4546. return new RegExp('^(' + arr.join('|') + ')\\b', 'i');
  4547. }
  4548. /**
  4549. * @private
  4550. * @param {Object} attributes Array of attributes to parse
  4551. */
  4552. function _setStrokeFillOpacity(attributes) {
  4553. for (var attr in colorAttributes) {
  4554. if (typeof attributes[colorAttributes[attr]] === 'undefined' || attributes[attr] === '') {
  4555. continue;
  4556. }
  4557. if (typeof attributes[attr] === 'undefined') {
  4558. if (!fabric.Object.prototype[attr]) {
  4559. continue;
  4560. }
  4561. attributes[attr] = fabric.Object.prototype[attr];
  4562. }
  4563. if (attributes[attr].indexOf('url(') === 0) {
  4564. continue;
  4565. }
  4566. var color = new fabric.Color(attributes[attr]);
  4567. attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
  4568. }
  4569. return attributes;
  4570. }
  4571. /**
  4572. * @private
  4573. */
  4574. function _getMultipleNodes(doc, nodeNames) {
  4575. var nodeName, nodeArray = [], nodeList, i, len;
  4576. for (i = 0, len = nodeNames.length; i < len; i++) {
  4577. nodeName = nodeNames[i];
  4578. nodeList = doc.getElementsByTagName(nodeName);
  4579. nodeArray = nodeArray.concat(Array.prototype.slice.call(nodeList));
  4580. }
  4581. return nodeArray;
  4582. }
  4583. /**
  4584. * Parses "transform" attribute, returning an array of values
  4585. * @static
  4586. * @function
  4587. * @memberOf fabric
  4588. * @param {String} attributeValue String containing attribute value
  4589. * @return {Array} Array of 6 elements representing transformation matrix
  4590. */
  4591. fabric.parseTransformAttribute = (function() {
  4592. function rotateMatrix(matrix, args) {
  4593. var cos = fabric.util.cos(args[0]), sin = fabric.util.sin(args[0]),
  4594. x = 0, y = 0;
  4595. if (args.length === 3) {
  4596. x = args[1];
  4597. y = args[2];
  4598. }
  4599. matrix[0] = cos;
  4600. matrix[1] = sin;
  4601. matrix[2] = -sin;
  4602. matrix[3] = cos;
  4603. matrix[4] = x - (cos * x - sin * y);
  4604. matrix[5] = y - (sin * x + cos * y);
  4605. }
  4606. function scaleMatrix(matrix, args) {
  4607. var multiplierX = args[0],
  4608. multiplierY = (args.length === 2) ? args[1] : args[0];
  4609. matrix[0] = multiplierX;
  4610. matrix[3] = multiplierY;
  4611. }
  4612. function skewMatrix(matrix, args, pos) {
  4613. matrix[pos] = Math.tan(fabric.util.degreesToRadians(args[0]));
  4614. }
  4615. function translateMatrix(matrix, args) {
  4616. matrix[4] = args[0];
  4617. if (args.length === 2) {
  4618. matrix[5] = args[1];
  4619. }
  4620. }
  4621. // identity matrix
  4622. var iMatrix = fabric.iMatrix,
  4623. // == begin transform regexp
  4624. number = fabric.reNum,
  4625. commaWsp = fabric.commaWsp,
  4626. skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
  4627. skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
  4628. rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' +
  4629. commaWsp + '(' + number + ')' +
  4630. commaWsp + '(' + number + '))?\\s*\\))',
  4631. scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' +
  4632. commaWsp + '(' + number + '))?\\s*\\))',
  4633. translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' +
  4634. commaWsp + '(' + number + '))?\\s*\\))',
  4635. matrix = '(?:(matrix)\\s*\\(\\s*' +
  4636. '(' + number + ')' + commaWsp +
  4637. '(' + number + ')' + commaWsp +
  4638. '(' + number + ')' + commaWsp +
  4639. '(' + number + ')' + commaWsp +
  4640. '(' + number + ')' + commaWsp +
  4641. '(' + number + ')' +
  4642. '\\s*\\))',
  4643. transform = '(?:' +
  4644. matrix + '|' +
  4645. translate + '|' +
  4646. scale + '|' +
  4647. rotate + '|' +
  4648. skewX + '|' +
  4649. skewY +
  4650. ')',
  4651. transforms = '(?:' + transform + '(?:' + commaWsp + '*' + transform + ')*' + ')',
  4652. transformList = '^\\s*(?:' + transforms + '?)\\s*$',
  4653. // http://www.w3.org/TR/SVG/coords.html#TransformAttribute
  4654. reTransformList = new RegExp(transformList),
  4655. // == end transform regexp
  4656. reTransform = new RegExp(transform, 'g');
  4657. return function(attributeValue) {
  4658. // start with identity matrix
  4659. var matrix = iMatrix.concat(),
  4660. matrices = [];
  4661. // return if no argument was given or
  4662. // an argument does not match transform attribute regexp
  4663. if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
  4664. return matrix;
  4665. }
  4666. attributeValue.replace(reTransform, function(match) {
  4667. var m = new RegExp(transform).exec(match).filter(function (match) {
  4668. // match !== '' && match != null
  4669. return (!!match);
  4670. }),
  4671. operation = m[1],
  4672. args = m.slice(2).map(parseFloat);
  4673. switch (operation) {
  4674. case 'translate':
  4675. translateMatrix(matrix, args);
  4676. break;
  4677. case 'rotate':
  4678. args[0] = fabric.util.degreesToRadians(args[0]);
  4679. rotateMatrix(matrix, args);
  4680. break;
  4681. case 'scale':
  4682. scaleMatrix(matrix, args);
  4683. break;
  4684. case 'skewX':
  4685. skewMatrix(matrix, args, 2);
  4686. break;
  4687. case 'skewY':
  4688. skewMatrix(matrix, args, 1);
  4689. break;
  4690. case 'matrix':
  4691. matrix = args;
  4692. break;
  4693. }
  4694. // snapshot current matrix into matrices array
  4695. matrices.push(matrix.concat());
  4696. // reset
  4697. matrix = iMatrix.concat();
  4698. });
  4699. var combinedMatrix = matrices[0];
  4700. while (matrices.length > 1) {
  4701. matrices.shift();
  4702. combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
  4703. }
  4704. return combinedMatrix;
  4705. };
  4706. })();
  4707. /**
  4708. * @private
  4709. */
  4710. function parseStyleString(style, oStyle) {
  4711. var attr, value;
  4712. style.replace(/;\s*$/, '').split(';').forEach(function (chunk) {
  4713. var pair = chunk.split(':');
  4714. attr = pair[0].trim().toLowerCase();
  4715. value = pair[1].trim();
  4716. oStyle[attr] = value;
  4717. });
  4718. }
  4719. /**
  4720. * @private
  4721. */
  4722. function parseStyleObject(style, oStyle) {
  4723. var attr, value;
  4724. for (var prop in style) {
  4725. if (typeof style[prop] === 'undefined') {
  4726. continue;
  4727. }
  4728. attr = prop.toLowerCase();
  4729. value = style[prop];
  4730. oStyle[attr] = value;
  4731. }
  4732. }
  4733. /**
  4734. * @private
  4735. */
  4736. function getGlobalStylesForElement(element, svgUid) {
  4737. var styles = { };
  4738. for (var rule in fabric.cssRules[svgUid]) {
  4739. if (elementMatchesRule(element, rule.split(' '))) {
  4740. for (var property in fabric.cssRules[svgUid][rule]) {
  4741. styles[property] = fabric.cssRules[svgUid][rule][property];
  4742. }
  4743. }
  4744. }
  4745. return styles;
  4746. }
  4747. /**
  4748. * @private
  4749. */
  4750. function elementMatchesRule(element, selectors) {
  4751. var firstMatching, parentMatching = true;
  4752. //start from rightmost selector.
  4753. firstMatching = selectorMatches(element, selectors.pop());
  4754. if (firstMatching && selectors.length) {
  4755. parentMatching = doesSomeParentMatch(element, selectors);
  4756. }
  4757. return firstMatching && parentMatching && (selectors.length === 0);
  4758. }
  4759. function doesSomeParentMatch(element, selectors) {
  4760. var selector, parentMatching = true;
  4761. while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {
  4762. if (parentMatching) {
  4763. selector = selectors.pop();
  4764. }
  4765. element = element.parentNode;
  4766. parentMatching = selectorMatches(element, selector);
  4767. }
  4768. return selectors.length === 0;
  4769. }
  4770. /**
  4771. * @private
  4772. */
  4773. function selectorMatches(element, selector) {
  4774. var nodeName = element.nodeName,
  4775. classNames = element.getAttribute('class'),
  4776. id = element.getAttribute('id'), matcher, i;
  4777. // i check if a selector matches slicing away part from it.
  4778. // if i get empty string i should match
  4779. matcher = new RegExp('^' + nodeName, 'i');
  4780. selector = selector.replace(matcher, '');
  4781. if (id && selector.length) {
  4782. matcher = new RegExp('#' + id + '(?![a-zA-Z\\-]+)', 'i');
  4783. selector = selector.replace(matcher, '');
  4784. }
  4785. if (classNames && selector.length) {
  4786. classNames = classNames.split(' ');
  4787. for (i = classNames.length; i--;) {
  4788. matcher = new RegExp('\\.' + classNames[i] + '(?![a-zA-Z\\-]+)', 'i');
  4789. selector = selector.replace(matcher, '');
  4790. }
  4791. }
  4792. return selector.length === 0;
  4793. }
  4794. /**
  4795. * @private
  4796. * to support IE8 missing getElementById on SVGdocument and on node xmlDOM
  4797. */
  4798. function elementById(doc, id) {
  4799. var el;
  4800. doc.getElementById && (el = doc.getElementById(id));
  4801. if (el) {
  4802. return el;
  4803. }
  4804. var node, i, len, nodelist = doc.getElementsByTagName('*');
  4805. for (i = 0, len = nodelist.length; i < len; i++) {
  4806. node = nodelist[i];
  4807. if (id === node.getAttribute('id')) {
  4808. return node;
  4809. }
  4810. }
  4811. }
  4812. /**
  4813. * @private
  4814. */
  4815. function parseUseDirectives(doc) {
  4816. var nodelist = _getMultipleNodes(doc, ['use', 'svg:use']), i = 0;
  4817. while (nodelist.length && i < nodelist.length) {
  4818. var el = nodelist[i],
  4819. xlinkAttribute = el.getAttribute('xlink:href') || el.getAttribute('href');
  4820. if (xlinkAttribute === null) {
  4821. return;
  4822. }
  4823. var xlink = xlinkAttribute.slice(1),
  4824. x = el.getAttribute('x') || 0,
  4825. y = el.getAttribute('y') || 0,
  4826. el2 = elementById(doc, xlink).cloneNode(true),
  4827. currentTrans = (el2.getAttribute('transform') || '') + ' translate(' + x + ', ' + y + ')',
  4828. parentNode,
  4829. oldLength = nodelist.length, attr,
  4830. j,
  4831. attrs,
  4832. len,
  4833. namespace = fabric.svgNS;
  4834. applyViewboxTransform(el2);
  4835. if (/^svg$/i.test(el2.nodeName)) {
  4836. var el3 = el2.ownerDocument.createElementNS(namespace, 'g');
  4837. for (j = 0, attrs = el2.attributes, len = attrs.length; j < len; j++) {
  4838. attr = attrs.item(j);
  4839. el3.setAttributeNS(namespace, attr.nodeName, attr.nodeValue);
  4840. }
  4841. // el2.firstChild != null
  4842. while (el2.firstChild) {
  4843. el3.appendChild(el2.firstChild);
  4844. }
  4845. el2 = el3;
  4846. }
  4847. for (j = 0, attrs = el.attributes, len = attrs.length; j < len; j++) {
  4848. attr = attrs.item(j);
  4849. if (attr.nodeName === 'x' || attr.nodeName === 'y' ||
  4850. attr.nodeName === 'xlink:href' || attr.nodeName === 'href') {
  4851. continue;
  4852. }
  4853. if (attr.nodeName === 'transform') {
  4854. currentTrans = attr.nodeValue + ' ' + currentTrans;
  4855. }
  4856. else {
  4857. el2.setAttribute(attr.nodeName, attr.nodeValue);
  4858. }
  4859. }
  4860. el2.setAttribute('transform', currentTrans);
  4861. el2.setAttribute('instantiated_by_use', '1');
  4862. el2.removeAttribute('id');
  4863. parentNode = el.parentNode;
  4864. parentNode.replaceChild(el2, el);
  4865. // some browsers do not shorten nodelist after replaceChild (IE8)
  4866. if (nodelist.length === oldLength) {
  4867. i++;
  4868. }
  4869. }
  4870. }
  4871. // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
  4872. // matches, e.g.: +14.56e-12, etc.
  4873. var reViewBoxAttrValue = new RegExp(
  4874. '^' +
  4875. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  4876. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  4877. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  4878. '\\s*(' + fabric.reNum + '+)\\s*' +
  4879. '$'
  4880. );
  4881. /**
  4882. * Add a <g> element that envelop all child elements and makes the viewbox transformMatrix descend on all elements
  4883. */
  4884. function applyViewboxTransform(element) {
  4885. if (!fabric.svgViewBoxElementsRegEx.test(element.nodeName)) {
  4886. return {};
  4887. }
  4888. var viewBoxAttr = element.getAttribute('viewBox'),
  4889. scaleX = 1,
  4890. scaleY = 1,
  4891. minX = 0,
  4892. minY = 0,
  4893. viewBoxWidth, viewBoxHeight, matrix, el,
  4894. widthAttr = element.getAttribute('width'),
  4895. heightAttr = element.getAttribute('height'),
  4896. x = element.getAttribute('x') || 0,
  4897. y = element.getAttribute('y') || 0,
  4898. preserveAspectRatio = element.getAttribute('preserveAspectRatio') || '',
  4899. missingViewBox = (!viewBoxAttr || !(viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))),
  4900. missingDimAttr = (!widthAttr || !heightAttr || widthAttr === '100%' || heightAttr === '100%'),
  4901. toBeParsed = missingViewBox && missingDimAttr,
  4902. parsedDim = { }, translateMatrix = '', widthDiff = 0, heightDiff = 0;
  4903. parsedDim.width = 0;
  4904. parsedDim.height = 0;
  4905. parsedDim.toBeParsed = toBeParsed;
  4906. if (missingViewBox) {
  4907. if (((x || y) && element.parentNode && element.parentNode.nodeName !== '#document')) {
  4908. translateMatrix = ' translate(' + parseUnit(x) + ' ' + parseUnit(y) + ') ';
  4909. matrix = (element.getAttribute('transform') || '') + translateMatrix;
  4910. element.setAttribute('transform', matrix);
  4911. element.removeAttribute('x');
  4912. element.removeAttribute('y');
  4913. }
  4914. }
  4915. if (toBeParsed) {
  4916. return parsedDim;
  4917. }
  4918. if (missingViewBox) {
  4919. parsedDim.width = parseUnit(widthAttr);
  4920. parsedDim.height = parseUnit(heightAttr);
  4921. // set a transform for elements that have x y and are inner(only) SVGs
  4922. return parsedDim;
  4923. }
  4924. minX = -parseFloat(viewBoxAttr[1]);
  4925. minY = -parseFloat(viewBoxAttr[2]);
  4926. viewBoxWidth = parseFloat(viewBoxAttr[3]);
  4927. viewBoxHeight = parseFloat(viewBoxAttr[4]);
  4928. parsedDim.minX = minX;
  4929. parsedDim.minY = minY;
  4930. parsedDim.viewBoxWidth = viewBoxWidth;
  4931. parsedDim.viewBoxHeight = viewBoxHeight;
  4932. if (!missingDimAttr) {
  4933. parsedDim.width = parseUnit(widthAttr);
  4934. parsedDim.height = parseUnit(heightAttr);
  4935. scaleX = parsedDim.width / viewBoxWidth;
  4936. scaleY = parsedDim.height / viewBoxHeight;
  4937. }
  4938. else {
  4939. parsedDim.width = viewBoxWidth;
  4940. parsedDim.height = viewBoxHeight;
  4941. }
  4942. // default is to preserve aspect ratio
  4943. preserveAspectRatio = fabric.util.parsePreserveAspectRatioAttribute(preserveAspectRatio);
  4944. if (preserveAspectRatio.alignX !== 'none') {
  4945. //translate all container for the effect of Mid, Min, Max
  4946. if (preserveAspectRatio.meetOrSlice === 'meet') {
  4947. scaleY = scaleX = (scaleX > scaleY ? scaleY : scaleX);
  4948. // calculate additional translation to move the viewbox
  4949. }
  4950. if (preserveAspectRatio.meetOrSlice === 'slice') {
  4951. scaleY = scaleX = (scaleX > scaleY ? scaleX : scaleY);
  4952. // calculate additional translation to move the viewbox
  4953. }
  4954. widthDiff = parsedDim.width - viewBoxWidth * scaleX;
  4955. heightDiff = parsedDim.height - viewBoxHeight * scaleX;
  4956. if (preserveAspectRatio.alignX === 'Mid') {
  4957. widthDiff /= 2;
  4958. }
  4959. if (preserveAspectRatio.alignY === 'Mid') {
  4960. heightDiff /= 2;
  4961. }
  4962. if (preserveAspectRatio.alignX === 'Min') {
  4963. widthDiff = 0;
  4964. }
  4965. if (preserveAspectRatio.alignY === 'Min') {
  4966. heightDiff = 0;
  4967. }
  4968. }
  4969. if (scaleX === 1 && scaleY === 1 && minX === 0 && minY === 0 && x === 0 && y === 0) {
  4970. return parsedDim;
  4971. }
  4972. if ((x || y) && element.parentNode.nodeName !== '#document') {
  4973. translateMatrix = ' translate(' + parseUnit(x) + ' ' + parseUnit(y) + ') ';
  4974. }
  4975. matrix = translateMatrix + ' matrix(' + scaleX +
  4976. ' 0' +
  4977. ' 0 ' +
  4978. scaleY + ' ' +
  4979. (minX * scaleX + widthDiff) + ' ' +
  4980. (minY * scaleY + heightDiff) + ') ';
  4981. // seems unused.
  4982. // parsedDim.viewboxTransform = fabric.parseTransformAttribute(matrix);
  4983. if (element.nodeName === 'svg') {
  4984. el = element.ownerDocument.createElementNS(fabric.svgNS, 'g');
  4985. // element.firstChild != null
  4986. while (element.firstChild) {
  4987. el.appendChild(element.firstChild);
  4988. }
  4989. element.appendChild(el);
  4990. }
  4991. else {
  4992. el = element;
  4993. el.removeAttribute('x');
  4994. el.removeAttribute('y');
  4995. matrix = el.getAttribute('transform') + matrix;
  4996. }
  4997. el.setAttribute('transform', matrix);
  4998. return parsedDim;
  4999. }
  5000. function hasAncestorWithNodeName(element, nodeName) {
  5001. while (element && (element = element.parentNode)) {
  5002. if (element.nodeName && nodeName.test(element.nodeName.replace('svg:', ''))
  5003. && !element.getAttribute('instantiated_by_use')) {
  5004. return true;
  5005. }
  5006. }
  5007. return false;
  5008. }
  5009. /**
  5010. * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
  5011. * @static
  5012. * @function
  5013. * @memberOf fabric
  5014. * @param {SVGDocument} doc SVG document to parse
  5015. * @param {Function} callback Callback to call when parsing is finished;
  5016. * It's being passed an array of elements (parsed from a document).
  5017. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  5018. * @param {Object} [parsingOptions] options for parsing document
  5019. * @param {String} [parsingOptions.crossOrigin] crossOrigin settings
  5020. */
  5021. fabric.parseSVGDocument = function(doc, callback, reviver, parsingOptions) {
  5022. if (!doc) {
  5023. return;
  5024. }
  5025. parseUseDirectives(doc);
  5026. var svgUid = fabric.Object.__uid++, i, len,
  5027. options = applyViewboxTransform(doc),
  5028. descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
  5029. options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;
  5030. options.svgUid = svgUid;
  5031. if (descendants.length === 0 && fabric.isLikelyNode) {
  5032. // we're likely in node, where "o3-xml" library fails to gEBTN("*")
  5033. // https://github.com/ajaxorg/node-o3-xml/issues/21
  5034. descendants = doc.selectNodes('//*[name(.)!="svg"]');
  5035. var arr = [];
  5036. for (i = 0, len = descendants.length; i < len; i++) {
  5037. arr[i] = descendants[i];
  5038. }
  5039. descendants = arr;
  5040. }
  5041. var elements = descendants.filter(function(el) {
  5042. applyViewboxTransform(el);
  5043. return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', '')) &&
  5044. !hasAncestorWithNodeName(el, fabric.svgInvalidAncestorsRegEx); // http://www.w3.org/TR/SVG/struct.html#DefsElement
  5045. });
  5046. if (!elements || (elements && !elements.length)) {
  5047. callback && callback([], {});
  5048. return;
  5049. }
  5050. var clipPaths = { };
  5051. descendants.filter(function(el) {
  5052. return el.nodeName.replace('svg:', '') === 'clipPath';
  5053. }).forEach(function(el) {
  5054. var id = el.getAttribute('id');
  5055. clipPaths[id] = fabric.util.toArray(el.getElementsByTagName('*')).filter(function(el) {
  5056. return fabric.svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', ''));
  5057. });
  5058. });
  5059. fabric.gradientDefs[svgUid] = fabric.getGradientDefs(doc);
  5060. fabric.cssRules[svgUid] = fabric.getCSSRules(doc);
  5061. fabric.clipPaths[svgUid] = clipPaths;
  5062. // Precedence of rules: style > class > attribute
  5063. fabric.parseElements(elements, function(instances, elements) {
  5064. if (callback) {
  5065. callback(instances, options, elements, descendants);
  5066. delete fabric.gradientDefs[svgUid];
  5067. delete fabric.cssRules[svgUid];
  5068. delete fabric.clipPaths[svgUid];
  5069. }
  5070. }, clone(options), reviver, parsingOptions);
  5071. };
  5072. function recursivelyParseGradientsXlink(doc, gradient) {
  5073. var gradientsAttrs = ['gradientTransform', 'x1', 'x2', 'y1', 'y2', 'gradientUnits', 'cx', 'cy', 'r', 'fx', 'fy'],
  5074. xlinkAttr = 'xlink:href',
  5075. xLink = gradient.getAttribute(xlinkAttr).slice(1),
  5076. referencedGradient = elementById(doc, xLink);
  5077. if (referencedGradient && referencedGradient.getAttribute(xlinkAttr)) {
  5078. recursivelyParseGradientsXlink(doc, referencedGradient);
  5079. }
  5080. gradientsAttrs.forEach(function(attr) {
  5081. if (referencedGradient && !gradient.hasAttribute(attr) && referencedGradient.hasAttribute(attr)) {
  5082. gradient.setAttribute(attr, referencedGradient.getAttribute(attr));
  5083. }
  5084. });
  5085. if (!gradient.children.length) {
  5086. var referenceClone = referencedGradient.cloneNode(true);
  5087. while (referenceClone.firstChild) {
  5088. gradient.appendChild(referenceClone.firstChild);
  5089. }
  5090. }
  5091. gradient.removeAttribute(xlinkAttr);
  5092. }
  5093. var reFontDeclaration = new RegExp(
  5094. '(normal|italic)?\\s*(normal|small-caps)?\\s*' +
  5095. '(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(' +
  5096. fabric.reNum +
  5097. '(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|' + fabric.reNum + '))?\\s+(.*)');
  5098. extend(fabric, {
  5099. /**
  5100. * Parses a short font declaration, building adding its properties to a style object
  5101. * @static
  5102. * @function
  5103. * @memberOf fabric
  5104. * @param {String} value font declaration
  5105. * @param {Object} oStyle definition
  5106. */
  5107. parseFontDeclaration: function(value, oStyle) {
  5108. var match = value.match(reFontDeclaration);
  5109. if (!match) {
  5110. return;
  5111. }
  5112. var fontStyle = match[1],
  5113. // font variant is not used
  5114. // fontVariant = match[2],
  5115. fontWeight = match[3],
  5116. fontSize = match[4],
  5117. lineHeight = match[5],
  5118. fontFamily = match[6];
  5119. if (fontStyle) {
  5120. oStyle.fontStyle = fontStyle;
  5121. }
  5122. if (fontWeight) {
  5123. oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
  5124. }
  5125. if (fontSize) {
  5126. oStyle.fontSize = parseUnit(fontSize);
  5127. }
  5128. if (fontFamily) {
  5129. oStyle.fontFamily = fontFamily;
  5130. }
  5131. if (lineHeight) {
  5132. oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;
  5133. }
  5134. },
  5135. /**
  5136. * Parses an SVG document, returning all of the gradient declarations found in it
  5137. * @static
  5138. * @function
  5139. * @memberOf fabric
  5140. * @param {SVGDocument} doc SVG document to parse
  5141. * @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
  5142. */
  5143. getGradientDefs: function(doc) {
  5144. var tagArray = [
  5145. 'linearGradient',
  5146. 'radialGradient',
  5147. 'svg:linearGradient',
  5148. 'svg:radialGradient'],
  5149. elList = _getMultipleNodes(doc, tagArray),
  5150. el, j = 0, gradientDefs = { };
  5151. j = elList.length;
  5152. while (j--) {
  5153. el = elList[j];
  5154. if (el.getAttribute('xlink:href')) {
  5155. recursivelyParseGradientsXlink(doc, el);
  5156. }
  5157. gradientDefs[el.getAttribute('id')] = el;
  5158. }
  5159. return gradientDefs;
  5160. },
  5161. /**
  5162. * Returns an object of attributes' name/value, given element and an array of attribute names;
  5163. * Parses parent "g" nodes recursively upwards.
  5164. * @static
  5165. * @memberOf fabric
  5166. * @param {DOMElement} element Element to parse
  5167. * @param {Array} attributes Array of attributes to parse
  5168. * @return {Object} object containing parsed attributes' names/values
  5169. */
  5170. parseAttributes: function(element, attributes, svgUid) {
  5171. if (!element) {
  5172. return;
  5173. }
  5174. var value,
  5175. parentAttributes = { },
  5176. fontSize, parentFontSize;
  5177. if (typeof svgUid === 'undefined') {
  5178. svgUid = element.getAttribute('svgUid');
  5179. }
  5180. // if there's a parent container (`g` or `a` or `symbol` node), parse its attributes recursively upwards
  5181. if (element.parentNode && fabric.svgValidParentsRegEx.test(element.parentNode.nodeName)) {
  5182. parentAttributes = fabric.parseAttributes(element.parentNode, attributes, svgUid);
  5183. }
  5184. var ownAttributes = attributes.reduce(function(memo, attr) {
  5185. value = element.getAttribute(attr);
  5186. if (value) { // eslint-disable-line
  5187. memo[attr] = value;
  5188. }
  5189. return memo;
  5190. }, { });
  5191. // add values parsed from style, which take precedence over attributes
  5192. // (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
  5193. var cssAttrs = extend(
  5194. getGlobalStylesForElement(element, svgUid),
  5195. fabric.parseStyleAttribute(element)
  5196. );
  5197. ownAttributes = extend(
  5198. ownAttributes,
  5199. cssAttrs
  5200. );
  5201. if (cssAttrs[cPath]) {
  5202. element.setAttribute(cPath, cssAttrs[cPath]);
  5203. }
  5204. fontSize = parentFontSize = parentAttributes.fontSize || fabric.Text.DEFAULT_SVG_FONT_SIZE;
  5205. if (ownAttributes[fSize]) {
  5206. // looks like the minimum should be 9px when dealing with ems. this is what looks like in browsers.
  5207. ownAttributes[fSize] = fontSize = parseUnit(ownAttributes[fSize], parentFontSize);
  5208. }
  5209. var normalizedAttr, normalizedValue, normalizedStyle = {};
  5210. for (var attr in ownAttributes) {
  5211. normalizedAttr = normalizeAttr(attr);
  5212. normalizedValue = normalizeValue(normalizedAttr, ownAttributes[attr], parentAttributes, fontSize);
  5213. normalizedStyle[normalizedAttr] = normalizedValue;
  5214. }
  5215. if (normalizedStyle && normalizedStyle.font) {
  5216. fabric.parseFontDeclaration(normalizedStyle.font, normalizedStyle);
  5217. }
  5218. var mergedAttrs = extend(parentAttributes, normalizedStyle);
  5219. return fabric.svgValidParentsRegEx.test(element.nodeName) ? mergedAttrs : _setStrokeFillOpacity(mergedAttrs);
  5220. },
  5221. /**
  5222. * Transforms an array of svg elements to corresponding fabric.* instances
  5223. * @static
  5224. * @memberOf fabric
  5225. * @param {Array} elements Array of elements to parse
  5226. * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
  5227. * @param {Object} [options] Options object
  5228. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  5229. */
  5230. parseElements: function(elements, callback, options, reviver, parsingOptions) {
  5231. new fabric.ElementsParser(elements, callback, options, reviver, parsingOptions).parse();
  5232. },
  5233. /**
  5234. * Parses "style" attribute, retuning an object with values
  5235. * @static
  5236. * @memberOf fabric
  5237. * @param {SVGElement} element Element to parse
  5238. * @return {Object} Objects with values parsed from style attribute of an element
  5239. */
  5240. parseStyleAttribute: function(element) {
  5241. var oStyle = { },
  5242. style = element.getAttribute('style');
  5243. if (!style) {
  5244. return oStyle;
  5245. }
  5246. if (typeof style === 'string') {
  5247. parseStyleString(style, oStyle);
  5248. }
  5249. else {
  5250. parseStyleObject(style, oStyle);
  5251. }
  5252. return oStyle;
  5253. },
  5254. /**
  5255. * Parses "points" attribute, returning an array of values
  5256. * @static
  5257. * @memberOf fabric
  5258. * @param {String} points points attribute string
  5259. * @return {Array} array of points
  5260. */
  5261. parsePointsAttribute: function(points) {
  5262. // points attribute is required and must not be empty
  5263. if (!points) {
  5264. return null;
  5265. }
  5266. // replace commas with whitespace and remove bookending whitespace
  5267. points = points.replace(/,/g, ' ').trim();
  5268. points = points.split(/\s+/);
  5269. var parsedPoints = [], i, len;
  5270. for (i = 0, len = points.length; i < len; i += 2) {
  5271. parsedPoints.push({
  5272. x: parseFloat(points[i]),
  5273. y: parseFloat(points[i + 1])
  5274. });
  5275. }
  5276. // odd number of points is an error
  5277. // if (parsedPoints.length % 2 !== 0) {
  5278. // return null;
  5279. // }
  5280. return parsedPoints;
  5281. },
  5282. /**
  5283. * Returns CSS rules for a given SVG document
  5284. * @static
  5285. * @function
  5286. * @memberOf fabric
  5287. * @param {SVGDocument} doc SVG document to parse
  5288. * @return {Object} CSS rules of this document
  5289. */
  5290. getCSSRules: function(doc) {
  5291. var styles = doc.getElementsByTagName('style'), i, len,
  5292. allRules = { }, rules;
  5293. // very crude parsing of style contents
  5294. for (i = 0, len = styles.length; i < len; i++) {
  5295. var styleContents = styles[i].textContent;
  5296. // remove comments
  5297. styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');
  5298. if (styleContents.trim() === '') {
  5299. continue;
  5300. }
  5301. // recovers all the rule in this form `body { style code... }`
  5302. // rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
  5303. rules = styleContents.split('}');
  5304. // remove empty rules.
  5305. rules = rules.filter(function(rule) { return rule.trim(); });
  5306. // at this point we have hopefully an array of rules `body { style code... `
  5307. // eslint-disable-next-line no-loop-func
  5308. rules.forEach(function(rule) {
  5309. var match = rule.split('{'),
  5310. ruleObj = { }, declaration = match[1].trim(),
  5311. propertyValuePairs = declaration.split(';').filter(function(pair) { return pair.trim(); });
  5312. for (i = 0, len = propertyValuePairs.length; i < len; i++) {
  5313. var pair = propertyValuePairs[i].split(':'),
  5314. property = pair[0].trim(),
  5315. value = pair[1].trim();
  5316. ruleObj[property] = value;
  5317. }
  5318. rule = match[0].trim();
  5319. rule.split(',').forEach(function(_rule) {
  5320. _rule = _rule.replace(/^svg/i, '').trim();
  5321. if (_rule === '') {
  5322. return;
  5323. }
  5324. if (allRules[_rule]) {
  5325. fabric.util.object.extend(allRules[_rule], ruleObj);
  5326. }
  5327. else {
  5328. allRules[_rule] = fabric.util.object.clone(ruleObj);
  5329. }
  5330. });
  5331. });
  5332. }
  5333. return allRules;
  5334. },
  5335. /**
  5336. * Takes url corresponding to an SVG document, and parses it into a set of fabric objects.
  5337. * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
  5338. * @memberOf fabric
  5339. * @param {String} url
  5340. * @param {Function} callback
  5341. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  5342. * @param {Object} [options] Object containing options for parsing
  5343. * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
  5344. */
  5345. loadSVGFromURL: function(url, callback, reviver, options) {
  5346. url = url.replace(/^\n\s*/, '').trim();
  5347. new fabric.util.request(url, {
  5348. method: 'get',
  5349. onComplete: onComplete
  5350. });
  5351. function onComplete(r) {
  5352. var xml = r.responseXML;
  5353. if (!xml || !xml.documentElement) {
  5354. callback && callback(null);
  5355. return false;
  5356. }
  5357. fabric.parseSVGDocument(xml.documentElement, function (results, _options, elements, allElements) {
  5358. callback && callback(results, _options, elements, allElements);
  5359. }, reviver, options);
  5360. }
  5361. },
  5362. /**
  5363. * Takes string corresponding to an SVG document, and parses it into a set of fabric objects
  5364. * @memberOf fabric
  5365. * @param {String} string
  5366. * @param {Function} callback
  5367. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  5368. * @param {Object} [options] Object containing options for parsing
  5369. * @param {String} [options.crossOrigin] crossOrigin crossOrigin setting to use for external resources
  5370. */
  5371. loadSVGFromString: function(string, callback, reviver, options) {
  5372. var parser = new fabric.window.DOMParser(),
  5373. doc = parser.parseFromString(string.trim(), 'text/xml');
  5374. fabric.parseSVGDocument(doc.documentElement, function (results, _options, elements, allElements) {
  5375. callback(results, _options, elements, allElements);
  5376. }, reviver, options);
  5377. }
  5378. });
  5379. })(typeof exports !== 'undefined' ? exports : this);
  5380. fabric.ElementsParser = function(elements, callback, options, reviver, parsingOptions, doc) {
  5381. this.elements = elements;
  5382. this.callback = callback;
  5383. this.options = options;
  5384. this.reviver = reviver;
  5385. this.svgUid = (options && options.svgUid) || 0;
  5386. this.parsingOptions = parsingOptions;
  5387. this.regexUrl = /^url\(['"]?#([^'"]+)['"]?\)/g;
  5388. this.doc = doc;
  5389. };
  5390. (function(proto) {
  5391. proto.parse = function() {
  5392. this.instances = new Array(this.elements.length);
  5393. this.numElements = this.elements.length;
  5394. this.createObjects();
  5395. };
  5396. proto.createObjects = function() {
  5397. var _this = this;
  5398. this.elements.forEach(function(element, i) {
  5399. element.setAttribute('svgUid', _this.svgUid);
  5400. _this.createObject(element, i);
  5401. });
  5402. };
  5403. proto.findTag = function(el) {
  5404. return fabric[fabric.util.string.capitalize(el.tagName.replace('svg:', ''))];
  5405. };
  5406. proto.createObject = function(el, index) {
  5407. var klass = this.findTag(el);
  5408. if (klass && klass.fromElement) {
  5409. try {
  5410. klass.fromElement(el, this.createCallback(index, el), this.options);
  5411. }
  5412. catch (err) {
  5413. fabric.log(err);
  5414. }
  5415. }
  5416. else {
  5417. this.checkIfDone();
  5418. }
  5419. };
  5420. proto.createCallback = function(index, el) {
  5421. var _this = this;
  5422. return function(obj) {
  5423. var _options;
  5424. _this.resolveGradient(obj, el, 'fill');
  5425. _this.resolveGradient(obj, el, 'stroke');
  5426. if (obj instanceof fabric.Image && obj._originalElement) {
  5427. _options = obj.parsePreserveAspectRatioAttribute(el);
  5428. }
  5429. obj._removeTransformMatrix(_options);
  5430. _this.resolveClipPath(obj, el);
  5431. _this.reviver && _this.reviver(el, obj);
  5432. _this.instances[index] = obj;
  5433. _this.checkIfDone();
  5434. };
  5435. };
  5436. proto.extractPropertyDefinition = function(obj, property, storage) {
  5437. var value = obj[property], regex = this.regexUrl;
  5438. if (!regex.test(value)) {
  5439. return;
  5440. }
  5441. regex.lastIndex = 0;
  5442. var id = regex.exec(value)[1];
  5443. regex.lastIndex = 0;
  5444. return fabric[storage][this.svgUid][id];
  5445. };
  5446. proto.resolveGradient = function(obj, el, property) {
  5447. var gradientDef = this.extractPropertyDefinition(obj, property, 'gradientDefs');
  5448. if (gradientDef) {
  5449. var opacityAttr = el.getAttribute(property + '-opacity');
  5450. var gradient = fabric.Gradient.fromElement(gradientDef, obj, opacityAttr, this.options);
  5451. obj.set(property, gradient);
  5452. }
  5453. };
  5454. proto.createClipPathCallback = function(obj, container) {
  5455. return function(_newObj) {
  5456. _newObj._removeTransformMatrix();
  5457. _newObj.fillRule = _newObj.clipRule;
  5458. container.push(_newObj);
  5459. };
  5460. };
  5461. proto.resolveClipPath = function(obj, usingElement) {
  5462. var clipPath = this.extractPropertyDefinition(obj, 'clipPath', 'clipPaths'),
  5463. element, klass, objTransformInv, container, gTransform, options;
  5464. if (clipPath) {
  5465. container = [];
  5466. objTransformInv = fabric.util.invertTransform(obj.calcTransformMatrix());
  5467. // move the clipPath tag as sibling to the real element that is using it
  5468. var clipPathTag = clipPath[0].parentNode;
  5469. var clipPathOwner = usingElement;
  5470. while (clipPathOwner.parentNode && clipPathOwner.getAttribute('clip-path') !== obj.clipPath) {
  5471. clipPathOwner = clipPathOwner.parentNode;
  5472. }
  5473. clipPathOwner.parentNode.appendChild(clipPathTag);
  5474. for (var i = 0; i < clipPath.length; i++) {
  5475. element = clipPath[i];
  5476. klass = this.findTag(element);
  5477. klass.fromElement(
  5478. element,
  5479. this.createClipPathCallback(obj, container),
  5480. this.options
  5481. );
  5482. }
  5483. if (container.length === 1) {
  5484. clipPath = container[0];
  5485. }
  5486. else {
  5487. clipPath = new fabric.Group(container);
  5488. }
  5489. gTransform = fabric.util.multiplyTransformMatrices(
  5490. objTransformInv,
  5491. clipPath.calcTransformMatrix()
  5492. );
  5493. if (clipPath.clipPath) {
  5494. this.resolveClipPath(clipPath, clipPathOwner);
  5495. }
  5496. var options = fabric.util.qrDecompose(gTransform);
  5497. clipPath.flipX = false;
  5498. clipPath.flipY = false;
  5499. clipPath.set('scaleX', options.scaleX);
  5500. clipPath.set('scaleY', options.scaleY);
  5501. clipPath.angle = options.angle;
  5502. clipPath.skewX = options.skewX;
  5503. clipPath.skewY = 0;
  5504. clipPath.setPositionByOrigin({ x: options.translateX, y: options.translateY }, 'center', 'center');
  5505. obj.clipPath = clipPath;
  5506. }
  5507. else {
  5508. // if clip-path does not resolve to any element, delete the property.
  5509. delete obj.clipPath;
  5510. }
  5511. };
  5512. proto.checkIfDone = function() {
  5513. if (--this.numElements === 0) {
  5514. this.instances = this.instances.filter(function(el) {
  5515. // eslint-disable-next-line no-eq-null, eqeqeq
  5516. return el != null;
  5517. });
  5518. this.callback(this.instances, this.elements);
  5519. }
  5520. };
  5521. })(fabric.ElementsParser.prototype);
  5522. (function(global) {
  5523. 'use strict';
  5524. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  5525. var fabric = global.fabric || (global.fabric = { });
  5526. if (fabric.Point) {
  5527. fabric.warn('fabric.Point is already defined');
  5528. return;
  5529. }
  5530. fabric.Point = Point;
  5531. /**
  5532. * Point class
  5533. * @class fabric.Point
  5534. * @memberOf fabric
  5535. * @constructor
  5536. * @param {Number} x
  5537. * @param {Number} y
  5538. * @return {fabric.Point} thisArg
  5539. */
  5540. function Point(x, y) {
  5541. this.x = x;
  5542. this.y = y;
  5543. }
  5544. Point.prototype = /** @lends fabric.Point.prototype */ {
  5545. type: 'point',
  5546. constructor: Point,
  5547. /**
  5548. * Adds another point to this one and returns another one
  5549. * @param {fabric.Point} that
  5550. * @return {fabric.Point} new Point instance with added values
  5551. */
  5552. add: function (that) {
  5553. return new Point(this.x + that.x, this.y + that.y);
  5554. },
  5555. /**
  5556. * Adds another point to this one
  5557. * @param {fabric.Point} that
  5558. * @return {fabric.Point} thisArg
  5559. * @chainable
  5560. */
  5561. addEquals: function (that) {
  5562. this.x += that.x;
  5563. this.y += that.y;
  5564. return this;
  5565. },
  5566. /**
  5567. * Adds value to this point and returns a new one
  5568. * @param {Number} scalar
  5569. * @return {fabric.Point} new Point with added value
  5570. */
  5571. scalarAdd: function (scalar) {
  5572. return new Point(this.x + scalar, this.y + scalar);
  5573. },
  5574. /**
  5575. * Adds value to this point
  5576. * @param {Number} scalar
  5577. * @return {fabric.Point} thisArg
  5578. * @chainable
  5579. */
  5580. scalarAddEquals: function (scalar) {
  5581. this.x += scalar;
  5582. this.y += scalar;
  5583. return this;
  5584. },
  5585. /**
  5586. * Subtracts another point from this point and returns a new one
  5587. * @param {fabric.Point} that
  5588. * @return {fabric.Point} new Point object with subtracted values
  5589. */
  5590. subtract: function (that) {
  5591. return new Point(this.x - that.x, this.y - that.y);
  5592. },
  5593. /**
  5594. * Subtracts another point from this point
  5595. * @param {fabric.Point} that
  5596. * @return {fabric.Point} thisArg
  5597. * @chainable
  5598. */
  5599. subtractEquals: function (that) {
  5600. this.x -= that.x;
  5601. this.y -= that.y;
  5602. return this;
  5603. },
  5604. /**
  5605. * Subtracts value from this point and returns a new one
  5606. * @param {Number} scalar
  5607. * @return {fabric.Point}
  5608. */
  5609. scalarSubtract: function (scalar) {
  5610. return new Point(this.x - scalar, this.y - scalar);
  5611. },
  5612. /**
  5613. * Subtracts value from this point
  5614. * @param {Number} scalar
  5615. * @return {fabric.Point} thisArg
  5616. * @chainable
  5617. */
  5618. scalarSubtractEquals: function (scalar) {
  5619. this.x -= scalar;
  5620. this.y -= scalar;
  5621. return this;
  5622. },
  5623. /**
  5624. * Multiplies this point by a value and returns a new one
  5625. * TODO: rename in scalarMultiply in 2.0
  5626. * @param {Number} scalar
  5627. * @return {fabric.Point}
  5628. */
  5629. multiply: function (scalar) {
  5630. return new Point(this.x * scalar, this.y * scalar);
  5631. },
  5632. /**
  5633. * Multiplies this point by a value
  5634. * TODO: rename in scalarMultiplyEquals in 2.0
  5635. * @param {Number} scalar
  5636. * @return {fabric.Point} thisArg
  5637. * @chainable
  5638. */
  5639. multiplyEquals: function (scalar) {
  5640. this.x *= scalar;
  5641. this.y *= scalar;
  5642. return this;
  5643. },
  5644. /**
  5645. * Divides this point by a value and returns a new one
  5646. * TODO: rename in scalarDivide in 2.0
  5647. * @param {Number} scalar
  5648. * @return {fabric.Point}
  5649. */
  5650. divide: function (scalar) {
  5651. return new Point(this.x / scalar, this.y / scalar);
  5652. },
  5653. /**
  5654. * Divides this point by a value
  5655. * TODO: rename in scalarDivideEquals in 2.0
  5656. * @param {Number} scalar
  5657. * @return {fabric.Point} thisArg
  5658. * @chainable
  5659. */
  5660. divideEquals: function (scalar) {
  5661. this.x /= scalar;
  5662. this.y /= scalar;
  5663. return this;
  5664. },
  5665. /**
  5666. * Returns true if this point is equal to another one
  5667. * @param {fabric.Point} that
  5668. * @return {Boolean}
  5669. */
  5670. eq: function (that) {
  5671. return (this.x === that.x && this.y === that.y);
  5672. },
  5673. /**
  5674. * Returns true if this point is less than another one
  5675. * @param {fabric.Point} that
  5676. * @return {Boolean}
  5677. */
  5678. lt: function (that) {
  5679. return (this.x < that.x && this.y < that.y);
  5680. },
  5681. /**
  5682. * Returns true if this point is less than or equal to another one
  5683. * @param {fabric.Point} that
  5684. * @return {Boolean}
  5685. */
  5686. lte: function (that) {
  5687. return (this.x <= that.x && this.y <= that.y);
  5688. },
  5689. /**
  5690. * Returns true if this point is greater another one
  5691. * @param {fabric.Point} that
  5692. * @return {Boolean}
  5693. */
  5694. gt: function (that) {
  5695. return (this.x > that.x && this.y > that.y);
  5696. },
  5697. /**
  5698. * Returns true if this point is greater than or equal to another one
  5699. * @param {fabric.Point} that
  5700. * @return {Boolean}
  5701. */
  5702. gte: function (that) {
  5703. return (this.x >= that.x && this.y >= that.y);
  5704. },
  5705. /**
  5706. * Returns new point which is the result of linear interpolation with this one and another one
  5707. * @param {fabric.Point} that
  5708. * @param {Number} t , position of interpolation, between 0 and 1 default 0.5
  5709. * @return {fabric.Point}
  5710. */
  5711. lerp: function (that, t) {
  5712. if (typeof t === 'undefined') {
  5713. t = 0.5;
  5714. }
  5715. t = Math.max(Math.min(1, t), 0);
  5716. return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
  5717. },
  5718. /**
  5719. * Returns distance from this point and another one
  5720. * @param {fabric.Point} that
  5721. * @return {Number}
  5722. */
  5723. distanceFrom: function (that) {
  5724. var dx = this.x - that.x,
  5725. dy = this.y - that.y;
  5726. return Math.sqrt(dx * dx + dy * dy);
  5727. },
  5728. /**
  5729. * Returns the point between this point and another one
  5730. * @param {fabric.Point} that
  5731. * @return {fabric.Point}
  5732. */
  5733. midPointFrom: function (that) {
  5734. return this.lerp(that);
  5735. },
  5736. /**
  5737. * Returns a new point which is the min of this and another one
  5738. * @param {fabric.Point} that
  5739. * @return {fabric.Point}
  5740. */
  5741. min: function (that) {
  5742. return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
  5743. },
  5744. /**
  5745. * Returns a new point which is the max of this and another one
  5746. * @param {fabric.Point} that
  5747. * @return {fabric.Point}
  5748. */
  5749. max: function (that) {
  5750. return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
  5751. },
  5752. /**
  5753. * Returns string representation of this point
  5754. * @return {String}
  5755. */
  5756. toString: function () {
  5757. return this.x + ',' + this.y;
  5758. },
  5759. /**
  5760. * Sets x/y of this point
  5761. * @param {Number} x
  5762. * @param {Number} y
  5763. * @chainable
  5764. */
  5765. setXY: function (x, y) {
  5766. this.x = x;
  5767. this.y = y;
  5768. return this;
  5769. },
  5770. /**
  5771. * Sets x of this point
  5772. * @param {Number} x
  5773. * @chainable
  5774. */
  5775. setX: function (x) {
  5776. this.x = x;
  5777. return this;
  5778. },
  5779. /**
  5780. * Sets y of this point
  5781. * @param {Number} y
  5782. * @chainable
  5783. */
  5784. setY: function (y) {
  5785. this.y = y;
  5786. return this;
  5787. },
  5788. /**
  5789. * Sets x/y of this point from another point
  5790. * @param {fabric.Point} that
  5791. * @chainable
  5792. */
  5793. setFromPoint: function (that) {
  5794. this.x = that.x;
  5795. this.y = that.y;
  5796. return this;
  5797. },
  5798. /**
  5799. * Swaps x/y of this point and another point
  5800. * @param {fabric.Point} that
  5801. */
  5802. swap: function (that) {
  5803. var x = this.x,
  5804. y = this.y;
  5805. this.x = that.x;
  5806. this.y = that.y;
  5807. that.x = x;
  5808. that.y = y;
  5809. },
  5810. /**
  5811. * return a cloned instance of the point
  5812. * @return {fabric.Point}
  5813. */
  5814. clone: function () {
  5815. return new Point(this.x, this.y);
  5816. }
  5817. };
  5818. })(typeof exports !== 'undefined' ? exports : this);
  5819. (function(global) {
  5820. 'use strict';
  5821. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  5822. var fabric = global.fabric || (global.fabric = { });
  5823. if (fabric.Intersection) {
  5824. fabric.warn('fabric.Intersection is already defined');
  5825. return;
  5826. }
  5827. /**
  5828. * Intersection class
  5829. * @class fabric.Intersection
  5830. * @memberOf fabric
  5831. * @constructor
  5832. */
  5833. function Intersection(status) {
  5834. this.status = status;
  5835. this.points = [];
  5836. }
  5837. fabric.Intersection = Intersection;
  5838. fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {
  5839. constructor: Intersection,
  5840. /**
  5841. * Appends a point to intersection
  5842. * @param {fabric.Point} point
  5843. * @return {fabric.Intersection} thisArg
  5844. * @chainable
  5845. */
  5846. appendPoint: function (point) {
  5847. this.points.push(point);
  5848. return this;
  5849. },
  5850. /**
  5851. * Appends points to intersection
  5852. * @param {Array} points
  5853. * @return {fabric.Intersection} thisArg
  5854. * @chainable
  5855. */
  5856. appendPoints: function (points) {
  5857. this.points = this.points.concat(points);
  5858. return this;
  5859. }
  5860. };
  5861. /**
  5862. * Checks if one line intersects another
  5863. * TODO: rename in intersectSegmentSegment
  5864. * @static
  5865. * @param {fabric.Point} a1
  5866. * @param {fabric.Point} a2
  5867. * @param {fabric.Point} b1
  5868. * @param {fabric.Point} b2
  5869. * @return {fabric.Intersection}
  5870. */
  5871. fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {
  5872. var result,
  5873. uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
  5874. ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
  5875. uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
  5876. if (uB !== 0) {
  5877. var ua = uaT / uB,
  5878. ub = ubT / uB;
  5879. if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
  5880. result = new Intersection('Intersection');
  5881. result.appendPoint(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
  5882. }
  5883. else {
  5884. result = new Intersection();
  5885. }
  5886. }
  5887. else {
  5888. if (uaT === 0 || ubT === 0) {
  5889. result = new Intersection('Coincident');
  5890. }
  5891. else {
  5892. result = new Intersection('Parallel');
  5893. }
  5894. }
  5895. return result;
  5896. };
  5897. /**
  5898. * Checks if line intersects polygon
  5899. * TODO: rename in intersectSegmentPolygon
  5900. * fix detection of coincident
  5901. * @static
  5902. * @param {fabric.Point} a1
  5903. * @param {fabric.Point} a2
  5904. * @param {Array} points
  5905. * @return {fabric.Intersection}
  5906. */
  5907. fabric.Intersection.intersectLinePolygon = function(a1, a2, points) {
  5908. var result = new Intersection(),
  5909. length = points.length,
  5910. b1, b2, inter, i;
  5911. for (i = 0; i < length; i++) {
  5912. b1 = points[i];
  5913. b2 = points[(i + 1) % length];
  5914. inter = Intersection.intersectLineLine(a1, a2, b1, b2);
  5915. result.appendPoints(inter.points);
  5916. }
  5917. if (result.points.length > 0) {
  5918. result.status = 'Intersection';
  5919. }
  5920. return result;
  5921. };
  5922. /**
  5923. * Checks if polygon intersects another polygon
  5924. * @static
  5925. * @param {Array} points1
  5926. * @param {Array} points2
  5927. * @return {fabric.Intersection}
  5928. */
  5929. fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {
  5930. var result = new Intersection(),
  5931. length = points1.length, i;
  5932. for (i = 0; i < length; i++) {
  5933. var a1 = points1[i],
  5934. a2 = points1[(i + 1) % length],
  5935. inter = Intersection.intersectLinePolygon(a1, a2, points2);
  5936. result.appendPoints(inter.points);
  5937. }
  5938. if (result.points.length > 0) {
  5939. result.status = 'Intersection';
  5940. }
  5941. return result;
  5942. };
  5943. /**
  5944. * Checks if polygon intersects rectangle
  5945. * @static
  5946. * @param {Array} points
  5947. * @param {fabric.Point} r1
  5948. * @param {fabric.Point} r2
  5949. * @return {fabric.Intersection}
  5950. */
  5951. fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {
  5952. var min = r1.min(r2),
  5953. max = r1.max(r2),
  5954. topRight = new fabric.Point(max.x, min.y),
  5955. bottomLeft = new fabric.Point(min.x, max.y),
  5956. inter1 = Intersection.intersectLinePolygon(min, topRight, points),
  5957. inter2 = Intersection.intersectLinePolygon(topRight, max, points),
  5958. inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),
  5959. inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),
  5960. result = new Intersection();
  5961. result.appendPoints(inter1.points);
  5962. result.appendPoints(inter2.points);
  5963. result.appendPoints(inter3.points);
  5964. result.appendPoints(inter4.points);
  5965. if (result.points.length > 0) {
  5966. result.status = 'Intersection';
  5967. }
  5968. return result;
  5969. };
  5970. })(typeof exports !== 'undefined' ? exports : this);
  5971. (function(global) {
  5972. 'use strict';
  5973. var fabric = global.fabric || (global.fabric = { });
  5974. if (fabric.Color) {
  5975. fabric.warn('fabric.Color is already defined.');
  5976. return;
  5977. }
  5978. /**
  5979. * Color class
  5980. * The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;
  5981. * {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.
  5982. *
  5983. * @class fabric.Color
  5984. * @param {String} color optional in hex or rgb(a) or hsl format or from known color list
  5985. * @return {fabric.Color} thisArg
  5986. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}
  5987. */
  5988. function Color(color) {
  5989. if (!color) {
  5990. this.setSource([0, 0, 0, 1]);
  5991. }
  5992. else {
  5993. this._tryParsingColor(color);
  5994. }
  5995. }
  5996. fabric.Color = Color;
  5997. fabric.Color.prototype = /** @lends fabric.Color.prototype */ {
  5998. /**
  5999. * @private
  6000. * @param {String|Array} color Color value to parse
  6001. */
  6002. _tryParsingColor: function(color) {
  6003. var source;
  6004. if (color in Color.colorNameMap) {
  6005. color = Color.colorNameMap[color];
  6006. }
  6007. if (color === 'transparent') {
  6008. source = [255, 255, 255, 0];
  6009. }
  6010. if (!source) {
  6011. source = Color.sourceFromHex(color);
  6012. }
  6013. if (!source) {
  6014. source = Color.sourceFromRgb(color);
  6015. }
  6016. if (!source) {
  6017. source = Color.sourceFromHsl(color);
  6018. }
  6019. if (!source) {
  6020. //if color is not recognize let's make black as canvas does
  6021. source = [0, 0, 0, 1];
  6022. }
  6023. if (source) {
  6024. this.setSource(source);
  6025. }
  6026. },
  6027. /**
  6028. * 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>
  6029. * @private
  6030. * @param {Number} r Red color value
  6031. * @param {Number} g Green color value
  6032. * @param {Number} b Blue color value
  6033. * @return {Array} Hsl color
  6034. */
  6035. _rgbToHsl: function(r, g, b) {
  6036. r /= 255; g /= 255; b /= 255;
  6037. var h, s, l,
  6038. max = fabric.util.array.max([r, g, b]),
  6039. min = fabric.util.array.min([r, g, b]);
  6040. l = (max + min) / 2;
  6041. if (max === min) {
  6042. h = s = 0; // achromatic
  6043. }
  6044. else {
  6045. var d = max - min;
  6046. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  6047. switch (max) {
  6048. case r:
  6049. h = (g - b) / d + (g < b ? 6 : 0);
  6050. break;
  6051. case g:
  6052. h = (b - r) / d + 2;
  6053. break;
  6054. case b:
  6055. h = (r - g) / d + 4;
  6056. break;
  6057. }
  6058. h /= 6;
  6059. }
  6060. return [
  6061. Math.round(h * 360),
  6062. Math.round(s * 100),
  6063. Math.round(l * 100)
  6064. ];
  6065. },
  6066. /**
  6067. * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  6068. * @return {Array}
  6069. */
  6070. getSource: function() {
  6071. return this._source;
  6072. },
  6073. /**
  6074. * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  6075. * @param {Array} source
  6076. */
  6077. setSource: function(source) {
  6078. this._source = source;
  6079. },
  6080. /**
  6081. * Returns color representation in RGB format
  6082. * @return {String} ex: rgb(0-255,0-255,0-255)
  6083. */
  6084. toRgb: function() {
  6085. var source = this.getSource();
  6086. return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';
  6087. },
  6088. /**
  6089. * Returns color representation in RGBA format
  6090. * @return {String} ex: rgba(0-255,0-255,0-255,0-1)
  6091. */
  6092. toRgba: function() {
  6093. var source = this.getSource();
  6094. return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';
  6095. },
  6096. /**
  6097. * Returns color representation in HSL format
  6098. * @return {String} ex: hsl(0-360,0%-100%,0%-100%)
  6099. */
  6100. toHsl: function() {
  6101. var source = this.getSource(),
  6102. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  6103. return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';
  6104. },
  6105. /**
  6106. * Returns color representation in HSLA format
  6107. * @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)
  6108. */
  6109. toHsla: function() {
  6110. var source = this.getSource(),
  6111. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  6112. return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';
  6113. },
  6114. /**
  6115. * Returns color representation in HEX format
  6116. * @return {String} ex: FF5555
  6117. */
  6118. toHex: function() {
  6119. var source = this.getSource(), r, g, b;
  6120. r = source[0].toString(16);
  6121. r = (r.length === 1) ? ('0' + r) : r;
  6122. g = source[1].toString(16);
  6123. g = (g.length === 1) ? ('0' + g) : g;
  6124. b = source[2].toString(16);
  6125. b = (b.length === 1) ? ('0' + b) : b;
  6126. return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();
  6127. },
  6128. /**
  6129. * Returns color representation in HEXA format
  6130. * @return {String} ex: FF5555CC
  6131. */
  6132. toHexa: function() {
  6133. var source = this.getSource(), a;
  6134. a = Math.round(source[3] * 255);
  6135. a = a.toString(16);
  6136. a = (a.length === 1) ? ('0' + a) : a;
  6137. return this.toHex() + a.toUpperCase();
  6138. },
  6139. /**
  6140. * Gets value of alpha channel for this color
  6141. * @return {Number} 0-1
  6142. */
  6143. getAlpha: function() {
  6144. return this.getSource()[3];
  6145. },
  6146. /**
  6147. * Sets value of alpha channel for this color
  6148. * @param {Number} alpha Alpha value 0-1
  6149. * @return {fabric.Color} thisArg
  6150. */
  6151. setAlpha: function(alpha) {
  6152. var source = this.getSource();
  6153. source[3] = alpha;
  6154. this.setSource(source);
  6155. return this;
  6156. },
  6157. /**
  6158. * Transforms color to its grayscale representation
  6159. * @return {fabric.Color} thisArg
  6160. */
  6161. toGrayscale: function() {
  6162. var source = this.getSource(),
  6163. average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),
  6164. currentAlpha = source[3];
  6165. this.setSource([average, average, average, currentAlpha]);
  6166. return this;
  6167. },
  6168. /**
  6169. * Transforms color to its black and white representation
  6170. * @param {Number} threshold
  6171. * @return {fabric.Color} thisArg
  6172. */
  6173. toBlackWhite: function(threshold) {
  6174. var source = this.getSource(),
  6175. average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),
  6176. currentAlpha = source[3];
  6177. threshold = threshold || 127;
  6178. average = (Number(average) < Number(threshold)) ? 0 : 255;
  6179. this.setSource([average, average, average, currentAlpha]);
  6180. return this;
  6181. },
  6182. /**
  6183. * Overlays color with another color
  6184. * @param {String|fabric.Color} otherColor
  6185. * @return {fabric.Color} thisArg
  6186. */
  6187. overlayWith: function(otherColor) {
  6188. if (!(otherColor instanceof Color)) {
  6189. otherColor = new Color(otherColor);
  6190. }
  6191. var result = [],
  6192. alpha = this.getAlpha(),
  6193. otherAlpha = 0.5,
  6194. source = this.getSource(),
  6195. otherSource = otherColor.getSource(), i;
  6196. for (i = 0; i < 3; i++) {
  6197. result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));
  6198. }
  6199. result[3] = alpha;
  6200. this.setSource(result);
  6201. return this;
  6202. }
  6203. };
  6204. /**
  6205. * 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))
  6206. * @static
  6207. * @field
  6208. * @memberOf fabric.Color
  6209. */
  6210. // eslint-disable-next-line max-len
  6211. 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;
  6212. /**
  6213. * 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 ))
  6214. * @static
  6215. * @field
  6216. * @memberOf fabric.Color
  6217. */
  6218. 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;
  6219. /**
  6220. * Regex matching color in HEX format (ex: #FF5544CC, #FF5555, 010155, aff)
  6221. * @static
  6222. * @field
  6223. * @memberOf fabric.Color
  6224. */
  6225. fabric.Color.reHex = /^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i;
  6226. /**
  6227. * Map of the 148 color names with HEX code
  6228. * @static
  6229. * @field
  6230. * @memberOf fabric.Color
  6231. * @see: https://www.w3.org/TR/css3-color/#svg-color
  6232. */
  6233. fabric.Color.colorNameMap = {
  6234. aliceblue: '#F0F8FF',
  6235. antiquewhite: '#FAEBD7',
  6236. aqua: '#00FFFF',
  6237. aquamarine: '#7FFFD4',
  6238. azure: '#F0FFFF',
  6239. beige: '#F5F5DC',
  6240. bisque: '#FFE4C4',
  6241. black: '#000000',
  6242. blanchedalmond: '#FFEBCD',
  6243. blue: '#0000FF',
  6244. blueviolet: '#8A2BE2',
  6245. brown: '#A52A2A',
  6246. burlywood: '#DEB887',
  6247. cadetblue: '#5F9EA0',
  6248. chartreuse: '#7FFF00',
  6249. chocolate: '#D2691E',
  6250. coral: '#FF7F50',
  6251. cornflowerblue: '#6495ED',
  6252. cornsilk: '#FFF8DC',
  6253. crimson: '#DC143C',
  6254. cyan: '#00FFFF',
  6255. darkblue: '#00008B',
  6256. darkcyan: '#008B8B',
  6257. darkgoldenrod: '#B8860B',
  6258. darkgray: '#A9A9A9',
  6259. darkgrey: '#A9A9A9',
  6260. darkgreen: '#006400',
  6261. darkkhaki: '#BDB76B',
  6262. darkmagenta: '#8B008B',
  6263. darkolivegreen: '#556B2F',
  6264. darkorange: '#FF8C00',
  6265. darkorchid: '#9932CC',
  6266. darkred: '#8B0000',
  6267. darksalmon: '#E9967A',
  6268. darkseagreen: '#8FBC8F',
  6269. darkslateblue: '#483D8B',
  6270. darkslategray: '#2F4F4F',
  6271. darkslategrey: '#2F4F4F',
  6272. darkturquoise: '#00CED1',
  6273. darkviolet: '#9400D3',
  6274. deeppink: '#FF1493',
  6275. deepskyblue: '#00BFFF',
  6276. dimgray: '#696969',
  6277. dimgrey: '#696969',
  6278. dodgerblue: '#1E90FF',
  6279. firebrick: '#B22222',
  6280. floralwhite: '#FFFAF0',
  6281. forestgreen: '#228B22',
  6282. fuchsia: '#FF00FF',
  6283. gainsboro: '#DCDCDC',
  6284. ghostwhite: '#F8F8FF',
  6285. gold: '#FFD700',
  6286. goldenrod: '#DAA520',
  6287. gray: '#808080',
  6288. grey: '#808080',
  6289. green: '#008000',
  6290. greenyellow: '#ADFF2F',
  6291. honeydew: '#F0FFF0',
  6292. hotpink: '#FF69B4',
  6293. indianred: '#CD5C5C',
  6294. indigo: '#4B0082',
  6295. ivory: '#FFFFF0',
  6296. khaki: '#F0E68C',
  6297. lavender: '#E6E6FA',
  6298. lavenderblush: '#FFF0F5',
  6299. lawngreen: '#7CFC00',
  6300. lemonchiffon: '#FFFACD',
  6301. lightblue: '#ADD8E6',
  6302. lightcoral: '#F08080',
  6303. lightcyan: '#E0FFFF',
  6304. lightgoldenrodyellow: '#FAFAD2',
  6305. lightgray: '#D3D3D3',
  6306. lightgrey: '#D3D3D3',
  6307. lightgreen: '#90EE90',
  6308. lightpink: '#FFB6C1',
  6309. lightsalmon: '#FFA07A',
  6310. lightseagreen: '#20B2AA',
  6311. lightskyblue: '#87CEFA',
  6312. lightslategray: '#778899',
  6313. lightslategrey: '#778899',
  6314. lightsteelblue: '#B0C4DE',
  6315. lightyellow: '#FFFFE0',
  6316. lime: '#00FF00',
  6317. limegreen: '#32CD32',
  6318. linen: '#FAF0E6',
  6319. magenta: '#FF00FF',
  6320. maroon: '#800000',
  6321. mediumaquamarine: '#66CDAA',
  6322. mediumblue: '#0000CD',
  6323. mediumorchid: '#BA55D3',
  6324. mediumpurple: '#9370DB',
  6325. mediumseagreen: '#3CB371',
  6326. mediumslateblue: '#7B68EE',
  6327. mediumspringgreen: '#00FA9A',
  6328. mediumturquoise: '#48D1CC',
  6329. mediumvioletred: '#C71585',
  6330. midnightblue: '#191970',
  6331. mintcream: '#F5FFFA',
  6332. mistyrose: '#FFE4E1',
  6333. moccasin: '#FFE4B5',
  6334. navajowhite: '#FFDEAD',
  6335. navy: '#000080',
  6336. oldlace: '#FDF5E6',
  6337. olive: '#808000',
  6338. olivedrab: '#6B8E23',
  6339. orange: '#FFA500',
  6340. orangered: '#FF4500',
  6341. orchid: '#DA70D6',
  6342. palegoldenrod: '#EEE8AA',
  6343. palegreen: '#98FB98',
  6344. paleturquoise: '#AFEEEE',
  6345. palevioletred: '#DB7093',
  6346. papayawhip: '#FFEFD5',
  6347. peachpuff: '#FFDAB9',
  6348. peru: '#CD853F',
  6349. pink: '#FFC0CB',
  6350. plum: '#DDA0DD',
  6351. powderblue: '#B0E0E6',
  6352. purple: '#800080',
  6353. rebeccapurple: '#663399',
  6354. red: '#FF0000',
  6355. rosybrown: '#BC8F8F',
  6356. royalblue: '#4169E1',
  6357. saddlebrown: '#8B4513',
  6358. salmon: '#FA8072',
  6359. sandybrown: '#F4A460',
  6360. seagreen: '#2E8B57',
  6361. seashell: '#FFF5EE',
  6362. sienna: '#A0522D',
  6363. silver: '#C0C0C0',
  6364. skyblue: '#87CEEB',
  6365. slateblue: '#6A5ACD',
  6366. slategray: '#708090',
  6367. slategrey: '#708090',
  6368. snow: '#FFFAFA',
  6369. springgreen: '#00FF7F',
  6370. steelblue: '#4682B4',
  6371. tan: '#D2B48C',
  6372. teal: '#008080',
  6373. thistle: '#D8BFD8',
  6374. tomato: '#FF6347',
  6375. turquoise: '#40E0D0',
  6376. violet: '#EE82EE',
  6377. wheat: '#F5DEB3',
  6378. white: '#FFFFFF',
  6379. whitesmoke: '#F5F5F5',
  6380. yellow: '#FFFF00',
  6381. yellowgreen: '#9ACD32'
  6382. };
  6383. /**
  6384. * @private
  6385. * @param {Number} p
  6386. * @param {Number} q
  6387. * @param {Number} t
  6388. * @return {Number}
  6389. */
  6390. function hue2rgb(p, q, t) {
  6391. if (t < 0) {
  6392. t += 1;
  6393. }
  6394. if (t > 1) {
  6395. t -= 1;
  6396. }
  6397. if (t < 1 / 6) {
  6398. return p + (q - p) * 6 * t;
  6399. }
  6400. if (t < 1 / 2) {
  6401. return q;
  6402. }
  6403. if (t < 2 / 3) {
  6404. return p + (q - p) * (2 / 3 - t) * 6;
  6405. }
  6406. return p;
  6407. }
  6408. /**
  6409. * Returns new color object, when given a color in RGB format
  6410. * @memberOf fabric.Color
  6411. * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
  6412. * @return {fabric.Color}
  6413. */
  6414. fabric.Color.fromRgb = function(color) {
  6415. return Color.fromSource(Color.sourceFromRgb(color));
  6416. };
  6417. /**
  6418. * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
  6419. * @memberOf fabric.Color
  6420. * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
  6421. * @return {Array} source
  6422. */
  6423. fabric.Color.sourceFromRgb = function(color) {
  6424. var match = color.match(Color.reRGBa);
  6425. if (match) {
  6426. var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),
  6427. g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),
  6428. b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
  6429. return [
  6430. parseInt(r, 10),
  6431. parseInt(g, 10),
  6432. parseInt(b, 10),
  6433. match[4] ? parseFloat(match[4]) : 1
  6434. ];
  6435. }
  6436. };
  6437. /**
  6438. * Returns new color object, when given a color in RGBA format
  6439. * @static
  6440. * @function
  6441. * @memberOf fabric.Color
  6442. * @param {String} color
  6443. * @return {fabric.Color}
  6444. */
  6445. fabric.Color.fromRgba = Color.fromRgb;
  6446. /**
  6447. * Returns new color object, when given a color in HSL format
  6448. * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
  6449. * @memberOf fabric.Color
  6450. * @return {fabric.Color}
  6451. */
  6452. fabric.Color.fromHsl = function(color) {
  6453. return Color.fromSource(Color.sourceFromHsl(color));
  6454. };
  6455. /**
  6456. * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
  6457. * 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>
  6458. * @memberOf fabric.Color
  6459. * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
  6460. * @return {Array} source
  6461. * @see http://http://www.w3.org/TR/css3-color/#hsl-color
  6462. */
  6463. fabric.Color.sourceFromHsl = function(color) {
  6464. var match = color.match(Color.reHSLa);
  6465. if (!match) {
  6466. return;
  6467. }
  6468. var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,
  6469. s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),
  6470. l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),
  6471. r, g, b;
  6472. if (s === 0) {
  6473. r = g = b = l;
  6474. }
  6475. else {
  6476. var q = l <= 0.5 ? l * (s + 1) : l + s - l * s,
  6477. p = l * 2 - q;
  6478. r = hue2rgb(p, q, h + 1 / 3);
  6479. g = hue2rgb(p, q, h);
  6480. b = hue2rgb(p, q, h - 1 / 3);
  6481. }
  6482. return [
  6483. Math.round(r * 255),
  6484. Math.round(g * 255),
  6485. Math.round(b * 255),
  6486. match[4] ? parseFloat(match[4]) : 1
  6487. ];
  6488. };
  6489. /**
  6490. * Returns new color object, when given a color in HSLA format
  6491. * @static
  6492. * @function
  6493. * @memberOf fabric.Color
  6494. * @param {String} color
  6495. * @return {fabric.Color}
  6496. */
  6497. fabric.Color.fromHsla = Color.fromHsl;
  6498. /**
  6499. * Returns new color object, when given a color in HEX format
  6500. * @static
  6501. * @memberOf fabric.Color
  6502. * @param {String} color Color value ex: FF5555
  6503. * @return {fabric.Color}
  6504. */
  6505. fabric.Color.fromHex = function(color) {
  6506. return Color.fromSource(Color.sourceFromHex(color));
  6507. };
  6508. /**
  6509. * Returns array representation (ex: [100, 100, 200, 1]) of a color that's in HEX format
  6510. * @static
  6511. * @memberOf fabric.Color
  6512. * @param {String} color ex: FF5555 or FF5544CC (RGBa)
  6513. * @return {Array} source
  6514. */
  6515. fabric.Color.sourceFromHex = function(color) {
  6516. if (color.match(Color.reHex)) {
  6517. var value = color.slice(color.indexOf('#') + 1),
  6518. isShortNotation = (value.length === 3 || value.length === 4),
  6519. isRGBa = (value.length === 8 || value.length === 4),
  6520. r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),
  6521. g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),
  6522. b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6),
  6523. a = isRGBa ? (isShortNotation ? (value.charAt(3) + value.charAt(3)) : value.substring(6, 8)) : 'FF';
  6524. return [
  6525. parseInt(r, 16),
  6526. parseInt(g, 16),
  6527. parseInt(b, 16),
  6528. parseFloat((parseInt(a, 16) / 255).toFixed(2))
  6529. ];
  6530. }
  6531. };
  6532. /**
  6533. * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
  6534. * @static
  6535. * @memberOf fabric.Color
  6536. * @param {Array} source
  6537. * @return {fabric.Color}
  6538. */
  6539. fabric.Color.fromSource = function(source) {
  6540. var oColor = new Color();
  6541. oColor.setSource(source);
  6542. return oColor;
  6543. };
  6544. })(typeof exports !== 'undefined' ? exports : this);
  6545. (function(global) {
  6546. 'use strict';
  6547. var fabric = global.fabric || (global.fabric = { }),
  6548. scaleMap = ['e', 'se', 's', 'sw', 'w', 'nw', 'n', 'ne', 'e'],
  6549. skewMap = ['ns', 'nesw', 'ew', 'nwse'],
  6550. controls = {},
  6551. LEFT = 'left', TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', CENTER = 'center',
  6552. opposite = {
  6553. top: BOTTOM,
  6554. bottom: TOP,
  6555. left: RIGHT,
  6556. right: LEFT,
  6557. center: CENTER,
  6558. }, radiansToDegrees = fabric.util.radiansToDegrees,
  6559. sign = (Math.sign || function(x) { return ((x > 0) - (x < 0)) || +x; });
  6560. /**
  6561. * Combine control position and object angle to find the control direction compared
  6562. * to the object center.
  6563. * @param {fabric.Object} fabricObject the fabric object for which we are rendering controls
  6564. * @param {fabric.Control} control the control class
  6565. * @return {Number} 0 - 7 a quadrant number
  6566. */
  6567. function findCornerQuadrant(fabricObject, control) {
  6568. var cornerAngle = fabricObject.angle + radiansToDegrees(Math.atan2(control.y, control.x)) + 360;
  6569. return Math.round((cornerAngle % 360) / 45);
  6570. }
  6571. function fireEvent(eventName, options) {
  6572. var target = options.transform.target,
  6573. canvas = target.canvas,
  6574. canvasOptions = fabric.util.object.clone(options);
  6575. canvasOptions.target = target;
  6576. canvas && canvas.fire('object:' + eventName, canvasOptions);
  6577. target.fire(eventName, options);
  6578. }
  6579. /**
  6580. * Inspect event and fabricObject properties to understand if the scaling action
  6581. * @param {Event} eventData from the user action
  6582. * @param {fabric.Object} fabricObject the fabric object about to scale
  6583. * @return {Boolean} true if scale is proportional
  6584. */
  6585. function scaleIsProportional(eventData, fabricObject) {
  6586. var canvas = fabricObject.canvas, uniScaleKey = canvas.uniScaleKey,
  6587. uniformIsToggled = eventData[uniScaleKey];
  6588. return (canvas.uniformScaling && !uniformIsToggled) ||
  6589. (!canvas.uniformScaling && uniformIsToggled);
  6590. }
  6591. /**
  6592. * Checks if transform is centered
  6593. * @param {Object} transform transform data
  6594. * @return {Boolean} true if transform is centered
  6595. */
  6596. function isTransformCentered(transform) {
  6597. return transform.originX === CENTER && transform.originY === CENTER;
  6598. }
  6599. /**
  6600. * Inspect fabricObject to understand if the current scaling action is allowed
  6601. * @param {fabric.Object} fabricObject the fabric object about to scale
  6602. * @param {String} by 'x' or 'y' or ''
  6603. * @param {Boolean} scaleProportionally true if we are trying to scale proportionally
  6604. * @return {Boolean} true if scaling is not allowed at current conditions
  6605. */
  6606. function scalingIsForbidden(fabricObject, by, scaleProportionally) {
  6607. var lockX = fabricObject.lockScalingX, lockY = fabricObject.lockScalingY;
  6608. if (lockX && lockY) {
  6609. return true;
  6610. }
  6611. if (!by && (lockX || lockY) && scaleProportionally) {
  6612. return true;
  6613. }
  6614. if (lockX && by === 'x') {
  6615. return true;
  6616. }
  6617. if (lockY && by === 'y') {
  6618. return true;
  6619. }
  6620. return false;
  6621. }
  6622. /**
  6623. * return the correct cursor style for the scale action
  6624. * @param {Event} eventData the javascript event that is causing the scale
  6625. * @param {fabric.Control} control the control that is interested in the action
  6626. * @param {fabric.Object} fabricObject the fabric object that is interested in the action
  6627. * @return {String} a valid css string for the cursor
  6628. */
  6629. function scaleCursorStyleHandler(eventData, control, fabricObject) {
  6630. var notAllowed = 'not-allowed',
  6631. scaleProportionally = scaleIsProportional(eventData, fabricObject),
  6632. by = '';
  6633. if (control.x !== 0 && control.y === 0) {
  6634. by = 'x';
  6635. }
  6636. else if (control.x === 0 && control.y !== 0) {
  6637. by = 'y';
  6638. }
  6639. if (scalingIsForbidden(fabricObject, by, scaleProportionally)) {
  6640. return notAllowed;
  6641. }
  6642. var n = findCornerQuadrant(fabricObject, control);
  6643. return scaleMap[n] + '-resize';
  6644. }
  6645. /**
  6646. * return the correct cursor style for the skew action
  6647. * @param {Event} eventData the javascript event that is causing the scale
  6648. * @param {fabric.Control} control the control that is interested in the action
  6649. * @param {fabric.Object} fabricObject the fabric object that is interested in the action
  6650. * @return {String} a valid css string for the cursor
  6651. */
  6652. function skewCursorStyleHandler(eventData, control, fabricObject) {
  6653. var notAllowed = 'not-allowed';
  6654. if (control.x !== 0 && fabricObject.lockSkewingY) {
  6655. return notAllowed;
  6656. }
  6657. if (control.y !== 0 && fabricObject.lockSkewingX) {
  6658. return notAllowed;
  6659. }
  6660. var n = findCornerQuadrant(fabricObject, control) % 4;
  6661. return skewMap[n] + '-resize';
  6662. }
  6663. /**
  6664. * Combine skew and scale style handlers to cover fabric standard use case
  6665. * @param {Event} eventData the javascript event that is causing the scale
  6666. * @param {fabric.Control} control the control that is interested in the action
  6667. * @param {fabric.Object} fabricObject the fabric object that is interested in the action
  6668. * @return {String} a valid css string for the cursor
  6669. */
  6670. function scaleSkewCursorStyleHandler(eventData, control, fabricObject) {
  6671. if (eventData[fabricObject.canvas.altActionKey]) {
  6672. return controls.skewCursorStyleHandler(eventData, control, fabricObject);
  6673. }
  6674. return controls.scaleCursorStyleHandler(eventData, control, fabricObject);
  6675. }
  6676. /**
  6677. * Inspect event, control and fabricObject to return the correct action name
  6678. * @param {Event} eventData the javascript event that is causing the scale
  6679. * @param {fabric.Control} control the control that is interested in the action
  6680. * @param {fabric.Object} fabricObject the fabric object that is interested in the action
  6681. * @return {String} an action name
  6682. */
  6683. function scaleOrSkewActionName(eventData, control, fabricObject) {
  6684. var isAlternative = eventData[fabricObject.canvas.altActionKey];
  6685. if (control.x === 0) {
  6686. // then is scaleY or skewX
  6687. return isAlternative ? 'skewX' : 'scaleY';
  6688. }
  6689. if (control.y === 0) {
  6690. // then is scaleY or skewX
  6691. return isAlternative ? 'skewY' : 'scaleX';
  6692. }
  6693. }
  6694. /**
  6695. * Find the correct style for the control that is used for rotation.
  6696. * this function is very simple and it just take care of not-allowed or standard cursor
  6697. * @param {Event} eventData the javascript event that is causing the scale
  6698. * @param {fabric.Control} control the control that is interested in the action
  6699. * @param {fabric.Object} fabricObject the fabric object that is interested in the action
  6700. * @return {String} a valid css string for the cursor
  6701. */
  6702. function rotationStyleHandler(eventData, control, fabricObject) {
  6703. if (fabricObject.lockRotation) {
  6704. return 'not-allowed';
  6705. }
  6706. return control.cursorStyle;
  6707. }
  6708. function commonEventInfo(eventData, transform, x, y) {
  6709. return {
  6710. e: eventData,
  6711. transform: transform,
  6712. pointer: {
  6713. x: x,
  6714. y: y,
  6715. }
  6716. };
  6717. }
  6718. /**
  6719. * Wrap an action handler with saving/restoring object position on the transform.
  6720. * this is the code that permits to objects to keep their position while transforming.
  6721. * @param {Function} actionHandler the function to wrap
  6722. * @return {Function} a function with an action handler signature
  6723. */
  6724. function wrapWithFixedAnchor(actionHandler) {
  6725. return function(eventData, transform, x, y) {
  6726. var target = transform.target, centerPoint = target.getCenterPoint(),
  6727. constraint = target.translateToOriginPoint(centerPoint, transform.originX, transform.originY),
  6728. actionPerformed = actionHandler(eventData, transform, x, y);
  6729. target.setPositionByOrigin(constraint, transform.originX, transform.originY);
  6730. return actionPerformed;
  6731. };
  6732. }
  6733. /**
  6734. * Wrap an action handler with firing an event if the action is performed
  6735. * @param {Function} actionHandler the function to wrap
  6736. * @return {Function} a function with an action handler signature
  6737. */
  6738. function wrapWithFireEvent(eventName, actionHandler) {
  6739. return function(eventData, transform, x, y) {
  6740. var actionPerformed = actionHandler(eventData, transform, x, y);
  6741. if (actionPerformed) {
  6742. fireEvent(eventName, commonEventInfo(eventData, transform, x, y));
  6743. }
  6744. return actionPerformed;
  6745. };
  6746. }
  6747. /**
  6748. * Transforms a point described by x and y in a distance from the top left corner of the object
  6749. * bounding box.
  6750. * @param {Object} transform
  6751. * @param {String} originX
  6752. * @param {String} originY
  6753. * @param {number} x
  6754. * @param {number} y
  6755. * @return {Fabric.Point} the normalized point
  6756. */
  6757. function getLocalPoint(transform, originX, originY, x, y) {
  6758. var target = transform.target,
  6759. control = target.controls[transform.corner],
  6760. zoom = target.canvas.getZoom(),
  6761. padding = target.padding / zoom,
  6762. localPoint = target.toLocalPoint(new fabric.Point(x, y), originX, originY);
  6763. if (localPoint.x >= padding) {
  6764. localPoint.x -= padding;
  6765. }
  6766. if (localPoint.x <= -padding) {
  6767. localPoint.x += padding;
  6768. }
  6769. if (localPoint.y >= padding) {
  6770. localPoint.y -= padding;
  6771. }
  6772. if (localPoint.y <= padding) {
  6773. localPoint.y += padding;
  6774. }
  6775. localPoint.x -= control.offsetX;
  6776. localPoint.y -= control.offsetY;
  6777. return localPoint;
  6778. }
  6779. /**
  6780. * Detect if the fabric object is flipped on one side.
  6781. * @param {fabric.Object} target
  6782. * @return {Boolean} true if one flip, but not two.
  6783. */
  6784. function targetHasOneFlip(target) {
  6785. return target.flipX !== target.flipY;
  6786. }
  6787. /**
  6788. * Utility function to compensate the scale factor when skew is applied on both axes
  6789. * @private
  6790. */
  6791. function compensateScaleForSkew(target, oppositeSkew, scaleToCompensate, axis, reference) {
  6792. if (target[oppositeSkew] !== 0) {
  6793. var newDim = target._getTransformedDimensions()[axis];
  6794. var newValue = reference / newDim * target[scaleToCompensate];
  6795. target.set(scaleToCompensate, newValue);
  6796. }
  6797. }
  6798. /**
  6799. * Action handler for skewing on the X axis
  6800. * @private
  6801. */
  6802. function skewObjectX(eventData, transform, x, y) {
  6803. var target = transform.target,
  6804. // find how big the object would be, if there was no skewX. takes in account scaling
  6805. dimNoSkew = target._getTransformedDimensions(0, target.skewY),
  6806. localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y),
  6807. // the mouse is in the center of the object, and we want it to stay there.
  6808. // so the object will grow twice as much as the mouse.
  6809. // this makes the skew growth to localPoint * 2 - dimNoSkew.
  6810. totalSkewSize = Math.abs(localPoint.x * 2) - dimNoSkew.x,
  6811. currentSkew = target.skewX, newSkew;
  6812. if (totalSkewSize < 2) {
  6813. // let's make it easy to go back to position 0.
  6814. newSkew = 0;
  6815. }
  6816. else {
  6817. newSkew = radiansToDegrees(
  6818. Math.atan2((totalSkewSize / target.scaleX), (dimNoSkew.y / target.scaleY))
  6819. );
  6820. // now we have to find the sign of the skew.
  6821. // it mostly depend on the origin of transformation.
  6822. if (transform.originX === LEFT && transform.originY === BOTTOM) {
  6823. newSkew = -newSkew;
  6824. }
  6825. if (transform.originX === RIGHT && transform.originY === TOP) {
  6826. newSkew = -newSkew;
  6827. }
  6828. if (targetHasOneFlip(target)) {
  6829. newSkew = -newSkew;
  6830. }
  6831. }
  6832. var hasSkewed = currentSkew !== newSkew;
  6833. if (hasSkewed) {
  6834. var dimBeforeSkewing = target._getTransformedDimensions().y;
  6835. target.set('skewX', newSkew);
  6836. compensateScaleForSkew(target, 'skewY', 'scaleY', 'y', dimBeforeSkewing);
  6837. }
  6838. return hasSkewed;
  6839. }
  6840. /**
  6841. * Action handler for skewing on the Y axis
  6842. * @private
  6843. */
  6844. function skewObjectY(eventData, transform, x, y) {
  6845. var target = transform.target,
  6846. // find how big the object would be, if there was no skewX. takes in account scaling
  6847. dimNoSkew = target._getTransformedDimensions(target.skewX, 0),
  6848. localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y),
  6849. // the mouse is in the center of the object, and we want it to stay there.
  6850. // so the object will grow twice as much as the mouse.
  6851. // this makes the skew growth to localPoint * 2 - dimNoSkew.
  6852. totalSkewSize = Math.abs(localPoint.y * 2) - dimNoSkew.y,
  6853. currentSkew = target.skewY, newSkew;
  6854. if (totalSkewSize < 2) {
  6855. // let's make it easy to go back to position 0.
  6856. newSkew = 0;
  6857. }
  6858. else {
  6859. newSkew = radiansToDegrees(
  6860. Math.atan2((totalSkewSize / target.scaleY), (dimNoSkew.x / target.scaleX))
  6861. );
  6862. // now we have to find the sign of the skew.
  6863. // it mostly depend on the origin of transformation.
  6864. if (transform.originX === LEFT && transform.originY === BOTTOM) {
  6865. newSkew = -newSkew;
  6866. }
  6867. if (transform.originX === RIGHT && transform.originY === TOP) {
  6868. newSkew = -newSkew;
  6869. }
  6870. if (targetHasOneFlip(target)) {
  6871. newSkew = -newSkew;
  6872. }
  6873. }
  6874. var hasSkewed = currentSkew !== newSkew;
  6875. if (hasSkewed) {
  6876. var dimBeforeSkewing = target._getTransformedDimensions().x;
  6877. target.set('skewY', newSkew);
  6878. compensateScaleForSkew(target, 'skewX', 'scaleX', 'x', dimBeforeSkewing);
  6879. }
  6880. return hasSkewed;
  6881. }
  6882. /**
  6883. * Wrapped Action handler for skewing on the Y axis, takes care of the
  6884. * skew direction and determine the correct transform origin for the anchor point
  6885. * @param {Event} eventData javascript event that is doing the transform
  6886. * @param {Object} transform javascript object containing a series of information around the current transform
  6887. * @param {number} x current mouse x position, canvas normalized
  6888. * @param {number} y current mouse y position, canvas normalized
  6889. * @return {Boolean} true if some change happened
  6890. */
  6891. function skewHandlerX(eventData, transform, x, y) {
  6892. // step1 figure out and change transform origin.
  6893. // if skewX > 0 and originY bottom we anchor on right
  6894. // if skewX > 0 and originY top we anchor on left
  6895. // if skewX < 0 and originY bottom we anchor on left
  6896. // if skewX < 0 and originY top we anchor on right
  6897. // if skewX is 0, we look for mouse position to understand where are we going.
  6898. var target = transform.target, currentSkew = target.skewX, originX, originY = transform.originY;
  6899. if (target.lockSkewingX) {
  6900. return false;
  6901. }
  6902. if (currentSkew === 0) {
  6903. var localPointFromCenter = getLocalPoint(transform, CENTER, CENTER, x, y);
  6904. if (localPointFromCenter.x > 0) {
  6905. // we are pulling right, anchor left;
  6906. originX = LEFT;
  6907. }
  6908. else {
  6909. // we are pulling right, anchor right
  6910. originX = RIGHT;
  6911. }
  6912. }
  6913. else {
  6914. if (currentSkew > 0) {
  6915. originX = originY === TOP ? LEFT : RIGHT;
  6916. }
  6917. if (currentSkew < 0) {
  6918. originX = originY === TOP ? RIGHT : LEFT;
  6919. }
  6920. // is the object flipped on one side only? swap the origin.
  6921. if (targetHasOneFlip(target)) {
  6922. originX = originX === LEFT ? RIGHT : LEFT;
  6923. }
  6924. }
  6925. // once we have the origin, we find the anchor point
  6926. transform.originX = originX;
  6927. var finalHandler = wrapWithFireEvent('skewing', wrapWithFixedAnchor(skewObjectX));
  6928. return finalHandler(eventData, transform, x, y);
  6929. }
  6930. /**
  6931. * Wrapped Action handler for skewing on the Y axis, takes care of the
  6932. * skew direction and determine the correct transform origin for the anchor point
  6933. * @param {Event} eventData javascript event that is doing the transform
  6934. * @param {Object} transform javascript object containing a series of information around the current transform
  6935. * @param {number} x current mouse x position, canvas normalized
  6936. * @param {number} y current mouse y position, canvas normalized
  6937. * @return {Boolean} true if some change happened
  6938. */
  6939. function skewHandlerY(eventData, transform, x, y) {
  6940. // step1 figure out and change transform origin.
  6941. // if skewY > 0 and originX left we anchor on top
  6942. // if skewY > 0 and originX right we anchor on bottom
  6943. // if skewY < 0 and originX left we anchor on bottom
  6944. // if skewY < 0 and originX right we anchor on top
  6945. // if skewY is 0, we look for mouse position to understand where are we going.
  6946. var target = transform.target, currentSkew = target.skewY, originY, originX = transform.originX;
  6947. if (target.lockSkewingY) {
  6948. return false;
  6949. }
  6950. if (currentSkew === 0) {
  6951. var localPointFromCenter = getLocalPoint(transform, CENTER, CENTER, x, y);
  6952. if (localPointFromCenter.y > 0) {
  6953. // we are pulling down, anchor up;
  6954. originY = TOP;
  6955. }
  6956. else {
  6957. // we are pulling up, anchor down
  6958. originY = BOTTOM;
  6959. }
  6960. }
  6961. else {
  6962. if (currentSkew > 0) {
  6963. originY = originX === LEFT ? TOP : BOTTOM;
  6964. }
  6965. if (currentSkew < 0) {
  6966. originY = originX === LEFT ? BOTTOM : TOP;
  6967. }
  6968. // is the object flipped on one side only? swap the origin.
  6969. if (targetHasOneFlip(target)) {
  6970. originY = originY === TOP ? BOTTOM : TOP;
  6971. }
  6972. }
  6973. // once we have the origin, we find the anchor point
  6974. transform.originY = originY;
  6975. var finalHandler = wrapWithFireEvent('skewing', wrapWithFixedAnchor(skewObjectY));
  6976. return finalHandler(eventData, transform, x, y);
  6977. }
  6978. /**
  6979. * Action handler for rotation and snapping, without anchor point.
  6980. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  6981. * @param {Event} eventData javascript event that is doing the transform
  6982. * @param {Object} transform javascript object containing a series of information around the current transform
  6983. * @param {number} x current mouse x position, canvas normalized
  6984. * @param {number} y current mouse y position, canvas normalized
  6985. * @return {Boolean} true if some change happened
  6986. * @private
  6987. */
  6988. function rotationWithSnapping(eventData, transform, x, y) {
  6989. var t = transform,
  6990. target = t.target,
  6991. pivotPoint = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY);
  6992. if (target.lockRotation) {
  6993. return false;
  6994. }
  6995. var lastAngle = Math.atan2(t.ey - pivotPoint.y, t.ex - pivotPoint.x),
  6996. curAngle = Math.atan2(y - pivotPoint.y, x - pivotPoint.x),
  6997. angle = radiansToDegrees(curAngle - lastAngle + t.theta),
  6998. hasRotated = true;
  6999. if (target.snapAngle > 0) {
  7000. var snapAngle = target.snapAngle,
  7001. snapThreshold = target.snapThreshold || snapAngle,
  7002. rightAngleLocked = Math.ceil(angle / snapAngle) * snapAngle,
  7003. leftAngleLocked = Math.floor(angle / snapAngle) * snapAngle;
  7004. if (Math.abs(angle - leftAngleLocked) < snapThreshold) {
  7005. angle = leftAngleLocked;
  7006. }
  7007. else if (Math.abs(angle - rightAngleLocked) < snapThreshold) {
  7008. angle = rightAngleLocked;
  7009. }
  7010. }
  7011. // normalize angle to positive value
  7012. if (angle < 0) {
  7013. angle = 360 + angle;
  7014. }
  7015. angle %= 360;
  7016. hasRotated = target.angle !== angle;
  7017. target.angle = angle;
  7018. return hasRotated;
  7019. }
  7020. /**
  7021. * Basic scaling logic, reused with different constrain for scaling X,Y, freely or equally.
  7022. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7023. * @param {Event} eventData javascript event that is doing the transform
  7024. * @param {Object} transform javascript object containing a series of information around the current transform
  7025. * @param {number} x current mouse x position, canvas normalized
  7026. * @param {number} y current mouse y position, canvas normalized
  7027. * @param {Object} options additional information for scaling
  7028. * @param {String} options.by 'x', 'y', 'equally' or '' to indicate type of scaling
  7029. * @return {Boolean} true if some change happened
  7030. * @private
  7031. */
  7032. function scaleObject(eventData, transform, x, y, options) {
  7033. options = options || {};
  7034. var target = transform.target,
  7035. lockScalingX = target.lockScalingX, lockScalingY = target.lockScalingY,
  7036. by = options.by, newPoint, scaleX, scaleY, dim,
  7037. scaleProportionally = scaleIsProportional(eventData, target),
  7038. forbidScaling = scalingIsForbidden(target, by, scaleProportionally),
  7039. signX, signY, gestureScale = transform.gestureScale;
  7040. if (forbidScaling) {
  7041. return false;
  7042. }
  7043. if (gestureScale) {
  7044. scaleX = transform.scaleX * gestureScale;
  7045. scaleY = transform.scaleY * gestureScale;
  7046. }
  7047. else {
  7048. newPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y);
  7049. // use of sign: We use sign to detect change of direction of an action. sign usually change when
  7050. // we cross the origin point with the mouse. So a scale flip for example. There is an issue when scaling
  7051. // by center and scaling using one middle control ( default: mr, mt, ml, mb), the mouse movement can easily
  7052. // cross many time the origin point and flip the object. so we need a way to filter out the noise.
  7053. // This ternary here should be ok to filter out X scaling when we want Y only and vice versa.
  7054. signX = by !== 'y' ? sign(newPoint.x) : 1;
  7055. signY = by !== 'x' ? sign(newPoint.y) : 1;
  7056. if (!transform.signX) {
  7057. transform.signX = signX;
  7058. }
  7059. if (!transform.signY) {
  7060. transform.signY = signY;
  7061. }
  7062. if (target.lockScalingFlip &&
  7063. (transform.signX !== signX || transform.signY !== signY)
  7064. ) {
  7065. return false;
  7066. }
  7067. dim = target._getTransformedDimensions();
  7068. // missing detection of flip and logic to switch the origin
  7069. if (scaleProportionally && !by) {
  7070. // uniform scaling
  7071. var distance = Math.abs(newPoint.x) + Math.abs(newPoint.y),
  7072. original = transform.original,
  7073. originalDistance = Math.abs(dim.x * original.scaleX / target.scaleX) +
  7074. Math.abs(dim.y * original.scaleY / target.scaleY),
  7075. scale = distance / originalDistance;
  7076. scaleX = original.scaleX * scale;
  7077. scaleY = original.scaleY * scale;
  7078. }
  7079. else {
  7080. scaleX = Math.abs(newPoint.x * target.scaleX / dim.x);
  7081. scaleY = Math.abs(newPoint.y * target.scaleY / dim.y);
  7082. }
  7083. // if we are scaling by center, we need to double the scale
  7084. if (isTransformCentered(transform)) {
  7085. scaleX *= 2;
  7086. scaleY *= 2;
  7087. }
  7088. if (transform.signX !== signX && by !== 'y') {
  7089. transform.originX = opposite[transform.originX];
  7090. scaleX *= -1;
  7091. transform.signX = signX;
  7092. }
  7093. if (transform.signY !== signY && by !== 'x') {
  7094. transform.originY = opposite[transform.originY];
  7095. scaleY *= -1;
  7096. transform.signY = signY;
  7097. }
  7098. }
  7099. // minScale is taken are in the setter.
  7100. var oldScaleX = target.scaleX, oldScaleY = target.scaleY;
  7101. if (!by) {
  7102. !lockScalingX && target.set('scaleX', scaleX);
  7103. !lockScalingY && target.set('scaleY', scaleY);
  7104. }
  7105. else {
  7106. // forbidden cases already handled on top here.
  7107. by === 'x' && target.set('scaleX', scaleX);
  7108. by === 'y' && target.set('scaleY', scaleY);
  7109. }
  7110. return oldScaleX !== target.scaleX || oldScaleY !== target.scaleY;
  7111. }
  7112. /**
  7113. * Generic scaling logic, to scale from corners either equally or freely.
  7114. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7115. * @param {Event} eventData javascript event that is doing the transform
  7116. * @param {Object} transform javascript object containing a series of information around the current transform
  7117. * @param {number} x current mouse x position, canvas normalized
  7118. * @param {number} y current mouse y position, canvas normalized
  7119. * @return {Boolean} true if some change happened
  7120. */
  7121. function scaleObjectFromCorner(eventData, transform, x, y) {
  7122. return scaleObject(eventData, transform, x, y);
  7123. }
  7124. /**
  7125. * Scaling logic for the X axis.
  7126. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7127. * @param {Event} eventData javascript event that is doing the transform
  7128. * @param {Object} transform javascript object containing a series of information around the current transform
  7129. * @param {number} x current mouse x position, canvas normalized
  7130. * @param {number} y current mouse y position, canvas normalized
  7131. * @return {Boolean} true if some change happened
  7132. */
  7133. function scaleObjectX(eventData, transform, x, y) {
  7134. return scaleObject(eventData, transform, x, y , { by: 'x' });
  7135. }
  7136. /**
  7137. * Scaling logic for the Y axis.
  7138. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7139. * @param {Event} eventData javascript event that is doing the transform
  7140. * @param {Object} transform javascript object containing a series of information around the current transform
  7141. * @param {number} x current mouse x position, canvas normalized
  7142. * @param {number} y current mouse y position, canvas normalized
  7143. * @return {Boolean} true if some change happened
  7144. */
  7145. function scaleObjectY(eventData, transform, x, y) {
  7146. return scaleObject(eventData, transform, x, y , { by: 'y' });
  7147. }
  7148. /**
  7149. * Composed action handler to either scale Y or skew X
  7150. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7151. * @param {Event} eventData javascript event that is doing the transform
  7152. * @param {Object} transform javascript object containing a series of information around the current transform
  7153. * @param {number} x current mouse x position, canvas normalized
  7154. * @param {number} y current mouse y position, canvas normalized
  7155. * @return {Boolean} true if some change happened
  7156. */
  7157. function scalingYOrSkewingX(eventData, transform, x, y) {
  7158. // ok some safety needed here.
  7159. if (eventData[transform.target.canvas.altActionKey]) {
  7160. return controls.skewHandlerX(eventData, transform, x, y);
  7161. }
  7162. return controls.scalingY(eventData, transform, x, y);
  7163. }
  7164. /**
  7165. * Composed action handler to either scale X or skew Y
  7166. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7167. * @param {Event} eventData javascript event that is doing the transform
  7168. * @param {Object} transform javascript object containing a series of information around the current transform
  7169. * @param {number} x current mouse x position, canvas normalized
  7170. * @param {number} y current mouse y position, canvas normalized
  7171. * @return {Boolean} true if some change happened
  7172. */
  7173. function scalingXOrSkewingY(eventData, transform, x, y) {
  7174. // ok some safety needed here.
  7175. if (eventData[transform.target.canvas.altActionKey]) {
  7176. return controls.skewHandlerY(eventData, transform, x, y);
  7177. }
  7178. return controls.scalingX(eventData, transform, x, y);
  7179. }
  7180. /**
  7181. * Action handler to change textbox width
  7182. * Needs to be wrapped with `wrapWithFixedAnchor` to be effective
  7183. * @param {Event} eventData javascript event that is doing the transform
  7184. * @param {Object} transform javascript object containing a series of information around the current transform
  7185. * @param {number} x current mouse x position, canvas normalized
  7186. * @param {number} y current mouse y position, canvas normalized
  7187. * @return {Boolean} true if some change happened
  7188. */
  7189. function changeWidth(eventData, transform, x, y) {
  7190. var target = transform.target, localPoint = getLocalPoint(transform, transform.originX, transform.originY, x, y),
  7191. strokePadding = target.strokeWidth / (target.strokeUniform ? target.scaleX : 1),
  7192. multiplier = isTransformCentered(transform) ? 2 : 1,
  7193. oldWidth = target.width,
  7194. newWidth = Math.abs(localPoint.x * multiplier / target.scaleX) - strokePadding;
  7195. target.set('width', Math.max(newWidth, 0));
  7196. return oldWidth !== newWidth;
  7197. }
  7198. /**
  7199. * Action handler
  7200. * @private
  7201. * @param {Event} eventData javascript event that is doing the transform
  7202. * @param {Object} transform javascript object containing a series of information around the current transform
  7203. * @param {number} x current mouse x position, canvas normalized
  7204. * @param {number} y current mouse y position, canvas normalized
  7205. * @return {Boolean} true if the translation occurred
  7206. */
  7207. function dragHandler(eventData, transform, x, y) {
  7208. var target = transform.target,
  7209. newLeft = x - transform.offsetX,
  7210. newTop = y - transform.offsetY,
  7211. moveX = !target.get('lockMovementX') && target.left !== newLeft,
  7212. moveY = !target.get('lockMovementY') && target.top !== newTop;
  7213. moveX && target.set('left', newLeft);
  7214. moveY && target.set('top', newTop);
  7215. if (moveX || moveY) {
  7216. fireEvent('moving', commonEventInfo(eventData, transform, x, y));
  7217. }
  7218. return moveX || moveY;
  7219. }
  7220. controls.scaleCursorStyleHandler = scaleCursorStyleHandler;
  7221. controls.skewCursorStyleHandler = skewCursorStyleHandler;
  7222. controls.scaleSkewCursorStyleHandler = scaleSkewCursorStyleHandler;
  7223. controls.rotationWithSnapping = wrapWithFireEvent('rotating', wrapWithFixedAnchor(rotationWithSnapping));
  7224. controls.scalingEqually = wrapWithFireEvent('scaling', wrapWithFixedAnchor( scaleObjectFromCorner));
  7225. controls.scalingX = wrapWithFireEvent('scaling', wrapWithFixedAnchor(scaleObjectX));
  7226. controls.scalingY = wrapWithFireEvent('scaling', wrapWithFixedAnchor(scaleObjectY));
  7227. controls.scalingYOrSkewingX = scalingYOrSkewingX;
  7228. controls.scalingXOrSkewingY = scalingXOrSkewingY;
  7229. controls.changeWidth = wrapWithFireEvent('resizing', wrapWithFixedAnchor(changeWidth));
  7230. controls.skewHandlerX = skewHandlerX;
  7231. controls.skewHandlerY = skewHandlerY;
  7232. controls.dragHandler = dragHandler;
  7233. controls.scaleOrSkewActionName = scaleOrSkewActionName;
  7234. controls.rotationStyleHandler = rotationStyleHandler;
  7235. controls.fireEvent = fireEvent;
  7236. controls.wrapWithFixedAnchor = wrapWithFixedAnchor;
  7237. controls.wrapWithFireEvent = wrapWithFireEvent;
  7238. controls.getLocalPoint = getLocalPoint;
  7239. fabric.controlsUtils = controls;
  7240. })(typeof exports !== 'undefined' ? exports : this);
  7241. (function(global) {
  7242. 'use strict';
  7243. var fabric = global.fabric || (global.fabric = { }),
  7244. degreesToRadians = fabric.util.degreesToRadians,
  7245. controls = fabric.controlsUtils;
  7246. /**
  7247. * Render a round control, as per fabric features.
  7248. * This function is written to respect object properties like transparentCorners, cornerSize
  7249. * cornerColor, cornerStrokeColor
  7250. * plus the addition of offsetY and offsetX.
  7251. * @param {CanvasRenderingContext2D} ctx context to render on
  7252. * @param {Number} left x coordinate where the control center should be
  7253. * @param {Number} top y coordinate where the control center should be
  7254. * @param {Object} styleOverride override for fabric.Object controls style
  7255. * @param {fabric.Object} fabricObject the fabric object for which we are rendering controls
  7256. */
  7257. function renderCircleControl (ctx, left, top, styleOverride, fabricObject) {
  7258. styleOverride = styleOverride || {};
  7259. var xSize = this.sizeX || styleOverride.cornerSize || fabricObject.cornerSize,
  7260. ySize = this.sizeY || styleOverride.cornerSize || fabricObject.cornerSize,
  7261. transparentCorners = typeof styleOverride.transparentCorners !== 'undefined' ?
  7262. styleOverride.transparentCorners : fabricObject.transparentCorners,
  7263. methodName = transparentCorners ? 'stroke' : 'fill',
  7264. stroke = !transparentCorners && (styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor),
  7265. myLeft = left,
  7266. myTop = top, size;
  7267. ctx.save();
  7268. ctx.fillStyle = styleOverride.cornerColor || fabricObject.cornerColor;
  7269. ctx.strokeStyle = styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor;
  7270. // as soon as fabric react v5, remove ie11, use proper ellipse code.
  7271. if (xSize > ySize) {
  7272. size = xSize;
  7273. ctx.scale(1.0, ySize / xSize);
  7274. myTop = top * xSize / ySize;
  7275. }
  7276. else if (ySize > xSize) {
  7277. size = ySize;
  7278. ctx.scale(xSize / ySize, 1.0);
  7279. myLeft = left * ySize / xSize;
  7280. }
  7281. else {
  7282. size = xSize;
  7283. }
  7284. // this is still wrong
  7285. ctx.lineWidth = 1;
  7286. ctx.beginPath();
  7287. ctx.arc(myLeft, myTop, size / 2, 0, 2 * Math.PI, false);
  7288. ctx[methodName]();
  7289. if (stroke) {
  7290. ctx.stroke();
  7291. }
  7292. ctx.restore();
  7293. }
  7294. /**
  7295. * Render a square control, as per fabric features.
  7296. * This function is written to respect object properties like transparentCorners, cornerSize
  7297. * cornerColor, cornerStrokeColor
  7298. * plus the addition of offsetY and offsetX.
  7299. * @param {CanvasRenderingContext2D} ctx context to render on
  7300. * @param {Number} left x coordinate where the control center should be
  7301. * @param {Number} top y coordinate where the control center should be
  7302. * @param {Object} styleOverride override for fabric.Object controls style
  7303. * @param {fabric.Object} fabricObject the fabric object for which we are rendering controls
  7304. */
  7305. function renderSquareControl(ctx, left, top, styleOverride, fabricObject) {
  7306. styleOverride = styleOverride || {};
  7307. var xSize = this.sizeX || styleOverride.cornerSize || fabricObject.cornerSize,
  7308. ySize = this.sizeY || styleOverride.cornerSize || fabricObject.cornerSize,
  7309. transparentCorners = typeof styleOverride.transparentCorners !== 'undefined' ?
  7310. styleOverride.transparentCorners : fabricObject.transparentCorners,
  7311. methodName = transparentCorners ? 'stroke' : 'fill',
  7312. stroke = !transparentCorners && (
  7313. styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor
  7314. ), xSizeBy2 = xSize / 2, ySizeBy2 = ySize / 2;
  7315. ctx.save();
  7316. ctx.fillStyle = styleOverride.cornerColor || fabricObject.cornerColor;
  7317. ctx.strokeStyle = styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor;
  7318. // this is still wrong
  7319. ctx.lineWidth = 1;
  7320. ctx.translate(left, top);
  7321. ctx.rotate(degreesToRadians(fabricObject.angle));
  7322. // this does not work, and fixed with ( && ) does not make sense.
  7323. // to have real transparent corners we need the controls on upperCanvas
  7324. // transparentCorners || ctx.clearRect(-xSizeBy2, -ySizeBy2, xSize, ySize);
  7325. ctx[methodName + 'Rect'](-xSizeBy2, -ySizeBy2, xSize, ySize);
  7326. if (stroke) {
  7327. ctx.strokeRect(-xSizeBy2, -ySizeBy2, xSize, ySize);
  7328. }
  7329. ctx.restore();
  7330. }
  7331. controls.renderCircleControl = renderCircleControl;
  7332. controls.renderSquareControl = renderSquareControl;
  7333. })(typeof exports !== 'undefined' ? exports : this);
  7334. (function(global) {
  7335. 'use strict';
  7336. var fabric = global.fabric || (global.fabric = { });
  7337. function Control(options) {
  7338. for (var i in options) {
  7339. this[i] = options[i];
  7340. }
  7341. }
  7342. fabric.Control = Control;
  7343. fabric.Control.prototype = /** @lends fabric.Control.prototype */ {
  7344. /**
  7345. * keep track of control visibility.
  7346. * mainly for backward compatibility.
  7347. * if you do not want to see a control, you can remove it
  7348. * from the controlset.
  7349. * @type {Boolean}
  7350. * @default true
  7351. */
  7352. visible: true,
  7353. /**
  7354. * Name of the action that the control will likely execute.
  7355. * This is optional. FabricJS uses to identify what the user is doing for some
  7356. * extra optimizations. If you are writing a custom control and you want to know
  7357. * somewhere else in the code what is going on, you can use this string here.
  7358. * you can also provide a custom getActionName if your control run multiple actions
  7359. * depending on some external state.
  7360. * default to scale since is the most common, used on 4 corners by default
  7361. * @type {String}
  7362. * @default 'scale'
  7363. */
  7364. actionName: 'scale',
  7365. /**
  7366. * Drawing angle of the control.
  7367. * NOT used for now, but name marked as needed for internal logic
  7368. * example: to reuse the same drawing function for different rotated controls
  7369. * @type {Number}
  7370. * @default 0
  7371. */
  7372. angle: 0,
  7373. /**
  7374. * Relative position of the control. X
  7375. * 0,0 is the center of the Object, while -0.5 (left) or 0.5 (right) are the extremities
  7376. * of the bounding box.
  7377. * @type {Number}
  7378. * @default 0
  7379. */
  7380. x: 0,
  7381. /**
  7382. * Relative position of the control. Y
  7383. * 0,0 is the center of the Object, while -0.5 (top) or 0.5 (bottom) are the extremities
  7384. * of the bounding box.
  7385. * @type {Number}
  7386. * @default 0
  7387. */
  7388. y: 0,
  7389. /**
  7390. * Horizontal offset of the control from the defined position. In pixels
  7391. * Positive offset moves the control to the right, negative to the left.
  7392. * It used when you want to have position of control that does not scale with
  7393. * the bounding box. Example: rotation control is placed at x:0, y: 0.5 on
  7394. * the boundindbox, with an offset of 30 pixels vertically. Those 30 pixels will
  7395. * stay 30 pixels no matter how the object is big. Another example is having 2
  7396. * controls in the corner, that stay in the same position when the object scale.
  7397. * of the bounding box.
  7398. * @type {Number}
  7399. * @default 0
  7400. */
  7401. offsetX: 0,
  7402. /**
  7403. * Vertical offset of the control from the defined position. In pixels
  7404. * Positive offset moves the control to the bottom, negative to the top.
  7405. * @type {Number}
  7406. * @default 0
  7407. */
  7408. offsetY: 0,
  7409. /**
  7410. * Sets the length of the control. If null, defaults to object's cornerSize.
  7411. * Expects both sizeX and sizeY to be set when set.
  7412. * @type {?Number}
  7413. * @default null
  7414. */
  7415. sizeX: null,
  7416. /**
  7417. * Sets the height of the control. If null, defaults to object's cornerSize.
  7418. * Expects both sizeX and sizeY to be set when set.
  7419. * @type {?Number}
  7420. * @default null
  7421. */
  7422. sizeY: null,
  7423. /**
  7424. * Sets the length of the touch area of the control. If null, defaults to object's touchCornerSize.
  7425. * Expects both touchSizeX and touchSizeY to be set when set.
  7426. * @type {?Number}
  7427. * @default null
  7428. */
  7429. touchSizeX: null,
  7430. /**
  7431. * Sets the height of the touch area of the control. If null, defaults to object's touchCornerSize.
  7432. * Expects both touchSizeX and touchSizeY to be set when set.
  7433. * @type {?Number}
  7434. * @default null
  7435. */
  7436. touchSizeY: null,
  7437. /**
  7438. * Css cursor style to display when the control is hovered.
  7439. * if the method `cursorStyleHandler` is provided, this property is ignored.
  7440. * @type {String}
  7441. * @default 'crosshair'
  7442. */
  7443. cursorStyle: 'crosshair',
  7444. /**
  7445. * If controls has an offsetY or offsetX, draw a line that connects
  7446. * the control to the bounding box
  7447. * @type {Boolean}
  7448. * @default false
  7449. */
  7450. withConnection: false,
  7451. /**
  7452. * The control actionHandler, provide one to handle action ( control being moved )
  7453. * @param {Event} eventData the native mouse event
  7454. * @param {Object} transformData properties of the current transform
  7455. * @param {Number} x x position of the cursor
  7456. * @param {Number} y y position of the cursor
  7457. * @return {Boolean} true if the action/event modified the object
  7458. */
  7459. actionHandler: function(/* eventData, transformData, x, y */) { },
  7460. /**
  7461. * The control handler for mouse down, provide one to handle mouse down on control
  7462. * @param {Event} eventData the native mouse event
  7463. * @param {Object} transformData properties of the current transform
  7464. * @param {Number} x x position of the cursor
  7465. * @param {Number} y y position of the cursor
  7466. * @return {Boolean} true if the action/event modified the object
  7467. */
  7468. mouseDownHandler: function(/* eventData, transformData, x, y */) { },
  7469. /**
  7470. * The control mouseUpHandler, provide one to handle an effect on mouse up.
  7471. * @param {Event} eventData the native mouse event
  7472. * @param {Object} transformData properties of the current transform
  7473. * @param {Number} x x position of the cursor
  7474. * @param {Number} y y position of the cursor
  7475. * @return {Boolean} true if the action/event modified the object
  7476. */
  7477. mouseUpHandler: function(/* eventData, transformData, x, y */) { },
  7478. /**
  7479. * Returns control actionHandler
  7480. * @param {Event} eventData the native mouse event
  7481. * @param {fabric.Object} fabricObject on which the control is displayed
  7482. * @param {fabric.Control} control control for which the action handler is being asked
  7483. * @return {Function} the action handler
  7484. */
  7485. getActionHandler: function(/* eventData, fabricObject, control */) {
  7486. return this.actionHandler;
  7487. },
  7488. /**
  7489. * Returns control mouseDown handler
  7490. * @param {Event} eventData the native mouse event
  7491. * @param {fabric.Object} fabricObject on which the control is displayed
  7492. * @param {fabric.Control} control control for which the action handler is being asked
  7493. * @return {Function} the action handler
  7494. */
  7495. getMouseDownHandler: function(/* eventData, fabricObject, control */) {
  7496. return this.mouseDownHandler;
  7497. },
  7498. /**
  7499. * Returns control mouseUp handler
  7500. * @param {Event} eventData the native mouse event
  7501. * @param {fabric.Object} fabricObject on which the control is displayed
  7502. * @param {fabric.Control} control control for which the action handler is being asked
  7503. * @return {Function} the action handler
  7504. */
  7505. getMouseUpHandler: function(/* eventData, fabricObject, control */) {
  7506. return this.mouseUpHandler;
  7507. },
  7508. /**
  7509. * Returns control cursorStyle for css using cursorStyle. If you need a more elaborate
  7510. * function you can pass one in the constructor
  7511. * the cursorStyle property
  7512. * @param {Event} eventData the native mouse event
  7513. * @param {fabric.Control} control the current control ( likely this)
  7514. * @param {fabric.Object} object on which the control is displayed
  7515. * @return {String}
  7516. */
  7517. cursorStyleHandler: function(eventData, control /* fabricObject */) {
  7518. return control.cursorStyle;
  7519. },
  7520. /**
  7521. * Returns the action name. The basic implementation just return the actionName property.
  7522. * @param {Event} eventData the native mouse event
  7523. * @param {fabric.Control} control the current control ( likely this)
  7524. * @param {fabric.Object} object on which the control is displayed
  7525. * @return {String}
  7526. */
  7527. getActionName: function(eventData, control /* fabricObject */) {
  7528. return control.actionName;
  7529. },
  7530. /**
  7531. * Returns controls visibility
  7532. * @param {fabric.Object} object on which the control is displayed
  7533. * @param {String} controlKey key where the control is memorized on the
  7534. * @return {Boolean}
  7535. */
  7536. getVisibility: function(fabricObject, controlKey) {
  7537. var objectVisibility = fabricObject._controlsVisibility;
  7538. if (objectVisibility && typeof objectVisibility[controlKey] !== 'undefined') {
  7539. return objectVisibility[controlKey];
  7540. }
  7541. return this.visible;
  7542. },
  7543. /**
  7544. * Sets controls visibility
  7545. * @param {Boolean} visibility for the object
  7546. * @return {Void}
  7547. */
  7548. setVisibility: function(visibility /* name, fabricObject */) {
  7549. this.visible = visibility;
  7550. },
  7551. positionHandler: function(dim, finalMatrix /*, fabricObject, currentControl */) {
  7552. var point = fabric.util.transformPoint({
  7553. x: this.x * dim.x + this.offsetX,
  7554. y: this.y * dim.y + this.offsetY }, finalMatrix);
  7555. return point;
  7556. },
  7557. /**
  7558. * Returns the coords for this control based on object values.
  7559. * @param {Number} objectAngle angle from the fabric object holding the control
  7560. * @param {Number} objectCornerSize cornerSize from the fabric object holding the control (or touchCornerSize if
  7561. * isTouch is true)
  7562. * @param {Number} centerX x coordinate where the control center should be
  7563. * @param {Number} centerY y coordinate where the control center should be
  7564. * @param {boolean} isTouch true if touch corner, false if normal corner
  7565. */
  7566. calcCornerCoords: function(objectAngle, objectCornerSize, centerX, centerY, isTouch) {
  7567. var cosHalfOffset,
  7568. sinHalfOffset,
  7569. cosHalfOffsetComp,
  7570. sinHalfOffsetComp,
  7571. xSize = (isTouch) ? this.touchSizeX : this.sizeX,
  7572. ySize = (isTouch) ? this.touchSizeY : this.sizeY;
  7573. if (xSize && ySize && xSize !== ySize) {
  7574. // handle rectangular corners
  7575. var controlTriangleAngle = Math.atan2(ySize, xSize);
  7576. var cornerHypotenuse = Math.sqrt(xSize * xSize + ySize * ySize) / 2;
  7577. var newTheta = controlTriangleAngle - fabric.util.degreesToRadians(objectAngle);
  7578. var newThetaComp = Math.PI / 2 - controlTriangleAngle - fabric.util.degreesToRadians(objectAngle);
  7579. cosHalfOffset = cornerHypotenuse * fabric.util.cos(newTheta);
  7580. sinHalfOffset = cornerHypotenuse * fabric.util.sin(newTheta);
  7581. // use complementary angle for two corners
  7582. cosHalfOffsetComp = cornerHypotenuse * fabric.util.cos(newThetaComp);
  7583. sinHalfOffsetComp = cornerHypotenuse * fabric.util.sin(newThetaComp);
  7584. }
  7585. else {
  7586. // handle square corners
  7587. // use default object corner size unless size is defined
  7588. var cornerSize = (xSize && ySize) ? xSize : objectCornerSize;
  7589. /* 0.7071067812 stands for sqrt(2)/2 */
  7590. cornerHypotenuse = cornerSize * 0.7071067812;
  7591. // complementary angles are equal since they're both 45 degrees
  7592. var newTheta = fabric.util.degreesToRadians(45 - objectAngle);
  7593. cosHalfOffset = cosHalfOffsetComp = cornerHypotenuse * fabric.util.cos(newTheta);
  7594. sinHalfOffset = sinHalfOffsetComp = cornerHypotenuse * fabric.util.sin(newTheta);
  7595. }
  7596. return {
  7597. tl: {
  7598. x: centerX - sinHalfOffsetComp,
  7599. y: centerY - cosHalfOffsetComp,
  7600. },
  7601. tr: {
  7602. x: centerX + cosHalfOffset,
  7603. y: centerY - sinHalfOffset,
  7604. },
  7605. bl: {
  7606. x: centerX - cosHalfOffset,
  7607. y: centerY + sinHalfOffset,
  7608. },
  7609. br: {
  7610. x: centerX + sinHalfOffsetComp,
  7611. y: centerY + cosHalfOffsetComp,
  7612. },
  7613. };
  7614. },
  7615. /**
  7616. * Render function for the control.
  7617. * When this function runs the context is unscaled. unrotate. Just retina scaled.
  7618. * all the functions will have to translate to the point left,top before starting Drawing
  7619. * if they want to draw a control where the position is detected.
  7620. * left and top are the result of the positionHandler function
  7621. * @param {RenderingContext2D} ctx the context where the control will be drawn
  7622. * @param {Number} left position of the canvas where we are about to render the control.
  7623. * @param {Number} top position of the canvas where we are about to render the control.
  7624. * @param {Object} styleOverride
  7625. * @param {fabric.Object} fabricObject the object where the control is about to be rendered
  7626. */
  7627. render: function(ctx, left, top, styleOverride, fabricObject) {
  7628. styleOverride = styleOverride || {};
  7629. switch (styleOverride.cornerStyle || fabricObject.cornerStyle) {
  7630. case 'circle':
  7631. fabric.controlsUtils.renderCircleControl.call(this, ctx, left, top, styleOverride, fabricObject);
  7632. break;
  7633. default:
  7634. fabric.controlsUtils.renderSquareControl.call(this, ctx, left, top, styleOverride, fabricObject);
  7635. }
  7636. },
  7637. };
  7638. })(typeof exports !== 'undefined' ? exports : this);
  7639. (function() {
  7640. /* _FROM_SVG_START_ */
  7641. function getColorStop(el, multiplier) {
  7642. var style = el.getAttribute('style'),
  7643. offset = el.getAttribute('offset') || 0,
  7644. color, colorAlpha, opacity, i;
  7645. // convert percents to absolute values
  7646. offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);
  7647. offset = offset < 0 ? 0 : offset > 1 ? 1 : offset;
  7648. if (style) {
  7649. var keyValuePairs = style.split(/\s*;\s*/);
  7650. if (keyValuePairs[keyValuePairs.length - 1] === '') {
  7651. keyValuePairs.pop();
  7652. }
  7653. for (i = keyValuePairs.length; i--; ) {
  7654. var split = keyValuePairs[i].split(/\s*:\s*/),
  7655. key = split[0].trim(),
  7656. value = split[1].trim();
  7657. if (key === 'stop-color') {
  7658. color = value;
  7659. }
  7660. else if (key === 'stop-opacity') {
  7661. opacity = value;
  7662. }
  7663. }
  7664. }
  7665. if (!color) {
  7666. color = el.getAttribute('stop-color') || 'rgb(0,0,0)';
  7667. }
  7668. if (!opacity) {
  7669. opacity = el.getAttribute('stop-opacity');
  7670. }
  7671. color = new fabric.Color(color);
  7672. colorAlpha = color.getAlpha();
  7673. opacity = isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity);
  7674. opacity *= colorAlpha * multiplier;
  7675. return {
  7676. offset: offset,
  7677. color: color.toRgb(),
  7678. opacity: opacity
  7679. };
  7680. }
  7681. function getLinearCoords(el) {
  7682. return {
  7683. x1: el.getAttribute('x1') || 0,
  7684. y1: el.getAttribute('y1') || 0,
  7685. x2: el.getAttribute('x2') || '100%',
  7686. y2: el.getAttribute('y2') || 0
  7687. };
  7688. }
  7689. function getRadialCoords(el) {
  7690. return {
  7691. x1: el.getAttribute('fx') || el.getAttribute('cx') || '50%',
  7692. y1: el.getAttribute('fy') || el.getAttribute('cy') || '50%',
  7693. r1: 0,
  7694. x2: el.getAttribute('cx') || '50%',
  7695. y2: el.getAttribute('cy') || '50%',
  7696. r2: el.getAttribute('r') || '50%'
  7697. };
  7698. }
  7699. /* _FROM_SVG_END_ */
  7700. var clone = fabric.util.object.clone;
  7701. /**
  7702. * Gradient class
  7703. * @class fabric.Gradient
  7704. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#gradients}
  7705. * @see {@link fabric.Gradient#initialize} for constructor definition
  7706. */
  7707. fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {
  7708. /**
  7709. * Horizontal offset for aligning gradients coming from SVG when outside pathgroups
  7710. * @type Number
  7711. * @default 0
  7712. */
  7713. offsetX: 0,
  7714. /**
  7715. * Vertical offset for aligning gradients coming from SVG when outside pathgroups
  7716. * @type Number
  7717. * @default 0
  7718. */
  7719. offsetY: 0,
  7720. /**
  7721. * A transform matrix to apply to the gradient before painting.
  7722. * Imported from svg gradients, is not applied with the current transform in the center.
  7723. * Before this transform is applied, the origin point is at the top left corner of the object
  7724. * plus the addition of offsetY and offsetX.
  7725. * @type Number[]
  7726. * @default null
  7727. */
  7728. gradientTransform: null,
  7729. /**
  7730. * coordinates units for coords.
  7731. * If `pixels`, the number of coords are in the same unit of width / height.
  7732. * If set as `percentage` the coords are still a number, but 1 means 100% of width
  7733. * for the X and 100% of the height for the y. It can be bigger than 1 and negative.
  7734. * allowed values pixels or percentage.
  7735. * @type String
  7736. * @default 'pixels'
  7737. */
  7738. gradientUnits: 'pixels',
  7739. /**
  7740. * Gradient type linear or radial
  7741. * @type String
  7742. * @default 'pixels'
  7743. */
  7744. type: 'linear',
  7745. /**
  7746. * Constructor
  7747. * @param {Object} options Options object with type, coords, gradientUnits and colorStops
  7748. * @param {Object} [options.type] gradient type linear or radial
  7749. * @param {Object} [options.gradientUnits] gradient units
  7750. * @param {Object} [options.offsetX] SVG import compatibility
  7751. * @param {Object} [options.offsetY] SVG import compatibility
  7752. * @param {Object[]} options.colorStops contains the colorstops.
  7753. * @param {Object} options.coords contains the coords of the gradient
  7754. * @param {Number} [options.coords.x1] X coordiante of the first point for linear or of the focal point for radial
  7755. * @param {Number} [options.coords.y1] Y coordiante of the first point for linear or of the focal point for radial
  7756. * @param {Number} [options.coords.x2] X coordiante of the second point for linear or of the center point for radial
  7757. * @param {Number} [options.coords.y2] Y coordiante of the second point for linear or of the center point for radial
  7758. * @param {Number} [options.coords.r1] only for radial gradient, radius of the inner circle
  7759. * @param {Number} [options.coords.r2] only for radial gradient, radius of the external circle
  7760. * @return {fabric.Gradient} thisArg
  7761. */
  7762. initialize: function(options) {
  7763. options || (options = { });
  7764. options.coords || (options.coords = { });
  7765. var coords, _this = this;
  7766. // sets everything, then coords and colorstops get sets again
  7767. Object.keys(options).forEach(function(option) {
  7768. _this[option] = options[option];
  7769. });
  7770. if (this.id) {
  7771. this.id += '_' + fabric.Object.__uid++;
  7772. }
  7773. else {
  7774. this.id = fabric.Object.__uid++;
  7775. }
  7776. coords = {
  7777. x1: options.coords.x1 || 0,
  7778. y1: options.coords.y1 || 0,
  7779. x2: options.coords.x2 || 0,
  7780. y2: options.coords.y2 || 0
  7781. };
  7782. if (this.type === 'radial') {
  7783. coords.r1 = options.coords.r1 || 0;
  7784. coords.r2 = options.coords.r2 || 0;
  7785. }
  7786. this.coords = coords;
  7787. this.colorStops = options.colorStops.slice();
  7788. },
  7789. /**
  7790. * Adds another colorStop
  7791. * @param {Object} colorStop Object with offset and color
  7792. * @return {fabric.Gradient} thisArg
  7793. */
  7794. addColorStop: function(colorStops) {
  7795. for (var position in colorStops) {
  7796. var color = new fabric.Color(colorStops[position]);
  7797. this.colorStops.push({
  7798. offset: parseFloat(position),
  7799. color: color.toRgb(),
  7800. opacity: color.getAlpha()
  7801. });
  7802. }
  7803. return this;
  7804. },
  7805. /**
  7806. * Returns object representation of a gradient
  7807. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  7808. * @return {Object}
  7809. */
  7810. toObject: function(propertiesToInclude) {
  7811. var object = {
  7812. type: this.type,
  7813. coords: this.coords,
  7814. colorStops: this.colorStops,
  7815. offsetX: this.offsetX,
  7816. offsetY: this.offsetY,
  7817. gradientUnits: this.gradientUnits,
  7818. gradientTransform: this.gradientTransform ? this.gradientTransform.concat() : this.gradientTransform
  7819. };
  7820. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  7821. return object;
  7822. },
  7823. /* _TO_SVG_START_ */
  7824. /**
  7825. * Returns SVG representation of an gradient
  7826. * @param {Object} object Object to create a gradient for
  7827. * @return {String} SVG representation of an gradient (linear/radial)
  7828. */
  7829. toSVG: function(object, options) {
  7830. var coords = clone(this.coords, true), i, len, options = options || {},
  7831. markup, commonAttributes, colorStops = clone(this.colorStops, true),
  7832. needsSwap = coords.r1 > coords.r2,
  7833. transform = this.gradientTransform ? this.gradientTransform.concat() : fabric.iMatrix.concat(),
  7834. offsetX = -this.offsetX, offsetY = -this.offsetY,
  7835. withViewport = !!options.additionalTransform,
  7836. gradientUnits = this.gradientUnits === 'pixels' ? 'userSpaceOnUse' : 'objectBoundingBox';
  7837. // colorStops must be sorted ascending
  7838. colorStops.sort(function(a, b) {
  7839. return a.offset - b.offset;
  7840. });
  7841. if (gradientUnits === 'objectBoundingBox') {
  7842. offsetX /= object.width;
  7843. offsetY /= object.height;
  7844. }
  7845. else {
  7846. offsetX += object.width / 2;
  7847. offsetY += object.height / 2;
  7848. }
  7849. if (object.type === 'path' && this.gradientUnits !== 'percentage') {
  7850. offsetX -= object.pathOffset.x;
  7851. offsetY -= object.pathOffset.y;
  7852. }
  7853. transform[4] -= offsetX;
  7854. transform[5] -= offsetY;
  7855. commonAttributes = 'id="SVGID_' + this.id +
  7856. '" gradientUnits="' + gradientUnits + '"';
  7857. commonAttributes += ' gradientTransform="' + (withViewport ?
  7858. options.additionalTransform + ' ' : '') + fabric.util.matrixToSVG(transform) + '" ';
  7859. if (this.type === 'linear') {
  7860. markup = [
  7861. '<linearGradient ',
  7862. commonAttributes,
  7863. ' x1="', coords.x1,
  7864. '" y1="', coords.y1,
  7865. '" x2="', coords.x2,
  7866. '" y2="', coords.y2,
  7867. '">\n'
  7868. ];
  7869. }
  7870. else if (this.type === 'radial') {
  7871. // svg radial gradient has just 1 radius. the biggest.
  7872. markup = [
  7873. '<radialGradient ',
  7874. commonAttributes,
  7875. ' cx="', needsSwap ? coords.x1 : coords.x2,
  7876. '" cy="', needsSwap ? coords.y1 : coords.y2,
  7877. '" r="', needsSwap ? coords.r1 : coords.r2,
  7878. '" fx="', needsSwap ? coords.x2 : coords.x1,
  7879. '" fy="', needsSwap ? coords.y2 : coords.y1,
  7880. '">\n'
  7881. ];
  7882. }
  7883. if (this.type === 'radial') {
  7884. if (needsSwap) {
  7885. // svg goes from internal to external radius. if radius are inverted, swap color stops.
  7886. colorStops = colorStops.concat();
  7887. colorStops.reverse();
  7888. for (i = 0, len = colorStops.length; i < len; i++) {
  7889. colorStops[i].offset = 1 - colorStops[i].offset;
  7890. }
  7891. }
  7892. var minRadius = Math.min(coords.r1, coords.r2);
  7893. if (minRadius > 0) {
  7894. // i have to shift all colorStops and add new one in 0.
  7895. var maxRadius = Math.max(coords.r1, coords.r2),
  7896. percentageShift = minRadius / maxRadius;
  7897. for (i = 0, len = colorStops.length; i < len; i++) {
  7898. colorStops[i].offset += percentageShift * (1 - colorStops[i].offset);
  7899. }
  7900. }
  7901. }
  7902. for (i = 0, len = colorStops.length; i < len; i++) {
  7903. var colorStop = colorStops[i];
  7904. markup.push(
  7905. '<stop ',
  7906. 'offset="', (colorStop.offset * 100) + '%',
  7907. '" style="stop-color:', colorStop.color,
  7908. (typeof colorStop.opacity !== 'undefined' ? ';stop-opacity: ' + colorStop.opacity : ';'),
  7909. '"/>\n'
  7910. );
  7911. }
  7912. markup.push((this.type === 'linear' ? '</linearGradient>\n' : '</radialGradient>\n'));
  7913. return markup.join('');
  7914. },
  7915. /* _TO_SVG_END_ */
  7916. /**
  7917. * Returns an instance of CanvasGradient
  7918. * @param {CanvasRenderingContext2D} ctx Context to render on
  7919. * @return {CanvasGradient}
  7920. */
  7921. toLive: function(ctx) {
  7922. var gradient, coords = fabric.util.object.clone(this.coords), i, len;
  7923. if (!this.type) {
  7924. return;
  7925. }
  7926. if (this.type === 'linear') {
  7927. gradient = ctx.createLinearGradient(
  7928. coords.x1, coords.y1, coords.x2, coords.y2);
  7929. }
  7930. else if (this.type === 'radial') {
  7931. gradient = ctx.createRadialGradient(
  7932. coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);
  7933. }
  7934. for (i = 0, len = this.colorStops.length; i < len; i++) {
  7935. var color = this.colorStops[i].color,
  7936. opacity = this.colorStops[i].opacity,
  7937. offset = this.colorStops[i].offset;
  7938. if (typeof opacity !== 'undefined') {
  7939. color = new fabric.Color(color).setAlpha(opacity).toRgba();
  7940. }
  7941. gradient.addColorStop(offset, color);
  7942. }
  7943. return gradient;
  7944. }
  7945. });
  7946. fabric.util.object.extend(fabric.Gradient, {
  7947. /* _FROM_SVG_START_ */
  7948. /**
  7949. * Returns {@link fabric.Gradient} instance from an SVG element
  7950. * @static
  7951. * @memberOf fabric.Gradient
  7952. * @param {SVGGradientElement} el SVG gradient element
  7953. * @param {fabric.Object} instance
  7954. * @param {String} opacityAttr A fill-opacity or stroke-opacity attribute to multiply to each stop's opacity.
  7955. * @param {Object} svgOptions an object containing the size of the SVG in order to parse correctly gradients
  7956. * that uses gradientUnits as 'userSpaceOnUse' and percentages.
  7957. * @param {Object.number} viewBoxWidth width part of the viewBox attribute on svg
  7958. * @param {Object.number} viewBoxHeight height part of the viewBox attribute on svg
  7959. * @param {Object.number} width width part of the svg tag if viewBox is not specified
  7960. * @param {Object.number} height height part of the svg tag if viewBox is not specified
  7961. * @return {fabric.Gradient} Gradient instance
  7962. * @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
  7963. * @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
  7964. */
  7965. fromElement: function(el, instance, opacityAttr, svgOptions) {
  7966. /**
  7967. * @example:
  7968. *
  7969. * <linearGradient id="linearGrad1">
  7970. * <stop offset="0%" stop-color="white"/>
  7971. * <stop offset="100%" stop-color="black"/>
  7972. * </linearGradient>
  7973. *
  7974. * OR
  7975. *
  7976. * <linearGradient id="linearGrad2">
  7977. * <stop offset="0" style="stop-color:rgb(255,255,255)"/>
  7978. * <stop offset="1" style="stop-color:rgb(0,0,0)"/>
  7979. * </linearGradient>
  7980. *
  7981. * OR
  7982. *
  7983. * <radialGradient id="radialGrad1">
  7984. * <stop offset="0%" stop-color="white" stop-opacity="1" />
  7985. * <stop offset="50%" stop-color="black" stop-opacity="0.5" />
  7986. * <stop offset="100%" stop-color="white" stop-opacity="1" />
  7987. * </radialGradient>
  7988. *
  7989. * OR
  7990. *
  7991. * <radialGradient id="radialGrad2">
  7992. * <stop offset="0" stop-color="rgb(255,255,255)" />
  7993. * <stop offset="0.5" stop-color="rgb(0,0,0)" />
  7994. * <stop offset="1" stop-color="rgb(255,255,255)" />
  7995. * </radialGradient>
  7996. *
  7997. */
  7998. var multiplier = parseFloat(opacityAttr) / (/%$/.test(opacityAttr) ? 100 : 1);
  7999. multiplier = multiplier < 0 ? 0 : multiplier > 1 ? 1 : multiplier;
  8000. if (isNaN(multiplier)) {
  8001. multiplier = 1;
  8002. }
  8003. var colorStopEls = el.getElementsByTagName('stop'),
  8004. type,
  8005. gradientUnits = el.getAttribute('gradientUnits') === 'userSpaceOnUse' ?
  8006. 'pixels' : 'percentage',
  8007. gradientTransform = el.getAttribute('gradientTransform') || '',
  8008. colorStops = [],
  8009. coords, i, offsetX = 0, offsetY = 0,
  8010. transformMatrix;
  8011. if (el.nodeName === 'linearGradient' || el.nodeName === 'LINEARGRADIENT') {
  8012. type = 'linear';
  8013. coords = getLinearCoords(el);
  8014. }
  8015. else {
  8016. type = 'radial';
  8017. coords = getRadialCoords(el);
  8018. }
  8019. for (i = colorStopEls.length; i--; ) {
  8020. colorStops.push(getColorStop(colorStopEls[i], multiplier));
  8021. }
  8022. transformMatrix = fabric.parseTransformAttribute(gradientTransform);
  8023. __convertPercentUnitsToValues(instance, coords, svgOptions, gradientUnits);
  8024. if (gradientUnits === 'pixels') {
  8025. offsetX = -instance.left;
  8026. offsetY = -instance.top;
  8027. }
  8028. var gradient = new fabric.Gradient({
  8029. id: el.getAttribute('id'),
  8030. type: type,
  8031. coords: coords,
  8032. colorStops: colorStops,
  8033. gradientUnits: gradientUnits,
  8034. gradientTransform: transformMatrix,
  8035. offsetX: offsetX,
  8036. offsetY: offsetY,
  8037. });
  8038. return gradient;
  8039. }
  8040. /* _FROM_SVG_END_ */
  8041. });
  8042. /**
  8043. * @private
  8044. */
  8045. function __convertPercentUnitsToValues(instance, options, svgOptions, gradientUnits) {
  8046. var propValue, finalValue;
  8047. Object.keys(options).forEach(function(prop) {
  8048. propValue = options[prop];
  8049. if (propValue === 'Infinity') {
  8050. finalValue = 1;
  8051. }
  8052. else if (propValue === '-Infinity') {
  8053. finalValue = 0;
  8054. }
  8055. else {
  8056. finalValue = parseFloat(options[prop], 10);
  8057. if (typeof propValue === 'string' && /^(\d+\.\d+)%|(\d+)%$/.test(propValue)) {
  8058. finalValue *= 0.01;
  8059. if (gradientUnits === 'pixels') {
  8060. // then we need to fix those percentages here in svg parsing
  8061. if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
  8062. finalValue *= svgOptions.viewBoxWidth || svgOptions.width;
  8063. }
  8064. if (prop === 'y1' || prop === 'y2') {
  8065. finalValue *= svgOptions.viewBoxHeight || svgOptions.height;
  8066. }
  8067. }
  8068. }
  8069. }
  8070. options[prop] = finalValue;
  8071. });
  8072. }
  8073. })();
  8074. (function() {
  8075. 'use strict';
  8076. var toFixed = fabric.util.toFixed;
  8077. /**
  8078. * Pattern class
  8079. * @class fabric.Pattern
  8080. * @see {@link http://fabricjs.com/patterns|Pattern demo}
  8081. * @see {@link http://fabricjs.com/dynamic-patterns|DynamicPattern demo}
  8082. * @see {@link fabric.Pattern#initialize} for constructor definition
  8083. */
  8084. fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {
  8085. /**
  8086. * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  8087. * @type String
  8088. * @default
  8089. */
  8090. repeat: 'repeat',
  8091. /**
  8092. * Pattern horizontal offset from object's left/top corner
  8093. * @type Number
  8094. * @default
  8095. */
  8096. offsetX: 0,
  8097. /**
  8098. * Pattern vertical offset from object's left/top corner
  8099. * @type Number
  8100. * @default
  8101. */
  8102. offsetY: 0,
  8103. /**
  8104. * crossOrigin value (one of "", "anonymous", "use-credentials")
  8105. * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
  8106. * @type String
  8107. * @default
  8108. */
  8109. crossOrigin: '',
  8110. /**
  8111. * transform matrix to change the pattern, imported from svgs.
  8112. * @type Array
  8113. * @default
  8114. */
  8115. patternTransform: null,
  8116. /**
  8117. * Constructor
  8118. * @param {Object} [options] Options object
  8119. * @param {Function} [callback] function to invoke after callback init.
  8120. * @return {fabric.Pattern} thisArg
  8121. */
  8122. initialize: function(options, callback) {
  8123. options || (options = { });
  8124. this.id = fabric.Object.__uid++;
  8125. this.setOptions(options);
  8126. if (!options.source || (options.source && typeof options.source !== 'string')) {
  8127. callback && callback(this);
  8128. return;
  8129. }
  8130. else {
  8131. // img src string
  8132. var _this = this;
  8133. this.source = fabric.util.createImage();
  8134. fabric.util.loadImage(options.source, function(img, isError) {
  8135. _this.source = img;
  8136. callback && callback(_this, isError);
  8137. }, null, this.crossOrigin);
  8138. }
  8139. },
  8140. /**
  8141. * Returns object representation of a pattern
  8142. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  8143. * @return {Object} Object representation of a pattern instance
  8144. */
  8145. toObject: function(propertiesToInclude) {
  8146. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  8147. source, object;
  8148. // <img> element
  8149. if (typeof this.source.src === 'string') {
  8150. source = this.source.src;
  8151. }
  8152. // <canvas> element
  8153. else if (typeof this.source === 'object' && this.source.toDataURL) {
  8154. source = this.source.toDataURL();
  8155. }
  8156. object = {
  8157. type: 'pattern',
  8158. source: source,
  8159. repeat: this.repeat,
  8160. crossOrigin: this.crossOrigin,
  8161. offsetX: toFixed(this.offsetX, NUM_FRACTION_DIGITS),
  8162. offsetY: toFixed(this.offsetY, NUM_FRACTION_DIGITS),
  8163. patternTransform: this.patternTransform ? this.patternTransform.concat() : null
  8164. };
  8165. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  8166. return object;
  8167. },
  8168. /* _TO_SVG_START_ */
  8169. /**
  8170. * Returns SVG representation of a pattern
  8171. * @param {fabric.Object} object
  8172. * @return {String} SVG representation of a pattern
  8173. */
  8174. toSVG: function(object) {
  8175. var patternSource = typeof this.source === 'function' ? this.source() : this.source,
  8176. patternWidth = patternSource.width / object.width,
  8177. patternHeight = patternSource.height / object.height,
  8178. patternOffsetX = this.offsetX / object.width,
  8179. patternOffsetY = this.offsetY / object.height,
  8180. patternImgSrc = '';
  8181. if (this.repeat === 'repeat-x' || this.repeat === 'no-repeat') {
  8182. patternHeight = 1;
  8183. if (patternOffsetY) {
  8184. patternHeight += Math.abs(patternOffsetY);
  8185. }
  8186. }
  8187. if (this.repeat === 'repeat-y' || this.repeat === 'no-repeat') {
  8188. patternWidth = 1;
  8189. if (patternOffsetX) {
  8190. patternWidth += Math.abs(patternOffsetX);
  8191. }
  8192. }
  8193. if (patternSource.src) {
  8194. patternImgSrc = patternSource.src;
  8195. }
  8196. else if (patternSource.toDataURL) {
  8197. patternImgSrc = patternSource.toDataURL();
  8198. }
  8199. return '<pattern id="SVGID_' + this.id +
  8200. '" x="' + patternOffsetX +
  8201. '" y="' + patternOffsetY +
  8202. '" width="' + patternWidth +
  8203. '" height="' + patternHeight + '">\n' +
  8204. '<image x="0" y="0"' +
  8205. ' width="' + patternSource.width +
  8206. '" height="' + patternSource.height +
  8207. '" xlink:href="' + patternImgSrc +
  8208. '"></image>\n' +
  8209. '</pattern>\n';
  8210. },
  8211. /* _TO_SVG_END_ */
  8212. setOptions: function(options) {
  8213. for (var prop in options) {
  8214. this[prop] = options[prop];
  8215. }
  8216. },
  8217. /**
  8218. * Returns an instance of CanvasPattern
  8219. * @param {CanvasRenderingContext2D} ctx Context to create pattern
  8220. * @return {CanvasPattern}
  8221. */
  8222. toLive: function(ctx) {
  8223. var source = this.source;
  8224. // if the image failed to load, return, and allow rest to continue loading
  8225. if (!source) {
  8226. return '';
  8227. }
  8228. // if an image
  8229. if (typeof source.src !== 'undefined') {
  8230. if (!source.complete) {
  8231. return '';
  8232. }
  8233. if (source.naturalWidth === 0 || source.naturalHeight === 0) {
  8234. return '';
  8235. }
  8236. }
  8237. return ctx.createPattern(source, this.repeat);
  8238. }
  8239. });
  8240. })();
  8241. (function(global) {
  8242. 'use strict';
  8243. var fabric = global.fabric || (global.fabric = { }),
  8244. toFixed = fabric.util.toFixed;
  8245. if (fabric.Shadow) {
  8246. fabric.warn('fabric.Shadow is already defined.');
  8247. return;
  8248. }
  8249. /**
  8250. * Shadow class
  8251. * @class fabric.Shadow
  8252. * @see {@link http://fabricjs.com/shadows|Shadow demo}
  8253. * @see {@link fabric.Shadow#initialize} for constructor definition
  8254. */
  8255. fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {
  8256. /**
  8257. * Shadow color
  8258. * @type String
  8259. * @default
  8260. */
  8261. color: 'rgb(0,0,0)',
  8262. /**
  8263. * Shadow blur
  8264. * @type Number
  8265. */
  8266. blur: 0,
  8267. /**
  8268. * Shadow horizontal offset
  8269. * @type Number
  8270. * @default
  8271. */
  8272. offsetX: 0,
  8273. /**
  8274. * Shadow vertical offset
  8275. * @type Number
  8276. * @default
  8277. */
  8278. offsetY: 0,
  8279. /**
  8280. * Whether the shadow should affect stroke operations
  8281. * @type Boolean
  8282. * @default
  8283. */
  8284. affectStroke: false,
  8285. /**
  8286. * Indicates whether toObject should include default values
  8287. * @type Boolean
  8288. * @default
  8289. */
  8290. includeDefaultValues: true,
  8291. /**
  8292. * When `false`, the shadow will scale with the object.
  8293. * When `true`, the shadow's offsetX, offsetY, and blur will not be affected by the object's scale.
  8294. * default to false
  8295. * @type Boolean
  8296. * @default
  8297. */
  8298. nonScaling: false,
  8299. /**
  8300. * Constructor
  8301. * @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")
  8302. * @return {fabric.Shadow} thisArg
  8303. */
  8304. initialize: function(options) {
  8305. if (typeof options === 'string') {
  8306. options = this._parseShadow(options);
  8307. }
  8308. for (var prop in options) {
  8309. this[prop] = options[prop];
  8310. }
  8311. this.id = fabric.Object.__uid++;
  8312. },
  8313. /**
  8314. * @private
  8315. * @param {String} shadow Shadow value to parse
  8316. * @return {Object} Shadow object with color, offsetX, offsetY and blur
  8317. */
  8318. _parseShadow: function(shadow) {
  8319. var shadowStr = shadow.trim(),
  8320. offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [],
  8321. color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';
  8322. return {
  8323. color: color.trim(),
  8324. offsetX: parseFloat(offsetsAndBlur[1], 10) || 0,
  8325. offsetY: parseFloat(offsetsAndBlur[2], 10) || 0,
  8326. blur: parseFloat(offsetsAndBlur[3], 10) || 0
  8327. };
  8328. },
  8329. /**
  8330. * Returns a string representation of an instance
  8331. * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
  8332. * @return {String} Returns CSS3 text-shadow declaration
  8333. */
  8334. toString: function() {
  8335. return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');
  8336. },
  8337. /* _TO_SVG_START_ */
  8338. /**
  8339. * Returns SVG representation of a shadow
  8340. * @param {fabric.Object} object
  8341. * @return {String} SVG representation of a shadow
  8342. */
  8343. toSVG: function(object) {
  8344. var fBoxX = 40, fBoxY = 40, NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  8345. offset = fabric.util.rotateVector(
  8346. { x: this.offsetX, y: this.offsetY },
  8347. fabric.util.degreesToRadians(-object.angle)),
  8348. BLUR_BOX = 20, color = new fabric.Color(this.color);
  8349. if (object.width && object.height) {
  8350. //http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion
  8351. // we add some extra space to filter box to contain the blur ( 20 )
  8352. fBoxX = toFixed((Math.abs(offset.x) + this.blur) / object.width, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;
  8353. fBoxY = toFixed((Math.abs(offset.y) + this.blur) / object.height, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;
  8354. }
  8355. if (object.flipX) {
  8356. offset.x *= -1;
  8357. }
  8358. if (object.flipY) {
  8359. offset.y *= -1;
  8360. }
  8361. return (
  8362. '<filter id="SVGID_' + this.id + '" y="-' + fBoxY + '%" height="' + (100 + 2 * fBoxY) + '%" ' +
  8363. 'x="-' + fBoxX + '%" width="' + (100 + 2 * fBoxX) + '%" ' + '>\n' +
  8364. '\t<feGaussianBlur in="SourceAlpha" stdDeviation="' +
  8365. toFixed(this.blur ? this.blur / 2 : 0, NUM_FRACTION_DIGITS) + '"></feGaussianBlur>\n' +
  8366. '\t<feOffset dx="' + toFixed(offset.x, NUM_FRACTION_DIGITS) +
  8367. '" dy="' + toFixed(offset.y, NUM_FRACTION_DIGITS) + '" result="oBlur" ></feOffset>\n' +
  8368. '\t<feFlood flood-color="' + color.toRgb() + '" flood-opacity="' + color.getAlpha() + '"/>\n' +
  8369. '\t<feComposite in2="oBlur" operator="in" />\n' +
  8370. '\t<feMerge>\n' +
  8371. '\t\t<feMergeNode></feMergeNode>\n' +
  8372. '\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n' +
  8373. '\t</feMerge>\n' +
  8374. '</filter>\n');
  8375. },
  8376. /* _TO_SVG_END_ */
  8377. /**
  8378. * Returns object representation of a shadow
  8379. * @return {Object} Object representation of a shadow instance
  8380. */
  8381. toObject: function() {
  8382. if (this.includeDefaultValues) {
  8383. return {
  8384. color: this.color,
  8385. blur: this.blur,
  8386. offsetX: this.offsetX,
  8387. offsetY: this.offsetY,
  8388. affectStroke: this.affectStroke,
  8389. nonScaling: this.nonScaling
  8390. };
  8391. }
  8392. var obj = { }, proto = fabric.Shadow.prototype;
  8393. ['color', 'blur', 'offsetX', 'offsetY', 'affectStroke', 'nonScaling'].forEach(function(prop) {
  8394. if (this[prop] !== proto[prop]) {
  8395. obj[prop] = this[prop];
  8396. }
  8397. }, this);
  8398. return obj;
  8399. }
  8400. });
  8401. /**
  8402. * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
  8403. * @static
  8404. * @field
  8405. * @memberOf fabric.Shadow
  8406. */
  8407. // eslint-disable-next-line max-len
  8408. fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/;
  8409. })(typeof exports !== 'undefined' ? exports : this);
  8410. (function () {
  8411. 'use strict';
  8412. if (fabric.StaticCanvas) {
  8413. fabric.warn('fabric.StaticCanvas is already defined.');
  8414. return;
  8415. }
  8416. // aliases for faster resolution
  8417. var extend = fabric.util.object.extend,
  8418. getElementOffset = fabric.util.getElementOffset,
  8419. removeFromArray = fabric.util.removeFromArray,
  8420. toFixed = fabric.util.toFixed,
  8421. transformPoint = fabric.util.transformPoint,
  8422. invertTransform = fabric.util.invertTransform,
  8423. getNodeCanvas = fabric.util.getNodeCanvas,
  8424. createCanvasElement = fabric.util.createCanvasElement,
  8425. CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');
  8426. /**
  8427. * Static canvas class
  8428. * @class fabric.StaticCanvas
  8429. * @mixes fabric.Collection
  8430. * @mixes fabric.Observable
  8431. * @see {@link http://fabricjs.com/static_canvas|StaticCanvas demo}
  8432. * @see {@link fabric.StaticCanvas#initialize} for constructor definition
  8433. * @fires before:render
  8434. * @fires after:render
  8435. * @fires canvas:cleared
  8436. * @fires object:added
  8437. * @fires object:removed
  8438. */
  8439. fabric.StaticCanvas = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.StaticCanvas.prototype */ {
  8440. /**
  8441. * Constructor
  8442. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  8443. * @param {Object} [options] Options object
  8444. * @return {Object} thisArg
  8445. */
  8446. initialize: function(el, options) {
  8447. options || (options = { });
  8448. this.renderAndResetBound = this.renderAndReset.bind(this);
  8449. this.requestRenderAllBound = this.requestRenderAll.bind(this);
  8450. this._initStatic(el, options);
  8451. },
  8452. /**
  8453. * Background color of canvas instance.
  8454. * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.
  8455. * @type {(String|fabric.Pattern)}
  8456. * @default
  8457. */
  8458. backgroundColor: '',
  8459. /**
  8460. * Background image of canvas instance.
  8461. * since 2.4.0 image caching is active, please when putting an image as background, add to the
  8462. * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom
  8463. * vale. As an alternative you can disable image objectCaching
  8464. * @type fabric.Image
  8465. * @default
  8466. */
  8467. backgroundImage: null,
  8468. /**
  8469. * Overlay color of canvas instance.
  8470. * Should be set via {@link fabric.StaticCanvas#setOverlayColor}
  8471. * @since 1.3.9
  8472. * @type {(String|fabric.Pattern)}
  8473. * @default
  8474. */
  8475. overlayColor: '',
  8476. /**
  8477. * Overlay image of canvas instance.
  8478. * since 2.4.0 image caching is active, please when putting an image as overlay, add to the
  8479. * canvas property a reference to the canvas it is on. Otherwise the image cannot detect the zoom
  8480. * vale. As an alternative you can disable image objectCaching
  8481. * @type fabric.Image
  8482. * @default
  8483. */
  8484. overlayImage: null,
  8485. /**
  8486. * Indicates whether toObject/toDatalessObject should include default values
  8487. * if set to false, takes precedence over the object value.
  8488. * @type Boolean
  8489. * @default
  8490. */
  8491. includeDefaultValues: true,
  8492. /**
  8493. * Indicates whether objects' state should be saved
  8494. * @type Boolean
  8495. * @default
  8496. */
  8497. stateful: false,
  8498. /**
  8499. * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove},
  8500. * {@link fabric.StaticCanvas.moveTo}, {@link fabric.StaticCanvas.clear} and many more, should also re-render canvas.
  8501. * Disabling this option will not give a performance boost when adding/removing a lot of objects to/from canvas at once
  8502. * since the renders are quequed and executed one per frame.
  8503. * Disabling is suggested anyway and managing the renders of the app manually is not a big effort ( canvas.requestRenderAll() )
  8504. * Left default to true to do not break documentation and old app, fiddles.
  8505. * @type Boolean
  8506. * @default
  8507. */
  8508. renderOnAddRemove: true,
  8509. /**
  8510. * Indicates whether object controls (borders/controls) are rendered above overlay image
  8511. * @type Boolean
  8512. * @default
  8513. */
  8514. controlsAboveOverlay: false,
  8515. /**
  8516. * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
  8517. * @type Boolean
  8518. * @default
  8519. */
  8520. allowTouchScrolling: false,
  8521. /**
  8522. * Indicates whether this canvas will use image smoothing, this is on by default in browsers
  8523. * @type Boolean
  8524. * @default
  8525. */
  8526. imageSmoothingEnabled: true,
  8527. /**
  8528. * The transformation (a Canvas 2D API transform matrix) which focuses the viewport
  8529. * @type Array
  8530. * @example <caption>Default transform</caption>
  8531. * canvas.viewportTransform = [1, 0, 0, 1, 0, 0];
  8532. * @example <caption>Scale by 70% and translate toward bottom-right by 50, without skewing</caption>
  8533. * canvas.viewportTransform = [0.7, 0, 0, 0.7, 50, 50];
  8534. * @default
  8535. */
  8536. viewportTransform: fabric.iMatrix.concat(),
  8537. /**
  8538. * if set to false background image is not affected by viewport transform
  8539. * @since 1.6.3
  8540. * @type Boolean
  8541. * @default
  8542. */
  8543. backgroundVpt: true,
  8544. /**
  8545. * if set to false overlya image is not affected by viewport transform
  8546. * @since 1.6.3
  8547. * @type Boolean
  8548. * @default
  8549. */
  8550. overlayVpt: true,
  8551. /**
  8552. * When true, canvas is scaled by devicePixelRatio for better rendering on retina screens
  8553. * @type Boolean
  8554. * @default
  8555. */
  8556. enableRetinaScaling: true,
  8557. /**
  8558. * Describe canvas element extension over design
  8559. * properties are tl,tr,bl,br.
  8560. * if canvas is not zoomed/panned those points are the four corner of canvas
  8561. * if canvas is viewportTransformed you those points indicate the extension
  8562. * of canvas element in plain untrasformed coordinates
  8563. * The coordinates get updated with @method calcViewportBoundaries.
  8564. * @memberOf fabric.StaticCanvas.prototype
  8565. */
  8566. vptCoords: { },
  8567. /**
  8568. * Based on vptCoords and object.aCoords, skip rendering of objects that
  8569. * are not included in current viewport.
  8570. * May greatly help in applications with crowded canvas and use of zoom/pan
  8571. * If One of the corner of the bounding box of the object is on the canvas
  8572. * the objects get rendered.
  8573. * @memberOf fabric.StaticCanvas.prototype
  8574. * @type Boolean
  8575. * @default
  8576. */
  8577. skipOffscreen: true,
  8578. /**
  8579. * a fabricObject that, without stroke define a clipping area with their shape. filled in black
  8580. * the clipPath object gets used when the canvas has rendered, and the context is placed in the
  8581. * top left corner of the canvas.
  8582. * clipPath will clip away controls, if you do not want this to happen use controlsAboveOverlay = true
  8583. * @type fabric.Object
  8584. */
  8585. clipPath: undefined,
  8586. /**
  8587. * @private
  8588. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  8589. * @param {Object} [options] Options object
  8590. */
  8591. _initStatic: function(el, options) {
  8592. var cb = this.requestRenderAllBound;
  8593. this._objects = [];
  8594. this._createLowerCanvas(el);
  8595. this._initOptions(options);
  8596. // only initialize retina scaling once
  8597. if (!this.interactive) {
  8598. this._initRetinaScaling();
  8599. }
  8600. if (options.overlayImage) {
  8601. this.setOverlayImage(options.overlayImage, cb);
  8602. }
  8603. if (options.backgroundImage) {
  8604. this.setBackgroundImage(options.backgroundImage, cb);
  8605. }
  8606. if (options.backgroundColor) {
  8607. this.setBackgroundColor(options.backgroundColor, cb);
  8608. }
  8609. if (options.overlayColor) {
  8610. this.setOverlayColor(options.overlayColor, cb);
  8611. }
  8612. this.calcOffset();
  8613. },
  8614. /**
  8615. * @private
  8616. */
  8617. _isRetinaScaling: function() {
  8618. return (fabric.devicePixelRatio > 1 && this.enableRetinaScaling);
  8619. },
  8620. /**
  8621. * @private
  8622. * @return {Number} retinaScaling if applied, otherwise 1;
  8623. */
  8624. getRetinaScaling: function() {
  8625. return this._isRetinaScaling() ? Math.max(1, fabric.devicePixelRatio) : 1;
  8626. },
  8627. /**
  8628. * @private
  8629. */
  8630. _initRetinaScaling: function() {
  8631. if (!this._isRetinaScaling()) {
  8632. return;
  8633. }
  8634. var scaleRatio = fabric.devicePixelRatio;
  8635. this.__initRetinaScaling(scaleRatio, this.lowerCanvasEl, this.contextContainer);
  8636. if (this.upperCanvasEl) {
  8637. this.__initRetinaScaling(scaleRatio, this.upperCanvasEl, this.contextTop);
  8638. }
  8639. },
  8640. __initRetinaScaling: function(scaleRatio, canvas, context) {
  8641. canvas.setAttribute('width', this.width * scaleRatio);
  8642. canvas.setAttribute('height', this.height * scaleRatio);
  8643. context.scale(scaleRatio, scaleRatio);
  8644. },
  8645. /**
  8646. * Calculates canvas element offset relative to the document
  8647. * This method is also attached as "resize" event handler of window
  8648. * @return {fabric.Canvas} instance
  8649. * @chainable
  8650. */
  8651. calcOffset: function () {
  8652. this._offset = getElementOffset(this.lowerCanvasEl);
  8653. return this;
  8654. },
  8655. /**
  8656. * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
  8657. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to
  8658. * @param {Function} callback callback to invoke when image is loaded and set as an overlay
  8659. * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.
  8660. * @return {fabric.Canvas} thisArg
  8661. * @chainable
  8662. * @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}
  8663. * @example <caption>Normal overlayImage with left/top = 0</caption>
  8664. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  8665. * // Needed to position overlayImage at 0/0
  8666. * originX: 'left',
  8667. * originY: 'top'
  8668. * });
  8669. * @example <caption>overlayImage with different properties</caption>
  8670. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  8671. * opacity: 0.5,
  8672. * angle: 45,
  8673. * left: 400,
  8674. * top: 400,
  8675. * originX: 'left',
  8676. * originY: 'top'
  8677. * });
  8678. * @example <caption>Stretched overlayImage #1 - width/height correspond to canvas width/height</caption>
  8679. * fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img, isError) {
  8680. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  8681. * canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));
  8682. * });
  8683. * @example <caption>Stretched overlayImage #2 - width/height correspond to canvas width/height</caption>
  8684. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  8685. * width: canvas.width,
  8686. * height: canvas.height,
  8687. * // Needed to position overlayImage at 0/0
  8688. * originX: 'left',
  8689. * originY: 'top'
  8690. * });
  8691. * @example <caption>overlayImage loaded from cross-origin</caption>
  8692. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  8693. * opacity: 0.5,
  8694. * angle: 45,
  8695. * left: 400,
  8696. * top: 400,
  8697. * originX: 'left',
  8698. * originY: 'top',
  8699. * crossOrigin: 'anonymous'
  8700. * });
  8701. */
  8702. setOverlayImage: function (image, callback, options) {
  8703. return this.__setBgOverlayImage('overlayImage', image, callback, options);
  8704. },
  8705. /**
  8706. * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
  8707. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to
  8708. * @param {Function} callback Callback to invoke when image is loaded and set as background
  8709. * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.
  8710. * @return {fabric.Canvas} thisArg
  8711. * @chainable
  8712. * @see {@link http://jsfiddle.net/djnr8o7a/28/|jsFiddle demo}
  8713. * @example <caption>Normal backgroundImage with left/top = 0</caption>
  8714. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  8715. * // Needed to position backgroundImage at 0/0
  8716. * originX: 'left',
  8717. * originY: 'top'
  8718. * });
  8719. * @example <caption>backgroundImage with different properties</caption>
  8720. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  8721. * opacity: 0.5,
  8722. * angle: 45,
  8723. * left: 400,
  8724. * top: 400,
  8725. * originX: 'left',
  8726. * originY: 'top'
  8727. * });
  8728. * @example <caption>Stretched backgroundImage #1 - width/height correspond to canvas width/height</caption>
  8729. * fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img, isError) {
  8730. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  8731. * canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
  8732. * });
  8733. * @example <caption>Stretched backgroundImage #2 - width/height correspond to canvas width/height</caption>
  8734. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  8735. * width: canvas.width,
  8736. * height: canvas.height,
  8737. * // Needed to position backgroundImage at 0/0
  8738. * originX: 'left',
  8739. * originY: 'top'
  8740. * });
  8741. * @example <caption>backgroundImage loaded from cross-origin</caption>
  8742. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  8743. * opacity: 0.5,
  8744. * angle: 45,
  8745. * left: 400,
  8746. * top: 400,
  8747. * originX: 'left',
  8748. * originY: 'top',
  8749. * crossOrigin: 'anonymous'
  8750. * });
  8751. */
  8752. // TODO: fix stretched examples
  8753. setBackgroundImage: function (image, callback, options) {
  8754. return this.__setBgOverlayImage('backgroundImage', image, callback, options);
  8755. },
  8756. /**
  8757. * Sets {@link fabric.StaticCanvas#overlayColor|foreground color} for this canvas
  8758. * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set foreground color to
  8759. * @param {Function} callback Callback to invoke when foreground color is set
  8760. * @return {fabric.Canvas} thisArg
  8761. * @chainable
  8762. * @see {@link http://jsfiddle.net/fabricjs/pB55h/|jsFiddle demo}
  8763. * @example <caption>Normal overlayColor - color value</caption>
  8764. * canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  8765. * @example <caption>fabric.Pattern used as overlayColor</caption>
  8766. * canvas.setOverlayColor({
  8767. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  8768. * }, canvas.renderAll.bind(canvas));
  8769. * @example <caption>fabric.Pattern used as overlayColor with repeat and offset</caption>
  8770. * canvas.setOverlayColor({
  8771. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  8772. * repeat: 'repeat',
  8773. * offsetX: 200,
  8774. * offsetY: 100
  8775. * }, canvas.renderAll.bind(canvas));
  8776. */
  8777. setOverlayColor: function(overlayColor, callback) {
  8778. return this.__setBgOverlayColor('overlayColor', overlayColor, callback);
  8779. },
  8780. /**
  8781. * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas
  8782. * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to
  8783. * @param {Function} callback Callback to invoke when background color is set
  8784. * @return {fabric.Canvas} thisArg
  8785. * @chainable
  8786. * @see {@link http://jsfiddle.net/fabricjs/hXzvk/|jsFiddle demo}
  8787. * @example <caption>Normal backgroundColor - color value</caption>
  8788. * canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  8789. * @example <caption>fabric.Pattern used as backgroundColor</caption>
  8790. * canvas.setBackgroundColor({
  8791. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  8792. * }, canvas.renderAll.bind(canvas));
  8793. * @example <caption>fabric.Pattern used as backgroundColor with repeat and offset</caption>
  8794. * canvas.setBackgroundColor({
  8795. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  8796. * repeat: 'repeat',
  8797. * offsetX: 200,
  8798. * offsetY: 100
  8799. * }, canvas.renderAll.bind(canvas));
  8800. */
  8801. setBackgroundColor: function(backgroundColor, callback) {
  8802. return this.__setBgOverlayColor('backgroundColor', backgroundColor, callback);
  8803. },
  8804. /**
  8805. * @private
  8806. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundImage|backgroundImage}
  8807. * or {@link fabric.StaticCanvas#overlayImage|overlayImage})
  8808. * @param {(fabric.Image|String|null)} image fabric.Image instance, URL of an image or null to set background or overlay to
  8809. * @param {Function} callback Callback to invoke when image is loaded and set as background or overlay. The first argument is the created image, the second argument is a flag indicating whether an error occurred or not.
  8810. * @param {Object} [options] Optional options to set for the {@link fabric.Image|image}.
  8811. */
  8812. __setBgOverlayImage: function(property, image, callback, options) {
  8813. if (typeof image === 'string') {
  8814. fabric.util.loadImage(image, function(img, isError) {
  8815. if (img) {
  8816. var instance = new fabric.Image(img, options);
  8817. this[property] = instance;
  8818. instance.canvas = this;
  8819. }
  8820. callback && callback(img, isError);
  8821. }, this, options && options.crossOrigin);
  8822. }
  8823. else {
  8824. options && image.setOptions(options);
  8825. this[property] = image;
  8826. image && (image.canvas = this);
  8827. callback && callback(image, false);
  8828. }
  8829. return this;
  8830. },
  8831. /**
  8832. * @private
  8833. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundColor|backgroundColor}
  8834. * or {@link fabric.StaticCanvas#overlayColor|overlayColor})
  8835. * @param {(Object|String|null)} color Object with pattern information, color value or null
  8836. * @param {Function} [callback] Callback is invoked when color is set
  8837. */
  8838. __setBgOverlayColor: function(property, color, callback) {
  8839. this[property] = color;
  8840. this._initGradient(color, property);
  8841. this._initPattern(color, property, callback);
  8842. return this;
  8843. },
  8844. /**
  8845. * @private
  8846. */
  8847. _createCanvasElement: function() {
  8848. var element = createCanvasElement();
  8849. if (!element) {
  8850. throw CANVAS_INIT_ERROR;
  8851. }
  8852. if (!element.style) {
  8853. element.style = { };
  8854. }
  8855. if (typeof element.getContext === 'undefined') {
  8856. throw CANVAS_INIT_ERROR;
  8857. }
  8858. return element;
  8859. },
  8860. /**
  8861. * @private
  8862. * @param {Object} [options] Options object
  8863. */
  8864. _initOptions: function (options) {
  8865. var lowerCanvasEl = this.lowerCanvasEl;
  8866. this._setOptions(options);
  8867. this.width = this.width || parseInt(lowerCanvasEl.width, 10) || 0;
  8868. this.height = this.height || parseInt(lowerCanvasEl.height, 10) || 0;
  8869. if (!this.lowerCanvasEl.style) {
  8870. return;
  8871. }
  8872. lowerCanvasEl.width = this.width;
  8873. lowerCanvasEl.height = this.height;
  8874. lowerCanvasEl.style.width = this.width + 'px';
  8875. lowerCanvasEl.style.height = this.height + 'px';
  8876. this.viewportTransform = this.viewportTransform.slice();
  8877. },
  8878. /**
  8879. * Creates a bottom canvas
  8880. * @private
  8881. * @param {HTMLElement} [canvasEl]
  8882. */
  8883. _createLowerCanvas: function (canvasEl) {
  8884. // canvasEl === 'HTMLCanvasElement' does not work on jsdom/node
  8885. if (canvasEl && canvasEl.getContext) {
  8886. this.lowerCanvasEl = canvasEl;
  8887. }
  8888. else {
  8889. this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();
  8890. }
  8891. fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');
  8892. this._originalCanvasStyle = this.lowerCanvasEl.style;
  8893. if (this.interactive) {
  8894. this._applyCanvasStyle(this.lowerCanvasEl);
  8895. }
  8896. this.contextContainer = this.lowerCanvasEl.getContext('2d');
  8897. },
  8898. /**
  8899. * Returns canvas width (in px)
  8900. * @return {Number}
  8901. */
  8902. getWidth: function () {
  8903. return this.width;
  8904. },
  8905. /**
  8906. * Returns canvas height (in px)
  8907. * @return {Number}
  8908. */
  8909. getHeight: function () {
  8910. return this.height;
  8911. },
  8912. /**
  8913. * Sets width of this canvas instance
  8914. * @param {Number|String} value Value to set width to
  8915. * @param {Object} [options] Options object
  8916. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  8917. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  8918. * @return {fabric.Canvas} instance
  8919. * @chainable true
  8920. */
  8921. setWidth: function (value, options) {
  8922. return this.setDimensions({ width: value }, options);
  8923. },
  8924. /**
  8925. * Sets height of this canvas instance
  8926. * @param {Number|String} value Value to set height to
  8927. * @param {Object} [options] Options object
  8928. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  8929. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  8930. * @return {fabric.Canvas} instance
  8931. * @chainable true
  8932. */
  8933. setHeight: function (value, options) {
  8934. return this.setDimensions({ height: value }, options);
  8935. },
  8936. /**
  8937. * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
  8938. * @param {Object} dimensions Object with width/height properties
  8939. * @param {Number|String} [dimensions.width] Width of canvas element
  8940. * @param {Number|String} [dimensions.height] Height of canvas element
  8941. * @param {Object} [options] Options object
  8942. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  8943. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  8944. * @return {fabric.Canvas} thisArg
  8945. * @chainable
  8946. */
  8947. setDimensions: function (dimensions, options) {
  8948. var cssValue;
  8949. options = options || {};
  8950. for (var prop in dimensions) {
  8951. cssValue = dimensions[prop];
  8952. if (!options.cssOnly) {
  8953. this._setBackstoreDimension(prop, dimensions[prop]);
  8954. cssValue += 'px';
  8955. this.hasLostContext = true;
  8956. }
  8957. if (!options.backstoreOnly) {
  8958. this._setCssDimension(prop, cssValue);
  8959. }
  8960. }
  8961. if (this._isCurrentlyDrawing) {
  8962. this.freeDrawingBrush && this.freeDrawingBrush._setBrushStyles(this.contextTop);
  8963. }
  8964. this._initRetinaScaling();
  8965. this.calcOffset();
  8966. if (!options.cssOnly) {
  8967. this.requestRenderAll();
  8968. }
  8969. return this;
  8970. },
  8971. /**
  8972. * Helper for setting width/height
  8973. * @private
  8974. * @param {String} prop property (width|height)
  8975. * @param {Number} value value to set property to
  8976. * @return {fabric.Canvas} instance
  8977. * @chainable true
  8978. */
  8979. _setBackstoreDimension: function (prop, value) {
  8980. this.lowerCanvasEl[prop] = value;
  8981. if (this.upperCanvasEl) {
  8982. this.upperCanvasEl[prop] = value;
  8983. }
  8984. if (this.cacheCanvasEl) {
  8985. this.cacheCanvasEl[prop] = value;
  8986. }
  8987. this[prop] = value;
  8988. return this;
  8989. },
  8990. /**
  8991. * Helper for setting css width/height
  8992. * @private
  8993. * @param {String} prop property (width|height)
  8994. * @param {String} value value to set property to
  8995. * @return {fabric.Canvas} instance
  8996. * @chainable true
  8997. */
  8998. _setCssDimension: function (prop, value) {
  8999. this.lowerCanvasEl.style[prop] = value;
  9000. if (this.upperCanvasEl) {
  9001. this.upperCanvasEl.style[prop] = value;
  9002. }
  9003. if (this.wrapperEl) {
  9004. this.wrapperEl.style[prop] = value;
  9005. }
  9006. return this;
  9007. },
  9008. /**
  9009. * Returns canvas zoom level
  9010. * @return {Number}
  9011. */
  9012. getZoom: function () {
  9013. return this.viewportTransform[0];
  9014. },
  9015. /**
  9016. * Sets viewport transformation of this canvas instance
  9017. * @param {Array} vpt a Canvas 2D API transform matrix
  9018. * @return {fabric.Canvas} instance
  9019. * @chainable true
  9020. */
  9021. setViewportTransform: function (vpt) {
  9022. var activeObject = this._activeObject,
  9023. backgroundObject = this.backgroundImage,
  9024. overlayObject = this.overlayImage,
  9025. object, i, len;
  9026. this.viewportTransform = vpt;
  9027. for (i = 0, len = this._objects.length; i < len; i++) {
  9028. object = this._objects[i];
  9029. object.group || object.setCoords(true);
  9030. }
  9031. if (activeObject) {
  9032. activeObject.setCoords();
  9033. }
  9034. if (backgroundObject) {
  9035. backgroundObject.setCoords(true);
  9036. }
  9037. if (overlayObject) {
  9038. overlayObject.setCoords(true);
  9039. }
  9040. this.calcViewportBoundaries();
  9041. this.renderOnAddRemove && this.requestRenderAll();
  9042. return this;
  9043. },
  9044. /**
  9045. * Sets zoom level of this canvas instance, the zoom centered around point
  9046. * meaning that following zoom to point with the same point will have the visual
  9047. * effect of the zoom originating from that point. The point won't move.
  9048. * It has nothing to do with canvas center or visual center of the viewport.
  9049. * @param {fabric.Point} point to zoom with respect to
  9050. * @param {Number} value to set zoom to, less than 1 zooms out
  9051. * @return {fabric.Canvas} instance
  9052. * @chainable true
  9053. */
  9054. zoomToPoint: function (point, value) {
  9055. // TODO: just change the scale, preserve other transformations
  9056. var before = point, vpt = this.viewportTransform.slice(0);
  9057. point = transformPoint(point, invertTransform(this.viewportTransform));
  9058. vpt[0] = value;
  9059. vpt[3] = value;
  9060. var after = transformPoint(point, vpt);
  9061. vpt[4] += before.x - after.x;
  9062. vpt[5] += before.y - after.y;
  9063. return this.setViewportTransform(vpt);
  9064. },
  9065. /**
  9066. * Sets zoom level of this canvas instance
  9067. * @param {Number} value to set zoom to, less than 1 zooms out
  9068. * @return {fabric.Canvas} instance
  9069. * @chainable true
  9070. */
  9071. setZoom: function (value) {
  9072. this.zoomToPoint(new fabric.Point(0, 0), value);
  9073. return this;
  9074. },
  9075. /**
  9076. * Pan viewport so as to place point at top left corner of canvas
  9077. * @param {fabric.Point} point to move to
  9078. * @return {fabric.Canvas} instance
  9079. * @chainable true
  9080. */
  9081. absolutePan: function (point) {
  9082. var vpt = this.viewportTransform.slice(0);
  9083. vpt[4] = -point.x;
  9084. vpt[5] = -point.y;
  9085. return this.setViewportTransform(vpt);
  9086. },
  9087. /**
  9088. * Pans viewpoint relatively
  9089. * @param {fabric.Point} point (position vector) to move by
  9090. * @return {fabric.Canvas} instance
  9091. * @chainable true
  9092. */
  9093. relativePan: function (point) {
  9094. return this.absolutePan(new fabric.Point(
  9095. -point.x - this.viewportTransform[4],
  9096. -point.y - this.viewportTransform[5]
  9097. ));
  9098. },
  9099. /**
  9100. * Returns &lt;canvas> element corresponding to this instance
  9101. * @return {HTMLCanvasElement}
  9102. */
  9103. getElement: function () {
  9104. return this.lowerCanvasEl;
  9105. },
  9106. /**
  9107. * @private
  9108. * @param {fabric.Object} obj Object that was added
  9109. */
  9110. _onObjectAdded: function(obj) {
  9111. this.stateful && obj.setupState();
  9112. obj._set('canvas', this);
  9113. obj.setCoords();
  9114. this.fire('object:added', { target: obj });
  9115. obj.fire('added');
  9116. },
  9117. /**
  9118. * @private
  9119. * @param {fabric.Object} obj Object that was removed
  9120. */
  9121. _onObjectRemoved: function(obj) {
  9122. this.fire('object:removed', { target: obj });
  9123. obj.fire('removed');
  9124. delete obj.canvas;
  9125. },
  9126. /**
  9127. * Clears specified context of canvas element
  9128. * @param {CanvasRenderingContext2D} ctx Context to clear
  9129. * @return {fabric.Canvas} thisArg
  9130. * @chainable
  9131. */
  9132. clearContext: function(ctx) {
  9133. ctx.clearRect(0, 0, this.width, this.height);
  9134. return this;
  9135. },
  9136. /**
  9137. * Returns context of canvas where objects are drawn
  9138. * @return {CanvasRenderingContext2D}
  9139. */
  9140. getContext: function () {
  9141. return this.contextContainer;
  9142. },
  9143. /**
  9144. * Clears all contexts (background, main, top) of an instance
  9145. * @return {fabric.Canvas} thisArg
  9146. * @chainable
  9147. */
  9148. clear: function () {
  9149. this.remove.apply(this, this.getObjects());
  9150. this.backgroundImage = null;
  9151. this.overlayImage = null;
  9152. this.backgroundColor = '';
  9153. this.overlayColor = '';
  9154. if (this._hasITextHandlers) {
  9155. this.off('mouse:up', this._mouseUpITextHandler);
  9156. this._iTextInstances = null;
  9157. this._hasITextHandlers = false;
  9158. }
  9159. this.clearContext(this.contextContainer);
  9160. this.fire('canvas:cleared');
  9161. this.renderOnAddRemove && this.requestRenderAll();
  9162. return this;
  9163. },
  9164. /**
  9165. * Renders the canvas
  9166. * @return {fabric.Canvas} instance
  9167. * @chainable
  9168. */
  9169. renderAll: function () {
  9170. var canvasToDrawOn = this.contextContainer;
  9171. this.renderCanvas(canvasToDrawOn, this._objects);
  9172. return this;
  9173. },
  9174. /**
  9175. * Function created to be instance bound at initialization
  9176. * used in requestAnimationFrame rendering
  9177. * Let the fabricJS call it. If you call it manually you could have more
  9178. * animationFrame stacking on to of each other
  9179. * for an imperative rendering, use canvas.renderAll
  9180. * @private
  9181. * @return {fabric.Canvas} instance
  9182. * @chainable
  9183. */
  9184. renderAndReset: function() {
  9185. this.isRendering = 0;
  9186. this.renderAll();
  9187. },
  9188. /**
  9189. * Append a renderAll request to next animation frame.
  9190. * unless one is already in progress, in that case nothing is done
  9191. * a boolean flag will avoid appending more.
  9192. * @return {fabric.Canvas} instance
  9193. * @chainable
  9194. */
  9195. requestRenderAll: function () {
  9196. if (!this.isRendering) {
  9197. this.isRendering = fabric.util.requestAnimFrame(this.renderAndResetBound);
  9198. }
  9199. return this;
  9200. },
  9201. /**
  9202. * Calculate the position of the 4 corner of canvas with current viewportTransform.
  9203. * helps to determinate when an object is in the current rendering viewport using
  9204. * object absolute coordinates ( aCoords )
  9205. * @return {Object} points.tl
  9206. * @chainable
  9207. */
  9208. calcViewportBoundaries: function() {
  9209. var points = { }, width = this.width, height = this.height,
  9210. iVpt = invertTransform(this.viewportTransform);
  9211. points.tl = transformPoint({ x: 0, y: 0 }, iVpt);
  9212. points.br = transformPoint({ x: width, y: height }, iVpt);
  9213. points.tr = new fabric.Point(points.br.x, points.tl.y);
  9214. points.bl = new fabric.Point(points.tl.x, points.br.y);
  9215. this.vptCoords = points;
  9216. return points;
  9217. },
  9218. cancelRequestedRender: function() {
  9219. if (this.isRendering) {
  9220. fabric.util.cancelAnimFrame(this.isRendering);
  9221. this.isRendering = 0;
  9222. }
  9223. },
  9224. /**
  9225. * Renders background, objects, overlay and controls.
  9226. * @param {CanvasRenderingContext2D} ctx
  9227. * @param {Array} objects to render
  9228. * @return {fabric.Canvas} instance
  9229. * @chainable
  9230. */
  9231. renderCanvas: function(ctx, objects) {
  9232. var v = this.viewportTransform, path = this.clipPath;
  9233. this.cancelRequestedRender();
  9234. this.calcViewportBoundaries();
  9235. this.clearContext(ctx);
  9236. fabric.util.setImageSmoothing(ctx, this.imageSmoothingEnabled);
  9237. this.fire('before:render', { ctx: ctx, });
  9238. this._renderBackground(ctx);
  9239. ctx.save();
  9240. //apply viewport transform once for all rendering process
  9241. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  9242. this._renderObjects(ctx, objects);
  9243. ctx.restore();
  9244. if (!this.controlsAboveOverlay && this.interactive) {
  9245. this.drawControls(ctx);
  9246. }
  9247. if (path) {
  9248. path.canvas = this;
  9249. // needed to setup a couple of variables
  9250. path.shouldCache();
  9251. path._transformDone = true;
  9252. path.renderCache({ forClipping: true });
  9253. this.drawClipPathOnCanvas(ctx);
  9254. }
  9255. this._renderOverlay(ctx);
  9256. if (this.controlsAboveOverlay && this.interactive) {
  9257. this.drawControls(ctx);
  9258. }
  9259. this.fire('after:render', { ctx: ctx, });
  9260. },
  9261. /**
  9262. * Paint the cached clipPath on the lowerCanvasEl
  9263. * @param {CanvasRenderingContext2D} ctx Context to render on
  9264. */
  9265. drawClipPathOnCanvas: function(ctx) {
  9266. var v = this.viewportTransform, path = this.clipPath;
  9267. ctx.save();
  9268. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  9269. // DEBUG: uncomment this line, comment the following
  9270. // ctx.globalAlpha = 0.4;
  9271. ctx.globalCompositeOperation = 'destination-in';
  9272. path.transform(ctx);
  9273. ctx.scale(1 / path.zoomX, 1 / path.zoomY);
  9274. ctx.drawImage(path._cacheCanvas, -path.cacheTranslationX, -path.cacheTranslationY);
  9275. ctx.restore();
  9276. },
  9277. /**
  9278. * @private
  9279. * @param {CanvasRenderingContext2D} ctx Context to render on
  9280. * @param {Array} objects to render
  9281. */
  9282. _renderObjects: function(ctx, objects) {
  9283. var i, len;
  9284. for (i = 0, len = objects.length; i < len; ++i) {
  9285. objects[i] && objects[i].render(ctx);
  9286. }
  9287. },
  9288. /**
  9289. * @private
  9290. * @param {CanvasRenderingContext2D} ctx Context to render on
  9291. * @param {string} property 'background' or 'overlay'
  9292. */
  9293. _renderBackgroundOrOverlay: function(ctx, property) {
  9294. var fill = this[property + 'Color'], object = this[property + 'Image'],
  9295. v = this.viewportTransform, needsVpt = this[property + 'Vpt'];
  9296. if (!fill && !object) {
  9297. return;
  9298. }
  9299. if (fill) {
  9300. ctx.save();
  9301. ctx.beginPath();
  9302. ctx.moveTo(0, 0);
  9303. ctx.lineTo(this.width, 0);
  9304. ctx.lineTo(this.width, this.height);
  9305. ctx.lineTo(0, this.height);
  9306. ctx.closePath();
  9307. ctx.fillStyle = fill.toLive
  9308. ? fill.toLive(ctx, this)
  9309. : fill;
  9310. if (needsVpt) {
  9311. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  9312. }
  9313. ctx.transform(1, 0, 0, 1, fill.offsetX || 0, fill.offsetY || 0);
  9314. var m = fill.gradientTransform || fill.patternTransform;
  9315. m && ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  9316. ctx.fill();
  9317. ctx.restore();
  9318. }
  9319. if (object) {
  9320. ctx.save();
  9321. if (needsVpt) {
  9322. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  9323. }
  9324. object.render(ctx);
  9325. ctx.restore();
  9326. }
  9327. },
  9328. /**
  9329. * @private
  9330. * @param {CanvasRenderingContext2D} ctx Context to render on
  9331. */
  9332. _renderBackground: function(ctx) {
  9333. this._renderBackgroundOrOverlay(ctx, 'background');
  9334. },
  9335. /**
  9336. * @private
  9337. * @param {CanvasRenderingContext2D} ctx Context to render on
  9338. */
  9339. _renderOverlay: function(ctx) {
  9340. this._renderBackgroundOrOverlay(ctx, 'overlay');
  9341. },
  9342. /**
  9343. * Returns coordinates of a center of canvas.
  9344. * Returned value is an object with top and left properties
  9345. * @return {Object} object with "top" and "left" number values
  9346. * @deprecated migrate to `getCenterPoint`
  9347. */
  9348. getCenter: function () {
  9349. return {
  9350. top: this.height / 2,
  9351. left: this.width / 2
  9352. };
  9353. },
  9354. /**
  9355. * Returns coordinates of a center of canvas.
  9356. * @return {fabric.Point}
  9357. */
  9358. getCenterPoint: function () {
  9359. return new fabric.Point(this.width / 2, this.height / 2);
  9360. },
  9361. /**
  9362. * Centers object horizontally in the canvas
  9363. * @param {fabric.Object} object Object to center horizontally
  9364. * @return {fabric.Canvas} thisArg
  9365. */
  9366. centerObjectH: function (object) {
  9367. return this._centerObject(object, new fabric.Point(this.getCenterPoint().x, object.getCenterPoint().y));
  9368. },
  9369. /**
  9370. * Centers object vertically in the canvas
  9371. * @param {fabric.Object} object Object to center vertically
  9372. * @return {fabric.Canvas} thisArg
  9373. * @chainable
  9374. */
  9375. centerObjectV: function (object) {
  9376. return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, this.getCenterPoint().y));
  9377. },
  9378. /**
  9379. * Centers object vertically and horizontally in the canvas
  9380. * @param {fabric.Object} object Object to center vertically and horizontally
  9381. * @return {fabric.Canvas} thisArg
  9382. * @chainable
  9383. */
  9384. centerObject: function(object) {
  9385. var center = this.getCenterPoint();
  9386. return this._centerObject(object, center);
  9387. },
  9388. /**
  9389. * Centers object vertically and horizontally in the viewport
  9390. * @param {fabric.Object} object Object to center vertically and horizontally
  9391. * @return {fabric.Canvas} thisArg
  9392. * @chainable
  9393. */
  9394. viewportCenterObject: function(object) {
  9395. var vpCenter = this.getVpCenter();
  9396. return this._centerObject(object, vpCenter);
  9397. },
  9398. /**
  9399. * Centers object horizontally in the viewport, object.top is unchanged
  9400. * @param {fabric.Object} object Object to center vertically and horizontally
  9401. * @return {fabric.Canvas} thisArg
  9402. * @chainable
  9403. */
  9404. viewportCenterObjectH: function(object) {
  9405. var vpCenter = this.getVpCenter();
  9406. this._centerObject(object, new fabric.Point(vpCenter.x, object.getCenterPoint().y));
  9407. return this;
  9408. },
  9409. /**
  9410. * Centers object Vertically in the viewport, object.top is unchanged
  9411. * @param {fabric.Object} object Object to center vertically and horizontally
  9412. * @return {fabric.Canvas} thisArg
  9413. * @chainable
  9414. */
  9415. viewportCenterObjectV: function(object) {
  9416. var vpCenter = this.getVpCenter();
  9417. return this._centerObject(object, new fabric.Point(object.getCenterPoint().x, vpCenter.y));
  9418. },
  9419. /**
  9420. * Calculate the point in canvas that correspond to the center of actual viewport.
  9421. * @return {fabric.Point} vpCenter, viewport center
  9422. * @chainable
  9423. */
  9424. getVpCenter: function() {
  9425. var center = this.getCenterPoint(),
  9426. iVpt = invertTransform(this.viewportTransform);
  9427. return transformPoint(center, iVpt);
  9428. },
  9429. /**
  9430. * @private
  9431. * @param {fabric.Object} object Object to center
  9432. * @param {fabric.Point} center Center point
  9433. * @return {fabric.Canvas} thisArg
  9434. * @chainable
  9435. */
  9436. _centerObject: function(object, center) {
  9437. object.setPositionByOrigin(center, 'center', 'center');
  9438. object.setCoords();
  9439. this.renderOnAddRemove && this.requestRenderAll();
  9440. return this;
  9441. },
  9442. /**
  9443. * Returns dataless JSON representation of canvas
  9444. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  9445. * @return {String} json string
  9446. */
  9447. toDatalessJSON: function (propertiesToInclude) {
  9448. return this.toDatalessObject(propertiesToInclude);
  9449. },
  9450. /**
  9451. * Returns object representation of canvas
  9452. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  9453. * @return {Object} object representation of an instance
  9454. */
  9455. toObject: function (propertiesToInclude) {
  9456. return this._toObjectMethod('toObject', propertiesToInclude);
  9457. },
  9458. /**
  9459. * Returns dataless object representation of canvas
  9460. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  9461. * @return {Object} object representation of an instance
  9462. */
  9463. toDatalessObject: function (propertiesToInclude) {
  9464. return this._toObjectMethod('toDatalessObject', propertiesToInclude);
  9465. },
  9466. /**
  9467. * @private
  9468. */
  9469. _toObjectMethod: function (methodName, propertiesToInclude) {
  9470. var clipPath = this.clipPath, data = {
  9471. version: fabric.version,
  9472. objects: this._toObjects(methodName, propertiesToInclude),
  9473. };
  9474. if (clipPath && !clipPath.excludeFromExport) {
  9475. data.clipPath = this._toObject(this.clipPath, methodName, propertiesToInclude);
  9476. }
  9477. extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));
  9478. fabric.util.populateWithProperties(this, data, propertiesToInclude);
  9479. return data;
  9480. },
  9481. /**
  9482. * @private
  9483. */
  9484. _toObjects: function(methodName, propertiesToInclude) {
  9485. return this._objects.filter(function(object) {
  9486. return !object.excludeFromExport;
  9487. }).map(function(instance) {
  9488. return this._toObject(instance, methodName, propertiesToInclude);
  9489. }, this);
  9490. },
  9491. /**
  9492. * @private
  9493. */
  9494. _toObject: function(instance, methodName, propertiesToInclude) {
  9495. var originalValue;
  9496. if (!this.includeDefaultValues) {
  9497. originalValue = instance.includeDefaultValues;
  9498. instance.includeDefaultValues = false;
  9499. }
  9500. var object = instance[methodName](propertiesToInclude);
  9501. if (!this.includeDefaultValues) {
  9502. instance.includeDefaultValues = originalValue;
  9503. }
  9504. return object;
  9505. },
  9506. /**
  9507. * @private
  9508. */
  9509. __serializeBgOverlay: function(methodName, propertiesToInclude) {
  9510. var data = {}, bgImage = this.backgroundImage, overlayImage = this.overlayImage,
  9511. bgColor = this.backgroundColor, overlayColor = this.overlayColor;
  9512. if (bgColor && bgColor.toObject) {
  9513. if (!bgColor.excludeFromExport) {
  9514. data.background = bgColor.toObject(propertiesToInclude);
  9515. }
  9516. }
  9517. else if (bgColor) {
  9518. data.background = bgColor;
  9519. }
  9520. if (overlayColor && overlayColor.toObject) {
  9521. if (!overlayColor.excludeFromExport) {
  9522. data.overlay = overlayColor.toObject(propertiesToInclude);
  9523. }
  9524. }
  9525. else if (overlayColor) {
  9526. data.overlay = overlayColor;
  9527. }
  9528. if (bgImage && !bgImage.excludeFromExport) {
  9529. data.backgroundImage = this._toObject(bgImage, methodName, propertiesToInclude);
  9530. }
  9531. if (overlayImage && !overlayImage.excludeFromExport) {
  9532. data.overlayImage = this._toObject(overlayImage, methodName, propertiesToInclude);
  9533. }
  9534. return data;
  9535. },
  9536. /* _TO_SVG_START_ */
  9537. /**
  9538. * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true,
  9539. * a zoomed canvas will then produce zoomed SVG output.
  9540. * @type Boolean
  9541. * @default
  9542. */
  9543. svgViewportTransformation: true,
  9544. /**
  9545. * Returns SVG representation of canvas
  9546. * @function
  9547. * @param {Object} [options] Options object for SVG output
  9548. * @param {Boolean} [options.suppressPreamble=false] If true xml tag is not included
  9549. * @param {Object} [options.viewBox] SVG viewbox object
  9550. * @param {Number} [options.viewBox.x] x-coordinate of viewbox
  9551. * @param {Number} [options.viewBox.y] y-coordinate of viewbox
  9552. * @param {Number} [options.viewBox.width] Width of viewbox
  9553. * @param {Number} [options.viewBox.height] Height of viewbox
  9554. * @param {String} [options.encoding=UTF-8] Encoding of SVG output
  9555. * @param {String} [options.width] desired width of svg with or without units
  9556. * @param {String} [options.height] desired height of svg with or without units
  9557. * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation.
  9558. * @return {String} SVG string
  9559. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}
  9560. * @see {@link http://jsfiddle.net/fabricjs/jQ3ZZ/|jsFiddle demo}
  9561. * @example <caption>Normal SVG output</caption>
  9562. * var svg = canvas.toSVG();
  9563. * @example <caption>SVG output without preamble (without &lt;?xml ../>)</caption>
  9564. * var svg = canvas.toSVG({suppressPreamble: true});
  9565. * @example <caption>SVG output with viewBox attribute</caption>
  9566. * var svg = canvas.toSVG({
  9567. * viewBox: {
  9568. * x: 100,
  9569. * y: 100,
  9570. * width: 200,
  9571. * height: 300
  9572. * }
  9573. * });
  9574. * @example <caption>SVG output with different encoding (default: UTF-8)</caption>
  9575. * var svg = canvas.toSVG({encoding: 'ISO-8859-1'});
  9576. * @example <caption>Modify SVG output with reviver function</caption>
  9577. * var svg = canvas.toSVG(null, function(svg) {
  9578. * return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
  9579. * });
  9580. */
  9581. toSVG: function(options, reviver) {
  9582. options || (options = { });
  9583. options.reviver = reviver;
  9584. var markup = [];
  9585. this._setSVGPreamble(markup, options);
  9586. this._setSVGHeader(markup, options);
  9587. if (this.clipPath) {
  9588. markup.push('<g clip-path="url(#' + this.clipPath.clipPathId + ')" >\n');
  9589. }
  9590. this._setSVGBgOverlayColor(markup, 'background');
  9591. this._setSVGBgOverlayImage(markup, 'backgroundImage', reviver);
  9592. this._setSVGObjects(markup, reviver);
  9593. if (this.clipPath) {
  9594. markup.push('</g>\n');
  9595. }
  9596. this._setSVGBgOverlayColor(markup, 'overlay');
  9597. this._setSVGBgOverlayImage(markup, 'overlayImage', reviver);
  9598. markup.push('</svg>');
  9599. return markup.join('');
  9600. },
  9601. /**
  9602. * @private
  9603. */
  9604. _setSVGPreamble: function(markup, options) {
  9605. if (options.suppressPreamble) {
  9606. return;
  9607. }
  9608. markup.push(
  9609. '<?xml version="1.0" encoding="', (options.encoding || 'UTF-8'), '" standalone="no" ?>\n',
  9610. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',
  9611. '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'
  9612. );
  9613. },
  9614. /**
  9615. * @private
  9616. */
  9617. _setSVGHeader: function(markup, options) {
  9618. var width = options.width || this.width,
  9619. height = options.height || this.height,
  9620. vpt, viewBox = 'viewBox="0 0 ' + this.width + ' ' + this.height + '" ',
  9621. NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;
  9622. if (options.viewBox) {
  9623. viewBox = 'viewBox="' +
  9624. options.viewBox.x + ' ' +
  9625. options.viewBox.y + ' ' +
  9626. options.viewBox.width + ' ' +
  9627. options.viewBox.height + '" ';
  9628. }
  9629. else {
  9630. if (this.svgViewportTransformation) {
  9631. vpt = this.viewportTransform;
  9632. viewBox = 'viewBox="' +
  9633. toFixed(-vpt[4] / vpt[0], NUM_FRACTION_DIGITS) + ' ' +
  9634. toFixed(-vpt[5] / vpt[3], NUM_FRACTION_DIGITS) + ' ' +
  9635. toFixed(this.width / vpt[0], NUM_FRACTION_DIGITS) + ' ' +
  9636. toFixed(this.height / vpt[3], NUM_FRACTION_DIGITS) + '" ';
  9637. }
  9638. }
  9639. markup.push(
  9640. '<svg ',
  9641. 'xmlns="http://www.w3.org/2000/svg" ',
  9642. 'xmlns:xlink="http://www.w3.org/1999/xlink" ',
  9643. 'version="1.1" ',
  9644. 'width="', width, '" ',
  9645. 'height="', height, '" ',
  9646. viewBox,
  9647. 'xml:space="preserve">\n',
  9648. '<desc>Created with Fabric.js ', fabric.version, '</desc>\n',
  9649. '<defs>\n',
  9650. this.createSVGFontFacesMarkup(),
  9651. this.createSVGRefElementsMarkup(),
  9652. this.createSVGClipPathMarkup(options),
  9653. '</defs>\n'
  9654. );
  9655. },
  9656. createSVGClipPathMarkup: function(options) {
  9657. var clipPath = this.clipPath;
  9658. if (clipPath) {
  9659. clipPath.clipPathId = 'CLIPPATH_' + fabric.Object.__uid++;
  9660. return '<clipPath id="' + clipPath.clipPathId + '" >\n' +
  9661. this.clipPath.toClipPathSVG(options.reviver) +
  9662. '</clipPath>\n';
  9663. }
  9664. return '';
  9665. },
  9666. /**
  9667. * Creates markup containing SVG referenced elements like patterns, gradients etc.
  9668. * @return {String}
  9669. */
  9670. createSVGRefElementsMarkup: function() {
  9671. var _this = this,
  9672. markup = ['background', 'overlay'].map(function(prop) {
  9673. var fill = _this[prop + 'Color'];
  9674. if (fill && fill.toLive) {
  9675. var shouldTransform = _this[prop + 'Vpt'], vpt = _this.viewportTransform,
  9676. object = {
  9677. width: _this.width / (shouldTransform ? vpt[0] : 1),
  9678. height: _this.height / (shouldTransform ? vpt[3] : 1)
  9679. };
  9680. return fill.toSVG(
  9681. object,
  9682. { additionalTransform: shouldTransform ? fabric.util.matrixToSVG(vpt) : '' }
  9683. );
  9684. }
  9685. });
  9686. return markup.join('');
  9687. },
  9688. /**
  9689. * Creates markup containing SVG font faces,
  9690. * font URLs for font faces must be collected by developers
  9691. * and are not extracted from the DOM by fabricjs
  9692. * @param {Array} objects Array of fabric objects
  9693. * @return {String}
  9694. */
  9695. createSVGFontFacesMarkup: function() {
  9696. var markup = '', fontList = { }, obj, fontFamily,
  9697. style, row, rowIndex, _char, charIndex, i, len,
  9698. fontPaths = fabric.fontPaths, objects = [];
  9699. this._objects.forEach(function add(object) {
  9700. objects.push(object);
  9701. if (object._objects) {
  9702. object._objects.forEach(add);
  9703. }
  9704. });
  9705. for (i = 0, len = objects.length; i < len; i++) {
  9706. obj = objects[i];
  9707. fontFamily = obj.fontFamily;
  9708. if (obj.type.indexOf('text') === -1 || fontList[fontFamily] || !fontPaths[fontFamily]) {
  9709. continue;
  9710. }
  9711. fontList[fontFamily] = true;
  9712. if (!obj.styles) {
  9713. continue;
  9714. }
  9715. style = obj.styles;
  9716. for (rowIndex in style) {
  9717. row = style[rowIndex];
  9718. for (charIndex in row) {
  9719. _char = row[charIndex];
  9720. fontFamily = _char.fontFamily;
  9721. if (!fontList[fontFamily] && fontPaths[fontFamily]) {
  9722. fontList[fontFamily] = true;
  9723. }
  9724. }
  9725. }
  9726. }
  9727. for (var j in fontList) {
  9728. markup += [
  9729. '\t\t@font-face {\n',
  9730. '\t\t\tfont-family: \'', j, '\';\n',
  9731. '\t\t\tsrc: url(\'', fontPaths[j], '\');\n',
  9732. '\t\t}\n'
  9733. ].join('');
  9734. }
  9735. if (markup) {
  9736. markup = [
  9737. '\t<style type="text/css">',
  9738. '<![CDATA[\n',
  9739. markup,
  9740. ']]>',
  9741. '</style>\n'
  9742. ].join('');
  9743. }
  9744. return markup;
  9745. },
  9746. /**
  9747. * @private
  9748. */
  9749. _setSVGObjects: function(markup, reviver) {
  9750. var instance, i, len, objects = this._objects;
  9751. for (i = 0, len = objects.length; i < len; i++) {
  9752. instance = objects[i];
  9753. if (instance.excludeFromExport) {
  9754. continue;
  9755. }
  9756. this._setSVGObject(markup, instance, reviver);
  9757. }
  9758. },
  9759. /**
  9760. * @private
  9761. */
  9762. _setSVGObject: function(markup, instance, reviver) {
  9763. markup.push(instance.toSVG(reviver));
  9764. },
  9765. /**
  9766. * @private
  9767. */
  9768. _setSVGBgOverlayImage: function(markup, property, reviver) {
  9769. if (this[property] && !this[property].excludeFromExport && this[property].toSVG) {
  9770. markup.push(this[property].toSVG(reviver));
  9771. }
  9772. },
  9773. /**
  9774. * @private
  9775. */
  9776. _setSVGBgOverlayColor: function(markup, property) {
  9777. var filler = this[property + 'Color'], vpt = this.viewportTransform, finalWidth = this.width,
  9778. finalHeight = this.height;
  9779. if (!filler) {
  9780. return;
  9781. }
  9782. if (filler.toLive) {
  9783. var repeat = filler.repeat, iVpt = fabric.util.invertTransform(vpt), shouldInvert = this[property + 'Vpt'],
  9784. additionalTransform = shouldInvert ? fabric.util.matrixToSVG(iVpt) : '';
  9785. markup.push(
  9786. '<rect transform="' + additionalTransform + ' translate(', finalWidth / 2, ',', finalHeight / 2, ')"',
  9787. ' x="', filler.offsetX - finalWidth / 2,
  9788. '" y="', filler.offsetY - finalHeight / 2, '" ',
  9789. 'width="',
  9790. (repeat === 'repeat-y' || repeat === 'no-repeat'
  9791. ? filler.source.width
  9792. : finalWidth ),
  9793. '" height="',
  9794. (repeat === 'repeat-x' || repeat === 'no-repeat'
  9795. ? filler.source.height
  9796. : finalHeight),
  9797. '" fill="url(#SVGID_' + filler.id + ')"',
  9798. '></rect>\n'
  9799. );
  9800. }
  9801. else {
  9802. markup.push(
  9803. '<rect x="0" y="0" width="100%" height="100%" ',
  9804. 'fill="', filler, '"',
  9805. '></rect>\n'
  9806. );
  9807. }
  9808. },
  9809. /* _TO_SVG_END_ */
  9810. /**
  9811. * Moves an object or the objects of a multiple selection
  9812. * to the bottom of the stack of drawn objects
  9813. * @param {fabric.Object} object Object to send to back
  9814. * @return {fabric.Canvas} thisArg
  9815. * @chainable
  9816. */
  9817. sendToBack: function (object) {
  9818. if (!object) {
  9819. return this;
  9820. }
  9821. var activeSelection = this._activeObject,
  9822. i, obj, objs;
  9823. if (object === activeSelection && object.type === 'activeSelection') {
  9824. objs = activeSelection._objects;
  9825. for (i = objs.length; i--;) {
  9826. obj = objs[i];
  9827. removeFromArray(this._objects, obj);
  9828. this._objects.unshift(obj);
  9829. }
  9830. }
  9831. else {
  9832. removeFromArray(this._objects, object);
  9833. this._objects.unshift(object);
  9834. }
  9835. this.renderOnAddRemove && this.requestRenderAll();
  9836. return this;
  9837. },
  9838. /**
  9839. * Moves an object or the objects of a multiple selection
  9840. * to the top of the stack of drawn objects
  9841. * @param {fabric.Object} object Object to send
  9842. * @return {fabric.Canvas} thisArg
  9843. * @chainable
  9844. */
  9845. bringToFront: function (object) {
  9846. if (!object) {
  9847. return this;
  9848. }
  9849. var activeSelection = this._activeObject,
  9850. i, obj, objs;
  9851. if (object === activeSelection && object.type === 'activeSelection') {
  9852. objs = activeSelection._objects;
  9853. for (i = 0; i < objs.length; i++) {
  9854. obj = objs[i];
  9855. removeFromArray(this._objects, obj);
  9856. this._objects.push(obj);
  9857. }
  9858. }
  9859. else {
  9860. removeFromArray(this._objects, object);
  9861. this._objects.push(object);
  9862. }
  9863. this.renderOnAddRemove && this.requestRenderAll();
  9864. return this;
  9865. },
  9866. /**
  9867. * Moves an object or a selection down in stack of drawn objects
  9868. * An optional parameter, intersecting allows to move the object in behind
  9869. * the first intersecting object. Where intersection is calculated with
  9870. * bounding box. If no intersection is found, there will not be change in the
  9871. * stack.
  9872. * @param {fabric.Object} object Object to send
  9873. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  9874. * @return {fabric.Canvas} thisArg
  9875. * @chainable
  9876. */
  9877. sendBackwards: function (object, intersecting) {
  9878. if (!object) {
  9879. return this;
  9880. }
  9881. var activeSelection = this._activeObject,
  9882. i, obj, idx, newIdx, objs, objsMoved = 0;
  9883. if (object === activeSelection && object.type === 'activeSelection') {
  9884. objs = activeSelection._objects;
  9885. for (i = 0; i < objs.length; i++) {
  9886. obj = objs[i];
  9887. idx = this._objects.indexOf(obj);
  9888. if (idx > 0 + objsMoved) {
  9889. newIdx = idx - 1;
  9890. removeFromArray(this._objects, obj);
  9891. this._objects.splice(newIdx, 0, obj);
  9892. }
  9893. objsMoved++;
  9894. }
  9895. }
  9896. else {
  9897. idx = this._objects.indexOf(object);
  9898. if (idx !== 0) {
  9899. // if object is not on the bottom of stack
  9900. newIdx = this._findNewLowerIndex(object, idx, intersecting);
  9901. removeFromArray(this._objects, object);
  9902. this._objects.splice(newIdx, 0, object);
  9903. }
  9904. }
  9905. this.renderOnAddRemove && this.requestRenderAll();
  9906. return this;
  9907. },
  9908. /**
  9909. * @private
  9910. */
  9911. _findNewLowerIndex: function(object, idx, intersecting) {
  9912. var newIdx, i;
  9913. if (intersecting) {
  9914. newIdx = idx;
  9915. // traverse down the stack looking for the nearest intersecting object
  9916. for (i = idx - 1; i >= 0; --i) {
  9917. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  9918. object.isContainedWithinObject(this._objects[i]) ||
  9919. this._objects[i].isContainedWithinObject(object);
  9920. if (isIntersecting) {
  9921. newIdx = i;
  9922. break;
  9923. }
  9924. }
  9925. }
  9926. else {
  9927. newIdx = idx - 1;
  9928. }
  9929. return newIdx;
  9930. },
  9931. /**
  9932. * Moves an object or a selection up in stack of drawn objects
  9933. * An optional parameter, intersecting allows to move the object in front
  9934. * of the first intersecting object. Where intersection is calculated with
  9935. * bounding box. If no intersection is found, there will not be change in the
  9936. * stack.
  9937. * @param {fabric.Object} object Object to send
  9938. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  9939. * @return {fabric.Canvas} thisArg
  9940. * @chainable
  9941. */
  9942. bringForward: function (object, intersecting) {
  9943. if (!object) {
  9944. return this;
  9945. }
  9946. var activeSelection = this._activeObject,
  9947. i, obj, idx, newIdx, objs, objsMoved = 0;
  9948. if (object === activeSelection && object.type === 'activeSelection') {
  9949. objs = activeSelection._objects;
  9950. for (i = objs.length; i--;) {
  9951. obj = objs[i];
  9952. idx = this._objects.indexOf(obj);
  9953. if (idx < this._objects.length - 1 - objsMoved) {
  9954. newIdx = idx + 1;
  9955. removeFromArray(this._objects, obj);
  9956. this._objects.splice(newIdx, 0, obj);
  9957. }
  9958. objsMoved++;
  9959. }
  9960. }
  9961. else {
  9962. idx = this._objects.indexOf(object);
  9963. if (idx !== this._objects.length - 1) {
  9964. // if object is not on top of stack (last item in an array)
  9965. newIdx = this._findNewUpperIndex(object, idx, intersecting);
  9966. removeFromArray(this._objects, object);
  9967. this._objects.splice(newIdx, 0, object);
  9968. }
  9969. }
  9970. this.renderOnAddRemove && this.requestRenderAll();
  9971. return this;
  9972. },
  9973. /**
  9974. * @private
  9975. */
  9976. _findNewUpperIndex: function(object, idx, intersecting) {
  9977. var newIdx, i, len;
  9978. if (intersecting) {
  9979. newIdx = idx;
  9980. // traverse up the stack looking for the nearest intersecting object
  9981. for (i = idx + 1, len = this._objects.length; i < len; ++i) {
  9982. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  9983. object.isContainedWithinObject(this._objects[i]) ||
  9984. this._objects[i].isContainedWithinObject(object);
  9985. if (isIntersecting) {
  9986. newIdx = i;
  9987. break;
  9988. }
  9989. }
  9990. }
  9991. else {
  9992. newIdx = idx + 1;
  9993. }
  9994. return newIdx;
  9995. },
  9996. /**
  9997. * Moves an object to specified level in stack of drawn objects
  9998. * @param {fabric.Object} object Object to send
  9999. * @param {Number} index Position to move to
  10000. * @return {fabric.Canvas} thisArg
  10001. * @chainable
  10002. */
  10003. moveTo: function (object, index) {
  10004. removeFromArray(this._objects, object);
  10005. this._objects.splice(index, 0, object);
  10006. return this.renderOnAddRemove && this.requestRenderAll();
  10007. },
  10008. /**
  10009. * Clears a canvas element and dispose objects
  10010. * @return {fabric.Canvas} thisArg
  10011. * @chainable
  10012. */
  10013. dispose: function () {
  10014. // cancel eventually ongoing renders
  10015. if (this.isRendering) {
  10016. fabric.util.cancelAnimFrame(this.isRendering);
  10017. this.isRendering = 0;
  10018. }
  10019. this.forEachObject(function(object) {
  10020. object.dispose && object.dispose();
  10021. });
  10022. this._objects = [];
  10023. if (this.backgroundImage && this.backgroundImage.dispose) {
  10024. this.backgroundImage.dispose();
  10025. }
  10026. this.backgroundImage = null;
  10027. if (this.overlayImage && this.overlayImage.dispose) {
  10028. this.overlayImage.dispose();
  10029. }
  10030. this.overlayImage = null;
  10031. this._iTextInstances = null;
  10032. this.contextContainer = null;
  10033. // restore canvas style
  10034. this.lowerCanvasEl.classList.remove('lower-canvas');
  10035. fabric.util.setStyle(this.lowerCanvasEl, this._originalCanvasStyle);
  10036. delete this._originalCanvasStyle;
  10037. // restore canvas size to original size in case retina scaling was applied
  10038. this.lowerCanvasEl.setAttribute('width', this.width);
  10039. this.lowerCanvasEl.setAttribute('height', this.height);
  10040. fabric.util.cleanUpJsdomNode(this.lowerCanvasEl);
  10041. this.lowerCanvasEl = undefined;
  10042. return this;
  10043. },
  10044. /**
  10045. * Returns a string representation of an instance
  10046. * @return {String} string representation of an instance
  10047. */
  10048. toString: function () {
  10049. return '#<fabric.Canvas (' + this.complexity() + '): ' +
  10050. '{ objects: ' + this._objects.length + ' }>';
  10051. }
  10052. });
  10053. extend(fabric.StaticCanvas.prototype, fabric.Observable);
  10054. extend(fabric.StaticCanvas.prototype, fabric.Collection);
  10055. extend(fabric.StaticCanvas.prototype, fabric.DataURLExporter);
  10056. extend(fabric.StaticCanvas, /** @lends fabric.StaticCanvas */ {
  10057. /**
  10058. * @static
  10059. * @type String
  10060. * @default
  10061. */
  10062. EMPTY_JSON: '{"objects": [], "background": "white"}',
  10063. /**
  10064. * Provides a way to check support of some of the canvas methods
  10065. * (either those of HTMLCanvasElement itself, or rendering context)
  10066. *
  10067. * @param {String} methodName Method to check support for;
  10068. * Could be one of "setLineDash"
  10069. * @return {Boolean | null} `true` if method is supported (or at least exists),
  10070. * `null` if canvas element or context can not be initialized
  10071. */
  10072. supports: function (methodName) {
  10073. var el = createCanvasElement();
  10074. if (!el || !el.getContext) {
  10075. return null;
  10076. }
  10077. var ctx = el.getContext('2d');
  10078. if (!ctx) {
  10079. return null;
  10080. }
  10081. switch (methodName) {
  10082. case 'setLineDash':
  10083. return typeof ctx.setLineDash !== 'undefined';
  10084. default:
  10085. return null;
  10086. }
  10087. }
  10088. });
  10089. /**
  10090. * Returns Object representation of canvas
  10091. * this alias is provided because if you call JSON.stringify on an instance,
  10092. * the toJSON object will be invoked if it exists.
  10093. * Having a toJSON method means you can do JSON.stringify(myCanvas)
  10094. * @function
  10095. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  10096. * @return {Object} JSON compatible object
  10097. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#serialization}
  10098. * @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}
  10099. * @example <caption>JSON without additional properties</caption>
  10100. * var json = canvas.toJSON();
  10101. * @example <caption>JSON with additional properties included</caption>
  10102. * var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY']);
  10103. * @example <caption>JSON without default values</caption>
  10104. * canvas.includeDefaultValues = false;
  10105. * var json = canvas.toJSON();
  10106. */
  10107. fabric.StaticCanvas.prototype.toJSON = fabric.StaticCanvas.prototype.toObject;
  10108. if (fabric.isLikelyNode) {
  10109. fabric.StaticCanvas.prototype.createPNGStream = function() {
  10110. var impl = getNodeCanvas(this.lowerCanvasEl);
  10111. return impl && impl.createPNGStream();
  10112. };
  10113. fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
  10114. var impl = getNodeCanvas(this.lowerCanvasEl);
  10115. return impl && impl.createJPEGStream(opts);
  10116. };
  10117. }
  10118. })();
  10119. /**
  10120. * BaseBrush class
  10121. * @class fabric.BaseBrush
  10122. * @see {@link http://fabricjs.com/freedrawing|Freedrawing demo}
  10123. */
  10124. fabric.BaseBrush = fabric.util.createClass(/** @lends fabric.BaseBrush.prototype */ {
  10125. /**
  10126. * Color of a brush
  10127. * @type String
  10128. * @default
  10129. */
  10130. color: 'rgb(0, 0, 0)',
  10131. /**
  10132. * Width of a brush, has to be a Number, no string literals
  10133. * @type Number
  10134. * @default
  10135. */
  10136. width: 1,
  10137. /**
  10138. * Shadow object representing shadow of this shape.
  10139. * <b>Backwards incompatibility note:</b> This property replaces "shadowColor" (String), "shadowOffsetX" (Number),
  10140. * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12
  10141. * @type fabric.Shadow
  10142. * @default
  10143. */
  10144. shadow: null,
  10145. /**
  10146. * Line endings style of a brush (one of "butt", "round", "square")
  10147. * @type String
  10148. * @default
  10149. */
  10150. strokeLineCap: 'round',
  10151. /**
  10152. * Corner style of a brush (one of "bevel", "round", "miter")
  10153. * @type String
  10154. * @default
  10155. */
  10156. strokeLineJoin: 'round',
  10157. /**
  10158. * Maximum miter length (used for strokeLineJoin = "miter") of a brush's
  10159. * @type Number
  10160. * @default
  10161. */
  10162. strokeMiterLimit: 10,
  10163. /**
  10164. * Stroke Dash Array.
  10165. * @type Array
  10166. * @default
  10167. */
  10168. strokeDashArray: null,
  10169. /**
  10170. * When `true`, the free drawing is limited to the whiteboard size. Default to false.
  10171. * @type Boolean
  10172. * @default false
  10173. */
  10174. limitedToCanvasSize: false,
  10175. /**
  10176. * Sets brush styles
  10177. * @private
  10178. * @param {CanvasRenderingContext2D} ctx
  10179. */
  10180. _setBrushStyles: function (ctx) {
  10181. ctx.strokeStyle = this.color;
  10182. ctx.lineWidth = this.width;
  10183. ctx.lineCap = this.strokeLineCap;
  10184. ctx.miterLimit = this.strokeMiterLimit;
  10185. ctx.lineJoin = this.strokeLineJoin;
  10186. ctx.setLineDash(this.strokeDashArray || []);
  10187. },
  10188. /**
  10189. * Sets the transformation on given context
  10190. * @param {RenderingContext2d} ctx context to render on
  10191. * @private
  10192. */
  10193. _saveAndTransform: function(ctx) {
  10194. var v = this.canvas.viewportTransform;
  10195. ctx.save();
  10196. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  10197. },
  10198. /**
  10199. * Sets brush shadow styles
  10200. * @private
  10201. */
  10202. _setShadow: function() {
  10203. if (!this.shadow) {
  10204. return;
  10205. }
  10206. var canvas = this.canvas,
  10207. shadow = this.shadow,
  10208. ctx = canvas.contextTop,
  10209. zoom = canvas.getZoom();
  10210. if (canvas && canvas._isRetinaScaling()) {
  10211. zoom *= fabric.devicePixelRatio;
  10212. }
  10213. ctx.shadowColor = shadow.color;
  10214. ctx.shadowBlur = shadow.blur * zoom;
  10215. ctx.shadowOffsetX = shadow.offsetX * zoom;
  10216. ctx.shadowOffsetY = shadow.offsetY * zoom;
  10217. },
  10218. needsFullRender: function() {
  10219. var color = new fabric.Color(this.color);
  10220. return color.getAlpha() < 1 || !!this.shadow;
  10221. },
  10222. /**
  10223. * Removes brush shadow styles
  10224. * @private
  10225. */
  10226. _resetShadow: function() {
  10227. var ctx = this.canvas.contextTop;
  10228. ctx.shadowColor = '';
  10229. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  10230. },
  10231. /**
  10232. * Check is pointer is outside canvas boundaries
  10233. * @param {Object} pointer
  10234. * @private
  10235. */
  10236. _isOutSideCanvas: function(pointer) {
  10237. return pointer.x < 0 || pointer.x > this.canvas.getWidth() || pointer.y < 0 || pointer.y > this.canvas.getHeight();
  10238. }
  10239. });
  10240. (function() {
  10241. /**
  10242. * PencilBrush class
  10243. * @class fabric.PencilBrush
  10244. * @extends fabric.BaseBrush
  10245. */
  10246. fabric.PencilBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.PencilBrush.prototype */ {
  10247. /**
  10248. * Discard points that are less than `decimate` pixel distant from each other
  10249. * @type Number
  10250. * @default 0.4
  10251. */
  10252. decimate: 0.4,
  10253. /**
  10254. * Draws a straight line between last recorded point to current pointer
  10255. * Used for `shift` functionality
  10256. *
  10257. * @type boolean
  10258. * @default false
  10259. */
  10260. drawStraightLine: false,
  10261. /**
  10262. * The event modifier key that makes the brush draw a straight line.
  10263. * If `null` or 'none' or any other string that is not a modifier key the feature is disabled.
  10264. * @type {'altKey' | 'shiftKey' | 'ctrlKey' | 'none' | undefined | null}
  10265. */
  10266. straightLineKey: 'shiftKey',
  10267. /**
  10268. * Constructor
  10269. * @param {fabric.Canvas} canvas
  10270. * @return {fabric.PencilBrush} Instance of a pencil brush
  10271. */
  10272. initialize: function(canvas) {
  10273. this.canvas = canvas;
  10274. this._points = [];
  10275. },
  10276. needsFullRender: function () {
  10277. return this.callSuper('needsFullRender') || this._hasStraightLine;
  10278. },
  10279. /**
  10280. * Invoked inside on mouse down and mouse move
  10281. * @param {Object} pointer
  10282. */
  10283. _drawSegment: function (ctx, p1, p2) {
  10284. var midPoint = p1.midPointFrom(p2);
  10285. ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
  10286. return midPoint;
  10287. },
  10288. /**
  10289. * Invoked on mouse down
  10290. * @param {Object} pointer
  10291. */
  10292. onMouseDown: function(pointer, options) {
  10293. if (!this.canvas._isMainEvent(options.e)) {
  10294. return;
  10295. }
  10296. this.drawStraightLine = options.e[this.straightLineKey];
  10297. this._prepareForDrawing(pointer);
  10298. // capture coordinates immediately
  10299. // this allows to draw dots (when movement never occurs)
  10300. this._captureDrawingPath(pointer);
  10301. this._render();
  10302. },
  10303. /**
  10304. * Invoked on mouse move
  10305. * @param {Object} pointer
  10306. */
  10307. onMouseMove: function(pointer, options) {
  10308. if (!this.canvas._isMainEvent(options.e)) {
  10309. return;
  10310. }
  10311. this.drawStraightLine = options.e[this.straightLineKey];
  10312. if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {
  10313. return;
  10314. }
  10315. if (this._captureDrawingPath(pointer) && this._points.length > 1) {
  10316. if (this.needsFullRender()) {
  10317. // redraw curve
  10318. // clear top canvas
  10319. this.canvas.clearContext(this.canvas.contextTop);
  10320. this._render();
  10321. }
  10322. else {
  10323. var points = this._points, length = points.length, ctx = this.canvas.contextTop;
  10324. // draw the curve update
  10325. this._saveAndTransform(ctx);
  10326. if (this.oldEnd) {
  10327. ctx.beginPath();
  10328. ctx.moveTo(this.oldEnd.x, this.oldEnd.y);
  10329. }
  10330. this.oldEnd = this._drawSegment(ctx, points[length - 2], points[length - 1], true);
  10331. ctx.stroke();
  10332. ctx.restore();
  10333. }
  10334. }
  10335. },
  10336. /**
  10337. * Invoked on mouse up
  10338. */
  10339. onMouseUp: function(options) {
  10340. if (!this.canvas._isMainEvent(options.e)) {
  10341. return true;
  10342. }
  10343. this.drawStraightLine = false;
  10344. this.oldEnd = undefined;
  10345. this._finalizeAndAddPath();
  10346. return false;
  10347. },
  10348. /**
  10349. * @private
  10350. * @param {Object} pointer Actual mouse position related to the canvas.
  10351. */
  10352. _prepareForDrawing: function(pointer) {
  10353. var p = new fabric.Point(pointer.x, pointer.y);
  10354. this._reset();
  10355. this._addPoint(p);
  10356. this.canvas.contextTop.moveTo(p.x, p.y);
  10357. },
  10358. /**
  10359. * @private
  10360. * @param {fabric.Point} point Point to be added to points array
  10361. */
  10362. _addPoint: function(point) {
  10363. if (this._points.length > 1 && point.eq(this._points[this._points.length - 1])) {
  10364. return false;
  10365. }
  10366. if (this.drawStraightLine && this._points.length > 1) {
  10367. this._hasStraightLine = true;
  10368. this._points.pop();
  10369. }
  10370. this._points.push(point);
  10371. return true;
  10372. },
  10373. /**
  10374. * Clear points array and set contextTop canvas style.
  10375. * @private
  10376. */
  10377. _reset: function() {
  10378. this._points = [];
  10379. this._setBrushStyles(this.canvas.contextTop);
  10380. this._setShadow();
  10381. this._hasStraightLine = false;
  10382. },
  10383. /**
  10384. * @private
  10385. * @param {Object} pointer Actual mouse position related to the canvas.
  10386. */
  10387. _captureDrawingPath: function(pointer) {
  10388. var pointerPoint = new fabric.Point(pointer.x, pointer.y);
  10389. return this._addPoint(pointerPoint);
  10390. },
  10391. /**
  10392. * Draw a smooth path on the topCanvas using quadraticCurveTo
  10393. * @private
  10394. * @param {CanvasRenderingContext2D} [ctx]
  10395. */
  10396. _render: function(ctx) {
  10397. var i, len,
  10398. p1 = this._points[0],
  10399. p2 = this._points[1];
  10400. ctx = ctx || this.canvas.contextTop;
  10401. this._saveAndTransform(ctx);
  10402. ctx.beginPath();
  10403. //if we only have 2 points in the path and they are the same
  10404. //it means that the user only clicked the canvas without moving the mouse
  10405. //then we should be drawing a dot. A path isn't drawn between two identical dots
  10406. //that's why we set them apart a bit
  10407. if (this._points.length === 2 && p1.x === p2.x && p1.y === p2.y) {
  10408. var width = this.width / 1000;
  10409. p1 = new fabric.Point(p1.x, p1.y);
  10410. p2 = new fabric.Point(p2.x, p2.y);
  10411. p1.x -= width;
  10412. p2.x += width;
  10413. }
  10414. ctx.moveTo(p1.x, p1.y);
  10415. for (i = 1, len = this._points.length; i < len; i++) {
  10416. // we pick the point between pi + 1 & pi + 2 as the
  10417. // end point and p1 as our control point.
  10418. this._drawSegment(ctx, p1, p2);
  10419. p1 = this._points[i];
  10420. p2 = this._points[i + 1];
  10421. }
  10422. // Draw last line as a straight line while
  10423. // we wait for the next point to be able to calculate
  10424. // the bezier control point
  10425. ctx.lineTo(p1.x, p1.y);
  10426. ctx.stroke();
  10427. ctx.restore();
  10428. },
  10429. /**
  10430. * Converts points to SVG path
  10431. * @param {Array} points Array of points
  10432. * @return {(string|number)[][]} SVG path commands
  10433. */
  10434. convertPointsToSVGPath: function (points) {
  10435. var correction = this.width / 1000;
  10436. return fabric.util.getSmoothPathFromPoints(points, correction);
  10437. },
  10438. /**
  10439. * @private
  10440. * @param {(string|number)[][]} pathData SVG path commands
  10441. * @returns {boolean}
  10442. */
  10443. _isEmptySVGPath: function (pathData) {
  10444. var pathString = fabric.util.joinPath(pathData);
  10445. return pathString === 'M 0 0 Q 0 0 0 0 L 0 0';
  10446. },
  10447. /**
  10448. * Creates fabric.Path object to add on canvas
  10449. * @param {(string|number)[][]} pathData Path data
  10450. * @return {fabric.Path} Path to add on canvas
  10451. */
  10452. createPath: function(pathData) {
  10453. var path = new fabric.Path(pathData, {
  10454. fill: null,
  10455. stroke: this.color,
  10456. strokeWidth: this.width,
  10457. strokeLineCap: this.strokeLineCap,
  10458. strokeMiterLimit: this.strokeMiterLimit,
  10459. strokeLineJoin: this.strokeLineJoin,
  10460. strokeDashArray: this.strokeDashArray,
  10461. });
  10462. if (this.shadow) {
  10463. this.shadow.affectStroke = true;
  10464. path.shadow = new fabric.Shadow(this.shadow);
  10465. }
  10466. return path;
  10467. },
  10468. /**
  10469. * Decimate points array with the decimate value
  10470. */
  10471. decimatePoints: function(points, distance) {
  10472. if (points.length <= 2) {
  10473. return points;
  10474. }
  10475. var zoom = this.canvas.getZoom(), adjustedDistance = Math.pow(distance / zoom, 2),
  10476. i, l = points.length - 1, lastPoint = points[0], newPoints = [lastPoint],
  10477. cDistance;
  10478. for (i = 1; i < l - 1; i++) {
  10479. cDistance = Math.pow(lastPoint.x - points[i].x, 2) + Math.pow(lastPoint.y - points[i].y, 2);
  10480. if (cDistance >= adjustedDistance) {
  10481. lastPoint = points[i];
  10482. newPoints.push(lastPoint);
  10483. }
  10484. }
  10485. /**
  10486. * Add the last point from the original line to the end of the array.
  10487. * This ensures decimate doesn't delete the last point on the line, and ensures the line is > 1 point.
  10488. */
  10489. newPoints.push(points[l]);
  10490. return newPoints;
  10491. },
  10492. /**
  10493. * On mouseup after drawing the path on contextTop canvas
  10494. * we use the points captured to create an new fabric path object
  10495. * and add it to the fabric canvas.
  10496. */
  10497. _finalizeAndAddPath: function() {
  10498. var ctx = this.canvas.contextTop;
  10499. ctx.closePath();
  10500. if (this.decimate) {
  10501. this._points = this.decimatePoints(this._points, this.decimate);
  10502. }
  10503. var pathData = this.convertPointsToSVGPath(this._points);
  10504. if (this._isEmptySVGPath(pathData)) {
  10505. // do not create 0 width/height paths, as they are
  10506. // rendered inconsistently across browsers
  10507. // Firefox 4, for example, renders a dot,
  10508. // whereas Chrome 10 renders nothing
  10509. this.canvas.requestRenderAll();
  10510. return;
  10511. }
  10512. var path = this.createPath(pathData);
  10513. this.canvas.clearContext(this.canvas.contextTop);
  10514. this.canvas.fire('before:path:created', { path: path });
  10515. this.canvas.add(path);
  10516. this.canvas.requestRenderAll();
  10517. path.setCoords();
  10518. this._resetShadow();
  10519. // fire event 'path' created
  10520. this.canvas.fire('path:created', { path: path });
  10521. }
  10522. });
  10523. })();
  10524. /**
  10525. * CircleBrush class
  10526. * @class fabric.CircleBrush
  10527. */
  10528. fabric.CircleBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.CircleBrush.prototype */ {
  10529. /**
  10530. * Width of a brush
  10531. * @type Number
  10532. * @default
  10533. */
  10534. width: 10,
  10535. /**
  10536. * Constructor
  10537. * @param {fabric.Canvas} canvas
  10538. * @return {fabric.CircleBrush} Instance of a circle brush
  10539. */
  10540. initialize: function(canvas) {
  10541. this.canvas = canvas;
  10542. this.points = [];
  10543. },
  10544. /**
  10545. * Invoked inside on mouse down and mouse move
  10546. * @param {Object} pointer
  10547. */
  10548. drawDot: function(pointer) {
  10549. var point = this.addPoint(pointer),
  10550. ctx = this.canvas.contextTop;
  10551. this._saveAndTransform(ctx);
  10552. this.dot(ctx, point);
  10553. ctx.restore();
  10554. },
  10555. dot: function(ctx, point) {
  10556. ctx.fillStyle = point.fill;
  10557. ctx.beginPath();
  10558. ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);
  10559. ctx.closePath();
  10560. ctx.fill();
  10561. },
  10562. /**
  10563. * Invoked on mouse down
  10564. */
  10565. onMouseDown: function(pointer) {
  10566. this.points.length = 0;
  10567. this.canvas.clearContext(this.canvas.contextTop);
  10568. this._setShadow();
  10569. this.drawDot(pointer);
  10570. },
  10571. /**
  10572. * Render the full state of the brush
  10573. * @private
  10574. */
  10575. _render: function() {
  10576. var ctx = this.canvas.contextTop, i, len,
  10577. points = this.points;
  10578. this._saveAndTransform(ctx);
  10579. for (i = 0, len = points.length; i < len; i++) {
  10580. this.dot(ctx, points[i]);
  10581. }
  10582. ctx.restore();
  10583. },
  10584. /**
  10585. * Invoked on mouse move
  10586. * @param {Object} pointer
  10587. */
  10588. onMouseMove: function(pointer) {
  10589. if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {
  10590. return;
  10591. }
  10592. if (this.needsFullRender()) {
  10593. this.canvas.clearContext(this.canvas.contextTop);
  10594. this.addPoint(pointer);
  10595. this._render();
  10596. }
  10597. else {
  10598. this.drawDot(pointer);
  10599. }
  10600. },
  10601. /**
  10602. * Invoked on mouse up
  10603. */
  10604. onMouseUp: function() {
  10605. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove, i, len;
  10606. this.canvas.renderOnAddRemove = false;
  10607. var circles = [];
  10608. for (i = 0, len = this.points.length; i < len; i++) {
  10609. var point = this.points[i],
  10610. circle = new fabric.Circle({
  10611. radius: point.radius,
  10612. left: point.x,
  10613. top: point.y,
  10614. originX: 'center',
  10615. originY: 'center',
  10616. fill: point.fill
  10617. });
  10618. this.shadow && (circle.shadow = new fabric.Shadow(this.shadow));
  10619. circles.push(circle);
  10620. }
  10621. var group = new fabric.Group(circles);
  10622. group.canvas = this.canvas;
  10623. this.canvas.fire('before:path:created', { path: group });
  10624. this.canvas.add(group);
  10625. this.canvas.fire('path:created', { path: group });
  10626. this.canvas.clearContext(this.canvas.contextTop);
  10627. this._resetShadow();
  10628. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  10629. this.canvas.requestRenderAll();
  10630. },
  10631. /**
  10632. * @param {Object} pointer
  10633. * @return {fabric.Point} Just added pointer point
  10634. */
  10635. addPoint: function(pointer) {
  10636. var pointerPoint = new fabric.Point(pointer.x, pointer.y),
  10637. circleRadius = fabric.util.getRandomInt(
  10638. Math.max(0, this.width - 20), this.width + 20) / 2,
  10639. circleColor = new fabric.Color(this.color)
  10640. .setAlpha(fabric.util.getRandomInt(0, 100) / 100)
  10641. .toRgba();
  10642. pointerPoint.radius = circleRadius;
  10643. pointerPoint.fill = circleColor;
  10644. this.points.push(pointerPoint);
  10645. return pointerPoint;
  10646. }
  10647. });
  10648. /**
  10649. * SprayBrush class
  10650. * @class fabric.SprayBrush
  10651. */
  10652. fabric.SprayBrush = fabric.util.createClass( fabric.BaseBrush, /** @lends fabric.SprayBrush.prototype */ {
  10653. /**
  10654. * Width of a spray
  10655. * @type Number
  10656. * @default
  10657. */
  10658. width: 10,
  10659. /**
  10660. * Density of a spray (number of dots per chunk)
  10661. * @type Number
  10662. * @default
  10663. */
  10664. density: 20,
  10665. /**
  10666. * Width of spray dots
  10667. * @type Number
  10668. * @default
  10669. */
  10670. dotWidth: 1,
  10671. /**
  10672. * Width variance of spray dots
  10673. * @type Number
  10674. * @default
  10675. */
  10676. dotWidthVariance: 1,
  10677. /**
  10678. * Whether opacity of a dot should be random
  10679. * @type Boolean
  10680. * @default
  10681. */
  10682. randomOpacity: false,
  10683. /**
  10684. * Whether overlapping dots (rectangles) should be removed (for performance reasons)
  10685. * @type Boolean
  10686. * @default
  10687. */
  10688. optimizeOverlapping: true,
  10689. /**
  10690. * Constructor
  10691. * @param {fabric.Canvas} canvas
  10692. * @return {fabric.SprayBrush} Instance of a spray brush
  10693. */
  10694. initialize: function(canvas) {
  10695. this.canvas = canvas;
  10696. this.sprayChunks = [];
  10697. },
  10698. /**
  10699. * Invoked on mouse down
  10700. * @param {Object} pointer
  10701. */
  10702. onMouseDown: function(pointer) {
  10703. this.sprayChunks.length = 0;
  10704. this.canvas.clearContext(this.canvas.contextTop);
  10705. this._setShadow();
  10706. this.addSprayChunk(pointer);
  10707. this.render(this.sprayChunkPoints);
  10708. },
  10709. /**
  10710. * Invoked on mouse move
  10711. * @param {Object} pointer
  10712. */
  10713. onMouseMove: function(pointer) {
  10714. if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {
  10715. return;
  10716. }
  10717. this.addSprayChunk(pointer);
  10718. this.render(this.sprayChunkPoints);
  10719. },
  10720. /**
  10721. * Invoked on mouse up
  10722. */
  10723. onMouseUp: function() {
  10724. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
  10725. this.canvas.renderOnAddRemove = false;
  10726. var rects = [];
  10727. for (var i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {
  10728. var sprayChunk = this.sprayChunks[i];
  10729. for (var j = 0, jlen = sprayChunk.length; j < jlen; j++) {
  10730. var rect = new fabric.Rect({
  10731. width: sprayChunk[j].width,
  10732. height: sprayChunk[j].width,
  10733. left: sprayChunk[j].x + 1,
  10734. top: sprayChunk[j].y + 1,
  10735. originX: 'center',
  10736. originY: 'center',
  10737. fill: this.color
  10738. });
  10739. rects.push(rect);
  10740. }
  10741. }
  10742. if (this.optimizeOverlapping) {
  10743. rects = this._getOptimizedRects(rects);
  10744. }
  10745. var group = new fabric.Group(rects);
  10746. this.shadow && group.set('shadow', new fabric.Shadow(this.shadow));
  10747. this.canvas.fire('before:path:created', { path: group });
  10748. this.canvas.add(group);
  10749. this.canvas.fire('path:created', { path: group });
  10750. this.canvas.clearContext(this.canvas.contextTop);
  10751. this._resetShadow();
  10752. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  10753. this.canvas.requestRenderAll();
  10754. },
  10755. /**
  10756. * @private
  10757. * @param {Array} rects
  10758. */
  10759. _getOptimizedRects: function(rects) {
  10760. // avoid creating duplicate rects at the same coordinates
  10761. var uniqueRects = { }, key, i, len;
  10762. for (i = 0, len = rects.length; i < len; i++) {
  10763. key = rects[i].left + '' + rects[i].top;
  10764. if (!uniqueRects[key]) {
  10765. uniqueRects[key] = rects[i];
  10766. }
  10767. }
  10768. var uniqueRectsArray = [];
  10769. for (key in uniqueRects) {
  10770. uniqueRectsArray.push(uniqueRects[key]);
  10771. }
  10772. return uniqueRectsArray;
  10773. },
  10774. /**
  10775. * Render new chunk of spray brush
  10776. */
  10777. render: function(sprayChunk) {
  10778. var ctx = this.canvas.contextTop, i, len;
  10779. ctx.fillStyle = this.color;
  10780. this._saveAndTransform(ctx);
  10781. for (i = 0, len = sprayChunk.length; i < len; i++) {
  10782. var point = sprayChunk[i];
  10783. if (typeof point.opacity !== 'undefined') {
  10784. ctx.globalAlpha = point.opacity;
  10785. }
  10786. ctx.fillRect(point.x, point.y, point.width, point.width);
  10787. }
  10788. ctx.restore();
  10789. },
  10790. /**
  10791. * Render all spray chunks
  10792. */
  10793. _render: function() {
  10794. var ctx = this.canvas.contextTop, i, ilen;
  10795. ctx.fillStyle = this.color;
  10796. this._saveAndTransform(ctx);
  10797. for (i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {
  10798. this.render(this.sprayChunks[i]);
  10799. }
  10800. ctx.restore();
  10801. },
  10802. /**
  10803. * @param {Object} pointer
  10804. */
  10805. addSprayChunk: function(pointer) {
  10806. this.sprayChunkPoints = [];
  10807. var x, y, width, radius = this.width / 2, i;
  10808. for (i = 0; i < this.density; i++) {
  10809. x = fabric.util.getRandomInt(pointer.x - radius, pointer.x + radius);
  10810. y = fabric.util.getRandomInt(pointer.y - radius, pointer.y + radius);
  10811. if (this.dotWidthVariance) {
  10812. width = fabric.util.getRandomInt(
  10813. // bottom clamp width to 1
  10814. Math.max(1, this.dotWidth - this.dotWidthVariance),
  10815. this.dotWidth + this.dotWidthVariance);
  10816. }
  10817. else {
  10818. width = this.dotWidth;
  10819. }
  10820. var point = new fabric.Point(x, y);
  10821. point.width = width;
  10822. if (this.randomOpacity) {
  10823. point.opacity = fabric.util.getRandomInt(0, 100) / 100;
  10824. }
  10825. this.sprayChunkPoints.push(point);
  10826. }
  10827. this.sprayChunks.push(this.sprayChunkPoints);
  10828. }
  10829. });
  10830. /**
  10831. * PatternBrush class
  10832. * @class fabric.PatternBrush
  10833. * @extends fabric.BaseBrush
  10834. */
  10835. fabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fabric.PatternBrush.prototype */ {
  10836. getPatternSrc: function() {
  10837. var dotWidth = 20,
  10838. dotDistance = 5,
  10839. patternCanvas = fabric.util.createCanvasElement(),
  10840. patternCtx = patternCanvas.getContext('2d');
  10841. patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;
  10842. patternCtx.fillStyle = this.color;
  10843. patternCtx.beginPath();
  10844. patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);
  10845. patternCtx.closePath();
  10846. patternCtx.fill();
  10847. return patternCanvas;
  10848. },
  10849. getPatternSrcFunction: function() {
  10850. return String(this.getPatternSrc).replace('this.color', '"' + this.color + '"');
  10851. },
  10852. /**
  10853. * Creates "pattern" instance property
  10854. * @param {CanvasRenderingContext2D} ctx
  10855. */
  10856. getPattern: function(ctx) {
  10857. return ctx.createPattern(this.source || this.getPatternSrc(), 'repeat');
  10858. },
  10859. /**
  10860. * Sets brush styles
  10861. * @param {CanvasRenderingContext2D} ctx
  10862. */
  10863. _setBrushStyles: function(ctx) {
  10864. this.callSuper('_setBrushStyles', ctx);
  10865. ctx.strokeStyle = this.getPattern(ctx);
  10866. },
  10867. /**
  10868. * Creates path
  10869. */
  10870. createPath: function(pathData) {
  10871. var path = this.callSuper('createPath', pathData),
  10872. topLeft = path._getLeftTopCoords().scalarAdd(path.strokeWidth / 2);
  10873. path.stroke = new fabric.Pattern({
  10874. source: this.source || this.getPatternSrcFunction(),
  10875. offsetX: -topLeft.x,
  10876. offsetY: -topLeft.y
  10877. });
  10878. return path;
  10879. }
  10880. });
  10881. (function() {
  10882. var getPointer = fabric.util.getPointer,
  10883. degreesToRadians = fabric.util.degreesToRadians,
  10884. isTouchEvent = fabric.util.isTouchEvent;
  10885. /**
  10886. * Canvas class
  10887. * @class fabric.Canvas
  10888. * @extends fabric.StaticCanvas
  10889. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#canvas}
  10890. * @see {@link fabric.Canvas#initialize} for constructor definition
  10891. *
  10892. * @fires object:modified at the end of a transform or any change when statefull is true
  10893. * @fires object:rotating while an object is being rotated from the control
  10894. * @fires object:scaling while an object is being scaled by controls
  10895. * @fires object:moving while an object is being dragged
  10896. * @fires object:skewing while an object is being skewed from the controls
  10897. *
  10898. * @fires before:transform before a transform is is started
  10899. * @fires before:selection:cleared
  10900. * @fires selection:cleared
  10901. * @fires selection:updated
  10902. * @fires selection:created
  10903. *
  10904. * @fires path:created after a drawing operation ends and the path is added
  10905. * @fires mouse:down
  10906. * @fires mouse:move
  10907. * @fires mouse:up
  10908. * @fires mouse:down:before on mouse down, before the inner fabric logic runs
  10909. * @fires mouse:move:before on mouse move, before the inner fabric logic runs
  10910. * @fires mouse:up:before on mouse up, before the inner fabric logic runs
  10911. * @fires mouse:over
  10912. * @fires mouse:out
  10913. * @fires mouse:dblclick whenever a native dbl click event fires on the canvas.
  10914. *
  10915. * @fires dragover
  10916. * @fires dragenter
  10917. * @fires dragleave
  10918. * @fires drop:before before drop event. same native event. This is added to handle edge cases
  10919. * @fires drop
  10920. * @fires after:render at the end of the render process, receives the context in the callback
  10921. * @fires before:render at start the render process, receives the context in the callback
  10922. *
  10923. */
  10924. fabric.Canvas = fabric.util.createClass(fabric.StaticCanvas, /** @lends fabric.Canvas.prototype */ {
  10925. /**
  10926. * Constructor
  10927. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  10928. * @param {Object} [options] Options object
  10929. * @return {Object} thisArg
  10930. */
  10931. initialize: function(el, options) {
  10932. options || (options = { });
  10933. this.renderAndResetBound = this.renderAndReset.bind(this);
  10934. this.requestRenderAllBound = this.requestRenderAll.bind(this);
  10935. this._initStatic(el, options);
  10936. this._initInteractive();
  10937. this._createCacheCanvas();
  10938. },
  10939. /**
  10940. * When true, objects can be transformed by one side (unproportionally)
  10941. * when dragged on the corners that normally would not do that.
  10942. * @type Boolean
  10943. * @default
  10944. * @since fabric 4.0 // changed name and default value
  10945. */
  10946. uniformScaling: true,
  10947. /**
  10948. * Indicates which key switches uniform scaling.
  10949. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  10950. * If `null` or 'none' or any other string that is not a modifier key
  10951. * feature is disabled.
  10952. * totally wrong named. this sounds like `uniform scaling`
  10953. * if Canvas.uniformScaling is true, pressing this will set it to false
  10954. * and viceversa.
  10955. * @since 1.6.2
  10956. * @type String
  10957. * @default
  10958. */
  10959. uniScaleKey: 'shiftKey',
  10960. /**
  10961. * When true, objects use center point as the origin of scale transformation.
  10962. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  10963. * @since 1.3.4
  10964. * @type Boolean
  10965. * @default
  10966. */
  10967. centeredScaling: false,
  10968. /**
  10969. * When true, objects use center point as the origin of rotate transformation.
  10970. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  10971. * @since 1.3.4
  10972. * @type Boolean
  10973. * @default
  10974. */
  10975. centeredRotation: false,
  10976. /**
  10977. * Indicates which key enable centered Transform
  10978. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  10979. * If `null` or 'none' or any other string that is not a modifier key
  10980. * feature is disabled feature disabled.
  10981. * @since 1.6.2
  10982. * @type String
  10983. * @default
  10984. */
  10985. centeredKey: 'altKey',
  10986. /**
  10987. * Indicates which key enable alternate action on corner
  10988. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  10989. * If `null` or 'none' or any other string that is not a modifier key
  10990. * feature is disabled feature disabled.
  10991. * @since 1.6.2
  10992. * @type String
  10993. * @default
  10994. */
  10995. altActionKey: 'shiftKey',
  10996. /**
  10997. * Indicates that canvas is interactive. This property should not be changed.
  10998. * @type Boolean
  10999. * @default
  11000. */
  11001. interactive: true,
  11002. /**
  11003. * Indicates whether group selection should be enabled
  11004. * @type Boolean
  11005. * @default
  11006. */
  11007. selection: true,
  11008. /**
  11009. * Indicates which key or keys enable multiple click selection
  11010. * Pass value as a string or array of strings
  11011. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  11012. * If `null` or empty or containing any other string that is not a modifier key
  11013. * feature is disabled.
  11014. * @since 1.6.2
  11015. * @type String|Array
  11016. * @default
  11017. */
  11018. selectionKey: 'shiftKey',
  11019. /**
  11020. * Indicates which key enable alternative selection
  11021. * in case of target overlapping with active object
  11022. * values: 'altKey', 'shiftKey', 'ctrlKey'.
  11023. * For a series of reason that come from the general expectations on how
  11024. * things should work, this feature works only for preserveObjectStacking true.
  11025. * If `null` or 'none' or any other string that is not a modifier key
  11026. * feature is disabled.
  11027. * @since 1.6.5
  11028. * @type null|String
  11029. * @default
  11030. */
  11031. altSelectionKey: null,
  11032. /**
  11033. * Color of selection
  11034. * @type String
  11035. * @default
  11036. */
  11037. selectionColor: 'rgba(100, 100, 255, 0.3)', // blue
  11038. /**
  11039. * Default dash array pattern
  11040. * If not empty the selection border is dashed
  11041. * @type Array
  11042. */
  11043. selectionDashArray: [],
  11044. /**
  11045. * Color of the border of selection (usually slightly darker than color of selection itself)
  11046. * @type String
  11047. * @default
  11048. */
  11049. selectionBorderColor: 'rgba(255, 255, 255, 0.3)',
  11050. /**
  11051. * Width of a line used in object/group selection
  11052. * @type Number
  11053. * @default
  11054. */
  11055. selectionLineWidth: 1,
  11056. /**
  11057. * Select only shapes that are fully contained in the dragged selection rectangle.
  11058. * @type Boolean
  11059. * @default
  11060. */
  11061. selectionFullyContained: false,
  11062. /**
  11063. * Default cursor value used when hovering over an object on canvas
  11064. * @type String
  11065. * @default
  11066. */
  11067. hoverCursor: 'move',
  11068. /**
  11069. * Default cursor value used when moving an object on canvas
  11070. * @type String
  11071. * @default
  11072. */
  11073. moveCursor: 'move',
  11074. /**
  11075. * Default cursor value used for the entire canvas
  11076. * @type String
  11077. * @default
  11078. */
  11079. defaultCursor: 'default',
  11080. /**
  11081. * Cursor value used during free drawing
  11082. * @type String
  11083. * @default
  11084. */
  11085. freeDrawingCursor: 'crosshair',
  11086. /**
  11087. * Cursor value used for disabled elements ( corners with disabled action )
  11088. * @type String
  11089. * @since 2.0.0
  11090. * @default
  11091. */
  11092. notAllowedCursor: 'not-allowed',
  11093. /**
  11094. * Default element class that's given to wrapper (div) element of canvas
  11095. * @type String
  11096. * @default
  11097. */
  11098. containerClass: 'canvas-container',
  11099. /**
  11100. * When true, object detection happens on per-pixel basis rather than on per-bounding-box
  11101. * @type Boolean
  11102. * @default
  11103. */
  11104. perPixelTargetFind: false,
  11105. /**
  11106. * Number of pixels around target pixel to tolerate (consider active) during object detection
  11107. * @type Number
  11108. * @default
  11109. */
  11110. targetFindTolerance: 0,
  11111. /**
  11112. * When true, target detection is skipped. Target detection will return always undefined.
  11113. * click selection won't work anymore, events will fire with no targets.
  11114. * if something is selected before setting it to true, it will be deselected at the first click.
  11115. * area selection will still work. check the `selection` property too.
  11116. * if you deactivate both, you should look into staticCanvas.
  11117. * @type Boolean
  11118. * @default
  11119. */
  11120. skipTargetFind: false,
  11121. /**
  11122. * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing.
  11123. * After mousedown, mousemove creates a shape,
  11124. * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas.
  11125. * @tutorial {@link http://fabricjs.com/fabric-intro-part-4#free_drawing}
  11126. * @type Boolean
  11127. * @default
  11128. */
  11129. isDrawingMode: false,
  11130. /**
  11131. * Indicates whether objects should remain in current stack position when selected.
  11132. * When false objects are brought to top and rendered as part of the selection group
  11133. * @type Boolean
  11134. * @default
  11135. */
  11136. preserveObjectStacking: false,
  11137. /**
  11138. * Indicates the angle that an object will lock to while rotating.
  11139. * @type Number
  11140. * @since 1.6.7
  11141. * @default
  11142. */
  11143. snapAngle: 0,
  11144. /**
  11145. * Indicates the distance from the snapAngle the rotation will lock to the snapAngle.
  11146. * When `null`, the snapThreshold will default to the snapAngle.
  11147. * @type null|Number
  11148. * @since 1.6.7
  11149. * @default
  11150. */
  11151. snapThreshold: null,
  11152. /**
  11153. * Indicates if the right click on canvas can output the context menu or not
  11154. * @type Boolean
  11155. * @since 1.6.5
  11156. * @default
  11157. */
  11158. stopContextMenu: false,
  11159. /**
  11160. * Indicates if the canvas can fire right click events
  11161. * @type Boolean
  11162. * @since 1.6.5
  11163. * @default
  11164. */
  11165. fireRightClick: false,
  11166. /**
  11167. * Indicates if the canvas can fire middle click events
  11168. * @type Boolean
  11169. * @since 1.7.8
  11170. * @default
  11171. */
  11172. fireMiddleClick: false,
  11173. /**
  11174. * Keep track of the subTargets for Mouse Events
  11175. * @type fabric.Object[]
  11176. */
  11177. targets: [],
  11178. /**
  11179. * When the option is enabled, PointerEvent is used instead of MouseEvent.
  11180. * @type Boolean
  11181. * @default
  11182. */
  11183. enablePointerEvents: false,
  11184. /**
  11185. * Keep track of the hovered target
  11186. * @type fabric.Object
  11187. * @private
  11188. */
  11189. _hoveredTarget: null,
  11190. /**
  11191. * hold the list of nested targets hovered
  11192. * @type fabric.Object[]
  11193. * @private
  11194. */
  11195. _hoveredTargets: [],
  11196. /**
  11197. * @private
  11198. */
  11199. _initInteractive: function() {
  11200. this._currentTransform = null;
  11201. this._groupSelector = null;
  11202. this._initWrapperElement();
  11203. this._createUpperCanvas();
  11204. this._initEventListeners();
  11205. this._initRetinaScaling();
  11206. this.freeDrawingBrush = fabric.PencilBrush && new fabric.PencilBrush(this);
  11207. this.calcOffset();
  11208. },
  11209. /**
  11210. * Divides objects in two groups, one to render immediately
  11211. * and one to render as activeGroup.
  11212. * @return {Array} objects to render immediately and pushes the other in the activeGroup.
  11213. */
  11214. _chooseObjectsToRender: function() {
  11215. var activeObjects = this.getActiveObjects(),
  11216. object, objsToRender, activeGroupObjects;
  11217. if (activeObjects.length > 0 && !this.preserveObjectStacking) {
  11218. objsToRender = [];
  11219. activeGroupObjects = [];
  11220. for (var i = 0, length = this._objects.length; i < length; i++) {
  11221. object = this._objects[i];
  11222. if (activeObjects.indexOf(object) === -1 ) {
  11223. objsToRender.push(object);
  11224. }
  11225. else {
  11226. activeGroupObjects.push(object);
  11227. }
  11228. }
  11229. if (activeObjects.length > 1) {
  11230. this._activeObject._objects = activeGroupObjects;
  11231. }
  11232. objsToRender.push.apply(objsToRender, activeGroupObjects);
  11233. }
  11234. else {
  11235. objsToRender = this._objects;
  11236. }
  11237. return objsToRender;
  11238. },
  11239. /**
  11240. * Renders both the top canvas and the secondary container canvas.
  11241. * @return {fabric.Canvas} instance
  11242. * @chainable
  11243. */
  11244. renderAll: function () {
  11245. if (this.contextTopDirty && !this._groupSelector && !this.isDrawingMode) {
  11246. this.clearContext(this.contextTop);
  11247. this.contextTopDirty = false;
  11248. }
  11249. if (this.hasLostContext) {
  11250. this.renderTopLayer(this.contextTop);
  11251. this.hasLostContext = false;
  11252. }
  11253. var canvasToDrawOn = this.contextContainer;
  11254. this.renderCanvas(canvasToDrawOn, this._chooseObjectsToRender());
  11255. return this;
  11256. },
  11257. renderTopLayer: function(ctx) {
  11258. ctx.save();
  11259. if (this.isDrawingMode && this._isCurrentlyDrawing) {
  11260. this.freeDrawingBrush && this.freeDrawingBrush._render();
  11261. this.contextTopDirty = true;
  11262. }
  11263. // we render the top context - last object
  11264. if (this.selection && this._groupSelector) {
  11265. this._drawSelection(ctx);
  11266. this.contextTopDirty = true;
  11267. }
  11268. ctx.restore();
  11269. },
  11270. /**
  11271. * Method to render only the top canvas.
  11272. * Also used to render the group selection box.
  11273. * @return {fabric.Canvas} thisArg
  11274. * @chainable
  11275. */
  11276. renderTop: function () {
  11277. var ctx = this.contextTop;
  11278. this.clearContext(ctx);
  11279. this.renderTopLayer(ctx);
  11280. this.fire('after:render');
  11281. return this;
  11282. },
  11283. /**
  11284. * @private
  11285. */
  11286. _normalizePointer: function (object, pointer) {
  11287. var m = object.calcTransformMatrix(),
  11288. invertedM = fabric.util.invertTransform(m),
  11289. vptPointer = this.restorePointerVpt(pointer);
  11290. return fabric.util.transformPoint(vptPointer, invertedM);
  11291. },
  11292. /**
  11293. * Returns true if object is transparent at a certain location
  11294. * @param {fabric.Object} target Object to check
  11295. * @param {Number} x Left coordinate
  11296. * @param {Number} y Top coordinate
  11297. * @return {Boolean}
  11298. */
  11299. isTargetTransparent: function (target, x, y) {
  11300. // in case the target is the activeObject, we cannot execute this optimization
  11301. // because we need to draw controls too.
  11302. if (target.shouldCache() && target._cacheCanvas && target !== this._activeObject) {
  11303. var normalizedPointer = this._normalizePointer(target, {x: x, y: y}),
  11304. targetRelativeX = Math.max(target.cacheTranslationX + (normalizedPointer.x * target.zoomX), 0),
  11305. targetRelativeY = Math.max(target.cacheTranslationY + (normalizedPointer.y * target.zoomY), 0);
  11306. var isTransparent = fabric.util.isTransparent(
  11307. target._cacheContext, Math.round(targetRelativeX), Math.round(targetRelativeY), this.targetFindTolerance);
  11308. return isTransparent;
  11309. }
  11310. var ctx = this.contextCache,
  11311. originalColor = target.selectionBackgroundColor, v = this.viewportTransform;
  11312. target.selectionBackgroundColor = '';
  11313. this.clearContext(ctx);
  11314. ctx.save();
  11315. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  11316. target.render(ctx);
  11317. ctx.restore();
  11318. target.selectionBackgroundColor = originalColor;
  11319. var isTransparent = fabric.util.isTransparent(
  11320. ctx, x, y, this.targetFindTolerance);
  11321. return isTransparent;
  11322. },
  11323. /**
  11324. * takes an event and determines if selection key has been pressed
  11325. * @private
  11326. * @param {Event} e Event object
  11327. */
  11328. _isSelectionKeyPressed: function(e) {
  11329. var selectionKeyPressed = false;
  11330. if (Array.isArray(this.selectionKey)) {
  11331. selectionKeyPressed = !!this.selectionKey.find(function(key) { return e[key] === true; });
  11332. }
  11333. else {
  11334. selectionKeyPressed = e[this.selectionKey];
  11335. }
  11336. return selectionKeyPressed;
  11337. },
  11338. /**
  11339. * @private
  11340. * @param {Event} e Event object
  11341. * @param {fabric.Object} target
  11342. */
  11343. _shouldClearSelection: function (e, target) {
  11344. var activeObjects = this.getActiveObjects(),
  11345. activeObject = this._activeObject;
  11346. return (
  11347. !target
  11348. ||
  11349. (target &&
  11350. activeObject &&
  11351. activeObjects.length > 1 &&
  11352. activeObjects.indexOf(target) === -1 &&
  11353. activeObject !== target &&
  11354. !this._isSelectionKeyPressed(e))
  11355. ||
  11356. (target && !target.evented)
  11357. ||
  11358. (target &&
  11359. !target.selectable &&
  11360. activeObject &&
  11361. activeObject !== target)
  11362. );
  11363. },
  11364. /**
  11365. * centeredScaling from object can't override centeredScaling from canvas.
  11366. * this should be fixed, since object setting should take precedence over canvas.
  11367. * also this should be something that will be migrated in the control properties.
  11368. * as ability to define the origin of the transformation that the control provide.
  11369. * @private
  11370. * @param {fabric.Object} target
  11371. * @param {String} action
  11372. * @param {Boolean} altKey
  11373. */
  11374. _shouldCenterTransform: function (target, action, altKey) {
  11375. if (!target) {
  11376. return;
  11377. }
  11378. var centerTransform;
  11379. if (action === 'scale' || action === 'scaleX' || action === 'scaleY' || action === 'resizing') {
  11380. centerTransform = this.centeredScaling || target.centeredScaling;
  11381. }
  11382. else if (action === 'rotate') {
  11383. centerTransform = this.centeredRotation || target.centeredRotation;
  11384. }
  11385. return centerTransform ? !altKey : altKey;
  11386. },
  11387. /**
  11388. * should disappear before release 4.0
  11389. * @private
  11390. */
  11391. _getOriginFromCorner: function(target, corner) {
  11392. var origin = {
  11393. x: target.originX,
  11394. y: target.originY
  11395. };
  11396. if (corner === 'ml' || corner === 'tl' || corner === 'bl') {
  11397. origin.x = 'right';
  11398. }
  11399. else if (corner === 'mr' || corner === 'tr' || corner === 'br') {
  11400. origin.x = 'left';
  11401. }
  11402. if (corner === 'tl' || corner === 'mt' || corner === 'tr') {
  11403. origin.y = 'bottom';
  11404. }
  11405. else if (corner === 'bl' || corner === 'mb' || corner === 'br') {
  11406. origin.y = 'top';
  11407. }
  11408. return origin;
  11409. },
  11410. /**
  11411. * @private
  11412. * @param {Boolean} alreadySelected true if target is already selected
  11413. * @param {String} corner a string representing the corner ml, mr, tl ...
  11414. * @param {Event} e Event object
  11415. * @param {fabric.Object} [target] inserted back to help overriding. Unused
  11416. */
  11417. _getActionFromCorner: function(alreadySelected, corner, e, target) {
  11418. if (!corner || !alreadySelected) {
  11419. return 'drag';
  11420. }
  11421. var control = target.controls[corner];
  11422. return control.getActionName(e, control, target);
  11423. },
  11424. /**
  11425. * @private
  11426. * @param {Event} e Event object
  11427. * @param {fabric.Object} target
  11428. */
  11429. _setupCurrentTransform: function (e, target, alreadySelected) {
  11430. if (!target) {
  11431. return;
  11432. }
  11433. var pointer = this.getPointer(e), corner = target.__corner,
  11434. control = target.controls[corner],
  11435. actionHandler = (alreadySelected && corner) ?
  11436. control.getActionHandler(e, target, control) : fabric.controlsUtils.dragHandler,
  11437. action = this._getActionFromCorner(alreadySelected, corner, e, target),
  11438. origin = this._getOriginFromCorner(target, corner),
  11439. altKey = e[this.centeredKey],
  11440. transform = {
  11441. target: target,
  11442. action: action,
  11443. actionHandler: actionHandler,
  11444. corner: corner,
  11445. scaleX: target.scaleX,
  11446. scaleY: target.scaleY,
  11447. skewX: target.skewX,
  11448. skewY: target.skewY,
  11449. // used by transation
  11450. offsetX: pointer.x - target.left,
  11451. offsetY: pointer.y - target.top,
  11452. originX: origin.x,
  11453. originY: origin.y,
  11454. ex: pointer.x,
  11455. ey: pointer.y,
  11456. lastX: pointer.x,
  11457. lastY: pointer.y,
  11458. // unsure they are useful anymore.
  11459. // left: target.left,
  11460. // top: target.top,
  11461. theta: degreesToRadians(target.angle),
  11462. // end of unsure
  11463. width: target.width * target.scaleX,
  11464. shiftKey: e.shiftKey,
  11465. altKey: altKey,
  11466. original: fabric.util.saveObjectTransform(target),
  11467. };
  11468. if (this._shouldCenterTransform(target, action, altKey)) {
  11469. transform.originX = 'center';
  11470. transform.originY = 'center';
  11471. }
  11472. transform.original.originX = origin.x;
  11473. transform.original.originY = origin.y;
  11474. this._currentTransform = transform;
  11475. this._beforeTransform(e);
  11476. },
  11477. /**
  11478. * Set the cursor type of the canvas element
  11479. * @param {String} value Cursor type of the canvas element.
  11480. * @see http://www.w3.org/TR/css3-ui/#cursor
  11481. */
  11482. setCursor: function (value) {
  11483. this.upperCanvasEl.style.cursor = value;
  11484. },
  11485. /**
  11486. * @private
  11487. * @param {CanvasRenderingContext2D} ctx to draw the selection on
  11488. */
  11489. _drawSelection: function (ctx) {
  11490. var selector = this._groupSelector,
  11491. viewportStart = new fabric.Point(selector.ex, selector.ey),
  11492. start = fabric.util.transformPoint(viewportStart, this.viewportTransform),
  11493. viewportExtent = new fabric.Point(selector.ex + selector.left, selector.ey + selector.top),
  11494. extent = fabric.util.transformPoint(viewportExtent, this.viewportTransform),
  11495. minX = Math.min(start.x, extent.x),
  11496. minY = Math.min(start.y, extent.y),
  11497. maxX = Math.max(start.x, extent.x),
  11498. maxY = Math.max(start.y, extent.y),
  11499. strokeOffset = this.selectionLineWidth / 2;
  11500. if (this.selectionColor) {
  11501. ctx.fillStyle = this.selectionColor;
  11502. ctx.fillRect(minX, minY, maxX - minX, maxY - minY);
  11503. }
  11504. if (!this.selectionLineWidth || !this.selectionBorderColor) {
  11505. return;
  11506. }
  11507. ctx.lineWidth = this.selectionLineWidth;
  11508. ctx.strokeStyle = this.selectionBorderColor;
  11509. minX += strokeOffset;
  11510. minY += strokeOffset;
  11511. maxX -= strokeOffset;
  11512. maxY -= strokeOffset;
  11513. // selection border
  11514. fabric.Object.prototype._setLineDash.call(this, ctx, this.selectionDashArray);
  11515. ctx.strokeRect(minX, minY, maxX - minX, maxY - minY);
  11516. },
  11517. /**
  11518. * Method that determines what object we are clicking on
  11519. * the skipGroup parameter is for internal use, is needed for shift+click action
  11520. * 11/09/2018 TODO: would be cool if findTarget could discern between being a full target
  11521. * or the outside part of the corner.
  11522. * @param {Event} e mouse event
  11523. * @param {Boolean} skipGroup when true, activeGroup is skipped and only objects are traversed through
  11524. * @return {fabric.Object} the target found
  11525. */
  11526. findTarget: function (e, skipGroup) {
  11527. if (this.skipTargetFind) {
  11528. return;
  11529. }
  11530. var ignoreZoom = true,
  11531. pointer = this.getPointer(e, ignoreZoom),
  11532. activeObject = this._activeObject,
  11533. aObjects = this.getActiveObjects(),
  11534. activeTarget, activeTargetSubs,
  11535. isTouch = isTouchEvent(e),
  11536. shouldLookForActive = (aObjects.length > 1 && !skipGroup) || aObjects.length === 1;
  11537. // first check current group (if one exists)
  11538. // active group does not check sub targets like normal groups.
  11539. // if active group just exits.
  11540. this.targets = [];
  11541. // if we hit the corner of an activeObject, let's return that.
  11542. if (shouldLookForActive && activeObject._findTargetCorner(pointer, isTouch)) {
  11543. return activeObject;
  11544. }
  11545. if (aObjects.length > 1 && !skipGroup && activeObject === this._searchPossibleTargets([activeObject], pointer)) {
  11546. return activeObject;
  11547. }
  11548. if (aObjects.length === 1 &&
  11549. activeObject === this._searchPossibleTargets([activeObject], pointer)) {
  11550. if (!this.preserveObjectStacking) {
  11551. return activeObject;
  11552. }
  11553. else {
  11554. activeTarget = activeObject;
  11555. activeTargetSubs = this.targets;
  11556. this.targets = [];
  11557. }
  11558. }
  11559. var target = this._searchPossibleTargets(this._objects, pointer);
  11560. if (e[this.altSelectionKey] && target && activeTarget && target !== activeTarget) {
  11561. target = activeTarget;
  11562. this.targets = activeTargetSubs;
  11563. }
  11564. return target;
  11565. },
  11566. /**
  11567. * Checks point is inside the object.
  11568. * @param {Object} [pointer] x,y object of point coordinates we want to check.
  11569. * @param {fabric.Object} obj Object to test against
  11570. * @param {Object} [globalPointer] x,y object of point coordinates relative to canvas used to search per pixel target.
  11571. * @return {Boolean} true if point is contained within an area of given object
  11572. * @private
  11573. */
  11574. _checkTarget: function(pointer, obj, globalPointer) {
  11575. if (obj &&
  11576. obj.visible &&
  11577. obj.evented &&
  11578. // http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html
  11579. // http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html
  11580. obj.containsPoint(pointer)
  11581. ) {
  11582. if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
  11583. var isTransparent = this.isTargetTransparent(obj, globalPointer.x, globalPointer.y);
  11584. if (!isTransparent) {
  11585. return true;
  11586. }
  11587. }
  11588. else {
  11589. return true;
  11590. }
  11591. }
  11592. },
  11593. /**
  11594. * Function used to search inside objects an object that contains pointer in bounding box or that contains pointerOnCanvas when painted
  11595. * @param {Array} [objects] objects array to look into
  11596. * @param {Object} [pointer] x,y object of point coordinates we want to check.
  11597. * @return {fabric.Object} object that contains pointer
  11598. * @private
  11599. */
  11600. _searchPossibleTargets: function(objects, pointer) {
  11601. // Cache all targets where their bounding box contains point.
  11602. var target, i = objects.length, subTarget;
  11603. // Do not check for currently grouped objects, since we check the parent group itself.
  11604. // until we call this function specifically to search inside the activeGroup
  11605. while (i--) {
  11606. var objToCheck = objects[i];
  11607. var pointerToUse = objToCheck.group ?
  11608. this._normalizePointer(objToCheck.group, pointer) : pointer;
  11609. if (this._checkTarget(pointerToUse, objToCheck, pointer)) {
  11610. target = objects[i];
  11611. if (target.subTargetCheck && target instanceof fabric.Group) {
  11612. subTarget = this._searchPossibleTargets(target._objects, pointer);
  11613. subTarget && this.targets.push(subTarget);
  11614. }
  11615. break;
  11616. }
  11617. }
  11618. return target;
  11619. },
  11620. /**
  11621. * Returns pointer coordinates without the effect of the viewport
  11622. * @param {Object} pointer with "x" and "y" number values
  11623. * @return {Object} object with "x" and "y" number values
  11624. */
  11625. restorePointerVpt: function(pointer) {
  11626. return fabric.util.transformPoint(
  11627. pointer,
  11628. fabric.util.invertTransform(this.viewportTransform)
  11629. );
  11630. },
  11631. /**
  11632. * Returns pointer coordinates relative to canvas.
  11633. * Can return coordinates with or without viewportTransform.
  11634. * ignoreZoom false gives back coordinates that represent
  11635. * the point clicked on canvas element.
  11636. * ignoreZoom true gives back coordinates after being processed
  11637. * by the viewportTransform ( sort of coordinates of what is displayed
  11638. * on the canvas where you are clicking.
  11639. * ignoreZoom true = HTMLElement coordinates relative to top,left
  11640. * ignoreZoom false, default = fabric space coordinates, the same used for shape position
  11641. * To interact with your shapes top and left you want to use ignoreZoom true
  11642. * most of the time, while ignoreZoom false will give you coordinates
  11643. * compatible with the object.oCoords system.
  11644. * of the time.
  11645. * @param {Event} e
  11646. * @param {Boolean} ignoreZoom
  11647. * @return {Object} object with "x" and "y" number values
  11648. */
  11649. getPointer: function (e, ignoreZoom) {
  11650. // return cached values if we are in the event processing chain
  11651. if (this._absolutePointer && !ignoreZoom) {
  11652. return this._absolutePointer;
  11653. }
  11654. if (this._pointer && ignoreZoom) {
  11655. return this._pointer;
  11656. }
  11657. var pointer = getPointer(e),
  11658. upperCanvasEl = this.upperCanvasEl,
  11659. bounds = upperCanvasEl.getBoundingClientRect(),
  11660. boundsWidth = bounds.width || 0,
  11661. boundsHeight = bounds.height || 0,
  11662. cssScale;
  11663. if (!boundsWidth || !boundsHeight ) {
  11664. if ('top' in bounds && 'bottom' in bounds) {
  11665. boundsHeight = Math.abs( bounds.top - bounds.bottom );
  11666. }
  11667. if ('right' in bounds && 'left' in bounds) {
  11668. boundsWidth = Math.abs( bounds.right - bounds.left );
  11669. }
  11670. }
  11671. this.calcOffset();
  11672. pointer.x = pointer.x - this._offset.left;
  11673. pointer.y = pointer.y - this._offset.top;
  11674. if (!ignoreZoom) {
  11675. pointer = this.restorePointerVpt(pointer);
  11676. }
  11677. var retinaScaling = this.getRetinaScaling();
  11678. if (retinaScaling !== 1) {
  11679. pointer.x /= retinaScaling;
  11680. pointer.y /= retinaScaling;
  11681. }
  11682. if (boundsWidth === 0 || boundsHeight === 0) {
  11683. // If bounds are not available (i.e. not visible), do not apply scale.
  11684. cssScale = { width: 1, height: 1 };
  11685. }
  11686. else {
  11687. cssScale = {
  11688. width: upperCanvasEl.width / boundsWidth,
  11689. height: upperCanvasEl.height / boundsHeight
  11690. };
  11691. }
  11692. return {
  11693. x: pointer.x * cssScale.width,
  11694. y: pointer.y * cssScale.height
  11695. };
  11696. },
  11697. /**
  11698. * @private
  11699. * @throws {CANVAS_INIT_ERROR} If canvas can not be initialized
  11700. */
  11701. _createUpperCanvas: function () {
  11702. var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/, ''),
  11703. lowerCanvasEl = this.lowerCanvasEl, upperCanvasEl = this.upperCanvasEl;
  11704. // there is no need to create a new upperCanvas element if we have already one.
  11705. if (upperCanvasEl) {
  11706. upperCanvasEl.className = '';
  11707. }
  11708. else {
  11709. upperCanvasEl = this._createCanvasElement();
  11710. this.upperCanvasEl = upperCanvasEl;
  11711. }
  11712. fabric.util.addClass(upperCanvasEl, 'upper-canvas ' + lowerCanvasClass);
  11713. this.wrapperEl.appendChild(upperCanvasEl);
  11714. this._copyCanvasStyle(lowerCanvasEl, upperCanvasEl);
  11715. this._applyCanvasStyle(upperCanvasEl);
  11716. this.contextTop = upperCanvasEl.getContext('2d');
  11717. },
  11718. /**
  11719. * Returns context of top canvas where interactions are drawn
  11720. * @returns {CanvasRenderingContext2D}
  11721. */
  11722. getTopContext: function () {
  11723. return this.contextTop;
  11724. },
  11725. /**
  11726. * @private
  11727. */
  11728. _createCacheCanvas: function () {
  11729. this.cacheCanvasEl = this._createCanvasElement();
  11730. this.cacheCanvasEl.setAttribute('width', this.width);
  11731. this.cacheCanvasEl.setAttribute('height', this.height);
  11732. this.contextCache = this.cacheCanvasEl.getContext('2d');
  11733. },
  11734. /**
  11735. * @private
  11736. */
  11737. _initWrapperElement: function () {
  11738. this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, 'div', {
  11739. 'class': this.containerClass
  11740. });
  11741. fabric.util.setStyle(this.wrapperEl, {
  11742. width: this.width + 'px',
  11743. height: this.height + 'px',
  11744. position: 'relative'
  11745. });
  11746. fabric.util.makeElementUnselectable(this.wrapperEl);
  11747. },
  11748. /**
  11749. * @private
  11750. * @param {HTMLElement} element canvas element to apply styles on
  11751. */
  11752. _applyCanvasStyle: function (element) {
  11753. var width = this.width || element.width,
  11754. height = this.height || element.height;
  11755. fabric.util.setStyle(element, {
  11756. position: 'absolute',
  11757. width: width + 'px',
  11758. height: height + 'px',
  11759. left: 0,
  11760. top: 0,
  11761. 'touch-action': this.allowTouchScrolling ? 'manipulation' : 'none',
  11762. '-ms-touch-action': this.allowTouchScrolling ? 'manipulation' : 'none'
  11763. });
  11764. element.width = width;
  11765. element.height = height;
  11766. fabric.util.makeElementUnselectable(element);
  11767. },
  11768. /**
  11769. * Copy the entire inline style from one element (fromEl) to another (toEl)
  11770. * @private
  11771. * @param {Element} fromEl Element style is copied from
  11772. * @param {Element} toEl Element copied style is applied to
  11773. */
  11774. _copyCanvasStyle: function (fromEl, toEl) {
  11775. toEl.style.cssText = fromEl.style.cssText;
  11776. },
  11777. /**
  11778. * Returns context of canvas where object selection is drawn
  11779. * @return {CanvasRenderingContext2D}
  11780. */
  11781. getSelectionContext: function() {
  11782. return this.contextTop;
  11783. },
  11784. /**
  11785. * Returns &lt;canvas> element on which object selection is drawn
  11786. * @return {HTMLCanvasElement}
  11787. */
  11788. getSelectionElement: function () {
  11789. return this.upperCanvasEl;
  11790. },
  11791. /**
  11792. * Returns currently active object
  11793. * @return {fabric.Object} active object
  11794. */
  11795. getActiveObject: function () {
  11796. return this._activeObject;
  11797. },
  11798. /**
  11799. * Returns an array with the current selected objects
  11800. * @return {fabric.Object} active object
  11801. */
  11802. getActiveObjects: function () {
  11803. var active = this._activeObject;
  11804. if (active) {
  11805. if (active.type === 'activeSelection' && active._objects) {
  11806. return active._objects.slice(0);
  11807. }
  11808. else {
  11809. return [active];
  11810. }
  11811. }
  11812. return [];
  11813. },
  11814. /**
  11815. * @private
  11816. * @param {fabric.Object} obj Object that was removed
  11817. */
  11818. _onObjectRemoved: function(obj) {
  11819. // removing active object should fire "selection:cleared" events
  11820. if (obj === this._activeObject) {
  11821. this.fire('before:selection:cleared', { target: obj });
  11822. this._discardActiveObject();
  11823. this.fire('selection:cleared', { target: obj });
  11824. obj.fire('deselected');
  11825. }
  11826. if (obj === this._hoveredTarget){
  11827. this._hoveredTarget = null;
  11828. this._hoveredTargets = [];
  11829. }
  11830. this.callSuper('_onObjectRemoved', obj);
  11831. },
  11832. /**
  11833. * @private
  11834. * Compares the old activeObject with the current one and fires correct events
  11835. * @param {fabric.Object} obj old activeObject
  11836. */
  11837. _fireSelectionEvents: function(oldObjects, e) {
  11838. var somethingChanged = false, objects = this.getActiveObjects(),
  11839. added = [], removed = [];
  11840. oldObjects.forEach(function(oldObject) {
  11841. if (objects.indexOf(oldObject) === -1) {
  11842. somethingChanged = true;
  11843. oldObject.fire('deselected', {
  11844. e: e,
  11845. target: oldObject
  11846. });
  11847. removed.push(oldObject);
  11848. }
  11849. });
  11850. objects.forEach(function(object) {
  11851. if (oldObjects.indexOf(object) === -1) {
  11852. somethingChanged = true;
  11853. object.fire('selected', {
  11854. e: e,
  11855. target: object
  11856. });
  11857. added.push(object);
  11858. }
  11859. });
  11860. if (oldObjects.length > 0 && objects.length > 0) {
  11861. somethingChanged && this.fire('selection:updated', {
  11862. e: e,
  11863. selected: added,
  11864. deselected: removed,
  11865. });
  11866. }
  11867. else if (objects.length > 0) {
  11868. this.fire('selection:created', {
  11869. e: e,
  11870. selected: added,
  11871. });
  11872. }
  11873. else if (oldObjects.length > 0) {
  11874. this.fire('selection:cleared', {
  11875. e: e,
  11876. deselected: removed,
  11877. });
  11878. }
  11879. },
  11880. /**
  11881. * Sets given object as the only active object on canvas
  11882. * @param {fabric.Object} object Object to set as an active one
  11883. * @param {Event} [e] Event (passed along when firing "object:selected")
  11884. * @return {fabric.Canvas} thisArg
  11885. * @chainable
  11886. */
  11887. setActiveObject: function (object, e) {
  11888. var currentActives = this.getActiveObjects();
  11889. this._setActiveObject(object, e);
  11890. this._fireSelectionEvents(currentActives, e);
  11891. return this;
  11892. },
  11893. /**
  11894. * This is a private method for now.
  11895. * This is supposed to be equivalent to setActiveObject but without firing
  11896. * any event. There is commitment to have this stay this way.
  11897. * This is the functional part of setActiveObject.
  11898. * @private
  11899. * @param {Object} object to set as active
  11900. * @param {Event} [e] Event (passed along when firing "object:selected")
  11901. * @return {Boolean} true if the selection happened
  11902. */
  11903. _setActiveObject: function(object, e) {
  11904. if (this._activeObject === object) {
  11905. return false;
  11906. }
  11907. if (!this._discardActiveObject(e, object)) {
  11908. return false;
  11909. }
  11910. if (object.onSelect({ e: e })) {
  11911. return false;
  11912. }
  11913. this._activeObject = object;
  11914. return true;
  11915. },
  11916. /**
  11917. * This is a private method for now.
  11918. * This is supposed to be equivalent to discardActiveObject but without firing
  11919. * any events. There is commitment to have this stay this way.
  11920. * This is the functional part of discardActiveObject.
  11921. * @param {Event} [e] Event (passed along when firing "object:deselected")
  11922. * @param {Object} object to set as active
  11923. * @return {Boolean} true if the selection happened
  11924. * @private
  11925. */
  11926. _discardActiveObject: function(e, object) {
  11927. var obj = this._activeObject;
  11928. if (obj) {
  11929. // onDeselect return TRUE to cancel selection;
  11930. if (obj.onDeselect({ e: e, object: object })) {
  11931. return false;
  11932. }
  11933. this._activeObject = null;
  11934. }
  11935. return true;
  11936. },
  11937. /**
  11938. * Discards currently active object and fire events. If the function is called by fabric
  11939. * as a consequence of a mouse event, the event is passed as a parameter and
  11940. * sent to the fire function for the custom events. When used as a method the
  11941. * e param does not have any application.
  11942. * @param {event} e
  11943. * @return {fabric.Canvas} thisArg
  11944. * @chainable
  11945. */
  11946. discardActiveObject: function (e) {
  11947. var currentActives = this.getActiveObjects(), activeObject = this.getActiveObject();
  11948. if (currentActives.length) {
  11949. this.fire('before:selection:cleared', { target: activeObject, e: e });
  11950. }
  11951. this._discardActiveObject(e);
  11952. this._fireSelectionEvents(currentActives, e);
  11953. return this;
  11954. },
  11955. /**
  11956. * Clears a canvas element and removes all event listeners
  11957. * @return {fabric.Canvas} thisArg
  11958. * @chainable
  11959. */
  11960. dispose: function () {
  11961. var wrapper = this.wrapperEl;
  11962. this.removeListeners();
  11963. wrapper.removeChild(this.upperCanvasEl);
  11964. wrapper.removeChild(this.lowerCanvasEl);
  11965. this.contextCache = null;
  11966. this.contextTop = null;
  11967. ['upperCanvasEl', 'cacheCanvasEl'].forEach((function(element) {
  11968. fabric.util.cleanUpJsdomNode(this[element]);
  11969. this[element] = undefined;
  11970. }).bind(this));
  11971. if (wrapper.parentNode) {
  11972. wrapper.parentNode.replaceChild(this.lowerCanvasEl, this.wrapperEl);
  11973. }
  11974. delete this.wrapperEl;
  11975. fabric.StaticCanvas.prototype.dispose.call(this);
  11976. return this;
  11977. },
  11978. /**
  11979. * Clears all contexts (background, main, top) of an instance
  11980. * @return {fabric.Canvas} thisArg
  11981. * @chainable
  11982. */
  11983. clear: function () {
  11984. // this.discardActiveGroup();
  11985. this.discardActiveObject();
  11986. this.clearContext(this.contextTop);
  11987. return this.callSuper('clear');
  11988. },
  11989. /**
  11990. * Draws objects' controls (borders/controls)
  11991. * @param {CanvasRenderingContext2D} ctx Context to render controls on
  11992. */
  11993. drawControls: function(ctx) {
  11994. var activeObject = this._activeObject;
  11995. if (activeObject) {
  11996. activeObject._renderControls(ctx);
  11997. }
  11998. },
  11999. /**
  12000. * @private
  12001. */
  12002. _toObject: function(instance, methodName, propertiesToInclude) {
  12003. //If the object is part of the current selection group, it should
  12004. //be transformed appropriately
  12005. //i.e. it should be serialised as it would appear if the selection group
  12006. //were to be destroyed.
  12007. var originalProperties = this._realizeGroupTransformOnObject(instance),
  12008. object = this.callSuper('_toObject', instance, methodName, propertiesToInclude);
  12009. //Undo the damage we did by changing all of its properties
  12010. this._unwindGroupTransformOnObject(instance, originalProperties);
  12011. return object;
  12012. },
  12013. /**
  12014. * Realises an object's group transformation on it
  12015. * @private
  12016. * @param {fabric.Object} [instance] the object to transform (gets mutated)
  12017. * @returns the original values of instance which were changed
  12018. */
  12019. _realizeGroupTransformOnObject: function(instance) {
  12020. if (instance.group && instance.group.type === 'activeSelection' && this._activeObject === instance.group) {
  12021. var layoutProps = ['angle', 'flipX', 'flipY', 'left', 'scaleX', 'scaleY', 'skewX', 'skewY', 'top'];
  12022. //Copy all the positionally relevant properties across now
  12023. var originalValues = {};
  12024. layoutProps.forEach(function(prop) {
  12025. originalValues[prop] = instance[prop];
  12026. });
  12027. fabric.util.addTransformToObject(instance, this._activeObject.calcOwnMatrix());
  12028. return originalValues;
  12029. }
  12030. else {
  12031. return null;
  12032. }
  12033. },
  12034. /**
  12035. * Restores the changed properties of instance
  12036. * @private
  12037. * @param {fabric.Object} [instance] the object to un-transform (gets mutated)
  12038. * @param {Object} [originalValues] the original values of instance, as returned by _realizeGroupTransformOnObject
  12039. */
  12040. _unwindGroupTransformOnObject: function(instance, originalValues) {
  12041. if (originalValues) {
  12042. instance.set(originalValues);
  12043. }
  12044. },
  12045. /**
  12046. * @private
  12047. */
  12048. _setSVGObject: function(markup, instance, reviver) {
  12049. //If the object is in a selection group, simulate what would happen to that
  12050. //object when the group is deselected
  12051. var originalProperties = this._realizeGroupTransformOnObject(instance);
  12052. this.callSuper('_setSVGObject', markup, instance, reviver);
  12053. this._unwindGroupTransformOnObject(instance, originalProperties);
  12054. },
  12055. setViewportTransform: function (vpt) {
  12056. if (this.renderOnAddRemove && this._activeObject && this._activeObject.isEditing) {
  12057. this._activeObject.clearContextTop();
  12058. }
  12059. fabric.StaticCanvas.prototype.setViewportTransform.call(this, vpt);
  12060. }
  12061. });
  12062. // copying static properties manually to work around Opera's bug,
  12063. // where "prototype" property is enumerable and overrides existing prototype
  12064. for (var prop in fabric.StaticCanvas) {
  12065. if (prop !== 'prototype') {
  12066. fabric.Canvas[prop] = fabric.StaticCanvas[prop];
  12067. }
  12068. }
  12069. })();
  12070. (function() {
  12071. var addListener = fabric.util.addListener,
  12072. removeListener = fabric.util.removeListener,
  12073. RIGHT_CLICK = 3, MIDDLE_CLICK = 2, LEFT_CLICK = 1,
  12074. addEventOptions = { passive: false };
  12075. function checkClick(e, value) {
  12076. return e.button && (e.button === value - 1);
  12077. }
  12078. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  12079. /**
  12080. * Contains the id of the touch event that owns the fabric transform
  12081. * @type Number
  12082. * @private
  12083. */
  12084. mainTouchId: null,
  12085. /**
  12086. * Adds mouse listeners to canvas
  12087. * @private
  12088. */
  12089. _initEventListeners: function () {
  12090. // in case we initialized the class twice. This should not happen normally
  12091. // but in some kind of applications where the canvas element may be changed
  12092. // this is a workaround to having double listeners.
  12093. this.removeListeners();
  12094. this._bindEvents();
  12095. this.addOrRemove(addListener, 'add');
  12096. },
  12097. /**
  12098. * return an event prefix pointer or mouse.
  12099. * @private
  12100. */
  12101. _getEventPrefix: function () {
  12102. return this.enablePointerEvents ? 'pointer' : 'mouse';
  12103. },
  12104. addOrRemove: function(functor, eventjsFunctor) {
  12105. var canvasElement = this.upperCanvasEl,
  12106. eventTypePrefix = this._getEventPrefix();
  12107. functor(fabric.window, 'resize', this._onResize);
  12108. functor(canvasElement, eventTypePrefix + 'down', this._onMouseDown);
  12109. functor(canvasElement, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);
  12110. functor(canvasElement, eventTypePrefix + 'out', this._onMouseOut);
  12111. functor(canvasElement, eventTypePrefix + 'enter', this._onMouseEnter);
  12112. functor(canvasElement, 'wheel', this._onMouseWheel);
  12113. functor(canvasElement, 'contextmenu', this._onContextMenu);
  12114. functor(canvasElement, 'dblclick', this._onDoubleClick);
  12115. functor(canvasElement, 'dragover', this._onDragOver);
  12116. functor(canvasElement, 'dragenter', this._onDragEnter);
  12117. functor(canvasElement, 'dragleave', this._onDragLeave);
  12118. functor(canvasElement, 'drop', this._onDrop);
  12119. if (!this.enablePointerEvents) {
  12120. functor(canvasElement, 'touchstart', this._onTouchStart, addEventOptions);
  12121. }
  12122. if (typeof eventjs !== 'undefined' && eventjsFunctor in eventjs) {
  12123. eventjs[eventjsFunctor](canvasElement, 'gesture', this._onGesture);
  12124. eventjs[eventjsFunctor](canvasElement, 'drag', this._onDrag);
  12125. eventjs[eventjsFunctor](canvasElement, 'orientation', this._onOrientationChange);
  12126. eventjs[eventjsFunctor](canvasElement, 'shake', this._onShake);
  12127. eventjs[eventjsFunctor](canvasElement, 'longpress', this._onLongPress);
  12128. }
  12129. },
  12130. /**
  12131. * Removes all event listeners
  12132. */
  12133. removeListeners: function() {
  12134. this.addOrRemove(removeListener, 'remove');
  12135. // if you dispose on a mouseDown, before mouse up, you need to clean document to...
  12136. var eventTypePrefix = this._getEventPrefix();
  12137. removeListener(fabric.document, eventTypePrefix + 'up', this._onMouseUp);
  12138. removeListener(fabric.document, 'touchend', this._onTouchEnd, addEventOptions);
  12139. removeListener(fabric.document, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);
  12140. removeListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);
  12141. },
  12142. /**
  12143. * @private
  12144. */
  12145. _bindEvents: function() {
  12146. if (this.eventsBound) {
  12147. // for any reason we pass here twice we do not want to bind events twice.
  12148. return;
  12149. }
  12150. this._onMouseDown = this._onMouseDown.bind(this);
  12151. this._onTouchStart = this._onTouchStart.bind(this);
  12152. this._onMouseMove = this._onMouseMove.bind(this);
  12153. this._onMouseUp = this._onMouseUp.bind(this);
  12154. this._onTouchEnd = this._onTouchEnd.bind(this);
  12155. this._onResize = this._onResize.bind(this);
  12156. this._onGesture = this._onGesture.bind(this);
  12157. this._onDrag = this._onDrag.bind(this);
  12158. this._onShake = this._onShake.bind(this);
  12159. this._onLongPress = this._onLongPress.bind(this);
  12160. this._onOrientationChange = this._onOrientationChange.bind(this);
  12161. this._onMouseWheel = this._onMouseWheel.bind(this);
  12162. this._onMouseOut = this._onMouseOut.bind(this);
  12163. this._onMouseEnter = this._onMouseEnter.bind(this);
  12164. this._onContextMenu = this._onContextMenu.bind(this);
  12165. this._onDoubleClick = this._onDoubleClick.bind(this);
  12166. this._onDragOver = this._onDragOver.bind(this);
  12167. this._onDragEnter = this._simpleEventHandler.bind(this, 'dragenter');
  12168. this._onDragLeave = this._simpleEventHandler.bind(this, 'dragleave');
  12169. this._onDrop = this._onDrop.bind(this);
  12170. this.eventsBound = true;
  12171. },
  12172. /**
  12173. * @private
  12174. * @param {Event} [e] Event object fired on Event.js gesture
  12175. * @param {Event} [self] Inner Event object
  12176. */
  12177. _onGesture: function(e, self) {
  12178. this.__onTransformGesture && this.__onTransformGesture(e, self);
  12179. },
  12180. /**
  12181. * @private
  12182. * @param {Event} [e] Event object fired on Event.js drag
  12183. * @param {Event} [self] Inner Event object
  12184. */
  12185. _onDrag: function(e, self) {
  12186. this.__onDrag && this.__onDrag(e, self);
  12187. },
  12188. /**
  12189. * @private
  12190. * @param {Event} [e] Event object fired on wheel event
  12191. */
  12192. _onMouseWheel: function(e) {
  12193. this.__onMouseWheel(e);
  12194. },
  12195. /**
  12196. * @private
  12197. * @param {Event} e Event object fired on mousedown
  12198. */
  12199. _onMouseOut: function(e) {
  12200. var target = this._hoveredTarget;
  12201. this.fire('mouse:out', { target: target, e: e });
  12202. this._hoveredTarget = null;
  12203. target && target.fire('mouseout', { e: e });
  12204. var _this = this;
  12205. this._hoveredTargets.forEach(function(_target){
  12206. _this.fire('mouse:out', { target: target, e: e });
  12207. _target && target.fire('mouseout', { e: e });
  12208. });
  12209. this._hoveredTargets = [];
  12210. if (this._iTextInstances) {
  12211. this._iTextInstances.forEach(function(obj) {
  12212. if (obj.isEditing) {
  12213. obj.hiddenTextarea.focus();
  12214. }
  12215. });
  12216. }
  12217. },
  12218. /**
  12219. * @private
  12220. * @param {Event} e Event object fired on mouseenter
  12221. */
  12222. _onMouseEnter: function(e) {
  12223. // This find target and consequent 'mouse:over' is used to
  12224. // clear old instances on hovered target.
  12225. // calling findTarget has the side effect of killing target.__corner.
  12226. // as a short term fix we are not firing this if we are currently transforming.
  12227. // as a long term fix we need to separate the action of finding a target with the
  12228. // side effects we added to it.
  12229. if (!this._currentTransform && !this.findTarget(e)) {
  12230. this.fire('mouse:over', { target: null, e: e });
  12231. this._hoveredTarget = null;
  12232. this._hoveredTargets = [];
  12233. }
  12234. },
  12235. /**
  12236. * @private
  12237. * @param {Event} [e] Event object fired on Event.js orientation change
  12238. * @param {Event} [self] Inner Event object
  12239. */
  12240. _onOrientationChange: function(e, self) {
  12241. this.__onOrientationChange && this.__onOrientationChange(e, self);
  12242. },
  12243. /**
  12244. * @private
  12245. * @param {Event} [e] Event object fired on Event.js shake
  12246. * @param {Event} [self] Inner Event object
  12247. */
  12248. _onShake: function(e, self) {
  12249. this.__onShake && this.__onShake(e, self);
  12250. },
  12251. /**
  12252. * @private
  12253. * @param {Event} [e] Event object fired on Event.js shake
  12254. * @param {Event} [self] Inner Event object
  12255. */
  12256. _onLongPress: function(e, self) {
  12257. this.__onLongPress && this.__onLongPress(e, self);
  12258. },
  12259. /**
  12260. * prevent default to allow drop event to be fired
  12261. * @private
  12262. * @param {Event} [e] Event object fired on Event.js shake
  12263. */
  12264. _onDragOver: function(e) {
  12265. e.preventDefault();
  12266. var target = this._simpleEventHandler('dragover', e);
  12267. this._fireEnterLeaveEvents(target, e);
  12268. },
  12269. /**
  12270. * `drop:before` is a an event that allow you to schedule logic
  12271. * before the `drop` event. Prefer `drop` event always, but if you need
  12272. * to run some drop-disabling logic on an event, since there is no way
  12273. * to handle event handlers ordering, use `drop:before`
  12274. * @param {Event} e
  12275. */
  12276. _onDrop: function (e) {
  12277. this._simpleEventHandler('drop:before', e);
  12278. return this._simpleEventHandler('drop', e);
  12279. },
  12280. /**
  12281. * @private
  12282. * @param {Event} e Event object fired on mousedown
  12283. */
  12284. _onContextMenu: function (e) {
  12285. if (this.stopContextMenu) {
  12286. e.stopPropagation();
  12287. e.preventDefault();
  12288. }
  12289. return false;
  12290. },
  12291. /**
  12292. * @private
  12293. * @param {Event} e Event object fired on mousedown
  12294. */
  12295. _onDoubleClick: function (e) {
  12296. this._cacheTransformEventData(e);
  12297. this._handleEvent(e, 'dblclick');
  12298. this._resetTransformEventData(e);
  12299. },
  12300. /**
  12301. * Return a the id of an event.
  12302. * returns either the pointerId or the identifier or 0 for the mouse event
  12303. * @private
  12304. * @param {Event} evt Event object
  12305. */
  12306. getPointerId: function(evt) {
  12307. var changedTouches = evt.changedTouches;
  12308. if (changedTouches) {
  12309. return changedTouches[0] && changedTouches[0].identifier;
  12310. }
  12311. if (this.enablePointerEvents) {
  12312. return evt.pointerId;
  12313. }
  12314. return -1;
  12315. },
  12316. /**
  12317. * Determines if an event has the id of the event that is considered main
  12318. * @private
  12319. * @param {evt} event Event object
  12320. */
  12321. _isMainEvent: function(evt) {
  12322. if (evt.isPrimary === true) {
  12323. return true;
  12324. }
  12325. if (evt.isPrimary === false) {
  12326. return false;
  12327. }
  12328. if (evt.type === 'touchend' && evt.touches.length === 0) {
  12329. return true;
  12330. }
  12331. if (evt.changedTouches) {
  12332. return evt.changedTouches[0].identifier === this.mainTouchId;
  12333. }
  12334. return true;
  12335. },
  12336. /**
  12337. * @private
  12338. * @param {Event} e Event object fired on mousedown
  12339. */
  12340. _onTouchStart: function(e) {
  12341. e.preventDefault();
  12342. if (this.mainTouchId === null) {
  12343. this.mainTouchId = this.getPointerId(e);
  12344. }
  12345. this.__onMouseDown(e);
  12346. this._resetTransformEventData();
  12347. var canvasElement = this.upperCanvasEl,
  12348. eventTypePrefix = this._getEventPrefix();
  12349. addListener(fabric.document, 'touchend', this._onTouchEnd, addEventOptions);
  12350. addListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);
  12351. // Unbind mousedown to prevent double triggers from touch devices
  12352. removeListener(canvasElement, eventTypePrefix + 'down', this._onMouseDown);
  12353. },
  12354. /**
  12355. * @private
  12356. * @param {Event} e Event object fired on mousedown
  12357. */
  12358. _onMouseDown: function (e) {
  12359. this.__onMouseDown(e);
  12360. this._resetTransformEventData();
  12361. var canvasElement = this.upperCanvasEl,
  12362. eventTypePrefix = this._getEventPrefix();
  12363. removeListener(canvasElement, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);
  12364. addListener(fabric.document, eventTypePrefix + 'up', this._onMouseUp);
  12365. addListener(fabric.document, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);
  12366. },
  12367. /**
  12368. * @private
  12369. * @param {Event} e Event object fired on mousedown
  12370. */
  12371. _onTouchEnd: function(e) {
  12372. if (e.touches.length > 0) {
  12373. // if there are still touches stop here
  12374. return;
  12375. }
  12376. this.__onMouseUp(e);
  12377. this._resetTransformEventData();
  12378. this.mainTouchId = null;
  12379. var eventTypePrefix = this._getEventPrefix();
  12380. removeListener(fabric.document, 'touchend', this._onTouchEnd, addEventOptions);
  12381. removeListener(fabric.document, 'touchmove', this._onMouseMove, addEventOptions);
  12382. var _this = this;
  12383. if (this._willAddMouseDown) {
  12384. clearTimeout(this._willAddMouseDown);
  12385. }
  12386. this._willAddMouseDown = setTimeout(function() {
  12387. // Wait 400ms before rebinding mousedown to prevent double triggers
  12388. // from touch devices
  12389. addListener(_this.upperCanvasEl, eventTypePrefix + 'down', _this._onMouseDown);
  12390. _this._willAddMouseDown = 0;
  12391. }, 400);
  12392. },
  12393. /**
  12394. * @private
  12395. * @param {Event} e Event object fired on mouseup
  12396. */
  12397. _onMouseUp: function (e) {
  12398. this.__onMouseUp(e);
  12399. this._resetTransformEventData();
  12400. var canvasElement = this.upperCanvasEl,
  12401. eventTypePrefix = this._getEventPrefix();
  12402. if (this._isMainEvent(e)) {
  12403. removeListener(fabric.document, eventTypePrefix + 'up', this._onMouseUp);
  12404. removeListener(fabric.document, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);
  12405. addListener(canvasElement, eventTypePrefix + 'move', this._onMouseMove, addEventOptions);
  12406. }
  12407. },
  12408. /**
  12409. * @private
  12410. * @param {Event} e Event object fired on mousemove
  12411. */
  12412. _onMouseMove: function (e) {
  12413. !this.allowTouchScrolling && e.preventDefault && e.preventDefault();
  12414. this.__onMouseMove(e);
  12415. },
  12416. /**
  12417. * @private
  12418. */
  12419. _onResize: function () {
  12420. this.calcOffset();
  12421. },
  12422. /**
  12423. * Decides whether the canvas should be redrawn in mouseup and mousedown events.
  12424. * @private
  12425. * @param {Object} target
  12426. */
  12427. _shouldRender: function(target) {
  12428. var activeObject = this._activeObject;
  12429. if (
  12430. !!activeObject !== !!target ||
  12431. (activeObject && target && (activeObject !== target))
  12432. ) {
  12433. // this covers: switch of target, from target to no target, selection of target
  12434. // multiSelection with key and mouse
  12435. return true;
  12436. }
  12437. else if (activeObject && activeObject.isEditing) {
  12438. // if we mouse up/down over a editing textbox a cursor change,
  12439. // there is no need to re render
  12440. return false;
  12441. }
  12442. return false;
  12443. },
  12444. /**
  12445. * Method that defines the actions when mouse is released on canvas.
  12446. * The method resets the currentTransform parameters, store the image corner
  12447. * position in the image object and render the canvas on top.
  12448. * @private
  12449. * @param {Event} e Event object fired on mouseup
  12450. */
  12451. __onMouseUp: function (e) {
  12452. var target, transform = this._currentTransform,
  12453. groupSelector = this._groupSelector, shouldRender = false,
  12454. isClick = (!groupSelector || (groupSelector.left === 0 && groupSelector.top === 0));
  12455. this._cacheTransformEventData(e);
  12456. target = this._target;
  12457. this._handleEvent(e, 'up:before');
  12458. // if right/middle click just fire events and return
  12459. // target undefined will make the _handleEvent search the target
  12460. if (checkClick(e, RIGHT_CLICK)) {
  12461. if (this.fireRightClick) {
  12462. this._handleEvent(e, 'up', RIGHT_CLICK, isClick);
  12463. }
  12464. return;
  12465. }
  12466. if (checkClick(e, MIDDLE_CLICK)) {
  12467. if (this.fireMiddleClick) {
  12468. this._handleEvent(e, 'up', MIDDLE_CLICK, isClick);
  12469. }
  12470. this._resetTransformEventData();
  12471. return;
  12472. }
  12473. if (this.isDrawingMode && this._isCurrentlyDrawing) {
  12474. this._onMouseUpInDrawingMode(e);
  12475. return;
  12476. }
  12477. if (!this._isMainEvent(e)) {
  12478. return;
  12479. }
  12480. if (transform) {
  12481. this._finalizeCurrentTransform(e);
  12482. shouldRender = transform.actionPerformed;
  12483. }
  12484. if (!isClick) {
  12485. var targetWasActive = target === this._activeObject;
  12486. this._maybeGroupObjects(e);
  12487. if (!shouldRender) {
  12488. shouldRender = (
  12489. this._shouldRender(target) ||
  12490. (!targetWasActive && target === this._activeObject)
  12491. );
  12492. }
  12493. }
  12494. var corner, pointer;
  12495. if (target) {
  12496. corner = target._findTargetCorner(
  12497. this.getPointer(e, true),
  12498. fabric.util.isTouchEvent(e)
  12499. );
  12500. if (target.selectable && target !== this._activeObject && target.activeOn === 'up') {
  12501. this.setActiveObject(target, e);
  12502. shouldRender = true;
  12503. }
  12504. else {
  12505. var control = target.controls[corner],
  12506. mouseUpHandler = control && control.getMouseUpHandler(e, target, control);
  12507. if (mouseUpHandler) {
  12508. pointer = this.getPointer(e);
  12509. mouseUpHandler(e, transform, pointer.x, pointer.y);
  12510. }
  12511. }
  12512. target.isMoving = false;
  12513. }
  12514. // if we are ending up a transform on a different control or a new object
  12515. // fire the original mouse up from the corner that started the transform
  12516. if (transform && (transform.target !== target || transform.corner !== corner)) {
  12517. var originalControl = transform.target && transform.target.controls[transform.corner],
  12518. originalMouseUpHandler = originalControl && originalControl.getMouseUpHandler(e, target, control);
  12519. pointer = pointer || this.getPointer(e);
  12520. originalMouseUpHandler && originalMouseUpHandler(e, transform, pointer.x, pointer.y);
  12521. }
  12522. this._setCursorFromEvent(e, target);
  12523. this._handleEvent(e, 'up', LEFT_CLICK, isClick);
  12524. this._groupSelector = null;
  12525. this._currentTransform = null;
  12526. // reset the target information about which corner is selected
  12527. target && (target.__corner = 0);
  12528. if (shouldRender) {
  12529. this.requestRenderAll();
  12530. }
  12531. else if (!isClick) {
  12532. this.renderTop();
  12533. }
  12534. },
  12535. /**
  12536. * @private
  12537. * Handle event firing for target and subtargets
  12538. * @param {Event} e event from mouse
  12539. * @param {String} eventType event to fire (up, down or move)
  12540. * @return {Fabric.Object} target return the the target found, for internal reasons.
  12541. */
  12542. _simpleEventHandler: function(eventType, e) {
  12543. var target = this.findTarget(e),
  12544. targets = this.targets,
  12545. options = {
  12546. e: e,
  12547. target: target,
  12548. subTargets: targets,
  12549. };
  12550. this.fire(eventType, options);
  12551. target && target.fire(eventType, options);
  12552. if (!targets) {
  12553. return target;
  12554. }
  12555. for (var i = 0; i < targets.length; i++) {
  12556. targets[i].fire(eventType, options);
  12557. }
  12558. return target;
  12559. },
  12560. /**
  12561. * @private
  12562. * Handle event firing for target and subtargets
  12563. * @param {Event} e event from mouse
  12564. * @param {String} eventType event to fire (up, down or move)
  12565. * @param {fabric.Object} targetObj receiving event
  12566. * @param {Number} [button] button used in the event 1 = left, 2 = middle, 3 = right
  12567. * @param {Boolean} isClick for left button only, indicates that the mouse up happened without move.
  12568. */
  12569. _handleEvent: function(e, eventType, button, isClick) {
  12570. var target = this._target,
  12571. targets = this.targets || [],
  12572. options = {
  12573. e: e,
  12574. target: target,
  12575. subTargets: targets,
  12576. button: button || LEFT_CLICK,
  12577. isClick: isClick || false,
  12578. pointer: this._pointer,
  12579. absolutePointer: this._absolutePointer,
  12580. transform: this._currentTransform
  12581. };
  12582. if (eventType === 'up') {
  12583. options.currentTarget = this.findTarget(e);
  12584. options.currentSubTargets = this.targets;
  12585. }
  12586. this.fire('mouse:' + eventType, options);
  12587. target && target.fire('mouse' + eventType, options);
  12588. for (var i = 0; i < targets.length; i++) {
  12589. targets[i].fire('mouse' + eventType, options);
  12590. }
  12591. },
  12592. /**
  12593. * @private
  12594. * @param {Event} e send the mouse event that generate the finalize down, so it can be used in the event
  12595. */
  12596. _finalizeCurrentTransform: function(e) {
  12597. var transform = this._currentTransform,
  12598. target = transform.target,
  12599. options = {
  12600. e: e,
  12601. target: target,
  12602. transform: transform,
  12603. action: transform.action,
  12604. };
  12605. if (target._scaling) {
  12606. target._scaling = false;
  12607. }
  12608. target.setCoords();
  12609. if (transform.actionPerformed || (this.stateful && target.hasStateChanged())) {
  12610. this._fire('modified', options);
  12611. }
  12612. },
  12613. /**
  12614. * @private
  12615. * @param {Event} e Event object fired on mousedown
  12616. */
  12617. _onMouseDownInDrawingMode: function(e) {
  12618. this._isCurrentlyDrawing = true;
  12619. if (this.getActiveObject()) {
  12620. this.discardActiveObject(e).requestRenderAll();
  12621. }
  12622. var pointer = this.getPointer(e);
  12623. this.freeDrawingBrush.onMouseDown(pointer, { e: e, pointer: pointer });
  12624. this._handleEvent(e, 'down');
  12625. },
  12626. /**
  12627. * @private
  12628. * @param {Event} e Event object fired on mousemove
  12629. */
  12630. _onMouseMoveInDrawingMode: function(e) {
  12631. if (this._isCurrentlyDrawing) {
  12632. var pointer = this.getPointer(e);
  12633. this.freeDrawingBrush.onMouseMove(pointer, { e: e, pointer: pointer });
  12634. }
  12635. this.setCursor(this.freeDrawingCursor);
  12636. this._handleEvent(e, 'move');
  12637. },
  12638. /**
  12639. * @private
  12640. * @param {Event} e Event object fired on mouseup
  12641. */
  12642. _onMouseUpInDrawingMode: function(e) {
  12643. var pointer = this.getPointer(e);
  12644. this._isCurrentlyDrawing = this.freeDrawingBrush.onMouseUp({ e: e, pointer: pointer });
  12645. this._handleEvent(e, 'up');
  12646. },
  12647. /**
  12648. * Method that defines the actions when mouse is clicked on canvas.
  12649. * The method inits the currentTransform parameters and renders all the
  12650. * canvas so the current image can be placed on the top canvas and the rest
  12651. * in on the container one.
  12652. * @private
  12653. * @param {Event} e Event object fired on mousedown
  12654. */
  12655. __onMouseDown: function (e) {
  12656. this._cacheTransformEventData(e);
  12657. this._handleEvent(e, 'down:before');
  12658. var target = this._target;
  12659. // if right click just fire events
  12660. if (checkClick(e, RIGHT_CLICK)) {
  12661. if (this.fireRightClick) {
  12662. this._handleEvent(e, 'down', RIGHT_CLICK);
  12663. }
  12664. return;
  12665. }
  12666. if (checkClick(e, MIDDLE_CLICK)) {
  12667. if (this.fireMiddleClick) {
  12668. this._handleEvent(e, 'down', MIDDLE_CLICK);
  12669. }
  12670. return;
  12671. }
  12672. if (this.isDrawingMode) {
  12673. this._onMouseDownInDrawingMode(e);
  12674. return;
  12675. }
  12676. if (!this._isMainEvent(e)) {
  12677. return;
  12678. }
  12679. // ignore if some object is being transformed at this moment
  12680. if (this._currentTransform) {
  12681. return;
  12682. }
  12683. var pointer = this._pointer;
  12684. // save pointer for check in __onMouseUp event
  12685. this._previousPointer = pointer;
  12686. var shouldRender = this._shouldRender(target),
  12687. shouldGroup = this._shouldGroup(e, target);
  12688. if (this._shouldClearSelection(e, target)) {
  12689. this.discardActiveObject(e);
  12690. }
  12691. else if (shouldGroup) {
  12692. this._handleGrouping(e, target);
  12693. target = this._activeObject;
  12694. }
  12695. if (this.selection && (!target ||
  12696. (!target.selectable && !target.isEditing && target !== this._activeObject))) {
  12697. this._groupSelector = {
  12698. ex: this._absolutePointer.x,
  12699. ey: this._absolutePointer.y,
  12700. top: 0,
  12701. left: 0
  12702. };
  12703. }
  12704. if (target) {
  12705. var alreadySelected = target === this._activeObject;
  12706. if (target.selectable && target.activeOn === 'down') {
  12707. this.setActiveObject(target, e);
  12708. }
  12709. var corner = target._findTargetCorner(
  12710. this.getPointer(e, true),
  12711. fabric.util.isTouchEvent(e)
  12712. );
  12713. target.__corner = corner;
  12714. if (target === this._activeObject && (corner || !shouldGroup)) {
  12715. this._setupCurrentTransform(e, target, alreadySelected);
  12716. var control = target.controls[corner],
  12717. pointer = this.getPointer(e),
  12718. mouseDownHandler = control && control.getMouseDownHandler(e, target, control);
  12719. if (mouseDownHandler) {
  12720. mouseDownHandler(e, this._currentTransform, pointer.x, pointer.y);
  12721. }
  12722. }
  12723. }
  12724. this._handleEvent(e, 'down');
  12725. // we must renderAll so that we update the visuals
  12726. (shouldRender || shouldGroup) && this.requestRenderAll();
  12727. },
  12728. /**
  12729. * reset cache form common information needed during event processing
  12730. * @private
  12731. */
  12732. _resetTransformEventData: function() {
  12733. this._target = null;
  12734. this._pointer = null;
  12735. this._absolutePointer = null;
  12736. },
  12737. /**
  12738. * Cache common information needed during event processing
  12739. * @private
  12740. * @param {Event} e Event object fired on event
  12741. */
  12742. _cacheTransformEventData: function(e) {
  12743. // reset in order to avoid stale caching
  12744. this._resetTransformEventData();
  12745. this._pointer = this.getPointer(e, true);
  12746. this._absolutePointer = this.restorePointerVpt(this._pointer);
  12747. this._target = this._currentTransform ? this._currentTransform.target : this.findTarget(e) || null;
  12748. },
  12749. /**
  12750. * @private
  12751. */
  12752. _beforeTransform: function(e) {
  12753. var t = this._currentTransform;
  12754. this.stateful && t.target.saveState();
  12755. this.fire('before:transform', {
  12756. e: e,
  12757. transform: t,
  12758. });
  12759. },
  12760. /**
  12761. * Method that defines the actions when mouse is hovering the canvas.
  12762. * The currentTransform parameter will define whether the user is rotating/scaling/translating
  12763. * an image or neither of them (only hovering). A group selection is also possible and would cancel
  12764. * all any other type of action.
  12765. * In case of an image transformation only the top canvas will be rendered.
  12766. * @private
  12767. * @param {Event} e Event object fired on mousemove
  12768. */
  12769. __onMouseMove: function (e) {
  12770. this._handleEvent(e, 'move:before');
  12771. this._cacheTransformEventData(e);
  12772. var target, pointer;
  12773. if (this.isDrawingMode) {
  12774. this._onMouseMoveInDrawingMode(e);
  12775. return;
  12776. }
  12777. if (!this._isMainEvent(e)) {
  12778. return;
  12779. }
  12780. var groupSelector = this._groupSelector;
  12781. // We initially clicked in an empty area, so we draw a box for multiple selection
  12782. if (groupSelector) {
  12783. pointer = this._absolutePointer;
  12784. groupSelector.left = pointer.x - groupSelector.ex;
  12785. groupSelector.top = pointer.y - groupSelector.ey;
  12786. this.renderTop();
  12787. }
  12788. else if (!this._currentTransform) {
  12789. target = this.findTarget(e) || null;
  12790. this._setCursorFromEvent(e, target);
  12791. this._fireOverOutEvents(target, e);
  12792. }
  12793. else {
  12794. this._transformObject(e);
  12795. }
  12796. this._handleEvent(e, 'move');
  12797. this._resetTransformEventData();
  12798. },
  12799. /**
  12800. * Manage the mouseout, mouseover events for the fabric object on the canvas
  12801. * @param {Fabric.Object} target the target where the target from the mousemove event
  12802. * @param {Event} e Event object fired on mousemove
  12803. * @private
  12804. */
  12805. _fireOverOutEvents: function(target, e) {
  12806. var _hoveredTarget = this._hoveredTarget,
  12807. _hoveredTargets = this._hoveredTargets, targets = this.targets,
  12808. length = Math.max(_hoveredTargets.length, targets.length);
  12809. this.fireSyntheticInOutEvents(target, e, {
  12810. oldTarget: _hoveredTarget,
  12811. evtOut: 'mouseout',
  12812. canvasEvtOut: 'mouse:out',
  12813. evtIn: 'mouseover',
  12814. canvasEvtIn: 'mouse:over',
  12815. });
  12816. for (var i = 0; i < length; i++){
  12817. this.fireSyntheticInOutEvents(targets[i], e, {
  12818. oldTarget: _hoveredTargets[i],
  12819. evtOut: 'mouseout',
  12820. evtIn: 'mouseover',
  12821. });
  12822. }
  12823. this._hoveredTarget = target;
  12824. this._hoveredTargets = this.targets.concat();
  12825. },
  12826. /**
  12827. * Manage the dragEnter, dragLeave events for the fabric objects on the canvas
  12828. * @param {Fabric.Object} target the target where the target from the onDrag event
  12829. * @param {Event} e Event object fired on ondrag
  12830. * @private
  12831. */
  12832. _fireEnterLeaveEvents: function(target, e) {
  12833. var _draggedoverTarget = this._draggedoverTarget,
  12834. _hoveredTargets = this._hoveredTargets, targets = this.targets,
  12835. length = Math.max(_hoveredTargets.length, targets.length);
  12836. this.fireSyntheticInOutEvents(target, e, {
  12837. oldTarget: _draggedoverTarget,
  12838. evtOut: 'dragleave',
  12839. evtIn: 'dragenter',
  12840. });
  12841. for (var i = 0; i < length; i++) {
  12842. this.fireSyntheticInOutEvents(targets[i], e, {
  12843. oldTarget: _hoveredTargets[i],
  12844. evtOut: 'dragleave',
  12845. evtIn: 'dragenter',
  12846. });
  12847. }
  12848. this._draggedoverTarget = target;
  12849. },
  12850. /**
  12851. * Manage the synthetic in/out events for the fabric objects on the canvas
  12852. * @param {Fabric.Object} target the target where the target from the supported events
  12853. * @param {Event} e Event object fired
  12854. * @param {Object} config configuration for the function to work
  12855. * @param {String} config.targetName property on the canvas where the old target is stored
  12856. * @param {String} [config.canvasEvtOut] name of the event to fire at canvas level for out
  12857. * @param {String} config.evtOut name of the event to fire for out
  12858. * @param {String} [config.canvasEvtIn] name of the event to fire at canvas level for in
  12859. * @param {String} config.evtIn name of the event to fire for in
  12860. * @private
  12861. */
  12862. fireSyntheticInOutEvents: function(target, e, config) {
  12863. var inOpt, outOpt, oldTarget = config.oldTarget, outFires, inFires,
  12864. targetChanged = oldTarget !== target, canvasEvtIn = config.canvasEvtIn, canvasEvtOut = config.canvasEvtOut;
  12865. if (targetChanged) {
  12866. inOpt = { e: e, target: target, previousTarget: oldTarget };
  12867. outOpt = { e: e, target: oldTarget, nextTarget: target };
  12868. }
  12869. inFires = target && targetChanged;
  12870. outFires = oldTarget && targetChanged;
  12871. if (outFires) {
  12872. canvasEvtOut && this.fire(canvasEvtOut, outOpt);
  12873. oldTarget.fire(config.evtOut, outOpt);
  12874. }
  12875. if (inFires) {
  12876. canvasEvtIn && this.fire(canvasEvtIn, inOpt);
  12877. target.fire(config.evtIn, inOpt);
  12878. }
  12879. },
  12880. /**
  12881. * Method that defines actions when an Event Mouse Wheel
  12882. * @param {Event} e Event object fired on mouseup
  12883. */
  12884. __onMouseWheel: function(e) {
  12885. this._cacheTransformEventData(e);
  12886. this._handleEvent(e, 'wheel');
  12887. this._resetTransformEventData();
  12888. },
  12889. /**
  12890. * @private
  12891. * @param {Event} e Event fired on mousemove
  12892. */
  12893. _transformObject: function(e) {
  12894. var pointer = this.getPointer(e),
  12895. transform = this._currentTransform;
  12896. transform.reset = false;
  12897. transform.shiftKey = e.shiftKey;
  12898. transform.altKey = e[this.centeredKey];
  12899. this._performTransformAction(e, transform, pointer);
  12900. transform.actionPerformed && this.requestRenderAll();
  12901. },
  12902. /**
  12903. * @private
  12904. */
  12905. _performTransformAction: function(e, transform, pointer) {
  12906. var x = pointer.x,
  12907. y = pointer.y,
  12908. action = transform.action,
  12909. actionPerformed = false,
  12910. actionHandler = transform.actionHandler;
  12911. // this object could be created from the function in the control handlers
  12912. if (actionHandler) {
  12913. actionPerformed = actionHandler(e, transform, x, y);
  12914. }
  12915. if (action === 'drag' && actionPerformed) {
  12916. transform.target.isMoving = true;
  12917. this.setCursor(transform.target.moveCursor || this.moveCursor);
  12918. }
  12919. transform.actionPerformed = transform.actionPerformed || actionPerformed;
  12920. },
  12921. /**
  12922. * @private
  12923. */
  12924. _fire: fabric.controlsUtils.fireEvent,
  12925. /**
  12926. * Sets the cursor depending on where the canvas is being hovered.
  12927. * Note: very buggy in Opera
  12928. * @param {Event} e Event object
  12929. * @param {Object} target Object that the mouse is hovering, if so.
  12930. */
  12931. _setCursorFromEvent: function (e, target) {
  12932. if (!target) {
  12933. this.setCursor(this.defaultCursor);
  12934. return false;
  12935. }
  12936. var hoverCursor = target.hoverCursor || this.hoverCursor,
  12937. activeSelection = this._activeObject && this._activeObject.type === 'activeSelection' ?
  12938. this._activeObject : null,
  12939. // only show proper corner when group selection is not active
  12940. corner = (!activeSelection || !activeSelection.contains(target))
  12941. // here we call findTargetCorner always with undefined for the touch parameter.
  12942. // we assume that if you are using a cursor you do not need to interact with
  12943. // the bigger touch area.
  12944. && target._findTargetCorner(this.getPointer(e, true));
  12945. if (!corner) {
  12946. if (target.subTargetCheck){
  12947. // hoverCursor should come from top-most subTarget,
  12948. // so we walk the array backwards
  12949. this.targets.concat().reverse().map(function(_target){
  12950. hoverCursor = _target.hoverCursor || hoverCursor;
  12951. });
  12952. }
  12953. this.setCursor(hoverCursor);
  12954. }
  12955. else {
  12956. this.setCursor(this.getCornerCursor(corner, target, e));
  12957. }
  12958. },
  12959. /**
  12960. * @private
  12961. */
  12962. getCornerCursor: function(corner, target, e) {
  12963. var control = target.controls[corner];
  12964. return control.cursorStyleHandler(e, control, target);
  12965. }
  12966. });
  12967. })();
  12968. (function() {
  12969. var min = Math.min,
  12970. max = Math.max;
  12971. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  12972. /**
  12973. * @private
  12974. * @param {Event} e Event object
  12975. * @param {fabric.Object} target
  12976. * @return {Boolean}
  12977. */
  12978. _shouldGroup: function(e, target) {
  12979. var activeObject = this._activeObject;
  12980. return activeObject && this._isSelectionKeyPressed(e) && target && target.selectable && this.selection &&
  12981. (activeObject !== target || activeObject.type === 'activeSelection') && !target.onSelect({ e: e });
  12982. },
  12983. /**
  12984. * @private
  12985. * @param {Event} e Event object
  12986. * @param {fabric.Object} target
  12987. */
  12988. _handleGrouping: function (e, target) {
  12989. var activeObject = this._activeObject;
  12990. // avoid multi select when shift click on a corner
  12991. if (activeObject.__corner) {
  12992. return;
  12993. }
  12994. if (target === activeObject) {
  12995. // if it's a group, find target again, using activeGroup objects
  12996. target = this.findTarget(e, true);
  12997. // if even object is not found or we are on activeObjectCorner, bail out
  12998. if (!target || !target.selectable) {
  12999. return;
  13000. }
  13001. }
  13002. if (activeObject && activeObject.type === 'activeSelection') {
  13003. this._updateActiveSelection(target, e);
  13004. }
  13005. else {
  13006. this._createActiveSelection(target, e);
  13007. }
  13008. },
  13009. /**
  13010. * @private
  13011. */
  13012. _updateActiveSelection: function(target, e) {
  13013. var activeSelection = this._activeObject,
  13014. currentActiveObjects = activeSelection._objects.slice(0);
  13015. if (activeSelection.contains(target)) {
  13016. activeSelection.removeWithUpdate(target);
  13017. this._hoveredTarget = target;
  13018. this._hoveredTargets = this.targets.concat();
  13019. if (activeSelection.size() === 1) {
  13020. // activate last remaining object
  13021. this._setActiveObject(activeSelection.item(0), e);
  13022. }
  13023. }
  13024. else {
  13025. activeSelection.addWithUpdate(target);
  13026. this._hoveredTarget = activeSelection;
  13027. this._hoveredTargets = this.targets.concat();
  13028. }
  13029. this._fireSelectionEvents(currentActiveObjects, e);
  13030. },
  13031. /**
  13032. * @private
  13033. */
  13034. _createActiveSelection: function(target, e) {
  13035. var currentActives = this.getActiveObjects(), group = this._createGroup(target);
  13036. this._hoveredTarget = group;
  13037. // ISSUE 4115: should we consider subTargets here?
  13038. // this._hoveredTargets = [];
  13039. // this._hoveredTargets = this.targets.concat();
  13040. this._setActiveObject(group, e);
  13041. this._fireSelectionEvents(currentActives, e);
  13042. },
  13043. /**
  13044. * @private
  13045. * @param {Object} target
  13046. */
  13047. _createGroup: function(target) {
  13048. var objects = this._objects,
  13049. isActiveLower = objects.indexOf(this._activeObject) < objects.indexOf(target),
  13050. groupObjects = isActiveLower
  13051. ? [this._activeObject, target]
  13052. : [target, this._activeObject];
  13053. this._activeObject.isEditing && this._activeObject.exitEditing();
  13054. return new fabric.ActiveSelection(groupObjects, {
  13055. canvas: this
  13056. });
  13057. },
  13058. /**
  13059. * @private
  13060. * @param {Event} e mouse event
  13061. */
  13062. _groupSelectedObjects: function (e) {
  13063. var group = this._collectObjects(e),
  13064. aGroup;
  13065. // do not create group for 1 element only
  13066. if (group.length === 1) {
  13067. this.setActiveObject(group[0], e);
  13068. }
  13069. else if (group.length > 1) {
  13070. aGroup = new fabric.ActiveSelection(group.reverse(), {
  13071. canvas: this
  13072. });
  13073. this.setActiveObject(aGroup, e);
  13074. }
  13075. },
  13076. /**
  13077. * @private
  13078. */
  13079. _collectObjects: function(e) {
  13080. var group = [],
  13081. currentObject,
  13082. x1 = this._groupSelector.ex,
  13083. y1 = this._groupSelector.ey,
  13084. x2 = x1 + this._groupSelector.left,
  13085. y2 = y1 + this._groupSelector.top,
  13086. selectionX1Y1 = new fabric.Point(min(x1, x2), min(y1, y2)),
  13087. selectionX2Y2 = new fabric.Point(max(x1, x2), max(y1, y2)),
  13088. allowIntersect = !this.selectionFullyContained,
  13089. isClick = x1 === x2 && y1 === y2;
  13090. // we iterate reverse order to collect top first in case of click.
  13091. for (var i = this._objects.length; i--; ) {
  13092. currentObject = this._objects[i];
  13093. if (!currentObject || !currentObject.selectable || !currentObject.visible) {
  13094. continue;
  13095. }
  13096. if ((allowIntersect && currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2, true)) ||
  13097. currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2, true) ||
  13098. (allowIntersect && currentObject.containsPoint(selectionX1Y1, null, true)) ||
  13099. (allowIntersect && currentObject.containsPoint(selectionX2Y2, null, true))
  13100. ) {
  13101. group.push(currentObject);
  13102. // only add one object if it's a click
  13103. if (isClick) {
  13104. break;
  13105. }
  13106. }
  13107. }
  13108. if (group.length > 1) {
  13109. group = group.filter(function(object) {
  13110. return !object.onSelect({ e: e });
  13111. });
  13112. }
  13113. return group;
  13114. },
  13115. /**
  13116. * @private
  13117. */
  13118. _maybeGroupObjects: function(e) {
  13119. if (this.selection && this._groupSelector) {
  13120. this._groupSelectedObjects(e);
  13121. }
  13122. this.setCursor(this.defaultCursor);
  13123. // clear selection and current transformation
  13124. this._groupSelector = null;
  13125. }
  13126. });
  13127. })();
  13128. (function () {
  13129. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  13130. /**
  13131. * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
  13132. * @param {Object} [options] Options object
  13133. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  13134. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  13135. * @param {Number} [options.multiplier=1] Multiplier to scale by, to have consistent
  13136. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  13137. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  13138. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  13139. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  13140. * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 2.0.0
  13141. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  13142. * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}
  13143. * @example <caption>Generate jpeg dataURL with lower quality</caption>
  13144. * var dataURL = canvas.toDataURL({
  13145. * format: 'jpeg',
  13146. * quality: 0.8
  13147. * });
  13148. * @example <caption>Generate cropped png dataURL (clipping of canvas)</caption>
  13149. * var dataURL = canvas.toDataURL({
  13150. * format: 'png',
  13151. * left: 100,
  13152. * top: 100,
  13153. * width: 200,
  13154. * height: 200
  13155. * });
  13156. * @example <caption>Generate double scaled png dataURL</caption>
  13157. * var dataURL = canvas.toDataURL({
  13158. * format: 'png',
  13159. * multiplier: 2
  13160. * });
  13161. */
  13162. toDataURL: function (options) {
  13163. options || (options = { });
  13164. var format = options.format || 'png',
  13165. quality = options.quality || 1,
  13166. multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? this.getRetinaScaling() : 1),
  13167. canvasEl = this.toCanvasElement(multiplier, options);
  13168. return fabric.util.toDataURL(canvasEl, format, quality);
  13169. },
  13170. /**
  13171. * Create a new HTMLCanvas element painted with the current canvas content.
  13172. * No need to resize the actual one or repaint it.
  13173. * Will transfer object ownership to a new canvas, paint it, and set everything back.
  13174. * This is an intermediary step used to get to a dataUrl but also it is useful to
  13175. * create quick image copies of a canvas without passing for the dataUrl string
  13176. * @param {Number} [multiplier] a zoom factor.
  13177. * @param {Object} [cropping] Cropping informations
  13178. * @param {Number} [cropping.left] Cropping left offset.
  13179. * @param {Number} [cropping.top] Cropping top offset.
  13180. * @param {Number} [cropping.width] Cropping width.
  13181. * @param {Number} [cropping.height] Cropping height.
  13182. */
  13183. toCanvasElement: function(multiplier, cropping) {
  13184. multiplier = multiplier || 1;
  13185. cropping = cropping || { };
  13186. var scaledWidth = (cropping.width || this.width) * multiplier,
  13187. scaledHeight = (cropping.height || this.height) * multiplier,
  13188. zoom = this.getZoom(),
  13189. originalWidth = this.width,
  13190. originalHeight = this.height,
  13191. newZoom = zoom * multiplier,
  13192. vp = this.viewportTransform,
  13193. translateX = (vp[4] - (cropping.left || 0)) * multiplier,
  13194. translateY = (vp[5] - (cropping.top || 0)) * multiplier,
  13195. originalInteractive = this.interactive,
  13196. newVp = [newZoom, 0, 0, newZoom, translateX, translateY],
  13197. originalRetina = this.enableRetinaScaling,
  13198. canvasEl = fabric.util.createCanvasElement(),
  13199. originalContextTop = this.contextTop;
  13200. canvasEl.width = scaledWidth;
  13201. canvasEl.height = scaledHeight;
  13202. this.contextTop = null;
  13203. this.enableRetinaScaling = false;
  13204. this.interactive = false;
  13205. this.viewportTransform = newVp;
  13206. this.width = scaledWidth;
  13207. this.height = scaledHeight;
  13208. this.calcViewportBoundaries();
  13209. this.renderCanvas(canvasEl.getContext('2d'), this._objects);
  13210. this.viewportTransform = vp;
  13211. this.width = originalWidth;
  13212. this.height = originalHeight;
  13213. this.calcViewportBoundaries();
  13214. this.interactive = originalInteractive;
  13215. this.enableRetinaScaling = originalRetina;
  13216. this.contextTop = originalContextTop;
  13217. return canvasEl;
  13218. },
  13219. });
  13220. })();
  13221. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  13222. /**
  13223. * Populates canvas with data from the specified JSON.
  13224. * JSON format must conform to the one of {@link fabric.Canvas#toJSON}
  13225. * @param {String|Object} json JSON string or object
  13226. * @param {Function} callback Callback, invoked when json is parsed
  13227. * and corresponding objects (e.g: {@link fabric.Image})
  13228. * are initialized
  13229. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  13230. * @return {fabric.Canvas} instance
  13231. * @chainable
  13232. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#deserialization}
  13233. * @see {@link http://jsfiddle.net/fabricjs/fmgXt/|jsFiddle demo}
  13234. * @example <caption>loadFromJSON</caption>
  13235. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));
  13236. * @example <caption>loadFromJSON with reviver</caption>
  13237. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
  13238. * // `o` = json object
  13239. * // `object` = fabric.Object instance
  13240. * // ... do some stuff ...
  13241. * });
  13242. */
  13243. loadFromJSON: function (json, callback, reviver) {
  13244. if (!json) {
  13245. return;
  13246. }
  13247. // serialize if it wasn't already
  13248. var serialized = (typeof json === 'string')
  13249. ? JSON.parse(json)
  13250. : fabric.util.object.clone(json);
  13251. var _this = this,
  13252. clipPath = serialized.clipPath,
  13253. renderOnAddRemove = this.renderOnAddRemove;
  13254. this.renderOnAddRemove = false;
  13255. delete serialized.clipPath;
  13256. this._enlivenObjects(serialized.objects, function (enlivenedObjects) {
  13257. _this.clear();
  13258. _this._setBgOverlay(serialized, function () {
  13259. if (clipPath) {
  13260. _this._enlivenObjects([clipPath], function (enlivenedCanvasClip) {
  13261. _this.clipPath = enlivenedCanvasClip[0];
  13262. _this.__setupCanvas.call(_this, serialized, enlivenedObjects, renderOnAddRemove, callback);
  13263. });
  13264. }
  13265. else {
  13266. _this.__setupCanvas.call(_this, serialized, enlivenedObjects, renderOnAddRemove, callback);
  13267. }
  13268. });
  13269. }, reviver);
  13270. return this;
  13271. },
  13272. /**
  13273. * @private
  13274. * @param {Object} serialized Object with background and overlay information
  13275. * @param {Array} restored canvas objects
  13276. * @param {Function} cached renderOnAddRemove callback
  13277. * @param {Function} callback Invoked after all background and overlay images/patterns loaded
  13278. */
  13279. __setupCanvas: function(serialized, enlivenedObjects, renderOnAddRemove, callback) {
  13280. var _this = this;
  13281. enlivenedObjects.forEach(function(obj, index) {
  13282. // we splice the array just in case some custom classes restored from JSON
  13283. // will add more object to canvas at canvas init.
  13284. _this.insertAt(obj, index);
  13285. });
  13286. this.renderOnAddRemove = renderOnAddRemove;
  13287. // remove parts i cannot set as options
  13288. delete serialized.objects;
  13289. delete serialized.backgroundImage;
  13290. delete serialized.overlayImage;
  13291. delete serialized.background;
  13292. delete serialized.overlay;
  13293. // this._initOptions does too many things to just
  13294. // call it. Normally loading an Object from JSON
  13295. // create the Object instance. Here the Canvas is
  13296. // already an instance and we are just loading things over it
  13297. this._setOptions(serialized);
  13298. this.renderAll();
  13299. callback && callback();
  13300. },
  13301. /**
  13302. * @private
  13303. * @param {Object} serialized Object with background and overlay information
  13304. * @param {Function} callback Invoked after all background and overlay images/patterns loaded
  13305. */
  13306. _setBgOverlay: function(serialized, callback) {
  13307. var loaded = {
  13308. backgroundColor: false,
  13309. overlayColor: false,
  13310. backgroundImage: false,
  13311. overlayImage: false
  13312. };
  13313. if (!serialized.backgroundImage && !serialized.overlayImage && !serialized.background && !serialized.overlay) {
  13314. callback && callback();
  13315. return;
  13316. }
  13317. var cbIfLoaded = function () {
  13318. if (loaded.backgroundImage && loaded.overlayImage && loaded.backgroundColor && loaded.overlayColor) {
  13319. callback && callback();
  13320. }
  13321. };
  13322. this.__setBgOverlay('backgroundImage', serialized.backgroundImage, loaded, cbIfLoaded);
  13323. this.__setBgOverlay('overlayImage', serialized.overlayImage, loaded, cbIfLoaded);
  13324. this.__setBgOverlay('backgroundColor', serialized.background, loaded, cbIfLoaded);
  13325. this.__setBgOverlay('overlayColor', serialized.overlay, loaded, cbIfLoaded);
  13326. },
  13327. /**
  13328. * @private
  13329. * @param {String} property Property to set (backgroundImage, overlayImage, backgroundColor, overlayColor)
  13330. * @param {(Object|String)} value Value to set
  13331. * @param {Object} loaded Set loaded property to true if property is set
  13332. * @param {Object} callback Callback function to invoke after property is set
  13333. */
  13334. __setBgOverlay: function(property, value, loaded, callback) {
  13335. var _this = this;
  13336. if (!value) {
  13337. loaded[property] = true;
  13338. callback && callback();
  13339. return;
  13340. }
  13341. if (property === 'backgroundImage' || property === 'overlayImage') {
  13342. fabric.util.enlivenObjects([value], function(enlivedObject){
  13343. _this[property] = enlivedObject[0];
  13344. loaded[property] = true;
  13345. callback && callback();
  13346. });
  13347. }
  13348. else {
  13349. this['set' + fabric.util.string.capitalize(property, true)](value, function() {
  13350. loaded[property] = true;
  13351. callback && callback();
  13352. });
  13353. }
  13354. },
  13355. /**
  13356. * @private
  13357. * @param {Array} objects
  13358. * @param {Function} callback
  13359. * @param {Function} [reviver]
  13360. */
  13361. _enlivenObjects: function (objects, callback, reviver) {
  13362. if (!objects || objects.length === 0) {
  13363. callback && callback([]);
  13364. return;
  13365. }
  13366. fabric.util.enlivenObjects(objects, function(enlivenedObjects) {
  13367. callback && callback(enlivenedObjects);
  13368. }, null, reviver);
  13369. },
  13370. /**
  13371. * @private
  13372. * @param {String} format
  13373. * @param {Function} callback
  13374. */
  13375. _toDataURL: function (format, callback) {
  13376. this.clone(function (clone) {
  13377. callback(clone.toDataURL(format));
  13378. });
  13379. },
  13380. /**
  13381. * @private
  13382. * @param {String} format
  13383. * @param {Number} multiplier
  13384. * @param {Function} callback
  13385. */
  13386. _toDataURLWithMultiplier: function (format, multiplier, callback) {
  13387. this.clone(function (clone) {
  13388. callback(clone.toDataURLWithMultiplier(format, multiplier));
  13389. });
  13390. },
  13391. /**
  13392. * Clones canvas instance
  13393. * @param {Object} [callback] Receives cloned instance as a first argument
  13394. * @param {Array} [properties] Array of properties to include in the cloned canvas and children
  13395. */
  13396. clone: function (callback, properties) {
  13397. var data = JSON.stringify(this.toJSON(properties));
  13398. this.cloneWithoutData(function(clone) {
  13399. clone.loadFromJSON(data, function() {
  13400. callback && callback(clone);
  13401. });
  13402. });
  13403. },
  13404. /**
  13405. * Clones canvas instance without cloning existing data.
  13406. * This essentially copies canvas dimensions, clipping properties, etc.
  13407. * but leaves data empty (so that you can populate it with your own)
  13408. * @param {Object} [callback] Receives cloned instance as a first argument
  13409. */
  13410. cloneWithoutData: function(callback) {
  13411. var el = fabric.util.createCanvasElement();
  13412. el.width = this.width;
  13413. el.height = this.height;
  13414. var clone = new fabric.Canvas(el);
  13415. if (this.backgroundImage) {
  13416. clone.setBackgroundImage(this.backgroundImage.src, function() {
  13417. clone.renderAll();
  13418. callback && callback(clone);
  13419. });
  13420. clone.backgroundImageOpacity = this.backgroundImageOpacity;
  13421. clone.backgroundImageStretch = this.backgroundImageStretch;
  13422. }
  13423. else {
  13424. callback && callback(clone);
  13425. }
  13426. }
  13427. });
  13428. (function(global) {
  13429. 'use strict';
  13430. var fabric = global.fabric || (global.fabric = { }),
  13431. extend = fabric.util.object.extend,
  13432. clone = fabric.util.object.clone,
  13433. toFixed = fabric.util.toFixed,
  13434. capitalize = fabric.util.string.capitalize,
  13435. degreesToRadians = fabric.util.degreesToRadians,
  13436. objectCaching = !fabric.isLikelyNode,
  13437. ALIASING_LIMIT = 2;
  13438. if (fabric.Object) {
  13439. return;
  13440. }
  13441. /**
  13442. * Root object class from which all 2d shape classes inherit from
  13443. * @class fabric.Object
  13444. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#objects}
  13445. * @see {@link fabric.Object#initialize} for constructor definition
  13446. *
  13447. * @fires added
  13448. * @fires removed
  13449. *
  13450. * @fires selected
  13451. * @fires deselected
  13452. * @fires modified
  13453. * @fires modified
  13454. * @fires moved
  13455. * @fires scaled
  13456. * @fires rotated
  13457. * @fires skewed
  13458. *
  13459. * @fires rotating
  13460. * @fires scaling
  13461. * @fires moving
  13462. * @fires skewing
  13463. *
  13464. * @fires mousedown
  13465. * @fires mouseup
  13466. * @fires mouseover
  13467. * @fires mouseout
  13468. * @fires mousewheel
  13469. * @fires mousedblclick
  13470. *
  13471. * @fires dragover
  13472. * @fires dragenter
  13473. * @fires dragleave
  13474. * @fires drop
  13475. */
  13476. fabric.Object = fabric.util.createClass(fabric.CommonMethods, /** @lends fabric.Object.prototype */ {
  13477. /**
  13478. * Type of an object (rect, circle, path, etc.).
  13479. * Note that this property is meant to be read-only and not meant to be modified.
  13480. * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly.
  13481. * @type String
  13482. * @default
  13483. */
  13484. type: 'object',
  13485. /**
  13486. * Horizontal origin of transformation of an object (one of "left", "right", "center")
  13487. * See http://jsfiddle.net/1ow02gea/244/ on how originX/originY affect objects in groups
  13488. * @type String
  13489. * @default
  13490. */
  13491. originX: 'left',
  13492. /**
  13493. * Vertical origin of transformation of an object (one of "top", "bottom", "center")
  13494. * See http://jsfiddle.net/1ow02gea/244/ on how originX/originY affect objects in groups
  13495. * @type String
  13496. * @default
  13497. */
  13498. originY: 'top',
  13499. /**
  13500. * 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}
  13501. * @type Number
  13502. * @default
  13503. */
  13504. top: 0,
  13505. /**
  13506. * 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}
  13507. * @type Number
  13508. * @default
  13509. */
  13510. left: 0,
  13511. /**
  13512. * Object width
  13513. * @type Number
  13514. * @default
  13515. */
  13516. width: 0,
  13517. /**
  13518. * Object height
  13519. * @type Number
  13520. * @default
  13521. */
  13522. height: 0,
  13523. /**
  13524. * Object scale factor (horizontal)
  13525. * @type Number
  13526. * @default
  13527. */
  13528. scaleX: 1,
  13529. /**
  13530. * Object scale factor (vertical)
  13531. * @type Number
  13532. * @default
  13533. */
  13534. scaleY: 1,
  13535. /**
  13536. * When true, an object is rendered as flipped horizontally
  13537. * @type Boolean
  13538. * @default
  13539. */
  13540. flipX: false,
  13541. /**
  13542. * When true, an object is rendered as flipped vertically
  13543. * @type Boolean
  13544. * @default
  13545. */
  13546. flipY: false,
  13547. /**
  13548. * Opacity of an object
  13549. * @type Number
  13550. * @default
  13551. */
  13552. opacity: 1,
  13553. /**
  13554. * Angle of rotation of an object (in degrees)
  13555. * @type Number
  13556. * @default
  13557. */
  13558. angle: 0,
  13559. /**
  13560. * Angle of skew on x axes of an object (in degrees)
  13561. * @type Number
  13562. * @default
  13563. */
  13564. skewX: 0,
  13565. /**
  13566. * Angle of skew on y axes of an object (in degrees)
  13567. * @type Number
  13568. * @default
  13569. */
  13570. skewY: 0,
  13571. /**
  13572. * Size of object's controlling corners (in pixels)
  13573. * @type Number
  13574. * @default
  13575. */
  13576. cornerSize: 13,
  13577. /**
  13578. * Size of object's controlling corners when touch interaction is detected
  13579. * @type Number
  13580. * @default
  13581. */
  13582. touchCornerSize: 24,
  13583. /**
  13584. * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill)
  13585. * @type Boolean
  13586. * @default
  13587. */
  13588. transparentCorners: true,
  13589. /**
  13590. * Default cursor value used when hovering over this object on canvas
  13591. * @type String
  13592. * @default
  13593. */
  13594. hoverCursor: null,
  13595. /**
  13596. * Default cursor value used when moving this object on canvas
  13597. * @type String
  13598. * @default
  13599. */
  13600. moveCursor: null,
  13601. /**
  13602. * Padding between object and its controlling borders (in pixels)
  13603. * @type Number
  13604. * @default
  13605. */
  13606. padding: 0,
  13607. /**
  13608. * Color of controlling borders of an object (when it's active)
  13609. * @type String
  13610. * @default
  13611. */
  13612. borderColor: 'rgb(178,204,255)',
  13613. /**
  13614. * Array specifying dash pattern of an object's borders (hasBorder must be true)
  13615. * @since 1.6.2
  13616. * @type Array
  13617. */
  13618. borderDashArray: null,
  13619. /**
  13620. * Color of controlling corners of an object (when it's active)
  13621. * @type String
  13622. * @default
  13623. */
  13624. cornerColor: 'rgb(178,204,255)',
  13625. /**
  13626. * Color of controlling corners of an object (when it's active and transparentCorners false)
  13627. * @since 1.6.2
  13628. * @type String
  13629. * @default
  13630. */
  13631. cornerStrokeColor: null,
  13632. /**
  13633. * Specify style of control, 'rect' or 'circle'
  13634. * @since 1.6.2
  13635. * @type String
  13636. */
  13637. cornerStyle: 'rect',
  13638. /**
  13639. * Array specifying dash pattern of an object's control (hasBorder must be true)
  13640. * @since 1.6.2
  13641. * @type Array
  13642. */
  13643. cornerDashArray: null,
  13644. /**
  13645. * When true, this object will use center point as the origin of transformation
  13646. * when being scaled via the controls.
  13647. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  13648. * @since 1.3.4
  13649. * @type Boolean
  13650. * @default
  13651. */
  13652. centeredScaling: false,
  13653. /**
  13654. * When true, this object will use center point as the origin of transformation
  13655. * when being rotated via the controls.
  13656. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  13657. * @since 1.3.4
  13658. * @type Boolean
  13659. * @default
  13660. */
  13661. centeredRotation: true,
  13662. /**
  13663. * Color of object's fill
  13664. * takes css colors https://www.w3.org/TR/css-color-3/
  13665. * @type String
  13666. * @default
  13667. */
  13668. fill: 'rgb(0,0,0)',
  13669. /**
  13670. * Fill rule used to fill an object
  13671. * accepted values are nonzero, evenodd
  13672. * <b>Backwards incompatibility note:</b> This property was used for setting globalCompositeOperation until v1.4.12 (use `fabric.Object#globalCompositeOperation` instead)
  13673. * @type String
  13674. * @default
  13675. */
  13676. fillRule: 'nonzero',
  13677. /**
  13678. * Composite rule used for canvas globalCompositeOperation
  13679. * @type String
  13680. * @default
  13681. */
  13682. globalCompositeOperation: 'source-over',
  13683. /**
  13684. * Background color of an object.
  13685. * takes css colors https://www.w3.org/TR/css-color-3/
  13686. * @type String
  13687. * @default
  13688. */
  13689. backgroundColor: '',
  13690. /**
  13691. * Selection Background color of an object. colored layer behind the object when it is active.
  13692. * does not mix good with globalCompositeOperation methods.
  13693. * @type String
  13694. * @default
  13695. */
  13696. selectionBackgroundColor: '',
  13697. /**
  13698. * When defined, an object is rendered via stroke and this property specifies its color
  13699. * takes css colors https://www.w3.org/TR/css-color-3/
  13700. * @type String
  13701. * @default
  13702. */
  13703. stroke: null,
  13704. /**
  13705. * Width of a stroke used to render this object
  13706. * @type Number
  13707. * @default
  13708. */
  13709. strokeWidth: 1,
  13710. /**
  13711. * Array specifying dash pattern of an object's stroke (stroke must be defined)
  13712. * @type Array
  13713. */
  13714. strokeDashArray: null,
  13715. /**
  13716. * Line offset of an object's stroke
  13717. * @type Number
  13718. * @default
  13719. */
  13720. strokeDashOffset: 0,
  13721. /**
  13722. * Line endings style of an object's stroke (one of "butt", "round", "square")
  13723. * @type String
  13724. * @default
  13725. */
  13726. strokeLineCap: 'butt',
  13727. /**
  13728. * Corner style of an object's stroke (one of "bevel", "round", "miter")
  13729. * @type String
  13730. * @default
  13731. */
  13732. strokeLineJoin: 'miter',
  13733. /**
  13734. * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke
  13735. * @type Number
  13736. * @default
  13737. */
  13738. strokeMiterLimit: 4,
  13739. /**
  13740. * Shadow object representing shadow of this shape
  13741. * @type fabric.Shadow
  13742. * @default
  13743. */
  13744. shadow: null,
  13745. /**
  13746. * Opacity of object's controlling borders when object is active and moving
  13747. * @type Number
  13748. * @default
  13749. */
  13750. borderOpacityWhenMoving: 0.4,
  13751. /**
  13752. * Scale factor of object's controlling borders
  13753. * bigger number will make a thicker border
  13754. * border is 1, so this is basically a border thickness
  13755. * since there is no way to change the border itself.
  13756. * @type Number
  13757. * @default
  13758. */
  13759. borderScaleFactor: 1,
  13760. /**
  13761. * Minimum allowed scale value of an object
  13762. * @type Number
  13763. * @default
  13764. */
  13765. minScaleLimit: 0,
  13766. /**
  13767. * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection).
  13768. * But events still fire on it.
  13769. * @type Boolean
  13770. * @default
  13771. */
  13772. selectable: true,
  13773. /**
  13774. * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4
  13775. * @type Boolean
  13776. * @default
  13777. */
  13778. evented: true,
  13779. /**
  13780. * When set to `false`, an object is not rendered on canvas
  13781. * @type Boolean
  13782. * @default
  13783. */
  13784. visible: true,
  13785. /**
  13786. * When set to `false`, object's controls are not displayed and can not be used to manipulate object
  13787. * @type Boolean
  13788. * @default
  13789. */
  13790. hasControls: true,
  13791. /**
  13792. * When set to `false`, object's controlling borders are not rendered
  13793. * @type Boolean
  13794. * @default
  13795. */
  13796. hasBorders: true,
  13797. /**
  13798. * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box
  13799. * @type Boolean
  13800. * @default
  13801. */
  13802. perPixelTargetFind: false,
  13803. /**
  13804. * When `false`, default object's values are not included in its serialization
  13805. * @type Boolean
  13806. * @default
  13807. */
  13808. includeDefaultValues: true,
  13809. /**
  13810. * When `true`, object horizontal movement is locked
  13811. * @type Boolean
  13812. * @default
  13813. */
  13814. lockMovementX: false,
  13815. /**
  13816. * When `true`, object vertical movement is locked
  13817. * @type Boolean
  13818. * @default
  13819. */
  13820. lockMovementY: false,
  13821. /**
  13822. * When `true`, object rotation is locked
  13823. * @type Boolean
  13824. * @default
  13825. */
  13826. lockRotation: false,
  13827. /**
  13828. * When `true`, object horizontal scaling is locked
  13829. * @type Boolean
  13830. * @default
  13831. */
  13832. lockScalingX: false,
  13833. /**
  13834. * When `true`, object vertical scaling is locked
  13835. * @type Boolean
  13836. * @default
  13837. */
  13838. lockScalingY: false,
  13839. /**
  13840. * When `true`, object horizontal skewing is locked
  13841. * @type Boolean
  13842. * @default
  13843. */
  13844. lockSkewingX: false,
  13845. /**
  13846. * When `true`, object vertical skewing is locked
  13847. * @type Boolean
  13848. * @default
  13849. */
  13850. lockSkewingY: false,
  13851. /**
  13852. * When `true`, object cannot be flipped by scaling into negative values
  13853. * @type Boolean
  13854. * @default
  13855. */
  13856. lockScalingFlip: false,
  13857. /**
  13858. * When `true`, object is not exported in OBJECT/JSON
  13859. * @since 1.6.3
  13860. * @type Boolean
  13861. * @default
  13862. */
  13863. excludeFromExport: false,
  13864. /**
  13865. * When `true`, object is cached on an additional canvas.
  13866. * When `false`, object is not cached unless necessary ( clipPath )
  13867. * default to true
  13868. * @since 1.7.0
  13869. * @type Boolean
  13870. * @default true
  13871. */
  13872. objectCaching: objectCaching,
  13873. /**
  13874. * When `true`, object properties are checked for cache invalidation. In some particular
  13875. * situation you may want this to be disabled ( spray brush, very big, groups)
  13876. * or if your application does not allow you to modify properties for groups child you want
  13877. * to disable it for groups.
  13878. * default to false
  13879. * since 1.7.0
  13880. * @type Boolean
  13881. * @default false
  13882. */
  13883. statefullCache: false,
  13884. /**
  13885. * When `true`, cache does not get updated during scaling. The picture will get blocky if scaled
  13886. * too much and will be redrawn with correct details at the end of scaling.
  13887. * this setting is performance and application dependant.
  13888. * default to true
  13889. * since 1.7.0
  13890. * @type Boolean
  13891. * @default true
  13892. */
  13893. noScaleCache: true,
  13894. /**
  13895. * When `false`, the stoke width will scale with the object.
  13896. * When `true`, the stroke will always match the exact pixel size entered for stroke width.
  13897. * this Property does not work on Text classes or drawing call that uses strokeText,fillText methods
  13898. * default to false
  13899. * @since 2.6.0
  13900. * @type Boolean
  13901. * @default false
  13902. * @type Boolean
  13903. * @default false
  13904. */
  13905. strokeUniform: false,
  13906. /**
  13907. * When set to `true`, object's cache will be rerendered next render call.
  13908. * since 1.7.0
  13909. * @type Boolean
  13910. * @default true
  13911. */
  13912. dirty: true,
  13913. /**
  13914. * keeps the value of the last hovered corner during mouse move.
  13915. * 0 is no corner, or 'mt', 'ml', 'mtr' etc..
  13916. * It should be private, but there is no harm in using it as
  13917. * a read-only property.
  13918. * @type number|string|any
  13919. * @default 0
  13920. */
  13921. __corner: 0,
  13922. /**
  13923. * Determines if the fill or the stroke is drawn first (one of "fill" or "stroke")
  13924. * @type String
  13925. * @default
  13926. */
  13927. paintFirst: 'fill',
  13928. /**
  13929. * When 'down', object is set to active on mousedown/touchstart
  13930. * When 'up', object is set to active on mouseup/touchend
  13931. * Experimental. Let's see if this breaks anything before supporting officially
  13932. * @private
  13933. * since 4.4.0
  13934. * @type String
  13935. * @default 'down'
  13936. */
  13937. activeOn: 'down',
  13938. /**
  13939. * List of properties to consider when checking if state
  13940. * of an object is changed (fabric.Object#hasStateChanged)
  13941. * as well as for history (undo/redo) purposes
  13942. * @type Array
  13943. */
  13944. stateProperties: (
  13945. 'top left width height scaleX scaleY flipX flipY originX originY transformMatrix ' +
  13946. 'stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit ' +
  13947. 'angle opacity fill globalCompositeOperation shadow visible backgroundColor ' +
  13948. 'skewX skewY fillRule paintFirst clipPath strokeUniform'
  13949. ).split(' '),
  13950. /**
  13951. * List of properties to consider when checking if cache needs refresh
  13952. * Those properties are checked by statefullCache ON ( or lazy mode if we want ) or from single
  13953. * calls to Object.set(key, value). If the key is in this list, the object is marked as dirty
  13954. * and refreshed at the next render
  13955. * @type Array
  13956. */
  13957. cacheProperties: (
  13958. 'fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform' +
  13959. ' strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath'
  13960. ).split(' '),
  13961. /**
  13962. * List of properties to consider for animating colors.
  13963. * @type Array
  13964. */
  13965. colorProperties: (
  13966. 'fill stroke backgroundColor'
  13967. ).split(' '),
  13968. /**
  13969. * a fabricObject that, without stroke define a clipping area with their shape. filled in black
  13970. * the clipPath object gets used when the object has rendered, and the context is placed in the center
  13971. * of the object cacheCanvas.
  13972. * If you want 0,0 of a clipPath to align with an object center, use clipPath.originX/Y to 'center'
  13973. * @type fabric.Object
  13974. */
  13975. clipPath: undefined,
  13976. /**
  13977. * Meaningful ONLY when the object is used as clipPath.
  13978. * if true, the clipPath will make the object clip to the outside of the clipPath
  13979. * since 2.4.0
  13980. * @type boolean
  13981. * @default false
  13982. */
  13983. inverted: false,
  13984. /**
  13985. * Meaningful ONLY when the object is used as clipPath.
  13986. * if true, the clipPath will have its top and left relative to canvas, and will
  13987. * not be influenced by the object transform. This will make the clipPath relative
  13988. * to the canvas, but clipping just a particular object.
  13989. * WARNING this is beta, this feature may change or be renamed.
  13990. * since 2.4.0
  13991. * @type boolean
  13992. * @default false
  13993. */
  13994. absolutePositioned: false,
  13995. /**
  13996. * Constructor
  13997. * @param {Object} [options] Options object
  13998. */
  13999. initialize: function(options) {
  14000. if (options) {
  14001. this.setOptions(options);
  14002. }
  14003. },
  14004. /**
  14005. * Create a the canvas used to keep the cached copy of the object
  14006. * @private
  14007. */
  14008. _createCacheCanvas: function() {
  14009. this._cacheProperties = {};
  14010. this._cacheCanvas = fabric.util.createCanvasElement();
  14011. this._cacheContext = this._cacheCanvas.getContext('2d');
  14012. this._updateCacheCanvas();
  14013. // if canvas gets created, is empty, so dirty.
  14014. this.dirty = true;
  14015. },
  14016. /**
  14017. * Limit the cache dimensions so that X * Y do not cross fabric.perfLimitSizeTotal
  14018. * and each side do not cross fabric.cacheSideLimit
  14019. * those numbers are configurable so that you can get as much detail as you want
  14020. * making bargain with performances.
  14021. * @param {Object} dims
  14022. * @param {Object} dims.width width of canvas
  14023. * @param {Object} dims.height height of canvas
  14024. * @param {Object} dims.zoomX zoomX zoom value to unscale the canvas before drawing cache
  14025. * @param {Object} dims.zoomY zoomY zoom value to unscale the canvas before drawing cache
  14026. * @return {Object}.width width of canvas
  14027. * @return {Object}.height height of canvas
  14028. * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache
  14029. * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
  14030. */
  14031. _limitCacheSize: function(dims) {
  14032. var perfLimitSizeTotal = fabric.perfLimitSizeTotal,
  14033. width = dims.width, height = dims.height,
  14034. max = fabric.maxCacheSideLimit, min = fabric.minCacheSideLimit;
  14035. if (width <= max && height <= max && width * height <= perfLimitSizeTotal) {
  14036. if (width < min) {
  14037. dims.width = min;
  14038. }
  14039. if (height < min) {
  14040. dims.height = min;
  14041. }
  14042. return dims;
  14043. }
  14044. var ar = width / height, limitedDims = fabric.util.limitDimsByArea(ar, perfLimitSizeTotal),
  14045. capValue = fabric.util.capValue,
  14046. x = capValue(min, limitedDims.x, max),
  14047. y = capValue(min, limitedDims.y, max);
  14048. if (width > x) {
  14049. dims.zoomX /= width / x;
  14050. dims.width = x;
  14051. dims.capped = true;
  14052. }
  14053. if (height > y) {
  14054. dims.zoomY /= height / y;
  14055. dims.height = y;
  14056. dims.capped = true;
  14057. }
  14058. return dims;
  14059. },
  14060. /**
  14061. * Return the dimension and the zoom level needed to create a cache canvas
  14062. * big enough to host the object to be cached.
  14063. * @private
  14064. * @return {Object}.x width of object to be cached
  14065. * @return {Object}.y height of object to be cached
  14066. * @return {Object}.width width of canvas
  14067. * @return {Object}.height height of canvas
  14068. * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache
  14069. * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
  14070. */
  14071. _getCacheCanvasDimensions: function() {
  14072. var objectScale = this.getTotalObjectScaling(),
  14073. // caculate dimensions without skewing
  14074. dim = this._getTransformedDimensions(0, 0),
  14075. neededX = dim.x * objectScale.scaleX / this.scaleX,
  14076. neededY = dim.y * objectScale.scaleY / this.scaleY;
  14077. return {
  14078. // for sure this ALIASING_LIMIT is slightly creating problem
  14079. // in situation in which the cache canvas gets an upper limit
  14080. // also objectScale contains already scaleX and scaleY
  14081. width: neededX + ALIASING_LIMIT,
  14082. height: neededY + ALIASING_LIMIT,
  14083. zoomX: objectScale.scaleX,
  14084. zoomY: objectScale.scaleY,
  14085. x: neededX,
  14086. y: neededY
  14087. };
  14088. },
  14089. /**
  14090. * Update width and height of the canvas for cache
  14091. * returns true or false if canvas needed resize.
  14092. * @private
  14093. * @return {Boolean} true if the canvas has been resized
  14094. */
  14095. _updateCacheCanvas: function() {
  14096. var targetCanvas = this.canvas;
  14097. if (this.noScaleCache && targetCanvas && targetCanvas._currentTransform) {
  14098. var target = targetCanvas._currentTransform.target,
  14099. action = targetCanvas._currentTransform.action;
  14100. if (this === target && action.slice && action.slice(0, 5) === 'scale') {
  14101. return false;
  14102. }
  14103. }
  14104. var canvas = this._cacheCanvas,
  14105. dims = this._limitCacheSize(this._getCacheCanvasDimensions()),
  14106. minCacheSize = fabric.minCacheSideLimit,
  14107. width = dims.width, height = dims.height, drawingWidth, drawingHeight,
  14108. zoomX = dims.zoomX, zoomY = dims.zoomY,
  14109. dimensionsChanged = width !== this.cacheWidth || height !== this.cacheHeight,
  14110. zoomChanged = this.zoomX !== zoomX || this.zoomY !== zoomY,
  14111. shouldRedraw = dimensionsChanged || zoomChanged,
  14112. additionalWidth = 0, additionalHeight = 0, shouldResizeCanvas = false;
  14113. if (dimensionsChanged) {
  14114. var canvasWidth = this._cacheCanvas.width,
  14115. canvasHeight = this._cacheCanvas.height,
  14116. sizeGrowing = width > canvasWidth || height > canvasHeight,
  14117. sizeShrinking = (width < canvasWidth * 0.9 || height < canvasHeight * 0.9) &&
  14118. canvasWidth > minCacheSize && canvasHeight > minCacheSize;
  14119. shouldResizeCanvas = sizeGrowing || sizeShrinking;
  14120. if (sizeGrowing && !dims.capped && (width > minCacheSize || height > minCacheSize)) {
  14121. additionalWidth = width * 0.1;
  14122. additionalHeight = height * 0.1;
  14123. }
  14124. }
  14125. if (this instanceof fabric.Text && this.path) {
  14126. shouldRedraw = true;
  14127. shouldResizeCanvas = true;
  14128. additionalWidth += this.getHeightOfLine(0) * this.zoomX;
  14129. additionalHeight += this.getHeightOfLine(0) * this.zoomY;
  14130. }
  14131. if (shouldRedraw) {
  14132. if (shouldResizeCanvas) {
  14133. canvas.width = Math.ceil(width + additionalWidth);
  14134. canvas.height = Math.ceil(height + additionalHeight);
  14135. }
  14136. else {
  14137. this._cacheContext.setTransform(1, 0, 0, 1, 0, 0);
  14138. this._cacheContext.clearRect(0, 0, canvas.width, canvas.height);
  14139. }
  14140. drawingWidth = dims.x / 2;
  14141. drawingHeight = dims.y / 2;
  14142. this.cacheTranslationX = Math.round(canvas.width / 2 - drawingWidth) + drawingWidth;
  14143. this.cacheTranslationY = Math.round(canvas.height / 2 - drawingHeight) + drawingHeight;
  14144. this.cacheWidth = width;
  14145. this.cacheHeight = height;
  14146. this._cacheContext.translate(this.cacheTranslationX, this.cacheTranslationY);
  14147. this._cacheContext.scale(zoomX, zoomY);
  14148. this.zoomX = zoomX;
  14149. this.zoomY = zoomY;
  14150. return true;
  14151. }
  14152. return false;
  14153. },
  14154. /**
  14155. * Sets object's properties from options
  14156. * @param {Object} [options] Options object
  14157. */
  14158. setOptions: function(options) {
  14159. this._setOptions(options);
  14160. this._initGradient(options.fill, 'fill');
  14161. this._initGradient(options.stroke, 'stroke');
  14162. this._initPattern(options.fill, 'fill');
  14163. this._initPattern(options.stroke, 'stroke');
  14164. },
  14165. /**
  14166. * Transforms context when rendering an object
  14167. * @param {CanvasRenderingContext2D} ctx Context
  14168. */
  14169. transform: function(ctx) {
  14170. var needFullTransform = (this.group && !this.group._transformDone) ||
  14171. (this.group && this.canvas && ctx === this.canvas.contextTop);
  14172. var m = this.calcTransformMatrix(!needFullTransform);
  14173. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  14174. },
  14175. /**
  14176. * Returns an object representation of an instance
  14177. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14178. * @return {Object} Object representation of an instance
  14179. */
  14180. toObject: function(propertiesToInclude) {
  14181. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  14182. object = {
  14183. type: this.type,
  14184. version: fabric.version,
  14185. originX: this.originX,
  14186. originY: this.originY,
  14187. left: toFixed(this.left, NUM_FRACTION_DIGITS),
  14188. top: toFixed(this.top, NUM_FRACTION_DIGITS),
  14189. width: toFixed(this.width, NUM_FRACTION_DIGITS),
  14190. height: toFixed(this.height, NUM_FRACTION_DIGITS),
  14191. fill: (this.fill && this.fill.toObject) ? this.fill.toObject() : this.fill,
  14192. stroke: (this.stroke && this.stroke.toObject) ? this.stroke.toObject() : this.stroke,
  14193. strokeWidth: toFixed(this.strokeWidth, NUM_FRACTION_DIGITS),
  14194. strokeDashArray: this.strokeDashArray ? this.strokeDashArray.concat() : this.strokeDashArray,
  14195. strokeLineCap: this.strokeLineCap,
  14196. strokeDashOffset: this.strokeDashOffset,
  14197. strokeLineJoin: this.strokeLineJoin,
  14198. strokeUniform: this.strokeUniform,
  14199. strokeMiterLimit: toFixed(this.strokeMiterLimit, NUM_FRACTION_DIGITS),
  14200. scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),
  14201. scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),
  14202. angle: toFixed(this.angle, NUM_FRACTION_DIGITS),
  14203. flipX: this.flipX,
  14204. flipY: this.flipY,
  14205. opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),
  14206. shadow: (this.shadow && this.shadow.toObject) ? this.shadow.toObject() : this.shadow,
  14207. visible: this.visible,
  14208. backgroundColor: this.backgroundColor,
  14209. fillRule: this.fillRule,
  14210. paintFirst: this.paintFirst,
  14211. globalCompositeOperation: this.globalCompositeOperation,
  14212. skewX: toFixed(this.skewX, NUM_FRACTION_DIGITS),
  14213. skewY: toFixed(this.skewY, NUM_FRACTION_DIGITS),
  14214. };
  14215. if (this.clipPath && !this.clipPath.excludeFromExport) {
  14216. object.clipPath = this.clipPath.toObject(propertiesToInclude);
  14217. object.clipPath.inverted = this.clipPath.inverted;
  14218. object.clipPath.absolutePositioned = this.clipPath.absolutePositioned;
  14219. }
  14220. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  14221. if (!this.includeDefaultValues) {
  14222. object = this._removeDefaultValues(object);
  14223. }
  14224. return object;
  14225. },
  14226. /**
  14227. * Returns (dataless) object representation of an instance
  14228. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14229. * @return {Object} Object representation of an instance
  14230. */
  14231. toDatalessObject: function(propertiesToInclude) {
  14232. // will be overwritten by subclasses
  14233. return this.toObject(propertiesToInclude);
  14234. },
  14235. /**
  14236. * @private
  14237. * @param {Object} object
  14238. */
  14239. _removeDefaultValues: function(object) {
  14240. var prototype = fabric.util.getKlass(object.type).prototype,
  14241. stateProperties = prototype.stateProperties;
  14242. stateProperties.forEach(function(prop) {
  14243. if (prop === 'left' || prop === 'top') {
  14244. return;
  14245. }
  14246. if (object[prop] === prototype[prop]) {
  14247. delete object[prop];
  14248. }
  14249. // basically a check for [] === []
  14250. if (Array.isArray(object[prop]) && Array.isArray(prototype[prop])
  14251. && object[prop].length === 0 && prototype[prop].length === 0) {
  14252. delete object[prop];
  14253. }
  14254. });
  14255. return object;
  14256. },
  14257. /**
  14258. * Returns a string representation of an instance
  14259. * @return {String}
  14260. */
  14261. toString: function() {
  14262. return '#<fabric.' + capitalize(this.type) + '>';
  14263. },
  14264. /**
  14265. * Return the object scale factor counting also the group scaling
  14266. * @return {Object} object with scaleX and scaleY properties
  14267. */
  14268. getObjectScaling: function() {
  14269. // if the object is a top level one, on the canvas, we go for simple aritmetic
  14270. // otherwise the complex method with angles will return approximations and decimals
  14271. // and will likely kill the cache when not needed
  14272. // https://github.com/fabricjs/fabric.js/issues/7157
  14273. if (!this.group) {
  14274. return {
  14275. scaleX: this.scaleX,
  14276. scaleY: this.scaleY,
  14277. };
  14278. }
  14279. // if we are inside a group total zoom calculation is complex, we defer to generic matrices
  14280. var options = fabric.util.qrDecompose(this.calcTransformMatrix());
  14281. return { scaleX: Math.abs(options.scaleX), scaleY: Math.abs(options.scaleY) };
  14282. },
  14283. /**
  14284. * Return the object scale factor counting also the group scaling, zoom and retina
  14285. * @return {Object} object with scaleX and scaleY properties
  14286. */
  14287. getTotalObjectScaling: function() {
  14288. var scale = this.getObjectScaling(), scaleX = scale.scaleX, scaleY = scale.scaleY;
  14289. if (this.canvas) {
  14290. var zoom = this.canvas.getZoom();
  14291. var retina = this.canvas.getRetinaScaling();
  14292. scaleX *= zoom * retina;
  14293. scaleY *= zoom * retina;
  14294. }
  14295. return { scaleX: scaleX, scaleY: scaleY };
  14296. },
  14297. /**
  14298. * Return the object opacity counting also the group property
  14299. * @return {Number}
  14300. */
  14301. getObjectOpacity: function() {
  14302. var opacity = this.opacity;
  14303. if (this.group) {
  14304. opacity *= this.group.getObjectOpacity();
  14305. }
  14306. return opacity;
  14307. },
  14308. /**
  14309. * @private
  14310. * @param {String} key
  14311. * @param {*} value
  14312. * @return {fabric.Object} thisArg
  14313. */
  14314. _set: function(key, value) {
  14315. var shouldConstrainValue = (key === 'scaleX' || key === 'scaleY'),
  14316. isChanged = this[key] !== value, groupNeedsUpdate = false;
  14317. if (shouldConstrainValue) {
  14318. value = this._constrainScale(value);
  14319. }
  14320. if (key === 'scaleX' && value < 0) {
  14321. this.flipX = !this.flipX;
  14322. value *= -1;
  14323. }
  14324. else if (key === 'scaleY' && value < 0) {
  14325. this.flipY = !this.flipY;
  14326. value *= -1;
  14327. }
  14328. else if (key === 'shadow' && value && !(value instanceof fabric.Shadow)) {
  14329. value = new fabric.Shadow(value);
  14330. }
  14331. else if (key === 'dirty' && this.group) {
  14332. this.group.set('dirty', value);
  14333. }
  14334. this[key] = value;
  14335. if (isChanged) {
  14336. groupNeedsUpdate = this.group && this.group.isOnACache();
  14337. if (this.cacheProperties.indexOf(key) > -1) {
  14338. this.dirty = true;
  14339. groupNeedsUpdate && this.group.set('dirty', true);
  14340. }
  14341. else if (groupNeedsUpdate && this.stateProperties.indexOf(key) > -1) {
  14342. this.group.set('dirty', true);
  14343. }
  14344. }
  14345. return this;
  14346. },
  14347. /**
  14348. * This callback function is called by the parent group of an object every
  14349. * time a non-delegated property changes on the group. It is passed the key
  14350. * and value as parameters. Not adding in this function's signature to avoid
  14351. * Travis build error about unused variables.
  14352. */
  14353. setOnGroup: function() {
  14354. // implemented by sub-classes, as needed.
  14355. },
  14356. /**
  14357. * Retrieves viewportTransform from Object's canvas if possible
  14358. * @method getViewportTransform
  14359. * @memberOf fabric.Object.prototype
  14360. * @return {Array}
  14361. */
  14362. getViewportTransform: function() {
  14363. if (this.canvas && this.canvas.viewportTransform) {
  14364. return this.canvas.viewportTransform;
  14365. }
  14366. return fabric.iMatrix.concat();
  14367. },
  14368. /*
  14369. * @private
  14370. * return if the object would be visible in rendering
  14371. * @memberOf fabric.Object.prototype
  14372. * @return {Boolean}
  14373. */
  14374. isNotVisible: function() {
  14375. return this.opacity === 0 ||
  14376. (!this.width && !this.height && this.strokeWidth === 0) ||
  14377. !this.visible;
  14378. },
  14379. /**
  14380. * Renders an object on a specified context
  14381. * @param {CanvasRenderingContext2D} ctx Context to render on
  14382. */
  14383. render: function(ctx) {
  14384. // do not render if width/height are zeros or object is not visible
  14385. if (this.isNotVisible()) {
  14386. return;
  14387. }
  14388. if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {
  14389. return;
  14390. }
  14391. ctx.save();
  14392. this._setupCompositeOperation(ctx);
  14393. this.drawSelectionBackground(ctx);
  14394. this.transform(ctx);
  14395. this._setOpacity(ctx);
  14396. this._setShadow(ctx, this);
  14397. if (this.shouldCache()) {
  14398. this.renderCache();
  14399. this.drawCacheOnCanvas(ctx);
  14400. }
  14401. else {
  14402. this._removeCacheCanvas();
  14403. this.dirty = false;
  14404. this.drawObject(ctx);
  14405. if (this.objectCaching && this.statefullCache) {
  14406. this.saveState({ propertySet: 'cacheProperties' });
  14407. }
  14408. }
  14409. ctx.restore();
  14410. },
  14411. renderCache: function(options) {
  14412. options = options || {};
  14413. if (!this._cacheCanvas || !this._cacheContext) {
  14414. this._createCacheCanvas();
  14415. }
  14416. if (this.isCacheDirty()) {
  14417. this.statefullCache && this.saveState({ propertySet: 'cacheProperties' });
  14418. this.drawObject(this._cacheContext, options.forClipping);
  14419. this.dirty = false;
  14420. }
  14421. },
  14422. /**
  14423. * Remove cacheCanvas and its dimensions from the objects
  14424. */
  14425. _removeCacheCanvas: function() {
  14426. this._cacheCanvas = null;
  14427. this._cacheContext = null;
  14428. this.cacheWidth = 0;
  14429. this.cacheHeight = 0;
  14430. },
  14431. /**
  14432. * return true if the object will draw a stroke
  14433. * Does not consider text styles. This is just a shortcut used at rendering time
  14434. * We want it to be an approximation and be fast.
  14435. * wrote to avoid extra caching, it has to return true when stroke happens,
  14436. * can guess when it will not happen at 100% chance, does not matter if it misses
  14437. * some use case where the stroke is invisible.
  14438. * @since 3.0.0
  14439. * @returns Boolean
  14440. */
  14441. hasStroke: function() {
  14442. return this.stroke && this.stroke !== 'transparent' && this.strokeWidth !== 0;
  14443. },
  14444. /**
  14445. * return true if the object will draw a fill
  14446. * Does not consider text styles. This is just a shortcut used at rendering time
  14447. * We want it to be an approximation and be fast.
  14448. * wrote to avoid extra caching, it has to return true when fill happens,
  14449. * can guess when it will not happen at 100% chance, does not matter if it misses
  14450. * some use case where the fill is invisible.
  14451. * @since 3.0.0
  14452. * @returns Boolean
  14453. */
  14454. hasFill: function() {
  14455. return this.fill && this.fill !== 'transparent';
  14456. },
  14457. /**
  14458. * When set to `true`, force the object to have its own cache, even if it is inside a group
  14459. * it may be needed when your object behave in a particular way on the cache and always needs
  14460. * its own isolated canvas to render correctly.
  14461. * Created to be overridden
  14462. * since 1.7.12
  14463. * @returns Boolean
  14464. */
  14465. needsItsOwnCache: function() {
  14466. if (this.paintFirst === 'stroke' &&
  14467. this.hasFill() && this.hasStroke() && typeof this.shadow === 'object') {
  14468. return true;
  14469. }
  14470. if (this.clipPath) {
  14471. return true;
  14472. }
  14473. return false;
  14474. },
  14475. /**
  14476. * Decide if the object should cache or not. Create its own cache level
  14477. * objectCaching is a global flag, wins over everything
  14478. * needsItsOwnCache should be used when the object drawing method requires
  14479. * a cache step. None of the fabric classes requires it.
  14480. * Generally you do not cache objects in groups because the group outside is cached.
  14481. * Read as: cache if is needed, or if the feature is enabled but we are not already caching.
  14482. * @return {Boolean}
  14483. */
  14484. shouldCache: function() {
  14485. this.ownCaching = this.needsItsOwnCache() || (
  14486. this.objectCaching &&
  14487. (!this.group || !this.group.isOnACache())
  14488. );
  14489. return this.ownCaching;
  14490. },
  14491. /**
  14492. * Check if this object or a child object will cast a shadow
  14493. * used by Group.shouldCache to know if child has a shadow recursively
  14494. * @return {Boolean}
  14495. */
  14496. willDrawShadow: function() {
  14497. return !!this.shadow && (this.shadow.offsetX !== 0 || this.shadow.offsetY !== 0);
  14498. },
  14499. /**
  14500. * Execute the drawing operation for an object clipPath
  14501. * @param {CanvasRenderingContext2D} ctx Context to render on
  14502. * @param {fabric.Object} clipPath
  14503. */
  14504. drawClipPathOnCache: function(ctx, clipPath) {
  14505. ctx.save();
  14506. // DEBUG: uncomment this line, comment the following
  14507. // ctx.globalAlpha = 0.4
  14508. if (clipPath.inverted) {
  14509. ctx.globalCompositeOperation = 'destination-out';
  14510. }
  14511. else {
  14512. ctx.globalCompositeOperation = 'destination-in';
  14513. }
  14514. //ctx.scale(1 / 2, 1 / 2);
  14515. if (clipPath.absolutePositioned) {
  14516. var m = fabric.util.invertTransform(this.calcTransformMatrix());
  14517. ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
  14518. }
  14519. clipPath.transform(ctx);
  14520. ctx.scale(1 / clipPath.zoomX, 1 / clipPath.zoomY);
  14521. ctx.drawImage(clipPath._cacheCanvas, -clipPath.cacheTranslationX, -clipPath.cacheTranslationY);
  14522. ctx.restore();
  14523. },
  14524. /**
  14525. * Execute the drawing operation for an object on a specified context
  14526. * @param {CanvasRenderingContext2D} ctx Context to render on
  14527. */
  14528. drawObject: function(ctx, forClipping) {
  14529. var originalFill = this.fill, originalStroke = this.stroke;
  14530. if (forClipping) {
  14531. this.fill = 'black';
  14532. this.stroke = '';
  14533. this._setClippingProperties(ctx);
  14534. }
  14535. else {
  14536. this._renderBackground(ctx);
  14537. }
  14538. this._render(ctx);
  14539. this._drawClipPath(ctx, this.clipPath);
  14540. this.fill = originalFill;
  14541. this.stroke = originalStroke;
  14542. },
  14543. /**
  14544. * Prepare clipPath state and cache and draw it on instance's cache
  14545. * @param {CanvasRenderingContext2D} ctx
  14546. * @param {fabric.Object} clipPath
  14547. */
  14548. _drawClipPath: function (ctx, clipPath) {
  14549. if (!clipPath) { return; }
  14550. // needed to setup a couple of variables
  14551. // path canvas gets overridden with this one.
  14552. // TODO find a better solution?
  14553. clipPath.canvas = this.canvas;
  14554. clipPath.shouldCache();
  14555. clipPath._transformDone = true;
  14556. clipPath.renderCache({ forClipping: true });
  14557. this.drawClipPathOnCache(ctx, clipPath);
  14558. },
  14559. /**
  14560. * Paint the cached copy of the object on the target context.
  14561. * @param {CanvasRenderingContext2D} ctx Context to render on
  14562. */
  14563. drawCacheOnCanvas: function(ctx) {
  14564. ctx.scale(1 / this.zoomX, 1 / this.zoomY);
  14565. ctx.drawImage(this._cacheCanvas, -this.cacheTranslationX, -this.cacheTranslationY);
  14566. },
  14567. /**
  14568. * Check if cache is dirty
  14569. * @param {Boolean} skipCanvas skip canvas checks because this object is painted
  14570. * on parent canvas.
  14571. */
  14572. isCacheDirty: function(skipCanvas) {
  14573. if (this.isNotVisible()) {
  14574. return false;
  14575. }
  14576. if (this._cacheCanvas && this._cacheContext && !skipCanvas && this._updateCacheCanvas()) {
  14577. // in this case the context is already cleared.
  14578. return true;
  14579. }
  14580. else {
  14581. if (this.dirty ||
  14582. (this.clipPath && this.clipPath.absolutePositioned) ||
  14583. (this.statefullCache && this.hasStateChanged('cacheProperties'))
  14584. ) {
  14585. if (this._cacheCanvas && this._cacheContext && !skipCanvas) {
  14586. var width = this.cacheWidth / this.zoomX;
  14587. var height = this.cacheHeight / this.zoomY;
  14588. this._cacheContext.clearRect(-width / 2, -height / 2, width, height);
  14589. }
  14590. return true;
  14591. }
  14592. }
  14593. return false;
  14594. },
  14595. /**
  14596. * Draws a background for the object big as its untransformed dimensions
  14597. * @private
  14598. * @param {CanvasRenderingContext2D} ctx Context to render on
  14599. */
  14600. _renderBackground: function(ctx) {
  14601. if (!this.backgroundColor) {
  14602. return;
  14603. }
  14604. var dim = this._getNonTransformedDimensions();
  14605. ctx.fillStyle = this.backgroundColor;
  14606. ctx.fillRect(
  14607. -dim.x / 2,
  14608. -dim.y / 2,
  14609. dim.x,
  14610. dim.y
  14611. );
  14612. // if there is background color no other shadows
  14613. // should be casted
  14614. this._removeShadow(ctx);
  14615. },
  14616. /**
  14617. * @private
  14618. * @param {CanvasRenderingContext2D} ctx Context to render on
  14619. */
  14620. _setOpacity: function(ctx) {
  14621. if (this.group && !this.group._transformDone) {
  14622. ctx.globalAlpha = this.getObjectOpacity();
  14623. }
  14624. else {
  14625. ctx.globalAlpha *= this.opacity;
  14626. }
  14627. },
  14628. _setStrokeStyles: function(ctx, decl) {
  14629. var stroke = decl.stroke;
  14630. if (stroke) {
  14631. ctx.lineWidth = decl.strokeWidth;
  14632. ctx.lineCap = decl.strokeLineCap;
  14633. ctx.lineDashOffset = decl.strokeDashOffset;
  14634. ctx.lineJoin = decl.strokeLineJoin;
  14635. ctx.miterLimit = decl.strokeMiterLimit;
  14636. if (stroke.toLive) {
  14637. if (stroke.gradientUnits === 'percentage' || stroke.gradientTransform || stroke.patternTransform) {
  14638. // need to transform gradient in a pattern.
  14639. // this is a slow process. If you are hitting this codepath, and the object
  14640. // is not using caching, you should consider switching it on.
  14641. // we need a canvas as big as the current object caching canvas.
  14642. this._applyPatternForTransformedGradient(ctx, stroke);
  14643. }
  14644. else {
  14645. // is a simple gradient or pattern
  14646. ctx.strokeStyle = stroke.toLive(ctx, this);
  14647. this._applyPatternGradientTransform(ctx, stroke);
  14648. }
  14649. }
  14650. else {
  14651. // is a color
  14652. ctx.strokeStyle = decl.stroke;
  14653. }
  14654. }
  14655. },
  14656. _setFillStyles: function(ctx, decl) {
  14657. var fill = decl.fill;
  14658. if (fill) {
  14659. if (fill.toLive) {
  14660. ctx.fillStyle = fill.toLive(ctx, this);
  14661. this._applyPatternGradientTransform(ctx, decl.fill);
  14662. }
  14663. else {
  14664. ctx.fillStyle = fill;
  14665. }
  14666. }
  14667. },
  14668. _setClippingProperties: function(ctx) {
  14669. ctx.globalAlpha = 1;
  14670. ctx.strokeStyle = 'transparent';
  14671. ctx.fillStyle = '#000000';
  14672. },
  14673. /**
  14674. * @private
  14675. * Sets line dash
  14676. * @param {CanvasRenderingContext2D} ctx Context to set the dash line on
  14677. * @param {Array} dashArray array representing dashes
  14678. */
  14679. _setLineDash: function(ctx, dashArray) {
  14680. if (!dashArray || dashArray.length === 0) {
  14681. return;
  14682. }
  14683. // Spec requires the concatenation of two copies the dash list when the number of elements is odd
  14684. if (1 & dashArray.length) {
  14685. dashArray.push.apply(dashArray, dashArray);
  14686. }
  14687. ctx.setLineDash(dashArray);
  14688. },
  14689. /**
  14690. * Renders controls and borders for the object
  14691. * the context here is not transformed
  14692. * @param {CanvasRenderingContext2D} ctx Context to render on
  14693. * @param {Object} [styleOverride] properties to override the object style
  14694. */
  14695. _renderControls: function(ctx, styleOverride) {
  14696. var vpt = this.getViewportTransform(),
  14697. matrix = this.calcTransformMatrix(),
  14698. options, drawBorders, drawControls;
  14699. styleOverride = styleOverride || { };
  14700. drawBorders = typeof styleOverride.hasBorders !== 'undefined' ? styleOverride.hasBorders : this.hasBorders;
  14701. drawControls = typeof styleOverride.hasControls !== 'undefined' ? styleOverride.hasControls : this.hasControls;
  14702. matrix = fabric.util.multiplyTransformMatrices(vpt, matrix);
  14703. options = fabric.util.qrDecompose(matrix);
  14704. ctx.save();
  14705. ctx.translate(options.translateX, options.translateY);
  14706. ctx.lineWidth = 1 * this.borderScaleFactor;
  14707. if (!this.group) {
  14708. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  14709. }
  14710. if (this.flipX) {
  14711. options.angle -= 180;
  14712. }
  14713. ctx.rotate(degreesToRadians(this.group ? options.angle : this.angle));
  14714. if (styleOverride.forActiveSelection || this.group) {
  14715. drawBorders && this.drawBordersInGroup(ctx, options, styleOverride);
  14716. }
  14717. else {
  14718. drawBorders && this.drawBorders(ctx, styleOverride);
  14719. }
  14720. drawControls && this.drawControls(ctx, styleOverride);
  14721. ctx.restore();
  14722. },
  14723. /**
  14724. * @private
  14725. * @param {CanvasRenderingContext2D} ctx Context to render on
  14726. */
  14727. _setShadow: function(ctx) {
  14728. if (!this.shadow) {
  14729. return;
  14730. }
  14731. var shadow = this.shadow, canvas = this.canvas, scaling,
  14732. multX = (canvas && canvas.viewportTransform[0]) || 1,
  14733. multY = (canvas && canvas.viewportTransform[3]) || 1;
  14734. if (shadow.nonScaling) {
  14735. scaling = { scaleX: 1, scaleY: 1 };
  14736. }
  14737. else {
  14738. scaling = this.getObjectScaling();
  14739. }
  14740. if (canvas && canvas._isRetinaScaling()) {
  14741. multX *= fabric.devicePixelRatio;
  14742. multY *= fabric.devicePixelRatio;
  14743. }
  14744. ctx.shadowColor = shadow.color;
  14745. ctx.shadowBlur = shadow.blur * fabric.browserShadowBlurConstant *
  14746. (multX + multY) * (scaling.scaleX + scaling.scaleY) / 4;
  14747. ctx.shadowOffsetX = shadow.offsetX * multX * scaling.scaleX;
  14748. ctx.shadowOffsetY = shadow.offsetY * multY * scaling.scaleY;
  14749. },
  14750. /**
  14751. * @private
  14752. * @param {CanvasRenderingContext2D} ctx Context to render on
  14753. */
  14754. _removeShadow: function(ctx) {
  14755. if (!this.shadow) {
  14756. return;
  14757. }
  14758. ctx.shadowColor = '';
  14759. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  14760. },
  14761. /**
  14762. * @private
  14763. * @param {CanvasRenderingContext2D} ctx Context to render on
  14764. * @param {Object} filler fabric.Pattern or fabric.Gradient
  14765. * @return {Object} offset.offsetX offset for text rendering
  14766. * @return {Object} offset.offsetY offset for text rendering
  14767. */
  14768. _applyPatternGradientTransform: function(ctx, filler) {
  14769. if (!filler || !filler.toLive) {
  14770. return { offsetX: 0, offsetY: 0 };
  14771. }
  14772. var t = filler.gradientTransform || filler.patternTransform;
  14773. var offsetX = -this.width / 2 + filler.offsetX || 0,
  14774. offsetY = -this.height / 2 + filler.offsetY || 0;
  14775. if (filler.gradientUnits === 'percentage') {
  14776. ctx.transform(this.width, 0, 0, this.height, offsetX, offsetY);
  14777. }
  14778. else {
  14779. ctx.transform(1, 0, 0, 1, offsetX, offsetY);
  14780. }
  14781. if (t) {
  14782. ctx.transform(t[0], t[1], t[2], t[3], t[4], t[5]);
  14783. }
  14784. return { offsetX: offsetX, offsetY: offsetY };
  14785. },
  14786. /**
  14787. * @private
  14788. * @param {CanvasRenderingContext2D} ctx Context to render on
  14789. */
  14790. _renderPaintInOrder: function(ctx) {
  14791. if (this.paintFirst === 'stroke') {
  14792. this._renderStroke(ctx);
  14793. this._renderFill(ctx);
  14794. }
  14795. else {
  14796. this._renderFill(ctx);
  14797. this._renderStroke(ctx);
  14798. }
  14799. },
  14800. /**
  14801. * @private
  14802. * function that actually render something on the context.
  14803. * empty here to allow Obects to work on tests to benchmark fabric functionalites
  14804. * not related to rendering
  14805. * @param {CanvasRenderingContext2D} ctx Context to render on
  14806. */
  14807. _render: function(/* ctx */) {
  14808. },
  14809. /**
  14810. * @private
  14811. * @param {CanvasRenderingContext2D} ctx Context to render on
  14812. */
  14813. _renderFill: function(ctx) {
  14814. if (!this.fill) {
  14815. return;
  14816. }
  14817. ctx.save();
  14818. this._setFillStyles(ctx, this);
  14819. if (this.fillRule === 'evenodd') {
  14820. ctx.fill('evenodd');
  14821. }
  14822. else {
  14823. ctx.fill();
  14824. }
  14825. ctx.restore();
  14826. },
  14827. /**
  14828. * @private
  14829. * @param {CanvasRenderingContext2D} ctx Context to render on
  14830. */
  14831. _renderStroke: function(ctx) {
  14832. if (!this.stroke || this.strokeWidth === 0) {
  14833. return;
  14834. }
  14835. if (this.shadow && !this.shadow.affectStroke) {
  14836. this._removeShadow(ctx);
  14837. }
  14838. ctx.save();
  14839. if (this.strokeUniform && this.group) {
  14840. var scaling = this.getObjectScaling();
  14841. ctx.scale(1 / scaling.scaleX, 1 / scaling.scaleY);
  14842. }
  14843. else if (this.strokeUniform) {
  14844. ctx.scale(1 / this.scaleX, 1 / this.scaleY);
  14845. }
  14846. this._setLineDash(ctx, this.strokeDashArray);
  14847. this._setStrokeStyles(ctx, this);
  14848. ctx.stroke();
  14849. ctx.restore();
  14850. },
  14851. /**
  14852. * This function try to patch the missing gradientTransform on canvas gradients.
  14853. * transforming a context to transform the gradient, is going to transform the stroke too.
  14854. * we want to transform the gradient but not the stroke operation, so we create
  14855. * a transformed gradient on a pattern and then we use the pattern instead of the gradient.
  14856. * this method has drwabacks: is slow, is in low resolution, needs a patch for when the size
  14857. * is limited.
  14858. * @private
  14859. * @param {CanvasRenderingContext2D} ctx Context to render on
  14860. * @param {fabric.Gradient} filler a fabric gradient instance
  14861. */
  14862. _applyPatternForTransformedGradient: function(ctx, filler) {
  14863. var dims = this._limitCacheSize(this._getCacheCanvasDimensions()),
  14864. pCanvas = fabric.util.createCanvasElement(), pCtx, retinaScaling = this.canvas.getRetinaScaling(),
  14865. width = dims.x / this.scaleX / retinaScaling, height = dims.y / this.scaleY / retinaScaling;
  14866. pCanvas.width = width;
  14867. pCanvas.height = height;
  14868. pCtx = pCanvas.getContext('2d');
  14869. pCtx.beginPath(); pCtx.moveTo(0, 0); pCtx.lineTo(width, 0); pCtx.lineTo(width, height);
  14870. pCtx.lineTo(0, height); pCtx.closePath();
  14871. pCtx.translate(width / 2, height / 2);
  14872. pCtx.scale(
  14873. dims.zoomX / this.scaleX / retinaScaling,
  14874. dims.zoomY / this.scaleY / retinaScaling
  14875. );
  14876. this._applyPatternGradientTransform(pCtx, filler);
  14877. pCtx.fillStyle = filler.toLive(ctx);
  14878. pCtx.fill();
  14879. ctx.translate(-this.width / 2 - this.strokeWidth / 2, -this.height / 2 - this.strokeWidth / 2);
  14880. ctx.scale(
  14881. retinaScaling * this.scaleX / dims.zoomX,
  14882. retinaScaling * this.scaleY / dims.zoomY
  14883. );
  14884. ctx.strokeStyle = pCtx.createPattern(pCanvas, 'no-repeat');
  14885. },
  14886. /**
  14887. * This function is an helper for svg import. it returns the center of the object in the svg
  14888. * untransformed coordinates
  14889. * @private
  14890. * @return {Object} center point from element coordinates
  14891. */
  14892. _findCenterFromElement: function() {
  14893. return { x: this.left + this.width / 2, y: this.top + this.height / 2 };
  14894. },
  14895. /**
  14896. * This function is an helper for svg import. it decompose the transformMatrix
  14897. * and assign properties to object.
  14898. * untransformed coordinates
  14899. * @private
  14900. * @chainable
  14901. */
  14902. _assignTransformMatrixProps: function() {
  14903. if (this.transformMatrix) {
  14904. var options = fabric.util.qrDecompose(this.transformMatrix);
  14905. this.flipX = false;
  14906. this.flipY = false;
  14907. this.set('scaleX', options.scaleX);
  14908. this.set('scaleY', options.scaleY);
  14909. this.angle = options.angle;
  14910. this.skewX = options.skewX;
  14911. this.skewY = 0;
  14912. }
  14913. },
  14914. /**
  14915. * This function is an helper for svg import. it removes the transform matrix
  14916. * and set to object properties that fabricjs can handle
  14917. * @private
  14918. * @param {Object} preserveAspectRatioOptions
  14919. * @return {thisArg}
  14920. */
  14921. _removeTransformMatrix: function(preserveAspectRatioOptions) {
  14922. var center = this._findCenterFromElement();
  14923. if (this.transformMatrix) {
  14924. this._assignTransformMatrixProps();
  14925. center = fabric.util.transformPoint(center, this.transformMatrix);
  14926. }
  14927. this.transformMatrix = null;
  14928. if (preserveAspectRatioOptions) {
  14929. this.scaleX *= preserveAspectRatioOptions.scaleX;
  14930. this.scaleY *= preserveAspectRatioOptions.scaleY;
  14931. this.cropX = preserveAspectRatioOptions.cropX;
  14932. this.cropY = preserveAspectRatioOptions.cropY;
  14933. center.x += preserveAspectRatioOptions.offsetLeft;
  14934. center.y += preserveAspectRatioOptions.offsetTop;
  14935. this.width = preserveAspectRatioOptions.width;
  14936. this.height = preserveAspectRatioOptions.height;
  14937. }
  14938. this.setPositionByOrigin(center, 'center', 'center');
  14939. },
  14940. /**
  14941. * Clones an instance, using a callback method will work for every object.
  14942. * @param {Function} callback Callback is invoked with a clone as a first argument
  14943. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14944. */
  14945. clone: function(callback, propertiesToInclude) {
  14946. var objectForm = this.toObject(propertiesToInclude);
  14947. if (this.constructor.fromObject) {
  14948. this.constructor.fromObject(objectForm, callback);
  14949. }
  14950. else {
  14951. fabric.Object._fromObject('Object', objectForm, callback);
  14952. }
  14953. },
  14954. /**
  14955. * Creates an instance of fabric.Image out of an object
  14956. * makes use of toCanvasElement.
  14957. * Once this method was based on toDataUrl and loadImage, so it also had a quality
  14958. * and format option. toCanvasElement is faster and produce no loss of quality.
  14959. * If you need to get a real Jpeg or Png from an object, using toDataURL is the right way to do it.
  14960. * toCanvasElement and then toBlob from the obtained canvas is also a good option.
  14961. * This method is sync now, but still support the callback because we did not want to break.
  14962. * When fabricJS 5.0 will be planned, this will probably be changed to not have a callback.
  14963. * @param {Function} callback callback, invoked with an instance as a first argument
  14964. * @param {Object} [options] for clone as image, passed to toDataURL
  14965. * @param {Number} [options.multiplier=1] Multiplier to scale by
  14966. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  14967. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  14968. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  14969. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  14970. * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4
  14971. * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4
  14972. * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2
  14973. * @return {fabric.Object} thisArg
  14974. */
  14975. cloneAsImage: function(callback, options) {
  14976. var canvasEl = this.toCanvasElement(options);
  14977. if (callback) {
  14978. callback(new fabric.Image(canvasEl));
  14979. }
  14980. return this;
  14981. },
  14982. /**
  14983. * Converts an object into a HTMLCanvas element
  14984. * @param {Object} options Options object
  14985. * @param {Number} [options.multiplier=1] Multiplier to scale by
  14986. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  14987. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  14988. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  14989. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  14990. * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4
  14991. * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4
  14992. * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2
  14993. * @return {HTMLCanvasElement} Returns DOM element <canvas> with the fabric.Object
  14994. */
  14995. toCanvasElement: function(options) {
  14996. options || (options = { });
  14997. var utils = fabric.util, origParams = utils.saveObjectTransform(this),
  14998. originalGroup = this.group,
  14999. originalShadow = this.shadow, abs = Math.abs,
  15000. multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? fabric.devicePixelRatio : 1);
  15001. delete this.group;
  15002. if (options.withoutTransform) {
  15003. utils.resetObjectTransform(this);
  15004. }
  15005. if (options.withoutShadow) {
  15006. this.shadow = null;
  15007. }
  15008. var el = fabric.util.createCanvasElement(),
  15009. // skip canvas zoom and calculate with setCoords now.
  15010. boundingRect = this.getBoundingRect(true, true),
  15011. shadow = this.shadow, scaling,
  15012. shadowOffset = { x: 0, y: 0 }, shadowBlur,
  15013. width, height;
  15014. if (shadow) {
  15015. shadowBlur = shadow.blur;
  15016. if (shadow.nonScaling) {
  15017. scaling = { scaleX: 1, scaleY: 1 };
  15018. }
  15019. else {
  15020. scaling = this.getObjectScaling();
  15021. }
  15022. // consider non scaling shadow.
  15023. shadowOffset.x = 2 * Math.round(abs(shadow.offsetX) + shadowBlur) * (abs(scaling.scaleX));
  15024. shadowOffset.y = 2 * Math.round(abs(shadow.offsetY) + shadowBlur) * (abs(scaling.scaleY));
  15025. }
  15026. width = boundingRect.width + shadowOffset.x;
  15027. height = boundingRect.height + shadowOffset.y;
  15028. // if the current width/height is not an integer
  15029. // we need to make it so.
  15030. el.width = Math.ceil(width);
  15031. el.height = Math.ceil(height);
  15032. var canvas = new fabric.StaticCanvas(el, {
  15033. enableRetinaScaling: false,
  15034. renderOnAddRemove: false,
  15035. skipOffscreen: false,
  15036. });
  15037. if (options.format === 'jpeg') {
  15038. canvas.backgroundColor = '#fff';
  15039. }
  15040. this.setPositionByOrigin(new fabric.Point(canvas.width / 2, canvas.height / 2), 'center', 'center');
  15041. var originalCanvas = this.canvas;
  15042. canvas.add(this);
  15043. var canvasEl = canvas.toCanvasElement(multiplier || 1, options);
  15044. this.shadow = originalShadow;
  15045. this.set('canvas', originalCanvas);
  15046. if (originalGroup) {
  15047. this.group = originalGroup;
  15048. }
  15049. this.set(origParams).setCoords();
  15050. // canvas.dispose will call image.dispose that will nullify the elements
  15051. // since this canvas is a simple element for the process, we remove references
  15052. // to objects in this way in order to avoid object trashing.
  15053. canvas._objects = [];
  15054. canvas.dispose();
  15055. canvas = null;
  15056. return canvasEl;
  15057. },
  15058. /**
  15059. * Converts an object into a data-url-like string
  15060. * @param {Object} options Options object
  15061. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  15062. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  15063. * @param {Number} [options.multiplier=1] Multiplier to scale by
  15064. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  15065. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  15066. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  15067. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  15068. * @param {Boolean} [options.enableRetinaScaling] Enable retina scaling for clone image. Introduce in 1.6.4
  15069. * @param {Boolean} [options.withoutTransform] Remove current object transform ( no scale , no angle, no flip, no skew ). Introduced in 2.3.4
  15070. * @param {Boolean} [options.withoutShadow] Remove current object shadow. Introduced in 2.4.2
  15071. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  15072. */
  15073. toDataURL: function(options) {
  15074. options || (options = { });
  15075. return fabric.util.toDataURL(this.toCanvasElement(options), options.format || 'png', options.quality || 1);
  15076. },
  15077. /**
  15078. * Returns true if specified type is identical to the type of an instance
  15079. * @param {String} type Type to check against
  15080. * @return {Boolean}
  15081. */
  15082. isType: function(type) {
  15083. return arguments.length > 1 ? Array.from(arguments).includes(this.type) : this.type === type;
  15084. },
  15085. /**
  15086. * Returns complexity of an instance
  15087. * @return {Number} complexity of this instance (is 1 unless subclassed)
  15088. */
  15089. complexity: function() {
  15090. return 1;
  15091. },
  15092. /**
  15093. * Returns a JSON representation of an instance
  15094. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  15095. * @return {Object} JSON
  15096. */
  15097. toJSON: function(propertiesToInclude) {
  15098. // delegate, not alias
  15099. return this.toObject(propertiesToInclude);
  15100. },
  15101. /**
  15102. * Sets "angle" of an instance with centered rotation
  15103. * @param {Number} angle Angle value (in degrees)
  15104. * @return {fabric.Object} thisArg
  15105. * @chainable
  15106. */
  15107. rotate: function(angle) {
  15108. var shouldCenterOrigin = (this.originX !== 'center' || this.originY !== 'center') && this.centeredRotation;
  15109. if (shouldCenterOrigin) {
  15110. this._setOriginToCenter();
  15111. }
  15112. this.set('angle', angle);
  15113. if (shouldCenterOrigin) {
  15114. this._resetOrigin();
  15115. }
  15116. return this;
  15117. },
  15118. /**
  15119. * Centers object horizontally on canvas to which it was added last.
  15120. * You might need to call `setCoords` on an object after centering, to update controls area.
  15121. * @return {fabric.Object} thisArg
  15122. * @chainable
  15123. */
  15124. centerH: function () {
  15125. this.canvas && this.canvas.centerObjectH(this);
  15126. return this;
  15127. },
  15128. /**
  15129. * Centers object horizontally on current viewport of canvas to which it was added last.
  15130. * You might need to call `setCoords` on an object after centering, to update controls area.
  15131. * @return {fabric.Object} thisArg
  15132. * @chainable
  15133. */
  15134. viewportCenterH: function () {
  15135. this.canvas && this.canvas.viewportCenterObjectH(this);
  15136. return this;
  15137. },
  15138. /**
  15139. * Centers object vertically on canvas to which it was added last.
  15140. * You might need to call `setCoords` on an object after centering, to update controls area.
  15141. * @return {fabric.Object} thisArg
  15142. * @chainable
  15143. */
  15144. centerV: function () {
  15145. this.canvas && this.canvas.centerObjectV(this);
  15146. return this;
  15147. },
  15148. /**
  15149. * Centers object vertically on current viewport of canvas to which it was added last.
  15150. * You might need to call `setCoords` on an object after centering, to update controls area.
  15151. * @return {fabric.Object} thisArg
  15152. * @chainable
  15153. */
  15154. viewportCenterV: function () {
  15155. this.canvas && this.canvas.viewportCenterObjectV(this);
  15156. return this;
  15157. },
  15158. /**
  15159. * Centers object vertically and horizontally on canvas to which is was added last
  15160. * You might need to call `setCoords` on an object after centering, to update controls area.
  15161. * @return {fabric.Object} thisArg
  15162. * @chainable
  15163. */
  15164. center: function () {
  15165. this.canvas && this.canvas.centerObject(this);
  15166. return this;
  15167. },
  15168. /**
  15169. * Centers object on current viewport of canvas to which it was added last.
  15170. * You might need to call `setCoords` on an object after centering, to update controls area.
  15171. * @return {fabric.Object} thisArg
  15172. * @chainable
  15173. */
  15174. viewportCenter: function () {
  15175. this.canvas && this.canvas.viewportCenterObject(this);
  15176. return this;
  15177. },
  15178. /**
  15179. * Returns coordinates of a pointer relative to an object
  15180. * @param {Event} e Event to operate upon
  15181. * @param {Object} [pointer] Pointer to operate upon (instead of event)
  15182. * @return {Object} Coordinates of a pointer (x, y)
  15183. */
  15184. getLocalPointer: function(e, pointer) {
  15185. pointer = pointer || this.canvas.getPointer(e);
  15186. var pClicked = new fabric.Point(pointer.x, pointer.y),
  15187. objectLeftTop = this._getLeftTopCoords();
  15188. if (this.angle) {
  15189. pClicked = fabric.util.rotatePoint(
  15190. pClicked, objectLeftTop, degreesToRadians(-this.angle));
  15191. }
  15192. return {
  15193. x: pClicked.x - objectLeftTop.x,
  15194. y: pClicked.y - objectLeftTop.y
  15195. };
  15196. },
  15197. /**
  15198. * Sets canvas globalCompositeOperation for specific object
  15199. * custom composition operation for the particular object can be specified using globalCompositeOperation property
  15200. * @param {CanvasRenderingContext2D} ctx Rendering canvas context
  15201. */
  15202. _setupCompositeOperation: function (ctx) {
  15203. if (this.globalCompositeOperation) {
  15204. ctx.globalCompositeOperation = this.globalCompositeOperation;
  15205. }
  15206. },
  15207. /**
  15208. * cancel instance's running animations
  15209. * override if necessary to dispose artifacts such as `clipPath`
  15210. */
  15211. dispose: function () {
  15212. if (fabric.runningAnimations) {
  15213. fabric.runningAnimations.cancelByTarget(this);
  15214. }
  15215. }
  15216. });
  15217. fabric.util.createAccessors && fabric.util.createAccessors(fabric.Object);
  15218. extend(fabric.Object.prototype, fabric.Observable);
  15219. /**
  15220. * Defines the number of fraction digits to use when serializing object values.
  15221. * You can use it to increase/decrease precision of such values like left, top, scaleX, scaleY, etc.
  15222. * @static
  15223. * @memberOf fabric.Object
  15224. * @constant
  15225. * @type Number
  15226. */
  15227. fabric.Object.NUM_FRACTION_DIGITS = 2;
  15228. /**
  15229. * Defines which properties should be enlivened from the object passed to {@link fabric.Object._fromObject}
  15230. * @static
  15231. * @memberOf fabric.Object
  15232. * @constant
  15233. * @type string[]
  15234. */
  15235. fabric.Object.ENLIVEN_PROPS = ['clipPath'];
  15236. fabric.Object._fromObject = function(className, object, callback, extraParam) {
  15237. var klass = fabric[className];
  15238. object = clone(object, true);
  15239. fabric.util.enlivenPatterns([object.fill, object.stroke], function(patterns) {
  15240. if (typeof patterns[0] !== 'undefined') {
  15241. object.fill = patterns[0];
  15242. }
  15243. if (typeof patterns[1] !== 'undefined') {
  15244. object.stroke = patterns[1];
  15245. }
  15246. fabric.util.enlivenObjectEnlivables(object, object, function () {
  15247. var instance = extraParam ? new klass(object[extraParam], object) : new klass(object);
  15248. callback && callback(instance);
  15249. });
  15250. });
  15251. };
  15252. /**
  15253. * Unique id used internally when creating SVG elements
  15254. * @static
  15255. * @memberOf fabric.Object
  15256. * @type Number
  15257. */
  15258. fabric.Object.__uid = 0;
  15259. })(typeof exports !== 'undefined' ? exports : this);
  15260. (function() {
  15261. var degreesToRadians = fabric.util.degreesToRadians,
  15262. originXOffset = {
  15263. left: -0.5,
  15264. center: 0,
  15265. right: 0.5
  15266. },
  15267. originYOffset = {
  15268. top: -0.5,
  15269. center: 0,
  15270. bottom: 0.5
  15271. };
  15272. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15273. /**
  15274. * Translates the coordinates from a set of origin to another (based on the object's dimensions)
  15275. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  15276. * @param {String} fromOriginX Horizontal origin: 'left', 'center' or 'right'
  15277. * @param {String} fromOriginY Vertical origin: 'top', 'center' or 'bottom'
  15278. * @param {String} toOriginX Horizontal origin: 'left', 'center' or 'right'
  15279. * @param {String} toOriginY Vertical origin: 'top', 'center' or 'bottom'
  15280. * @return {fabric.Point}
  15281. */
  15282. translateToGivenOrigin: function(point, fromOriginX, fromOriginY, toOriginX, toOriginY) {
  15283. var x = point.x,
  15284. y = point.y,
  15285. offsetX, offsetY, dim;
  15286. if (typeof fromOriginX === 'string') {
  15287. fromOriginX = originXOffset[fromOriginX];
  15288. }
  15289. else {
  15290. fromOriginX -= 0.5;
  15291. }
  15292. if (typeof toOriginX === 'string') {
  15293. toOriginX = originXOffset[toOriginX];
  15294. }
  15295. else {
  15296. toOriginX -= 0.5;
  15297. }
  15298. offsetX = toOriginX - fromOriginX;
  15299. if (typeof fromOriginY === 'string') {
  15300. fromOriginY = originYOffset[fromOriginY];
  15301. }
  15302. else {
  15303. fromOriginY -= 0.5;
  15304. }
  15305. if (typeof toOriginY === 'string') {
  15306. toOriginY = originYOffset[toOriginY];
  15307. }
  15308. else {
  15309. toOriginY -= 0.5;
  15310. }
  15311. offsetY = toOriginY - fromOriginY;
  15312. if (offsetX || offsetY) {
  15313. dim = this._getTransformedDimensions();
  15314. x = point.x + offsetX * dim.x;
  15315. y = point.y + offsetY * dim.y;
  15316. }
  15317. return new fabric.Point(x, y);
  15318. },
  15319. /**
  15320. * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
  15321. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  15322. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  15323. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  15324. * @return {fabric.Point}
  15325. */
  15326. translateToCenterPoint: function(point, originX, originY) {
  15327. var p = this.translateToGivenOrigin(point, originX, originY, 'center', 'center');
  15328. if (this.angle) {
  15329. return fabric.util.rotatePoint(p, point, degreesToRadians(this.angle));
  15330. }
  15331. return p;
  15332. },
  15333. /**
  15334. * Translates the coordinates from center to origin coordinates (based on the object's dimensions)
  15335. * @param {fabric.Point} center The point which corresponds to center of the object
  15336. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  15337. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  15338. * @return {fabric.Point}
  15339. */
  15340. translateToOriginPoint: function(center, originX, originY) {
  15341. var p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
  15342. if (this.angle) {
  15343. return fabric.util.rotatePoint(p, center, degreesToRadians(this.angle));
  15344. }
  15345. return p;
  15346. },
  15347. /**
  15348. * Returns the real center coordinates of the object
  15349. * @return {fabric.Point}
  15350. */
  15351. getCenterPoint: function() {
  15352. var leftTop = new fabric.Point(this.left, this.top);
  15353. return this.translateToCenterPoint(leftTop, this.originX, this.originY);
  15354. },
  15355. /**
  15356. * Returns the coordinates of the object based on center coordinates
  15357. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  15358. * @return {fabric.Point}
  15359. */
  15360. // getOriginPoint: function(center) {
  15361. // return this.translateToOriginPoint(center, this.originX, this.originY);
  15362. // },
  15363. /**
  15364. * Returns the coordinates of the object as if it has a different origin
  15365. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  15366. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  15367. * @return {fabric.Point}
  15368. */
  15369. getPointByOrigin: function(originX, originY) {
  15370. var center = this.getCenterPoint();
  15371. return this.translateToOriginPoint(center, originX, originY);
  15372. },
  15373. /**
  15374. * Returns the point in local coordinates
  15375. * @param {fabric.Point} point The point relative to the global coordinate system
  15376. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  15377. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  15378. * @return {fabric.Point}
  15379. */
  15380. toLocalPoint: function(point, originX, originY) {
  15381. var center = this.getCenterPoint(),
  15382. p, p2;
  15383. if (typeof originX !== 'undefined' && typeof originY !== 'undefined' ) {
  15384. p = this.translateToGivenOrigin(center, 'center', 'center', originX, originY);
  15385. }
  15386. else {
  15387. p = new fabric.Point(this.left, this.top);
  15388. }
  15389. p2 = new fabric.Point(point.x, point.y);
  15390. if (this.angle) {
  15391. p2 = fabric.util.rotatePoint(p2, center, -degreesToRadians(this.angle));
  15392. }
  15393. return p2.subtractEquals(p);
  15394. },
  15395. /**
  15396. * Returns the point in global coordinates
  15397. * @param {fabric.Point} The point relative to the local coordinate system
  15398. * @return {fabric.Point}
  15399. */
  15400. // toGlobalPoint: function(point) {
  15401. // return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));
  15402. // },
  15403. /**
  15404. * Sets the position of the object taking into consideration the object's origin
  15405. * @param {fabric.Point} pos The new position of the object
  15406. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  15407. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  15408. * @return {void}
  15409. */
  15410. setPositionByOrigin: function(pos, originX, originY) {
  15411. var center = this.translateToCenterPoint(pos, originX, originY),
  15412. position = this.translateToOriginPoint(center, this.originX, this.originY);
  15413. this.set('left', position.x);
  15414. this.set('top', position.y);
  15415. },
  15416. /**
  15417. * @param {String} to One of 'left', 'center', 'right'
  15418. */
  15419. adjustPosition: function(to) {
  15420. var angle = degreesToRadians(this.angle),
  15421. hypotFull = this.getScaledWidth(),
  15422. xFull = fabric.util.cos(angle) * hypotFull,
  15423. yFull = fabric.util.sin(angle) * hypotFull,
  15424. offsetFrom, offsetTo;
  15425. //TODO: this function does not consider mixed situation like top, center.
  15426. if (typeof this.originX === 'string') {
  15427. offsetFrom = originXOffset[this.originX];
  15428. }
  15429. else {
  15430. offsetFrom = this.originX - 0.5;
  15431. }
  15432. if (typeof to === 'string') {
  15433. offsetTo = originXOffset[to];
  15434. }
  15435. else {
  15436. offsetTo = to - 0.5;
  15437. }
  15438. this.left += xFull * (offsetTo - offsetFrom);
  15439. this.top += yFull * (offsetTo - offsetFrom);
  15440. this.setCoords();
  15441. this.originX = to;
  15442. },
  15443. /**
  15444. * Sets the origin/position of the object to it's center point
  15445. * @private
  15446. * @return {void}
  15447. */
  15448. _setOriginToCenter: function() {
  15449. this._originalOriginX = this.originX;
  15450. this._originalOriginY = this.originY;
  15451. var center = this.getCenterPoint();
  15452. this.originX = 'center';
  15453. this.originY = 'center';
  15454. this.left = center.x;
  15455. this.top = center.y;
  15456. },
  15457. /**
  15458. * Resets the origin/position of the object to it's original origin
  15459. * @private
  15460. * @return {void}
  15461. */
  15462. _resetOrigin: function() {
  15463. var originPoint = this.translateToOriginPoint(
  15464. this.getCenterPoint(),
  15465. this._originalOriginX,
  15466. this._originalOriginY);
  15467. this.originX = this._originalOriginX;
  15468. this.originY = this._originalOriginY;
  15469. this.left = originPoint.x;
  15470. this.top = originPoint.y;
  15471. this._originalOriginX = null;
  15472. this._originalOriginY = null;
  15473. },
  15474. /**
  15475. * @private
  15476. */
  15477. _getLeftTopCoords: function() {
  15478. return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');
  15479. },
  15480. });
  15481. })();
  15482. (function() {
  15483. function arrayFromCoords(coords) {
  15484. return [
  15485. new fabric.Point(coords.tl.x, coords.tl.y),
  15486. new fabric.Point(coords.tr.x, coords.tr.y),
  15487. new fabric.Point(coords.br.x, coords.br.y),
  15488. new fabric.Point(coords.bl.x, coords.bl.y)
  15489. ];
  15490. }
  15491. var util = fabric.util,
  15492. degreesToRadians = util.degreesToRadians,
  15493. multiplyMatrices = util.multiplyTransformMatrices,
  15494. transformPoint = util.transformPoint;
  15495. util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15496. /**
  15497. * Describe object's corner position in canvas element coordinates.
  15498. * properties are depending on control keys and padding the main controls.
  15499. * each property is an object with x, y and corner.
  15500. * The `corner` property contains in a similar manner the 4 points of the
  15501. * interactive area of the corner.
  15502. * The coordinates depends from the controls positionHandler and are used
  15503. * to draw and locate controls
  15504. * @memberOf fabric.Object.prototype
  15505. */
  15506. oCoords: null,
  15507. /**
  15508. * Describe object's corner position in canvas object absolute coordinates
  15509. * properties are tl,tr,bl,br and describe the four main corner.
  15510. * each property is an object with x, y, instance of Fabric.Point.
  15511. * The coordinates depends from this properties: width, height, scaleX, scaleY
  15512. * skewX, skewY, angle, strokeWidth, top, left.
  15513. * Those coordinates are useful to understand where an object is. They get updated
  15514. * with oCoords but they do not need to be updated when zoom or panning change.
  15515. * The coordinates get updated with @method setCoords.
  15516. * You can calculate them without updating with @method calcACoords();
  15517. * @memberOf fabric.Object.prototype
  15518. */
  15519. aCoords: null,
  15520. /**
  15521. * Describe object's corner position in canvas element coordinates.
  15522. * includes padding. Used of object detection.
  15523. * set and refreshed with setCoords.
  15524. * @memberOf fabric.Object.prototype
  15525. */
  15526. lineCoords: null,
  15527. /**
  15528. * storage for object transform matrix
  15529. */
  15530. ownMatrixCache: null,
  15531. /**
  15532. * storage for object full transform matrix
  15533. */
  15534. matrixCache: null,
  15535. /**
  15536. * custom controls interface
  15537. * controls are added by default_controls.js
  15538. */
  15539. controls: { },
  15540. /**
  15541. * return correct set of coordinates for intersection
  15542. * this will return either aCoords or lineCoords.
  15543. * @param {Boolean} absolute will return aCoords if true or lineCoords
  15544. * @return {Object} {tl, tr, br, bl} points
  15545. */
  15546. _getCoords: function(absolute, calculate) {
  15547. if (calculate) {
  15548. return (absolute ? this.calcACoords() : this.calcLineCoords());
  15549. }
  15550. if (!this.aCoords || !this.lineCoords) {
  15551. this.setCoords(true);
  15552. }
  15553. return (absolute ? this.aCoords : this.lineCoords);
  15554. },
  15555. /**
  15556. * return correct set of coordinates for intersection
  15557. * this will return either aCoords or lineCoords.
  15558. * The coords are returned in an array.
  15559. * @return {Array} [tl, tr, br, bl] of points
  15560. */
  15561. getCoords: function(absolute, calculate) {
  15562. return arrayFromCoords(this._getCoords(absolute, calculate));
  15563. },
  15564. /**
  15565. * Checks if object intersects with an area formed by 2 points
  15566. * @param {Object} pointTL top-left point of area
  15567. * @param {Object} pointBR bottom-right point of area
  15568. * @param {Boolean} [absolute] use coordinates without viewportTransform
  15569. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  15570. * @return {Boolean} true if object intersects with an area formed by 2 points
  15571. */
  15572. intersectsWithRect: function(pointTL, pointBR, absolute, calculate) {
  15573. var coords = this.getCoords(absolute, calculate),
  15574. intersection = fabric.Intersection.intersectPolygonRectangle(
  15575. coords,
  15576. pointTL,
  15577. pointBR
  15578. );
  15579. return intersection.status === 'Intersection';
  15580. },
  15581. /**
  15582. * Checks if object intersects with another object
  15583. * @param {Object} other Object to test
  15584. * @param {Boolean} [absolute] use coordinates without viewportTransform
  15585. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  15586. * @return {Boolean} true if object intersects with another object
  15587. */
  15588. intersectsWithObject: function(other, absolute, calculate) {
  15589. var intersection = fabric.Intersection.intersectPolygonPolygon(
  15590. this.getCoords(absolute, calculate),
  15591. other.getCoords(absolute, calculate)
  15592. );
  15593. return intersection.status === 'Intersection'
  15594. || other.isContainedWithinObject(this, absolute, calculate)
  15595. || this.isContainedWithinObject(other, absolute, calculate);
  15596. },
  15597. /**
  15598. * Checks if object is fully contained within area of another object
  15599. * @param {Object} other Object to test
  15600. * @param {Boolean} [absolute] use coordinates without viewportTransform
  15601. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  15602. * @return {Boolean} true if object is fully contained within area of another object
  15603. */
  15604. isContainedWithinObject: function(other, absolute, calculate) {
  15605. var points = this.getCoords(absolute, calculate),
  15606. otherCoords = absolute ? other.aCoords : other.lineCoords,
  15607. i = 0, lines = other._getImageLines(otherCoords);
  15608. for (; i < 4; i++) {
  15609. if (!other.containsPoint(points[i], lines)) {
  15610. return false;
  15611. }
  15612. }
  15613. return true;
  15614. },
  15615. /**
  15616. * Checks if object is fully contained within area formed by 2 points
  15617. * @param {Object} pointTL top-left point of area
  15618. * @param {Object} pointBR bottom-right point of area
  15619. * @param {Boolean} [absolute] use coordinates without viewportTransform
  15620. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  15621. * @return {Boolean} true if object is fully contained within area formed by 2 points
  15622. */
  15623. isContainedWithinRect: function(pointTL, pointBR, absolute, calculate) {
  15624. var boundingRect = this.getBoundingRect(absolute, calculate);
  15625. return (
  15626. boundingRect.left >= pointTL.x &&
  15627. boundingRect.left + boundingRect.width <= pointBR.x &&
  15628. boundingRect.top >= pointTL.y &&
  15629. boundingRect.top + boundingRect.height <= pointBR.y
  15630. );
  15631. },
  15632. /**
  15633. * Checks if point is inside the object
  15634. * @param {fabric.Point} point Point to check against
  15635. * @param {Object} [lines] object returned from @method _getImageLines
  15636. * @param {Boolean} [absolute] use coordinates without viewportTransform
  15637. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  15638. * @return {Boolean} true if point is inside the object
  15639. */
  15640. containsPoint: function(point, lines, absolute, calculate) {
  15641. var coords = this._getCoords(absolute, calculate),
  15642. lines = lines || this._getImageLines(coords),
  15643. xPoints = this._findCrossPoints(point, lines);
  15644. // if xPoints is odd then point is inside the object
  15645. return (xPoints !== 0 && xPoints % 2 === 1);
  15646. },
  15647. /**
  15648. * Checks if object is contained within the canvas with current viewportTransform
  15649. * the check is done stopping at first point that appears on screen
  15650. * @param {Boolean} [calculate] use coordinates of current position instead of .aCoords
  15651. * @return {Boolean} true if object is fully or partially contained within canvas
  15652. */
  15653. isOnScreen: function(calculate) {
  15654. if (!this.canvas) {
  15655. return false;
  15656. }
  15657. var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;
  15658. var points = this.getCoords(true, calculate);
  15659. // if some point is on screen, the object is on screen.
  15660. if (points.some(function(point) {
  15661. return point.x <= pointBR.x && point.x >= pointTL.x &&
  15662. point.y <= pointBR.y && point.y >= pointTL.y;
  15663. })) {
  15664. return true;
  15665. }
  15666. // no points on screen, check intersection with absolute coordinates
  15667. if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {
  15668. return true;
  15669. }
  15670. return this._containsCenterOfCanvas(pointTL, pointBR, calculate);
  15671. },
  15672. /**
  15673. * Checks if the object contains the midpoint between canvas extremities
  15674. * Does not make sense outside the context of isOnScreen and isPartiallyOnScreen
  15675. * @private
  15676. * @param {Fabric.Point} pointTL Top Left point
  15677. * @param {Fabric.Point} pointBR Top Right point
  15678. * @param {Boolean} calculate use coordinates of current position instead of .oCoords
  15679. * @return {Boolean} true if the object contains the point
  15680. */
  15681. _containsCenterOfCanvas: function(pointTL, pointBR, calculate) {
  15682. // worst case scenario the object is so big that contains the screen
  15683. var centerPoint = { x: (pointTL.x + pointBR.x) / 2, y: (pointTL.y + pointBR.y) / 2 };
  15684. if (this.containsPoint(centerPoint, null, true, calculate)) {
  15685. return true;
  15686. }
  15687. return false;
  15688. },
  15689. /**
  15690. * Checks if object is partially contained within the canvas with current viewportTransform
  15691. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords
  15692. * @return {Boolean} true if object is partially contained within canvas
  15693. */
  15694. isPartiallyOnScreen: function(calculate) {
  15695. if (!this.canvas) {
  15696. return false;
  15697. }
  15698. var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;
  15699. if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {
  15700. return true;
  15701. }
  15702. var allPointsAreOutside = this.getCoords(true, calculate).every(function(point) {
  15703. return (point.x >= pointBR.x || point.x <= pointTL.x) &&
  15704. (point.y >= pointBR.y || point.y <= pointTL.y);
  15705. });
  15706. return allPointsAreOutside && this._containsCenterOfCanvas(pointTL, pointBR, calculate);
  15707. },
  15708. /**
  15709. * Method that returns an object with the object edges in it, given the coordinates of the corners
  15710. * @private
  15711. * @param {Object} oCoords Coordinates of the object corners
  15712. */
  15713. _getImageLines: function(oCoords) {
  15714. var lines = {
  15715. topline: {
  15716. o: oCoords.tl,
  15717. d: oCoords.tr
  15718. },
  15719. rightline: {
  15720. o: oCoords.tr,
  15721. d: oCoords.br
  15722. },
  15723. bottomline: {
  15724. o: oCoords.br,
  15725. d: oCoords.bl
  15726. },
  15727. leftline: {
  15728. o: oCoords.bl,
  15729. d: oCoords.tl
  15730. }
  15731. };
  15732. // // debugging
  15733. // if (this.canvas.contextTop) {
  15734. // this.canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);
  15735. // this.canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);
  15736. //
  15737. // this.canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);
  15738. // this.canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);
  15739. //
  15740. // this.canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);
  15741. // this.canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);
  15742. //
  15743. // this.canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);
  15744. // this.canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);
  15745. // }
  15746. return lines;
  15747. },
  15748. /**
  15749. * Helper method to determine how many cross points are between the 4 object edges
  15750. * and the horizontal line determined by a point on canvas
  15751. * @private
  15752. * @param {fabric.Point} point Point to check
  15753. * @param {Object} lines Coordinates of the object being evaluated
  15754. */
  15755. // remove yi, not used but left code here just in case.
  15756. _findCrossPoints: function(point, lines) {
  15757. var b1, b2, a1, a2, xi, // yi,
  15758. xcount = 0,
  15759. iLine;
  15760. for (var lineKey in lines) {
  15761. iLine = lines[lineKey];
  15762. // optimisation 1: line below point. no cross
  15763. if ((iLine.o.y < point.y) && (iLine.d.y < point.y)) {
  15764. continue;
  15765. }
  15766. // optimisation 2: line above point. no cross
  15767. if ((iLine.o.y >= point.y) && (iLine.d.y >= point.y)) {
  15768. continue;
  15769. }
  15770. // optimisation 3: vertical line case
  15771. if ((iLine.o.x === iLine.d.x) && (iLine.o.x >= point.x)) {
  15772. xi = iLine.o.x;
  15773. // yi = point.y;
  15774. }
  15775. // calculate the intersection point
  15776. else {
  15777. b1 = 0;
  15778. b2 = (iLine.d.y - iLine.o.y) / (iLine.d.x - iLine.o.x);
  15779. a1 = point.y - b1 * point.x;
  15780. a2 = iLine.o.y - b2 * iLine.o.x;
  15781. xi = -(a1 - a2) / (b1 - b2);
  15782. // yi = a1 + b1 * xi;
  15783. }
  15784. // dont count xi < point.x cases
  15785. if (xi >= point.x) {
  15786. xcount += 1;
  15787. }
  15788. // optimisation 4: specific for square images
  15789. if (xcount === 2) {
  15790. break;
  15791. }
  15792. }
  15793. return xcount;
  15794. },
  15795. /**
  15796. * Returns coordinates of object's bounding rectangle (left, top, width, height)
  15797. * the box is intended as aligned to axis of canvas.
  15798. * @param {Boolean} [absolute] use coordinates without viewportTransform
  15799. * @param {Boolean} [calculate] use coordinates of current position instead of .oCoords / .aCoords
  15800. * @return {Object} Object with left, top, width, height properties
  15801. */
  15802. getBoundingRect: function(absolute, calculate) {
  15803. var coords = this.getCoords(absolute, calculate);
  15804. return util.makeBoundingBoxFromPoints(coords);
  15805. },
  15806. /**
  15807. * Returns width of an object's bounding box counting transformations
  15808. * before 2.0 it was named getWidth();
  15809. * @return {Number} width value
  15810. */
  15811. getScaledWidth: function() {
  15812. return this._getTransformedDimensions().x;
  15813. },
  15814. /**
  15815. * Returns height of an object bounding box counting transformations
  15816. * before 2.0 it was named getHeight();
  15817. * @return {Number} height value
  15818. */
  15819. getScaledHeight: function() {
  15820. return this._getTransformedDimensions().y;
  15821. },
  15822. /**
  15823. * Makes sure the scale is valid and modifies it if necessary
  15824. * @private
  15825. * @param {Number} value
  15826. * @return {Number}
  15827. */
  15828. _constrainScale: function(value) {
  15829. if (Math.abs(value) < this.minScaleLimit) {
  15830. if (value < 0) {
  15831. return -this.minScaleLimit;
  15832. }
  15833. else {
  15834. return this.minScaleLimit;
  15835. }
  15836. }
  15837. else if (value === 0) {
  15838. return 0.0001;
  15839. }
  15840. return value;
  15841. },
  15842. /**
  15843. * Scales an object (equally by x and y)
  15844. * @param {Number} value Scale factor
  15845. * @return {fabric.Object} thisArg
  15846. * @chainable
  15847. */
  15848. scale: function(value) {
  15849. this._set('scaleX', value);
  15850. this._set('scaleY', value);
  15851. return this.setCoords();
  15852. },
  15853. /**
  15854. * Scales an object to a given width, with respect to bounding box (scaling by x/y equally)
  15855. * @param {Number} value New width value
  15856. * @param {Boolean} absolute ignore viewport
  15857. * @return {fabric.Object} thisArg
  15858. * @chainable
  15859. */
  15860. scaleToWidth: function(value, absolute) {
  15861. // adjust to bounding rect factor so that rotated shapes would fit as well
  15862. var boundingRectFactor = this.getBoundingRect(absolute).width / this.getScaledWidth();
  15863. return this.scale(value / this.width / boundingRectFactor);
  15864. },
  15865. /**
  15866. * Scales an object to a given height, with respect to bounding box (scaling by x/y equally)
  15867. * @param {Number} value New height value
  15868. * @param {Boolean} absolute ignore viewport
  15869. * @return {fabric.Object} thisArg
  15870. * @chainable
  15871. */
  15872. scaleToHeight: function(value, absolute) {
  15873. // adjust to bounding rect factor so that rotated shapes would fit as well
  15874. var boundingRectFactor = this.getBoundingRect(absolute).height / this.getScaledHeight();
  15875. return this.scale(value / this.height / boundingRectFactor);
  15876. },
  15877. calcLineCoords: function() {
  15878. var vpt = this.getViewportTransform(),
  15879. padding = this.padding, angle = degreesToRadians(this.angle),
  15880. cos = util.cos(angle), sin = util.sin(angle),
  15881. cosP = cos * padding, sinP = sin * padding, cosPSinP = cosP + sinP,
  15882. cosPMinusSinP = cosP - sinP, aCoords = this.calcACoords();
  15883. var lineCoords = {
  15884. tl: transformPoint(aCoords.tl, vpt),
  15885. tr: transformPoint(aCoords.tr, vpt),
  15886. bl: transformPoint(aCoords.bl, vpt),
  15887. br: transformPoint(aCoords.br, vpt),
  15888. };
  15889. if (padding) {
  15890. lineCoords.tl.x -= cosPMinusSinP;
  15891. lineCoords.tl.y -= cosPSinP;
  15892. lineCoords.tr.x += cosPSinP;
  15893. lineCoords.tr.y -= cosPMinusSinP;
  15894. lineCoords.bl.x -= cosPSinP;
  15895. lineCoords.bl.y += cosPMinusSinP;
  15896. lineCoords.br.x += cosPMinusSinP;
  15897. lineCoords.br.y += cosPSinP;
  15898. }
  15899. return lineCoords;
  15900. },
  15901. calcOCoords: function() {
  15902. var rotateMatrix = this._calcRotateMatrix(),
  15903. translateMatrix = this._calcTranslateMatrix(),
  15904. vpt = this.getViewportTransform(),
  15905. startMatrix = multiplyMatrices(vpt, translateMatrix),
  15906. finalMatrix = multiplyMatrices(startMatrix, rotateMatrix),
  15907. finalMatrix = multiplyMatrices(finalMatrix, [1 / vpt[0], 0, 0, 1 / vpt[3], 0, 0]),
  15908. dim = this._calculateCurrentDimensions(),
  15909. coords = {};
  15910. this.forEachControl(function(control, key, fabricObject) {
  15911. coords[key] = control.positionHandler(dim, finalMatrix, fabricObject);
  15912. });
  15913. // debug code
  15914. // var canvas = this.canvas;
  15915. // setTimeout(function() {
  15916. // canvas.contextTop.clearRect(0, 0, 700, 700);
  15917. // canvas.contextTop.fillStyle = 'green';
  15918. // Object.keys(coords).forEach(function(key) {
  15919. // var control = coords[key];
  15920. // canvas.contextTop.fillRect(control.x, control.y, 3, 3);
  15921. // });
  15922. // }, 50);
  15923. return coords;
  15924. },
  15925. calcACoords: function() {
  15926. var rotateMatrix = this._calcRotateMatrix(),
  15927. translateMatrix = this._calcTranslateMatrix(),
  15928. finalMatrix = multiplyMatrices(translateMatrix, rotateMatrix),
  15929. dim = this._getTransformedDimensions(),
  15930. w = dim.x / 2, h = dim.y / 2;
  15931. return {
  15932. // corners
  15933. tl: transformPoint({ x: -w, y: -h }, finalMatrix),
  15934. tr: transformPoint({ x: w, y: -h }, finalMatrix),
  15935. bl: transformPoint({ x: -w, y: h }, finalMatrix),
  15936. br: transformPoint({ x: w, y: h }, finalMatrix)
  15937. };
  15938. },
  15939. /**
  15940. * Sets corner and controls position coordinates based on current angle, width and height, left and top.
  15941. * oCoords are used to find the corners
  15942. * aCoords are used to quickly find an object on the canvas
  15943. * lineCoords are used to quickly find object during pointer events.
  15944. * See {@link https://github.com/fabricjs/fabric.js/wiki/When-to-call-setCoords} and {@link http://fabricjs.com/fabric-gotchas}
  15945. *
  15946. * @param {Boolean} [skipCorners] skip calculation of oCoords.
  15947. * @return {fabric.Object} thisArg
  15948. * @chainable
  15949. */
  15950. setCoords: function(skipCorners) {
  15951. this.aCoords = this.calcACoords();
  15952. // in case we are in a group, for how the inner group target check works,
  15953. // lineCoords are exactly aCoords. Since the vpt gets absorbed by the normalized pointer.
  15954. this.lineCoords = this.group ? this.aCoords : this.calcLineCoords();
  15955. if (skipCorners) {
  15956. return this;
  15957. }
  15958. // set coordinates of the draggable boxes in the corners used to scale/rotate the image
  15959. this.oCoords = this.calcOCoords();
  15960. this._setCornerCoords && this._setCornerCoords();
  15961. return this;
  15962. },
  15963. /**
  15964. * calculate rotation matrix of an object
  15965. * @return {Array} rotation matrix for the object
  15966. */
  15967. _calcRotateMatrix: function() {
  15968. return util.calcRotateMatrix(this);
  15969. },
  15970. /**
  15971. * calculate the translation matrix for an object transform
  15972. * @return {Array} rotation matrix for the object
  15973. */
  15974. _calcTranslateMatrix: function() {
  15975. var center = this.getCenterPoint();
  15976. return [1, 0, 0, 1, center.x, center.y];
  15977. },
  15978. transformMatrixKey: function(skipGroup) {
  15979. var sep = '_', prefix = '';
  15980. if (!skipGroup && this.group) {
  15981. prefix = this.group.transformMatrixKey(skipGroup) + sep;
  15982. };
  15983. return prefix + this.top + sep + this.left + sep + this.scaleX + sep + this.scaleY +
  15984. sep + this.skewX + sep + this.skewY + sep + this.angle + sep + this.originX + sep + this.originY +
  15985. sep + this.width + sep + this.height + sep + this.strokeWidth + this.flipX + this.flipY;
  15986. },
  15987. /**
  15988. * calculate transform matrix that represents the current transformations from the
  15989. * object's properties.
  15990. * @param {Boolean} [skipGroup] return transform matrix for object not counting parent transformations
  15991. * There are some situation in which this is useful to avoid the fake rotation.
  15992. * @return {Array} transform matrix for the object
  15993. */
  15994. calcTransformMatrix: function(skipGroup) {
  15995. var matrix = this.calcOwnMatrix();
  15996. if (skipGroup || !this.group) {
  15997. return matrix;
  15998. }
  15999. var key = this.transformMatrixKey(skipGroup), cache = this.matrixCache || (this.matrixCache = {});
  16000. if (cache.key === key) {
  16001. return cache.value;
  16002. }
  16003. if (this.group) {
  16004. matrix = multiplyMatrices(this.group.calcTransformMatrix(false), matrix);
  16005. }
  16006. cache.key = key;
  16007. cache.value = matrix;
  16008. return matrix;
  16009. },
  16010. /**
  16011. * calculate transform matrix that represents the current transformations from the
  16012. * object's properties, this matrix does not include the group transformation
  16013. * @return {Array} transform matrix for the object
  16014. */
  16015. calcOwnMatrix: function() {
  16016. var key = this.transformMatrixKey(true), cache = this.ownMatrixCache || (this.ownMatrixCache = {});
  16017. if (cache.key === key) {
  16018. return cache.value;
  16019. }
  16020. var tMatrix = this._calcTranslateMatrix(),
  16021. options = {
  16022. angle: this.angle,
  16023. translateX: tMatrix[4],
  16024. translateY: tMatrix[5],
  16025. scaleX: this.scaleX,
  16026. scaleY: this.scaleY,
  16027. skewX: this.skewX,
  16028. skewY: this.skewY,
  16029. flipX: this.flipX,
  16030. flipY: this.flipY,
  16031. };
  16032. cache.key = key;
  16033. cache.value = util.composeMatrix(options);
  16034. return cache.value;
  16035. },
  16036. /*
  16037. * Calculate object dimensions from its properties
  16038. * @private
  16039. * @return {Object} .x width dimension
  16040. * @return {Object} .y height dimension
  16041. */
  16042. _getNonTransformedDimensions: function() {
  16043. var strokeWidth = this.strokeWidth,
  16044. w = this.width + strokeWidth,
  16045. h = this.height + strokeWidth;
  16046. return { x: w, y: h };
  16047. },
  16048. /*
  16049. * Calculate object bounding box dimensions from its properties scale, skew.
  16050. * @param {Number} skewX, a value to override current skewX
  16051. * @param {Number} skewY, a value to override current skewY
  16052. * @private
  16053. * @return {Object} .x width dimension
  16054. * @return {Object} .y height dimension
  16055. */
  16056. _getTransformedDimensions: function(skewX, skewY) {
  16057. if (typeof skewX === 'undefined') {
  16058. skewX = this.skewX;
  16059. }
  16060. if (typeof skewY === 'undefined') {
  16061. skewY = this.skewY;
  16062. }
  16063. var dimensions, dimX, dimY,
  16064. noSkew = skewX === 0 && skewY === 0;
  16065. if (this.strokeUniform) {
  16066. dimX = this.width;
  16067. dimY = this.height;
  16068. }
  16069. else {
  16070. dimensions = this._getNonTransformedDimensions();
  16071. dimX = dimensions.x;
  16072. dimY = dimensions.y;
  16073. }
  16074. if (noSkew) {
  16075. return this._finalizeDimensions(dimX * this.scaleX, dimY * this.scaleY);
  16076. }
  16077. var bbox = util.sizeAfterTransform(dimX, dimY, {
  16078. scaleX: this.scaleX,
  16079. scaleY: this.scaleY,
  16080. skewX: skewX,
  16081. skewY: skewY,
  16082. });
  16083. return this._finalizeDimensions(bbox.x, bbox.y);
  16084. },
  16085. /*
  16086. * Calculate object bounding box dimensions from its properties scale, skew.
  16087. * @param Number width width of the bbox
  16088. * @param Number height height of the bbox
  16089. * @private
  16090. * @return {Object} .x finalized width dimension
  16091. * @return {Object} .y finalized height dimension
  16092. */
  16093. _finalizeDimensions: function(width, height) {
  16094. return this.strokeUniform ?
  16095. { x: width + this.strokeWidth, y: height + this.strokeWidth }
  16096. :
  16097. { x: width, y: height };
  16098. },
  16099. /*
  16100. * Calculate object dimensions for controls box, including padding and canvas zoom.
  16101. * and active selection
  16102. * private
  16103. */
  16104. _calculateCurrentDimensions: function() {
  16105. var vpt = this.getViewportTransform(),
  16106. dim = this._getTransformedDimensions(),
  16107. p = transformPoint(dim, vpt, true);
  16108. return p.scalarAdd(2 * this.padding);
  16109. },
  16110. });
  16111. })();
  16112. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  16113. /**
  16114. * Moves an object to the bottom of the stack of drawn objects
  16115. * @return {fabric.Object} thisArg
  16116. * @chainable
  16117. */
  16118. sendToBack: function() {
  16119. if (this.group) {
  16120. fabric.StaticCanvas.prototype.sendToBack.call(this.group, this);
  16121. }
  16122. else if (this.canvas) {
  16123. this.canvas.sendToBack(this);
  16124. }
  16125. return this;
  16126. },
  16127. /**
  16128. * Moves an object to the top of the stack of drawn objects
  16129. * @return {fabric.Object} thisArg
  16130. * @chainable
  16131. */
  16132. bringToFront: function() {
  16133. if (this.group) {
  16134. fabric.StaticCanvas.prototype.bringToFront.call(this.group, this);
  16135. }
  16136. else if (this.canvas) {
  16137. this.canvas.bringToFront(this);
  16138. }
  16139. return this;
  16140. },
  16141. /**
  16142. * Moves an object down in stack of drawn objects
  16143. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  16144. * @return {fabric.Object} thisArg
  16145. * @chainable
  16146. */
  16147. sendBackwards: function(intersecting) {
  16148. if (this.group) {
  16149. fabric.StaticCanvas.prototype.sendBackwards.call(this.group, this, intersecting);
  16150. }
  16151. else if (this.canvas) {
  16152. this.canvas.sendBackwards(this, intersecting);
  16153. }
  16154. return this;
  16155. },
  16156. /**
  16157. * Moves an object up in stack of drawn objects
  16158. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  16159. * @return {fabric.Object} thisArg
  16160. * @chainable
  16161. */
  16162. bringForward: function(intersecting) {
  16163. if (this.group) {
  16164. fabric.StaticCanvas.prototype.bringForward.call(this.group, this, intersecting);
  16165. }
  16166. else if (this.canvas) {
  16167. this.canvas.bringForward(this, intersecting);
  16168. }
  16169. return this;
  16170. },
  16171. /**
  16172. * Moves an object to specified level in stack of drawn objects
  16173. * @param {Number} index New position of object
  16174. * @return {fabric.Object} thisArg
  16175. * @chainable
  16176. */
  16177. moveTo: function(index) {
  16178. if (this.group && this.group.type !== 'activeSelection') {
  16179. fabric.StaticCanvas.prototype.moveTo.call(this.group, this, index);
  16180. }
  16181. else if (this.canvas) {
  16182. this.canvas.moveTo(this, index);
  16183. }
  16184. return this;
  16185. }
  16186. });
  16187. /* _TO_SVG_START_ */
  16188. (function() {
  16189. function getSvgColorString(prop, value) {
  16190. if (!value) {
  16191. return prop + ': none; ';
  16192. }
  16193. else if (value.toLive) {
  16194. return prop + ': url(#SVGID_' + value.id + '); ';
  16195. }
  16196. else {
  16197. var color = new fabric.Color(value),
  16198. str = prop + ': ' + color.toRgb() + '; ',
  16199. opacity = color.getAlpha();
  16200. if (opacity !== 1) {
  16201. //change the color in rgb + opacity
  16202. str += prop + '-opacity: ' + opacity.toString() + '; ';
  16203. }
  16204. return str;
  16205. }
  16206. }
  16207. var toFixed = fabric.util.toFixed;
  16208. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  16209. /**
  16210. * Returns styles-string for svg-export
  16211. * @param {Boolean} skipShadow a boolean to skip shadow filter output
  16212. * @return {String}
  16213. */
  16214. getSvgStyles: function(skipShadow) {
  16215. var fillRule = this.fillRule ? this.fillRule : 'nonzero',
  16216. strokeWidth = this.strokeWidth ? this.strokeWidth : '0',
  16217. strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(' ') : 'none',
  16218. strokeDashOffset = this.strokeDashOffset ? this.strokeDashOffset : '0',
  16219. strokeLineCap = this.strokeLineCap ? this.strokeLineCap : 'butt',
  16220. strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : 'miter',
  16221. strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : '4',
  16222. opacity = typeof this.opacity !== 'undefined' ? this.opacity : '1',
  16223. visibility = this.visible ? '' : ' visibility: hidden;',
  16224. filter = skipShadow ? '' : this.getSvgFilter(),
  16225. fill = getSvgColorString('fill', this.fill),
  16226. stroke = getSvgColorString('stroke', this.stroke);
  16227. return [
  16228. stroke,
  16229. 'stroke-width: ', strokeWidth, '; ',
  16230. 'stroke-dasharray: ', strokeDashArray, '; ',
  16231. 'stroke-linecap: ', strokeLineCap, '; ',
  16232. 'stroke-dashoffset: ', strokeDashOffset, '; ',
  16233. 'stroke-linejoin: ', strokeLineJoin, '; ',
  16234. 'stroke-miterlimit: ', strokeMiterLimit, '; ',
  16235. fill,
  16236. 'fill-rule: ', fillRule, '; ',
  16237. 'opacity: ', opacity, ';',
  16238. filter,
  16239. visibility
  16240. ].join('');
  16241. },
  16242. /**
  16243. * Returns styles-string for svg-export
  16244. * @param {Object} style the object from which to retrieve style properties
  16245. * @param {Boolean} useWhiteSpace a boolean to include an additional attribute in the style.
  16246. * @return {String}
  16247. */
  16248. getSvgSpanStyles: function(style, useWhiteSpace) {
  16249. var term = '; ';
  16250. var fontFamily = style.fontFamily ?
  16251. 'font-family: ' + (((style.fontFamily.indexOf('\'') === -1 && style.fontFamily.indexOf('"') === -1) ?
  16252. '\'' + style.fontFamily + '\'' : style.fontFamily)) + term : '';
  16253. var strokeWidth = style.strokeWidth ? 'stroke-width: ' + style.strokeWidth + term : '',
  16254. fontFamily = fontFamily,
  16255. fontSize = style.fontSize ? 'font-size: ' + style.fontSize + 'px' + term : '',
  16256. fontStyle = style.fontStyle ? 'font-style: ' + style.fontStyle + term : '',
  16257. fontWeight = style.fontWeight ? 'font-weight: ' + style.fontWeight + term : '',
  16258. fill = style.fill ? getSvgColorString('fill', style.fill) : '',
  16259. stroke = style.stroke ? getSvgColorString('stroke', style.stroke) : '',
  16260. textDecoration = this.getSvgTextDecoration(style),
  16261. deltaY = style.deltaY ? 'baseline-shift: ' + (-style.deltaY) + '; ' : '';
  16262. if (textDecoration) {
  16263. textDecoration = 'text-decoration: ' + textDecoration + term;
  16264. }
  16265. return [
  16266. stroke,
  16267. strokeWidth,
  16268. fontFamily,
  16269. fontSize,
  16270. fontStyle,
  16271. fontWeight,
  16272. textDecoration,
  16273. fill,
  16274. deltaY,
  16275. useWhiteSpace ? 'white-space: pre; ' : ''
  16276. ].join('');
  16277. },
  16278. /**
  16279. * Returns text-decoration property for svg-export
  16280. * @param {Object} style the object from which to retrieve style properties
  16281. * @return {String}
  16282. */
  16283. getSvgTextDecoration: function(style) {
  16284. return ['overline', 'underline', 'line-through'].filter(function(decoration) {
  16285. return style[decoration.replace('-', '')];
  16286. }).join(' ');
  16287. },
  16288. /**
  16289. * Returns filter for svg shadow
  16290. * @return {String}
  16291. */
  16292. getSvgFilter: function() {
  16293. return this.shadow ? 'filter: url(#SVGID_' + this.shadow.id + ');' : '';
  16294. },
  16295. /**
  16296. * Returns id attribute for svg output
  16297. * @return {String}
  16298. */
  16299. getSvgCommons: function() {
  16300. return [
  16301. this.id ? 'id="' + this.id + '" ' : '',
  16302. this.clipPath ? 'clip-path="url(#' + this.clipPath.clipPathId + ')" ' : '',
  16303. ].join('');
  16304. },
  16305. /**
  16306. * Returns transform-string for svg-export
  16307. * @param {Boolean} use the full transform or the single object one.
  16308. * @return {String}
  16309. */
  16310. getSvgTransform: function(full, additionalTransform) {
  16311. var transform = full ? this.calcTransformMatrix() : this.calcOwnMatrix(),
  16312. svgTransform = 'transform="' + fabric.util.matrixToSVG(transform);
  16313. return svgTransform +
  16314. (additionalTransform || '') + '" ';
  16315. },
  16316. _setSVGBg: function(textBgRects) {
  16317. if (this.backgroundColor) {
  16318. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;
  16319. textBgRects.push(
  16320. '\t\t<rect ',
  16321. this._getFillAttributes(this.backgroundColor),
  16322. ' x="',
  16323. toFixed(-this.width / 2, NUM_FRACTION_DIGITS),
  16324. '" y="',
  16325. toFixed(-this.height / 2, NUM_FRACTION_DIGITS),
  16326. '" width="',
  16327. toFixed(this.width, NUM_FRACTION_DIGITS),
  16328. '" height="',
  16329. toFixed(this.height, NUM_FRACTION_DIGITS),
  16330. '"></rect>\n');
  16331. }
  16332. },
  16333. /**
  16334. * Returns svg representation of an instance
  16335. * @param {Function} [reviver] Method for further parsing of svg representation.
  16336. * @return {String} svg representation of an instance
  16337. */
  16338. toSVG: function(reviver) {
  16339. return this._createBaseSVGMarkup(this._toSVG(reviver), { reviver: reviver });
  16340. },
  16341. /**
  16342. * Returns svg clipPath representation of an instance
  16343. * @param {Function} [reviver] Method for further parsing of svg representation.
  16344. * @return {String} svg representation of an instance
  16345. */
  16346. toClipPathSVG: function(reviver) {
  16347. return '\t' + this._createBaseClipPathSVGMarkup(this._toSVG(reviver), { reviver: reviver });
  16348. },
  16349. /**
  16350. * @private
  16351. */
  16352. _createBaseClipPathSVGMarkup: function(objectMarkup, options) {
  16353. options = options || {};
  16354. var reviver = options.reviver,
  16355. additionalTransform = options.additionalTransform || '',
  16356. commonPieces = [
  16357. this.getSvgTransform(true, additionalTransform),
  16358. this.getSvgCommons(),
  16359. ].join(''),
  16360. // insert commons in the markup, style and svgCommons
  16361. index = objectMarkup.indexOf('COMMON_PARTS');
  16362. objectMarkup[index] = commonPieces;
  16363. return reviver ? reviver(objectMarkup.join('')) : objectMarkup.join('');
  16364. },
  16365. /**
  16366. * @private
  16367. */
  16368. _createBaseSVGMarkup: function(objectMarkup, options) {
  16369. options = options || {};
  16370. var noStyle = options.noStyle,
  16371. reviver = options.reviver,
  16372. styleInfo = noStyle ? '' : 'style="' + this.getSvgStyles() + '" ',
  16373. shadowInfo = options.withShadow ? 'style="' + this.getSvgFilter() + '" ' : '',
  16374. clipPath = this.clipPath,
  16375. vectorEffect = this.strokeUniform ? 'vector-effect="non-scaling-stroke" ' : '',
  16376. absoluteClipPath = clipPath && clipPath.absolutePositioned,
  16377. stroke = this.stroke, fill = this.fill, shadow = this.shadow,
  16378. commonPieces, markup = [], clipPathMarkup,
  16379. // insert commons in the markup, style and svgCommons
  16380. index = objectMarkup.indexOf('COMMON_PARTS'),
  16381. additionalTransform = options.additionalTransform;
  16382. if (clipPath) {
  16383. clipPath.clipPathId = 'CLIPPATH_' + fabric.Object.__uid++;
  16384. clipPathMarkup = '<clipPath id="' + clipPath.clipPathId + '" >\n' +
  16385. clipPath.toClipPathSVG(reviver) +
  16386. '</clipPath>\n';
  16387. }
  16388. if (absoluteClipPath) {
  16389. markup.push(
  16390. '<g ', shadowInfo, this.getSvgCommons(), ' >\n'
  16391. );
  16392. }
  16393. markup.push(
  16394. '<g ',
  16395. this.getSvgTransform(false),
  16396. !absoluteClipPath ? shadowInfo + this.getSvgCommons() : '',
  16397. ' >\n'
  16398. );
  16399. commonPieces = [
  16400. styleInfo,
  16401. vectorEffect,
  16402. noStyle ? '' : this.addPaintOrder(), ' ',
  16403. additionalTransform ? 'transform="' + additionalTransform + '" ' : '',
  16404. ].join('');
  16405. objectMarkup[index] = commonPieces;
  16406. if (fill && fill.toLive) {
  16407. markup.push(fill.toSVG(this));
  16408. }
  16409. if (stroke && stroke.toLive) {
  16410. markup.push(stroke.toSVG(this));
  16411. }
  16412. if (shadow) {
  16413. markup.push(shadow.toSVG(this));
  16414. }
  16415. if (clipPath) {
  16416. markup.push(clipPathMarkup);
  16417. }
  16418. markup.push(objectMarkup.join(''));
  16419. markup.push('</g>\n');
  16420. absoluteClipPath && markup.push('</g>\n');
  16421. return reviver ? reviver(markup.join('')) : markup.join('');
  16422. },
  16423. addPaintOrder: function() {
  16424. return this.paintFirst !== 'fill' ? ' paint-order="' + this.paintFirst + '" ' : '';
  16425. }
  16426. });
  16427. })();
  16428. /* _TO_SVG_END_ */
  16429. (function() {
  16430. var extend = fabric.util.object.extend,
  16431. originalSet = 'stateProperties';
  16432. /*
  16433. Depends on `stateProperties`
  16434. */
  16435. function saveProps(origin, destination, props) {
  16436. var tmpObj = { }, deep = true;
  16437. props.forEach(function(prop) {
  16438. tmpObj[prop] = origin[prop];
  16439. });
  16440. extend(origin[destination], tmpObj, deep);
  16441. }
  16442. function _isEqual(origValue, currentValue, firstPass) {
  16443. if (origValue === currentValue) {
  16444. // if the objects are identical, return
  16445. return true;
  16446. }
  16447. else if (Array.isArray(origValue)) {
  16448. if (!Array.isArray(currentValue) || origValue.length !== currentValue.length) {
  16449. return false;
  16450. }
  16451. for (var i = 0, len = origValue.length; i < len; i++) {
  16452. if (!_isEqual(origValue[i], currentValue[i])) {
  16453. return false;
  16454. }
  16455. }
  16456. return true;
  16457. }
  16458. else if (origValue && typeof origValue === 'object') {
  16459. var keys = Object.keys(origValue), key;
  16460. if (!currentValue ||
  16461. typeof currentValue !== 'object' ||
  16462. (!firstPass && keys.length !== Object.keys(currentValue).length)
  16463. ) {
  16464. return false;
  16465. }
  16466. for (var i = 0, len = keys.length; i < len; i++) {
  16467. key = keys[i];
  16468. // since clipPath is in the statefull cache list and the clipPath objects
  16469. // would be iterated as an object, this would lead to possible infinite recursion
  16470. // we do not want to compare those.
  16471. if (key === 'canvas' || key === 'group') {
  16472. continue;
  16473. }
  16474. if (!_isEqual(origValue[key], currentValue[key])) {
  16475. return false;
  16476. }
  16477. }
  16478. return true;
  16479. }
  16480. }
  16481. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  16482. /**
  16483. * Returns true if object state (one of its state properties) was changed
  16484. * @param {String} [propertySet] optional name for the set of property we want to save
  16485. * @return {Boolean} true if instance' state has changed since `{@link fabric.Object#saveState}` was called
  16486. */
  16487. hasStateChanged: function(propertySet) {
  16488. propertySet = propertySet || originalSet;
  16489. var dashedPropertySet = '_' + propertySet;
  16490. if (Object.keys(this[dashedPropertySet]).length < this[propertySet].length) {
  16491. return true;
  16492. }
  16493. return !_isEqual(this[dashedPropertySet], this, true);
  16494. },
  16495. /**
  16496. * Saves state of an object
  16497. * @param {Object} [options] Object with additional `stateProperties` array to include when saving state
  16498. * @return {fabric.Object} thisArg
  16499. */
  16500. saveState: function(options) {
  16501. var propertySet = options && options.propertySet || originalSet,
  16502. destination = '_' + propertySet;
  16503. if (!this[destination]) {
  16504. return this.setupState(options);
  16505. }
  16506. saveProps(this, destination, this[propertySet]);
  16507. if (options && options.stateProperties) {
  16508. saveProps(this, destination, options.stateProperties);
  16509. }
  16510. return this;
  16511. },
  16512. /**
  16513. * Setups state of an object
  16514. * @param {Object} [options] Object with additional `stateProperties` array to include when saving state
  16515. * @return {fabric.Object} thisArg
  16516. */
  16517. setupState: function(options) {
  16518. options = options || { };
  16519. var propertySet = options.propertySet || originalSet;
  16520. options.propertySet = propertySet;
  16521. this['_' + propertySet] = { };
  16522. this.saveState(options);
  16523. return this;
  16524. }
  16525. });
  16526. })();
  16527. (function() {
  16528. var degreesToRadians = fabric.util.degreesToRadians;
  16529. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  16530. /**
  16531. * Determines which corner has been clicked
  16532. * @private
  16533. * @param {Object} pointer The pointer indicating the mouse position
  16534. * @return {String|Boolean} corner code (tl, tr, bl, br, etc.), or false if nothing is found
  16535. */
  16536. _findTargetCorner: function(pointer, forTouch) {
  16537. // objects in group, anykind, are not self modificable,
  16538. // must not return an hovered corner.
  16539. if (!this.hasControls || this.group || (!this.canvas || this.canvas._activeObject !== this)) {
  16540. return false;
  16541. }
  16542. var ex = pointer.x,
  16543. ey = pointer.y,
  16544. xPoints,
  16545. lines, keys = Object.keys(this.oCoords),
  16546. j = keys.length - 1, i;
  16547. this.__corner = 0;
  16548. // cycle in reverse order so we pick first the one on top
  16549. for (; j >= 0; j--) {
  16550. i = keys[j];
  16551. if (!this.isControlVisible(i)) {
  16552. continue;
  16553. }
  16554. lines = this._getImageLines(forTouch ? this.oCoords[i].touchCorner : this.oCoords[i].corner);
  16555. // // debugging
  16556. //
  16557. // this.canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);
  16558. // this.canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);
  16559. //
  16560. // this.canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);
  16561. // this.canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);
  16562. //
  16563. // this.canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);
  16564. // this.canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);
  16565. //
  16566. // this.canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);
  16567. // this.canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);
  16568. xPoints = this._findCrossPoints({ x: ex, y: ey }, lines);
  16569. if (xPoints !== 0 && xPoints % 2 === 1) {
  16570. this.__corner = i;
  16571. return i;
  16572. }
  16573. }
  16574. return false;
  16575. },
  16576. /**
  16577. * Calls a function for each control. The function gets called,
  16578. * with the control, the object that is calling the iterator and the control's key
  16579. * @param {Function} fn function to iterate over the controls over
  16580. */
  16581. forEachControl: function(fn) {
  16582. for (var i in this.controls) {
  16583. fn(this.controls[i], i, this);
  16584. };
  16585. },
  16586. /**
  16587. * Sets the coordinates of the draggable boxes in the corners of
  16588. * the image used to scale/rotate it.
  16589. * note: if we would switch to ROUND corner area, all of this would disappear.
  16590. * everything would resolve to a single point and a pythagorean theorem for the distance
  16591. * @private
  16592. */
  16593. _setCornerCoords: function() {
  16594. var coords = this.oCoords;
  16595. for (var control in coords) {
  16596. var controlObject = this.controls[control];
  16597. coords[control].corner = controlObject.calcCornerCoords(
  16598. this.angle, this.cornerSize, coords[control].x, coords[control].y, false);
  16599. coords[control].touchCorner = controlObject.calcCornerCoords(
  16600. this.angle, this.touchCornerSize, coords[control].x, coords[control].y, true);
  16601. }
  16602. },
  16603. /**
  16604. * Draws a colored layer behind the object, inside its selection borders.
  16605. * Requires public options: padding, selectionBackgroundColor
  16606. * this function is called when the context is transformed
  16607. * has checks to be skipped when the object is on a staticCanvas
  16608. * @param {CanvasRenderingContext2D} ctx Context to draw on
  16609. * @return {fabric.Object} thisArg
  16610. * @chainable
  16611. */
  16612. drawSelectionBackground: function(ctx) {
  16613. if (!this.selectionBackgroundColor ||
  16614. (this.canvas && !this.canvas.interactive) ||
  16615. (this.canvas && this.canvas._activeObject !== this)
  16616. ) {
  16617. return this;
  16618. }
  16619. ctx.save();
  16620. var center = this.getCenterPoint(), wh = this._calculateCurrentDimensions(),
  16621. vpt = this.canvas.viewportTransform;
  16622. ctx.translate(center.x, center.y);
  16623. ctx.scale(1 / vpt[0], 1 / vpt[3]);
  16624. ctx.rotate(degreesToRadians(this.angle));
  16625. ctx.fillStyle = this.selectionBackgroundColor;
  16626. ctx.fillRect(-wh.x / 2, -wh.y / 2, wh.x, wh.y);
  16627. ctx.restore();
  16628. return this;
  16629. },
  16630. /**
  16631. * Draws borders of an object's bounding box.
  16632. * Requires public properties: width, height
  16633. * Requires public options: padding, borderColor
  16634. * @param {CanvasRenderingContext2D} ctx Context to draw on
  16635. * @param {Object} styleOverride object to override the object style
  16636. * @return {fabric.Object} thisArg
  16637. * @chainable
  16638. */
  16639. drawBorders: function(ctx, styleOverride) {
  16640. styleOverride = styleOverride || {};
  16641. var wh = this._calculateCurrentDimensions(),
  16642. strokeWidth = this.borderScaleFactor,
  16643. width = wh.x + strokeWidth,
  16644. height = wh.y + strokeWidth,
  16645. hasControls = typeof styleOverride.hasControls !== 'undefined' ?
  16646. styleOverride.hasControls : this.hasControls,
  16647. shouldStroke = false;
  16648. ctx.save();
  16649. ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
  16650. this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray);
  16651. ctx.strokeRect(
  16652. -width / 2,
  16653. -height / 2,
  16654. width,
  16655. height
  16656. );
  16657. if (hasControls) {
  16658. ctx.beginPath();
  16659. this.forEachControl(function(control, key, fabricObject) {
  16660. // in this moment, the ctx is centered on the object.
  16661. // width and height of the above function are the size of the bbox.
  16662. if (control.withConnection && control.getVisibility(fabricObject, key)) {
  16663. // reset movement for each control
  16664. shouldStroke = true;
  16665. ctx.moveTo(control.x * width, control.y * height);
  16666. ctx.lineTo(
  16667. control.x * width + control.offsetX,
  16668. control.y * height + control.offsetY
  16669. );
  16670. }
  16671. });
  16672. if (shouldStroke) {
  16673. ctx.stroke();
  16674. }
  16675. }
  16676. ctx.restore();
  16677. return this;
  16678. },
  16679. /**
  16680. * Draws borders of an object's bounding box when it is inside a group.
  16681. * Requires public properties: width, height
  16682. * Requires public options: padding, borderColor
  16683. * @param {CanvasRenderingContext2D} ctx Context to draw on
  16684. * @param {object} options object representing current object parameters
  16685. * @param {Object} styleOverride object to override the object style
  16686. * @return {fabric.Object} thisArg
  16687. * @chainable
  16688. */
  16689. drawBordersInGroup: function(ctx, options, styleOverride) {
  16690. styleOverride = styleOverride || {};
  16691. var bbox = fabric.util.sizeAfterTransform(this.width, this.height, options),
  16692. strokeWidth = this.strokeWidth,
  16693. strokeUniform = this.strokeUniform,
  16694. borderScaleFactor = this.borderScaleFactor,
  16695. width =
  16696. bbox.x + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleX) + borderScaleFactor,
  16697. height =
  16698. bbox.y + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleY) + borderScaleFactor;
  16699. ctx.save();
  16700. this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray);
  16701. ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
  16702. ctx.strokeRect(
  16703. -width / 2,
  16704. -height / 2,
  16705. width,
  16706. height
  16707. );
  16708. ctx.restore();
  16709. return this;
  16710. },
  16711. /**
  16712. * Draws corners of an object's bounding box.
  16713. * Requires public properties: width, height
  16714. * Requires public options: cornerSize, padding
  16715. * @param {CanvasRenderingContext2D} ctx Context to draw on
  16716. * @param {Object} styleOverride object to override the object style
  16717. * @return {fabric.Object} thisArg
  16718. * @chainable
  16719. */
  16720. drawControls: function(ctx, styleOverride) {
  16721. styleOverride = styleOverride || {};
  16722. ctx.save();
  16723. var retinaScaling = this.canvas.getRetinaScaling(), matrix, p;
  16724. ctx.setTransform(retinaScaling, 0, 0, retinaScaling, 0, 0);
  16725. ctx.strokeStyle = ctx.fillStyle = styleOverride.cornerColor || this.cornerColor;
  16726. if (!this.transparentCorners) {
  16727. ctx.strokeStyle = styleOverride.cornerStrokeColor || this.cornerStrokeColor;
  16728. }
  16729. this._setLineDash(ctx, styleOverride.cornerDashArray || this.cornerDashArray);
  16730. this.setCoords();
  16731. if (this.group) {
  16732. // fabricJS does not really support drawing controls inside groups,
  16733. // this piece of code here helps having at least the control in places.
  16734. // If an application needs to show some objects as selected because of some UI state
  16735. // can still call Object._renderControls() on any object they desire, independently of groups.
  16736. // using no padding, circular controls and hiding the rotating cursor is higly suggested,
  16737. matrix = this.group.calcTransformMatrix();
  16738. }
  16739. this.forEachControl(function(control, key, fabricObject) {
  16740. p = fabricObject.oCoords[key];
  16741. if (control.getVisibility(fabricObject, key)) {
  16742. if (matrix) {
  16743. p = fabric.util.transformPoint(p, matrix);
  16744. }
  16745. control.render(ctx, p.x, p.y, styleOverride, fabricObject);
  16746. }
  16747. });
  16748. ctx.restore();
  16749. return this;
  16750. },
  16751. /**
  16752. * Returns true if the specified control is visible, false otherwise.
  16753. * @param {String} controlKey The key of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  16754. * @returns {Boolean} true if the specified control is visible, false otherwise
  16755. */
  16756. isControlVisible: function(controlKey) {
  16757. return this.controls[controlKey] && this.controls[controlKey].getVisibility(this, controlKey);
  16758. },
  16759. /**
  16760. * Sets the visibility of the specified control.
  16761. * @param {String} controlKey The key of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  16762. * @param {Boolean} visible true to set the specified control visible, false otherwise
  16763. * @return {fabric.Object} thisArg
  16764. * @chainable
  16765. */
  16766. setControlVisible: function(controlKey, visible) {
  16767. if (!this._controlsVisibility) {
  16768. this._controlsVisibility = {};
  16769. }
  16770. this._controlsVisibility[controlKey] = visible;
  16771. return this;
  16772. },
  16773. /**
  16774. * Sets the visibility state of object controls.
  16775. * @param {Object} [options] Options object
  16776. * @param {Boolean} [options.bl] true to enable the bottom-left control, false to disable it
  16777. * @param {Boolean} [options.br] true to enable the bottom-right control, false to disable it
  16778. * @param {Boolean} [options.mb] true to enable the middle-bottom control, false to disable it
  16779. * @param {Boolean} [options.ml] true to enable the middle-left control, false to disable it
  16780. * @param {Boolean} [options.mr] true to enable the middle-right control, false to disable it
  16781. * @param {Boolean} [options.mt] true to enable the middle-top control, false to disable it
  16782. * @param {Boolean} [options.tl] true to enable the top-left control, false to disable it
  16783. * @param {Boolean} [options.tr] true to enable the top-right control, false to disable it
  16784. * @param {Boolean} [options.mtr] true to enable the middle-top-rotate control, false to disable it
  16785. * @return {fabric.Object} thisArg
  16786. * @chainable
  16787. */
  16788. setControlsVisibility: function(options) {
  16789. options || (options = { });
  16790. for (var p in options) {
  16791. this.setControlVisible(p, options[p]);
  16792. }
  16793. return this;
  16794. },
  16795. /**
  16796. * This callback function is called every time _discardActiveObject or _setActiveObject
  16797. * try to to deselect this object. If the function returns true, the process is cancelled
  16798. * @param {Object} [options] options sent from the upper functions
  16799. * @param {Event} [options.e] event if the process is generated by an event
  16800. */
  16801. onDeselect: function() {
  16802. // implemented by sub-classes, as needed.
  16803. },
  16804. /**
  16805. * This callback function is called every time _discardActiveObject or _setActiveObject
  16806. * try to to select this object. If the function returns true, the process is cancelled
  16807. * @param {Object} [options] options sent from the upper functions
  16808. * @param {Event} [options.e] event if the process is generated by an event
  16809. */
  16810. onSelect: function() {
  16811. // implemented by sub-classes, as needed.
  16812. }
  16813. });
  16814. })();
  16815. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  16816. /**
  16817. * Animation duration (in ms) for fx* methods
  16818. * @type Number
  16819. * @default
  16820. */
  16821. FX_DURATION: 500,
  16822. /**
  16823. * Centers object horizontally with animation.
  16824. * @param {fabric.Object} object Object to center
  16825. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  16826. * @param {Function} [callbacks.onComplete] Invoked on completion
  16827. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  16828. * @return {fabric.AnimationContext} context
  16829. */
  16830. fxCenterObjectH: function (object, callbacks) {
  16831. callbacks = callbacks || { };
  16832. var empty = function() { },
  16833. onComplete = callbacks.onComplete || empty,
  16834. onChange = callbacks.onChange || empty,
  16835. _this = this;
  16836. return fabric.util.animate({
  16837. target: this,
  16838. startValue: object.left,
  16839. endValue: this.getCenterPoint().x,
  16840. duration: this.FX_DURATION,
  16841. onChange: function(value) {
  16842. object.set('left', value);
  16843. _this.requestRenderAll();
  16844. onChange();
  16845. },
  16846. onComplete: function() {
  16847. object.setCoords();
  16848. onComplete();
  16849. }
  16850. });
  16851. },
  16852. /**
  16853. * Centers object vertically with animation.
  16854. * @param {fabric.Object} object Object to center
  16855. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  16856. * @param {Function} [callbacks.onComplete] Invoked on completion
  16857. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  16858. * @return {fabric.AnimationContext} context
  16859. */
  16860. fxCenterObjectV: function (object, callbacks) {
  16861. callbacks = callbacks || { };
  16862. var empty = function() { },
  16863. onComplete = callbacks.onComplete || empty,
  16864. onChange = callbacks.onChange || empty,
  16865. _this = this;
  16866. return fabric.util.animate({
  16867. target: this,
  16868. startValue: object.top,
  16869. endValue: this.getCenterPoint().y,
  16870. duration: this.FX_DURATION,
  16871. onChange: function(value) {
  16872. object.set('top', value);
  16873. _this.requestRenderAll();
  16874. onChange();
  16875. },
  16876. onComplete: function() {
  16877. object.setCoords();
  16878. onComplete();
  16879. }
  16880. });
  16881. },
  16882. /**
  16883. * Same as `fabric.Canvas#remove` but animated
  16884. * @param {fabric.Object} object Object to remove
  16885. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  16886. * @param {Function} [callbacks.onComplete] Invoked on completion
  16887. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  16888. * @return {fabric.AnimationContext} context
  16889. */
  16890. fxRemove: function (object, callbacks) {
  16891. callbacks = callbacks || { };
  16892. var empty = function() { },
  16893. onComplete = callbacks.onComplete || empty,
  16894. onChange = callbacks.onChange || empty,
  16895. _this = this;
  16896. return fabric.util.animate({
  16897. target: this,
  16898. startValue: object.opacity,
  16899. endValue: 0,
  16900. duration: this.FX_DURATION,
  16901. onChange: function(value) {
  16902. object.set('opacity', value);
  16903. _this.requestRenderAll();
  16904. onChange();
  16905. },
  16906. onComplete: function () {
  16907. _this.remove(object);
  16908. onComplete();
  16909. }
  16910. });
  16911. }
  16912. });
  16913. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  16914. /**
  16915. * Animates object's properties
  16916. * @param {String|Object} property Property to animate (if string) or properties to animate (if object)
  16917. * @param {Number|Object} value Value to animate property to (if string was given first) or options object
  16918. * @return {fabric.Object} thisArg
  16919. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#animation}
  16920. * @return {fabric.AnimationContext | fabric.AnimationContext[]} animation context (or an array if passed multiple properties)
  16921. *
  16922. * As object — multiple properties
  16923. *
  16924. * object.animate({ left: ..., top: ... });
  16925. * object.animate({ left: ..., top: ... }, { duration: ... });
  16926. *
  16927. * As string — one property
  16928. *
  16929. * object.animate('left', ...);
  16930. * object.animate('left', { duration: ... });
  16931. *
  16932. */
  16933. animate: function () {
  16934. if (arguments[0] && typeof arguments[0] === 'object') {
  16935. var propsToAnimate = [], prop, skipCallbacks, out = [];
  16936. for (prop in arguments[0]) {
  16937. propsToAnimate.push(prop);
  16938. }
  16939. for (var i = 0, len = propsToAnimate.length; i < len; i++) {
  16940. prop = propsToAnimate[i];
  16941. skipCallbacks = i !== len - 1;
  16942. out.push(this._animate(prop, arguments[0][prop], arguments[1], skipCallbacks));
  16943. }
  16944. return out;
  16945. }
  16946. else {
  16947. return this._animate.apply(this, arguments);
  16948. }
  16949. },
  16950. /**
  16951. * @private
  16952. * @param {String} property Property to animate
  16953. * @param {String} to Value to animate to
  16954. * @param {Object} [options] Options object
  16955. * @param {Boolean} [skipCallbacks] When true, callbacks like onchange and oncomplete are not invoked
  16956. */
  16957. _animate: function(property, to, options, skipCallbacks) {
  16958. var _this = this, propPair;
  16959. to = to.toString();
  16960. if (!options) {
  16961. options = { };
  16962. }
  16963. else {
  16964. options = fabric.util.object.clone(options);
  16965. }
  16966. if (~property.indexOf('.')) {
  16967. propPair = property.split('.');
  16968. }
  16969. var propIsColor =
  16970. _this.colorProperties.indexOf(property) > -1 ||
  16971. (propPair && _this.colorProperties.indexOf(propPair[1]) > -1);
  16972. var currentValue = propPair
  16973. ? this.get(propPair[0])[propPair[1]]
  16974. : this.get(property);
  16975. if (!('from' in options)) {
  16976. options.from = currentValue;
  16977. }
  16978. if (!propIsColor) {
  16979. if (~to.indexOf('=')) {
  16980. to = currentValue + parseFloat(to.replace('=', ''));
  16981. }
  16982. else {
  16983. to = parseFloat(to);
  16984. }
  16985. }
  16986. var _options = {
  16987. target: this,
  16988. startValue: options.from,
  16989. endValue: to,
  16990. byValue: options.by,
  16991. easing: options.easing,
  16992. duration: options.duration,
  16993. abort: options.abort && function(value, valueProgress, timeProgress) {
  16994. return options.abort.call(_this, value, valueProgress, timeProgress);
  16995. },
  16996. onChange: function (value, valueProgress, timeProgress) {
  16997. if (propPair) {
  16998. _this[propPair[0]][propPair[1]] = value;
  16999. }
  17000. else {
  17001. _this.set(property, value);
  17002. }
  17003. if (skipCallbacks) {
  17004. return;
  17005. }
  17006. options.onChange && options.onChange(value, valueProgress, timeProgress);
  17007. },
  17008. onComplete: function (value, valueProgress, timeProgress) {
  17009. if (skipCallbacks) {
  17010. return;
  17011. }
  17012. _this.setCoords();
  17013. options.onComplete && options.onComplete(value, valueProgress, timeProgress);
  17014. }
  17015. };
  17016. if (propIsColor) {
  17017. return fabric.util.animateColor(_options.startValue, _options.endValue, _options.duration, _options);
  17018. }
  17019. else {
  17020. return fabric.util.animate(_options);
  17021. }
  17022. }
  17023. });
  17024. (function(global) {
  17025. 'use strict';
  17026. var fabric = global.fabric || (global.fabric = { }),
  17027. extend = fabric.util.object.extend,
  17028. clone = fabric.util.object.clone,
  17029. coordProps = { x1: 1, x2: 1, y1: 1, y2: 1 };
  17030. if (fabric.Line) {
  17031. fabric.warn('fabric.Line is already defined');
  17032. return;
  17033. }
  17034. /**
  17035. * Line class
  17036. * @class fabric.Line
  17037. * @extends fabric.Object
  17038. * @see {@link fabric.Line#initialize} for constructor definition
  17039. */
  17040. fabric.Line = fabric.util.createClass(fabric.Object, /** @lends fabric.Line.prototype */ {
  17041. /**
  17042. * Type of an object
  17043. * @type String
  17044. * @default
  17045. */
  17046. type: 'line',
  17047. /**
  17048. * x value or first line edge
  17049. * @type Number
  17050. * @default
  17051. */
  17052. x1: 0,
  17053. /**
  17054. * y value or first line edge
  17055. * @type Number
  17056. * @default
  17057. */
  17058. y1: 0,
  17059. /**
  17060. * x value or second line edge
  17061. * @type Number
  17062. * @default
  17063. */
  17064. x2: 0,
  17065. /**
  17066. * y value or second line edge
  17067. * @type Number
  17068. * @default
  17069. */
  17070. y2: 0,
  17071. cacheProperties: fabric.Object.prototype.cacheProperties.concat('x1', 'x2', 'y1', 'y2'),
  17072. /**
  17073. * Constructor
  17074. * @param {Array} [points] Array of points
  17075. * @param {Object} [options] Options object
  17076. * @return {fabric.Line} thisArg
  17077. */
  17078. initialize: function(points, options) {
  17079. if (!points) {
  17080. points = [0, 0, 0, 0];
  17081. }
  17082. this.callSuper('initialize', options);
  17083. this.set('x1', points[0]);
  17084. this.set('y1', points[1]);
  17085. this.set('x2', points[2]);
  17086. this.set('y2', points[3]);
  17087. this._setWidthHeight(options);
  17088. },
  17089. /**
  17090. * @private
  17091. * @param {Object} [options] Options
  17092. */
  17093. _setWidthHeight: function(options) {
  17094. options || (options = { });
  17095. this.width = Math.abs(this.x2 - this.x1);
  17096. this.height = Math.abs(this.y2 - this.y1);
  17097. this.left = 'left' in options
  17098. ? options.left
  17099. : this._getLeftToOriginX();
  17100. this.top = 'top' in options
  17101. ? options.top
  17102. : this._getTopToOriginY();
  17103. },
  17104. /**
  17105. * @private
  17106. * @param {String} key
  17107. * @param {*} value
  17108. */
  17109. _set: function(key, value) {
  17110. this.callSuper('_set', key, value);
  17111. if (typeof coordProps[key] !== 'undefined') {
  17112. this._setWidthHeight();
  17113. }
  17114. return this;
  17115. },
  17116. /**
  17117. * @private
  17118. * @return {Number} leftToOriginX Distance from left edge of canvas to originX of Line.
  17119. */
  17120. _getLeftToOriginX: makeEdgeToOriginGetter(
  17121. { // property names
  17122. origin: 'originX',
  17123. axis1: 'x1',
  17124. axis2: 'x2',
  17125. dimension: 'width'
  17126. },
  17127. { // possible values of origin
  17128. nearest: 'left',
  17129. center: 'center',
  17130. farthest: 'right'
  17131. }
  17132. ),
  17133. /**
  17134. * @private
  17135. * @return {Number} topToOriginY Distance from top edge of canvas to originY of Line.
  17136. */
  17137. _getTopToOriginY: makeEdgeToOriginGetter(
  17138. { // property names
  17139. origin: 'originY',
  17140. axis1: 'y1',
  17141. axis2: 'y2',
  17142. dimension: 'height'
  17143. },
  17144. { // possible values of origin
  17145. nearest: 'top',
  17146. center: 'center',
  17147. farthest: 'bottom'
  17148. }
  17149. ),
  17150. /**
  17151. * @private
  17152. * @param {CanvasRenderingContext2D} ctx Context to render on
  17153. */
  17154. _render: function(ctx) {
  17155. ctx.beginPath();
  17156. var p = this.calcLinePoints();
  17157. ctx.moveTo(p.x1, p.y1);
  17158. ctx.lineTo(p.x2, p.y2);
  17159. ctx.lineWidth = this.strokeWidth;
  17160. // TODO: test this
  17161. // make sure setting "fill" changes color of a line
  17162. // (by copying fillStyle to strokeStyle, since line is stroked, not filled)
  17163. var origStrokeStyle = ctx.strokeStyle;
  17164. ctx.strokeStyle = this.stroke || ctx.fillStyle;
  17165. this.stroke && this._renderStroke(ctx);
  17166. ctx.strokeStyle = origStrokeStyle;
  17167. },
  17168. /**
  17169. * This function is an helper for svg import. it returns the center of the object in the svg
  17170. * untransformed coordinates
  17171. * @private
  17172. * @return {Object} center point from element coordinates
  17173. */
  17174. _findCenterFromElement: function() {
  17175. return {
  17176. x: (this.x1 + this.x2) / 2,
  17177. y: (this.y1 + this.y2) / 2,
  17178. };
  17179. },
  17180. /**
  17181. * Returns object representation of an instance
  17182. * @method toObject
  17183. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17184. * @return {Object} object representation of an instance
  17185. */
  17186. toObject: function(propertiesToInclude) {
  17187. return extend(this.callSuper('toObject', propertiesToInclude), this.calcLinePoints());
  17188. },
  17189. /*
  17190. * Calculate object dimensions from its properties
  17191. * @private
  17192. */
  17193. _getNonTransformedDimensions: function() {
  17194. var dim = this.callSuper('_getNonTransformedDimensions');
  17195. if (this.strokeLineCap === 'butt') {
  17196. if (this.width === 0) {
  17197. dim.y -= this.strokeWidth;
  17198. }
  17199. if (this.height === 0) {
  17200. dim.x -= this.strokeWidth;
  17201. }
  17202. }
  17203. return dim;
  17204. },
  17205. /**
  17206. * Recalculates line points given width and height
  17207. * @private
  17208. */
  17209. calcLinePoints: function() {
  17210. var xMult = this.x1 <= this.x2 ? -1 : 1,
  17211. yMult = this.y1 <= this.y2 ? -1 : 1,
  17212. x1 = (xMult * this.width * 0.5),
  17213. y1 = (yMult * this.height * 0.5),
  17214. x2 = (xMult * this.width * -0.5),
  17215. y2 = (yMult * this.height * -0.5);
  17216. return {
  17217. x1: x1,
  17218. x2: x2,
  17219. y1: y1,
  17220. y2: y2
  17221. };
  17222. },
  17223. /* _TO_SVG_START_ */
  17224. /**
  17225. * Returns svg representation of an instance
  17226. * @return {Array} an array of strings with the specific svg representation
  17227. * of the instance
  17228. */
  17229. _toSVG: function() {
  17230. var p = this.calcLinePoints();
  17231. return [
  17232. '<line ', 'COMMON_PARTS',
  17233. 'x1="', p.x1,
  17234. '" y1="', p.y1,
  17235. '" x2="', p.x2,
  17236. '" y2="', p.y2,
  17237. '" />\n'
  17238. ];
  17239. },
  17240. /* _TO_SVG_END_ */
  17241. });
  17242. /* _FROM_SVG_START_ */
  17243. /**
  17244. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Line.fromElement})
  17245. * @static
  17246. * @memberOf fabric.Line
  17247. * @see http://www.w3.org/TR/SVG/shapes.html#LineElement
  17248. */
  17249. fabric.Line.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x1 y1 x2 y2'.split(' '));
  17250. /**
  17251. * Returns fabric.Line instance from an SVG element
  17252. * @static
  17253. * @memberOf fabric.Line
  17254. * @param {SVGElement} element Element to parse
  17255. * @param {Object} [options] Options object
  17256. * @param {Function} [callback] callback function invoked after parsing
  17257. */
  17258. fabric.Line.fromElement = function(element, callback, options) {
  17259. options = options || { };
  17260. var parsedAttributes = fabric.parseAttributes(element, fabric.Line.ATTRIBUTE_NAMES),
  17261. points = [
  17262. parsedAttributes.x1 || 0,
  17263. parsedAttributes.y1 || 0,
  17264. parsedAttributes.x2 || 0,
  17265. parsedAttributes.y2 || 0
  17266. ];
  17267. callback(new fabric.Line(points, extend(parsedAttributes, options)));
  17268. };
  17269. /* _FROM_SVG_END_ */
  17270. /**
  17271. * Returns fabric.Line instance from an object representation
  17272. * @static
  17273. * @memberOf fabric.Line
  17274. * @param {Object} object Object to create an instance from
  17275. * @param {function} [callback] invoked with new instance as first argument
  17276. */
  17277. fabric.Line.fromObject = function(object, callback) {
  17278. function _callback(instance) {
  17279. delete instance.points;
  17280. callback && callback(instance);
  17281. };
  17282. var options = clone(object, true);
  17283. options.points = [object.x1, object.y1, object.x2, object.y2];
  17284. fabric.Object._fromObject('Line', options, _callback, 'points');
  17285. };
  17286. /**
  17287. * Produces a function that calculates distance from canvas edge to Line origin.
  17288. */
  17289. function makeEdgeToOriginGetter(propertyNames, originValues) {
  17290. var origin = propertyNames.origin,
  17291. axis1 = propertyNames.axis1,
  17292. axis2 = propertyNames.axis2,
  17293. dimension = propertyNames.dimension,
  17294. nearest = originValues.nearest,
  17295. center = originValues.center,
  17296. farthest = originValues.farthest;
  17297. return function() {
  17298. switch (this.get(origin)) {
  17299. case nearest:
  17300. return Math.min(this.get(axis1), this.get(axis2));
  17301. case center:
  17302. return Math.min(this.get(axis1), this.get(axis2)) + (0.5 * this.get(dimension));
  17303. case farthest:
  17304. return Math.max(this.get(axis1), this.get(axis2));
  17305. }
  17306. };
  17307. }
  17308. })(typeof exports !== 'undefined' ? exports : this);
  17309. (function(global) {
  17310. 'use strict';
  17311. var fabric = global.fabric || (global.fabric = { }),
  17312. degreesToRadians = fabric.util.degreesToRadians;
  17313. if (fabric.Circle) {
  17314. fabric.warn('fabric.Circle is already defined.');
  17315. return;
  17316. }
  17317. /**
  17318. * Circle class
  17319. * @class fabric.Circle
  17320. * @extends fabric.Object
  17321. * @see {@link fabric.Circle#initialize} for constructor definition
  17322. */
  17323. fabric.Circle = fabric.util.createClass(fabric.Object, /** @lends fabric.Circle.prototype */ {
  17324. /**
  17325. * Type of an object
  17326. * @type String
  17327. * @default
  17328. */
  17329. type: 'circle',
  17330. /**
  17331. * Radius of this circle
  17332. * @type Number
  17333. * @default
  17334. */
  17335. radius: 0,
  17336. /**
  17337. * degrees of start of the circle.
  17338. * probably will change to degrees in next major version
  17339. * @type Number 0 - 359
  17340. * @default 0
  17341. */
  17342. startAngle: 0,
  17343. /**
  17344. * End angle of the circle
  17345. * probably will change to degrees in next major version
  17346. * @type Number 1 - 360
  17347. * @default 360
  17348. */
  17349. endAngle: 360,
  17350. cacheProperties: fabric.Object.prototype.cacheProperties.concat('radius', 'startAngle', 'endAngle'),
  17351. /**
  17352. * @private
  17353. * @param {String} key
  17354. * @param {*} value
  17355. * @return {fabric.Circle} thisArg
  17356. */
  17357. _set: function(key, value) {
  17358. this.callSuper('_set', key, value);
  17359. if (key === 'radius') {
  17360. this.setRadius(value);
  17361. }
  17362. return this;
  17363. },
  17364. /**
  17365. * Returns object representation of an instance
  17366. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17367. * @return {Object} object representation of an instance
  17368. */
  17369. toObject: function(propertiesToInclude) {
  17370. return this.callSuper('toObject', ['radius', 'startAngle', 'endAngle'].concat(propertiesToInclude));
  17371. },
  17372. /* _TO_SVG_START_ */
  17373. /**
  17374. * Returns svg representation of an instance
  17375. * @return {Array} an array of strings with the specific svg representation
  17376. * of the instance
  17377. */
  17378. _toSVG: function() {
  17379. var svgString, x = 0, y = 0,
  17380. angle = (this.endAngle - this.startAngle) % 360;
  17381. if (angle === 0) {
  17382. svgString = [
  17383. '<circle ', 'COMMON_PARTS',
  17384. 'cx="' + x + '" cy="' + y + '" ',
  17385. 'r="', this.radius,
  17386. '" />\n'
  17387. ];
  17388. }
  17389. else {
  17390. var start = degreesToRadians(this.startAngle),
  17391. end = degreesToRadians(this.endAngle),
  17392. radius = this.radius,
  17393. startX = fabric.util.cos(start) * radius,
  17394. startY = fabric.util.sin(start) * radius,
  17395. endX = fabric.util.cos(end) * radius,
  17396. endY = fabric.util.sin(end) * radius,
  17397. largeFlag = angle > 180 ? '1' : '0';
  17398. svgString = [
  17399. '<path d="M ' + startX + ' ' + startY,
  17400. ' A ' + radius + ' ' + radius,
  17401. ' 0 ', +largeFlag + ' 1', ' ' + endX + ' ' + endY,
  17402. '" ', 'COMMON_PARTS', ' />\n'
  17403. ];
  17404. }
  17405. return svgString;
  17406. },
  17407. /* _TO_SVG_END_ */
  17408. /**
  17409. * @private
  17410. * @param {CanvasRenderingContext2D} ctx context to render on
  17411. */
  17412. _render: function(ctx) {
  17413. ctx.beginPath();
  17414. ctx.arc(
  17415. 0,
  17416. 0,
  17417. this.radius,
  17418. degreesToRadians(this.startAngle),
  17419. degreesToRadians(this.endAngle),
  17420. false
  17421. );
  17422. this._renderPaintInOrder(ctx);
  17423. },
  17424. /**
  17425. * Returns horizontal radius of an object (according to how an object is scaled)
  17426. * @return {Number}
  17427. */
  17428. getRadiusX: function() {
  17429. return this.get('radius') * this.get('scaleX');
  17430. },
  17431. /**
  17432. * Returns vertical radius of an object (according to how an object is scaled)
  17433. * @return {Number}
  17434. */
  17435. getRadiusY: function() {
  17436. return this.get('radius') * this.get('scaleY');
  17437. },
  17438. /**
  17439. * Sets radius of an object (and updates width accordingly)
  17440. * @return {fabric.Circle} thisArg
  17441. */
  17442. setRadius: function(value) {
  17443. this.radius = value;
  17444. return this.set('width', value * 2).set('height', value * 2);
  17445. },
  17446. });
  17447. /* _FROM_SVG_START_ */
  17448. /**
  17449. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement})
  17450. * @static
  17451. * @memberOf fabric.Circle
  17452. * @see: http://www.w3.org/TR/SVG/shapes.html#CircleElement
  17453. */
  17454. fabric.Circle.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy r'.split(' '));
  17455. /**
  17456. * Returns {@link fabric.Circle} instance from an SVG element
  17457. * @static
  17458. * @memberOf fabric.Circle
  17459. * @param {SVGElement} element Element to parse
  17460. * @param {Function} [callback] Options callback invoked after parsing is finished
  17461. * @param {Object} [options] Options object
  17462. * @throws {Error} If value of `r` attribute is missing or invalid
  17463. */
  17464. fabric.Circle.fromElement = function(element, callback) {
  17465. var parsedAttributes = fabric.parseAttributes(element, fabric.Circle.ATTRIBUTE_NAMES);
  17466. if (!isValidRadius(parsedAttributes)) {
  17467. throw new Error('value of `r` attribute is required and can not be negative');
  17468. }
  17469. parsedAttributes.left = (parsedAttributes.left || 0) - parsedAttributes.radius;
  17470. parsedAttributes.top = (parsedAttributes.top || 0) - parsedAttributes.radius;
  17471. callback(new fabric.Circle(parsedAttributes));
  17472. };
  17473. /**
  17474. * @private
  17475. */
  17476. function isValidRadius(attributes) {
  17477. return (('radius' in attributes) && (attributes.radius >= 0));
  17478. }
  17479. /* _FROM_SVG_END_ */
  17480. /**
  17481. * Returns {@link fabric.Circle} instance from an object representation
  17482. * @static
  17483. * @memberOf fabric.Circle
  17484. * @param {Object} object Object to create an instance from
  17485. * @param {function} [callback] invoked with new instance as first argument
  17486. * @return {void}
  17487. */
  17488. fabric.Circle.fromObject = function(object, callback) {
  17489. fabric.Object._fromObject('Circle', object, callback);
  17490. };
  17491. })(typeof exports !== 'undefined' ? exports : this);
  17492. (function(global) {
  17493. 'use strict';
  17494. var fabric = global.fabric || (global.fabric = { });
  17495. if (fabric.Triangle) {
  17496. fabric.warn('fabric.Triangle is already defined');
  17497. return;
  17498. }
  17499. /**
  17500. * Triangle class
  17501. * @class fabric.Triangle
  17502. * @extends fabric.Object
  17503. * @return {fabric.Triangle} thisArg
  17504. * @see {@link fabric.Triangle#initialize} for constructor definition
  17505. */
  17506. fabric.Triangle = fabric.util.createClass(fabric.Object, /** @lends fabric.Triangle.prototype */ {
  17507. /**
  17508. * Type of an object
  17509. * @type String
  17510. * @default
  17511. */
  17512. type: 'triangle',
  17513. /**
  17514. * Width is set to 100 to compensate the old initialize code that was setting it to 100
  17515. * @type Number
  17516. * @default
  17517. */
  17518. width: 100,
  17519. /**
  17520. * Height is set to 100 to compensate the old initialize code that was setting it to 100
  17521. * @type Number
  17522. * @default
  17523. */
  17524. height: 100,
  17525. /**
  17526. * @private
  17527. * @param {CanvasRenderingContext2D} ctx Context to render on
  17528. */
  17529. _render: function(ctx) {
  17530. var widthBy2 = this.width / 2,
  17531. heightBy2 = this.height / 2;
  17532. ctx.beginPath();
  17533. ctx.moveTo(-widthBy2, heightBy2);
  17534. ctx.lineTo(0, -heightBy2);
  17535. ctx.lineTo(widthBy2, heightBy2);
  17536. ctx.closePath();
  17537. this._renderPaintInOrder(ctx);
  17538. },
  17539. /* _TO_SVG_START_ */
  17540. /**
  17541. * Returns svg representation of an instance
  17542. * @return {Array} an array of strings with the specific svg representation
  17543. * of the instance
  17544. */
  17545. _toSVG: function() {
  17546. var widthBy2 = this.width / 2,
  17547. heightBy2 = this.height / 2,
  17548. points = [
  17549. -widthBy2 + ' ' + heightBy2,
  17550. '0 ' + -heightBy2,
  17551. widthBy2 + ' ' + heightBy2
  17552. ].join(',');
  17553. return [
  17554. '<polygon ', 'COMMON_PARTS',
  17555. 'points="', points,
  17556. '" />'
  17557. ];
  17558. },
  17559. /* _TO_SVG_END_ */
  17560. });
  17561. /**
  17562. * Returns {@link fabric.Triangle} instance from an object representation
  17563. * @static
  17564. * @memberOf fabric.Triangle
  17565. * @param {Object} object Object to create an instance from
  17566. * @param {function} [callback] invoked with new instance as first argument
  17567. */
  17568. fabric.Triangle.fromObject = function(object, callback) {
  17569. return fabric.Object._fromObject('Triangle', object, callback);
  17570. };
  17571. })(typeof exports !== 'undefined' ? exports : this);
  17572. (function(global) {
  17573. 'use strict';
  17574. var fabric = global.fabric || (global.fabric = { }),
  17575. piBy2 = Math.PI * 2;
  17576. if (fabric.Ellipse) {
  17577. fabric.warn('fabric.Ellipse is already defined.');
  17578. return;
  17579. }
  17580. /**
  17581. * Ellipse class
  17582. * @class fabric.Ellipse
  17583. * @extends fabric.Object
  17584. * @return {fabric.Ellipse} thisArg
  17585. * @see {@link fabric.Ellipse#initialize} for constructor definition
  17586. */
  17587. fabric.Ellipse = fabric.util.createClass(fabric.Object, /** @lends fabric.Ellipse.prototype */ {
  17588. /**
  17589. * Type of an object
  17590. * @type String
  17591. * @default
  17592. */
  17593. type: 'ellipse',
  17594. /**
  17595. * Horizontal radius
  17596. * @type Number
  17597. * @default
  17598. */
  17599. rx: 0,
  17600. /**
  17601. * Vertical radius
  17602. * @type Number
  17603. * @default
  17604. */
  17605. ry: 0,
  17606. cacheProperties: fabric.Object.prototype.cacheProperties.concat('rx', 'ry'),
  17607. /**
  17608. * Constructor
  17609. * @param {Object} [options] Options object
  17610. * @return {fabric.Ellipse} thisArg
  17611. */
  17612. initialize: function(options) {
  17613. this.callSuper('initialize', options);
  17614. this.set('rx', options && options.rx || 0);
  17615. this.set('ry', options && options.ry || 0);
  17616. },
  17617. /**
  17618. * @private
  17619. * @param {String} key
  17620. * @param {*} value
  17621. * @return {fabric.Ellipse} thisArg
  17622. */
  17623. _set: function(key, value) {
  17624. this.callSuper('_set', key, value);
  17625. switch (key) {
  17626. case 'rx':
  17627. this.rx = value;
  17628. this.set('width', value * 2);
  17629. break;
  17630. case 'ry':
  17631. this.ry = value;
  17632. this.set('height', value * 2);
  17633. break;
  17634. }
  17635. return this;
  17636. },
  17637. /**
  17638. * Returns horizontal radius of an object (according to how an object is scaled)
  17639. * @return {Number}
  17640. */
  17641. getRx: function() {
  17642. return this.get('rx') * this.get('scaleX');
  17643. },
  17644. /**
  17645. * Returns Vertical radius of an object (according to how an object is scaled)
  17646. * @return {Number}
  17647. */
  17648. getRy: function() {
  17649. return this.get('ry') * this.get('scaleY');
  17650. },
  17651. /**
  17652. * Returns object representation of an instance
  17653. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17654. * @return {Object} object representation of an instance
  17655. */
  17656. toObject: function(propertiesToInclude) {
  17657. return this.callSuper('toObject', ['rx', 'ry'].concat(propertiesToInclude));
  17658. },
  17659. /* _TO_SVG_START_ */
  17660. /**
  17661. * Returns svg representation of an instance
  17662. * @return {Array} an array of strings with the specific svg representation
  17663. * of the instance
  17664. */
  17665. _toSVG: function() {
  17666. return [
  17667. '<ellipse ', 'COMMON_PARTS',
  17668. 'cx="0" cy="0" ',
  17669. 'rx="', this.rx,
  17670. '" ry="', this.ry,
  17671. '" />\n'
  17672. ];
  17673. },
  17674. /* _TO_SVG_END_ */
  17675. /**
  17676. * @private
  17677. * @param {CanvasRenderingContext2D} ctx context to render on
  17678. */
  17679. _render: function(ctx) {
  17680. ctx.beginPath();
  17681. ctx.save();
  17682. ctx.transform(1, 0, 0, this.ry / this.rx, 0, 0);
  17683. ctx.arc(
  17684. 0,
  17685. 0,
  17686. this.rx,
  17687. 0,
  17688. piBy2,
  17689. false);
  17690. ctx.restore();
  17691. this._renderPaintInOrder(ctx);
  17692. },
  17693. });
  17694. /* _FROM_SVG_START_ */
  17695. /**
  17696. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement})
  17697. * @static
  17698. * @memberOf fabric.Ellipse
  17699. * @see http://www.w3.org/TR/SVG/shapes.html#EllipseElement
  17700. */
  17701. fabric.Ellipse.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy rx ry'.split(' '));
  17702. /**
  17703. * Returns {@link fabric.Ellipse} instance from an SVG element
  17704. * @static
  17705. * @memberOf fabric.Ellipse
  17706. * @param {SVGElement} element Element to parse
  17707. * @param {Function} [callback] Options callback invoked after parsing is finished
  17708. * @return {fabric.Ellipse}
  17709. */
  17710. fabric.Ellipse.fromElement = function(element, callback) {
  17711. var parsedAttributes = fabric.parseAttributes(element, fabric.Ellipse.ATTRIBUTE_NAMES);
  17712. parsedAttributes.left = (parsedAttributes.left || 0) - parsedAttributes.rx;
  17713. parsedAttributes.top = (parsedAttributes.top || 0) - parsedAttributes.ry;
  17714. callback(new fabric.Ellipse(parsedAttributes));
  17715. };
  17716. /* _FROM_SVG_END_ */
  17717. /**
  17718. * Returns {@link fabric.Ellipse} instance from an object representation
  17719. * @static
  17720. * @memberOf fabric.Ellipse
  17721. * @param {Object} object Object to create an instance from
  17722. * @param {function} [callback] invoked with new instance as first argument
  17723. * @return {void}
  17724. */
  17725. fabric.Ellipse.fromObject = function(object, callback) {
  17726. fabric.Object._fromObject('Ellipse', object, callback);
  17727. };
  17728. })(typeof exports !== 'undefined' ? exports : this);
  17729. (function(global) {
  17730. 'use strict';
  17731. var fabric = global.fabric || (global.fabric = { }),
  17732. extend = fabric.util.object.extend;
  17733. if (fabric.Rect) {
  17734. fabric.warn('fabric.Rect is already defined');
  17735. return;
  17736. }
  17737. /**
  17738. * Rectangle class
  17739. * @class fabric.Rect
  17740. * @extends fabric.Object
  17741. * @return {fabric.Rect} thisArg
  17742. * @see {@link fabric.Rect#initialize} for constructor definition
  17743. */
  17744. fabric.Rect = fabric.util.createClass(fabric.Object, /** @lends fabric.Rect.prototype */ {
  17745. /**
  17746. * List of properties to consider when checking if state of an object is changed ({@link fabric.Object#hasStateChanged})
  17747. * as well as for history (undo/redo) purposes
  17748. * @type Array
  17749. */
  17750. stateProperties: fabric.Object.prototype.stateProperties.concat('rx', 'ry'),
  17751. /**
  17752. * Type of an object
  17753. * @type String
  17754. * @default
  17755. */
  17756. type: 'rect',
  17757. /**
  17758. * Horizontal border radius
  17759. * @type Number
  17760. * @default
  17761. */
  17762. rx: 0,
  17763. /**
  17764. * Vertical border radius
  17765. * @type Number
  17766. * @default
  17767. */
  17768. ry: 0,
  17769. cacheProperties: fabric.Object.prototype.cacheProperties.concat('rx', 'ry'),
  17770. /**
  17771. * Constructor
  17772. * @param {Object} [options] Options object
  17773. * @return {Object} thisArg
  17774. */
  17775. initialize: function(options) {
  17776. this.callSuper('initialize', options);
  17777. this._initRxRy();
  17778. },
  17779. /**
  17780. * Initializes rx/ry attributes
  17781. * @private
  17782. */
  17783. _initRxRy: function() {
  17784. if (this.rx && !this.ry) {
  17785. this.ry = this.rx;
  17786. }
  17787. else if (this.ry && !this.rx) {
  17788. this.rx = this.ry;
  17789. }
  17790. },
  17791. /**
  17792. * @private
  17793. * @param {CanvasRenderingContext2D} ctx Context to render on
  17794. */
  17795. _render: function(ctx) {
  17796. // 1x1 case (used in spray brush) optimization was removed because
  17797. // with caching and higher zoom level this makes more damage than help
  17798. var rx = this.rx ? Math.min(this.rx, this.width / 2) : 0,
  17799. ry = this.ry ? Math.min(this.ry, this.height / 2) : 0,
  17800. w = this.width,
  17801. h = this.height,
  17802. x = -this.width / 2,
  17803. y = -this.height / 2,
  17804. isRounded = rx !== 0 || ry !== 0,
  17805. /* "magic number" for bezier approximations of arcs (http://itc.ktu.lt/itc354/Riskus354.pdf) */
  17806. k = 1 - 0.5522847498;
  17807. ctx.beginPath();
  17808. ctx.moveTo(x + rx, y);
  17809. ctx.lineTo(x + w - rx, y);
  17810. isRounded && ctx.bezierCurveTo(x + w - k * rx, y, x + w, y + k * ry, x + w, y + ry);
  17811. ctx.lineTo(x + w, y + h - ry);
  17812. isRounded && ctx.bezierCurveTo(x + w, y + h - k * ry, x + w - k * rx, y + h, x + w - rx, y + h);
  17813. ctx.lineTo(x + rx, y + h);
  17814. isRounded && ctx.bezierCurveTo(x + k * rx, y + h, x, y + h - k * ry, x, y + h - ry);
  17815. ctx.lineTo(x, y + ry);
  17816. isRounded && ctx.bezierCurveTo(x, y + k * ry, x + k * rx, y, x + rx, y);
  17817. ctx.closePath();
  17818. this._renderPaintInOrder(ctx);
  17819. },
  17820. /**
  17821. * Returns object representation of an instance
  17822. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17823. * @return {Object} object representation of an instance
  17824. */
  17825. toObject: function(propertiesToInclude) {
  17826. return this.callSuper('toObject', ['rx', 'ry'].concat(propertiesToInclude));
  17827. },
  17828. /* _TO_SVG_START_ */
  17829. /**
  17830. * Returns svg representation of an instance
  17831. * @return {Array} an array of strings with the specific svg representation
  17832. * of the instance
  17833. */
  17834. _toSVG: function() {
  17835. var x = -this.width / 2, y = -this.height / 2;
  17836. return [
  17837. '<rect ', 'COMMON_PARTS',
  17838. 'x="', x, '" y="', y,
  17839. '" rx="', this.rx, '" ry="', this.ry,
  17840. '" width="', this.width, '" height="', this.height,
  17841. '" />\n'
  17842. ];
  17843. },
  17844. /* _TO_SVG_END_ */
  17845. });
  17846. /* _FROM_SVG_START_ */
  17847. /**
  17848. * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`)
  17849. * @static
  17850. * @memberOf fabric.Rect
  17851. * @see: http://www.w3.org/TR/SVG/shapes.html#RectElement
  17852. */
  17853. fabric.Rect.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x y rx ry width height'.split(' '));
  17854. /**
  17855. * Returns {@link fabric.Rect} instance from an SVG element
  17856. * @static
  17857. * @memberOf fabric.Rect
  17858. * @param {SVGElement} element Element to parse
  17859. * @param {Function} callback callback function invoked after parsing
  17860. * @param {Object} [options] Options object
  17861. */
  17862. fabric.Rect.fromElement = function(element, callback, options) {
  17863. if (!element) {
  17864. return callback(null);
  17865. }
  17866. options = options || { };
  17867. var parsedAttributes = fabric.parseAttributes(element, fabric.Rect.ATTRIBUTE_NAMES);
  17868. parsedAttributes.left = parsedAttributes.left || 0;
  17869. parsedAttributes.top = parsedAttributes.top || 0;
  17870. parsedAttributes.height = parsedAttributes.height || 0;
  17871. parsedAttributes.width = parsedAttributes.width || 0;
  17872. var rect = new fabric.Rect(extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));
  17873. rect.visible = rect.visible && rect.width > 0 && rect.height > 0;
  17874. callback(rect);
  17875. };
  17876. /* _FROM_SVG_END_ */
  17877. /**
  17878. * Returns {@link fabric.Rect} instance from an object representation
  17879. * @static
  17880. * @memberOf fabric.Rect
  17881. * @param {Object} object Object to create an instance from
  17882. * @param {Function} [callback] Callback to invoke when an fabric.Rect instance is created
  17883. */
  17884. fabric.Rect.fromObject = function(object, callback) {
  17885. return fabric.Object._fromObject('Rect', object, callback);
  17886. };
  17887. })(typeof exports !== 'undefined' ? exports : this);
  17888. (function(global) {
  17889. 'use strict';
  17890. var fabric = global.fabric || (global.fabric = { }),
  17891. extend = fabric.util.object.extend,
  17892. min = fabric.util.array.min,
  17893. max = fabric.util.array.max,
  17894. toFixed = fabric.util.toFixed,
  17895. projectStrokeOnPoints = fabric.util.projectStrokeOnPoints;
  17896. if (fabric.Polyline) {
  17897. fabric.warn('fabric.Polyline is already defined');
  17898. return;
  17899. }
  17900. /**
  17901. * Polyline class
  17902. * @class fabric.Polyline
  17903. * @extends fabric.Object
  17904. * @see {@link fabric.Polyline#initialize} for constructor definition
  17905. */
  17906. fabric.Polyline = fabric.util.createClass(fabric.Object, /** @lends fabric.Polyline.prototype */ {
  17907. /**
  17908. * Type of an object
  17909. * @type String
  17910. * @default
  17911. */
  17912. type: 'polyline',
  17913. /**
  17914. * Points array
  17915. * @type Array
  17916. * @default
  17917. */
  17918. points: null,
  17919. /**
  17920. * WARNING: Feature in progress
  17921. * Calculate the exact bounding box taking in account strokeWidth on acute angles
  17922. * this will be turned to true by default on fabric 6.0
  17923. * maybe will be left in as an optimization since calculations may be slow
  17924. * @deprecated
  17925. * @type Boolean
  17926. * @default false
  17927. */
  17928. exactBoundingBox: false,
  17929. cacheProperties: fabric.Object.prototype.cacheProperties.concat('points'),
  17930. /**
  17931. * Constructor
  17932. * @param {Array} points Array of points (where each point is an object with x and y)
  17933. * @param {Object} [options] Options object
  17934. * @return {fabric.Polyline} thisArg
  17935. * @example
  17936. * var poly = new fabric.Polyline([
  17937. * { x: 10, y: 10 },
  17938. * { x: 50, y: 30 },
  17939. * { x: 40, y: 70 },
  17940. * { x: 60, y: 50 },
  17941. * { x: 100, y: 150 },
  17942. * { x: 40, y: 100 }
  17943. * ], {
  17944. * stroke: 'red',
  17945. * left: 100,
  17946. * top: 100
  17947. * });
  17948. */
  17949. initialize: function(points, options) {
  17950. options = options || {};
  17951. this.points = points || [];
  17952. this.callSuper('initialize', options);
  17953. this._setPositionDimensions(options);
  17954. },
  17955. /**
  17956. * @private
  17957. */
  17958. _projectStrokeOnPoints: function () {
  17959. return projectStrokeOnPoints(this.points, this, true);
  17960. },
  17961. _setPositionDimensions: function(options) {
  17962. var calcDim = this._calcDimensions(options), correctLeftTop,
  17963. correctSize = this.exactBoundingBox ? this.strokeWidth : 0;
  17964. this.width = calcDim.width - correctSize;
  17965. this.height = calcDim.height - correctSize;
  17966. if (!options.fromSVG) {
  17967. correctLeftTop = this.translateToGivenOrigin(
  17968. {
  17969. // this looks bad, but is one way to keep it optional for now.
  17970. x: calcDim.left - this.strokeWidth / 2 + correctSize / 2,
  17971. y: calcDim.top - this.strokeWidth / 2 + correctSize / 2
  17972. },
  17973. 'left',
  17974. 'top',
  17975. this.originX,
  17976. this.originY
  17977. );
  17978. }
  17979. if (typeof options.left === 'undefined') {
  17980. this.left = options.fromSVG ? calcDim.left : correctLeftTop.x;
  17981. }
  17982. if (typeof options.top === 'undefined') {
  17983. this.top = options.fromSVG ? calcDim.top : correctLeftTop.y;
  17984. }
  17985. this.pathOffset = {
  17986. x: calcDim.left + this.width / 2 + correctSize / 2,
  17987. y: calcDim.top + this.height / 2 + correctSize / 2
  17988. };
  17989. },
  17990. /**
  17991. * Calculate the polygon min and max point from points array,
  17992. * returning an object with left, top, width, height to measure the
  17993. * polygon size
  17994. * @return {Object} object.left X coordinate of the polygon leftmost point
  17995. * @return {Object} object.top Y coordinate of the polygon topmost point
  17996. * @return {Object} object.width distance between X coordinates of the polygon leftmost and rightmost point
  17997. * @return {Object} object.height distance between Y coordinates of the polygon topmost and bottommost point
  17998. * @private
  17999. */
  18000. _calcDimensions: function() {
  18001. var points = this.exactBoundingBox ? this._projectStrokeOnPoints() : this.points,
  18002. minX = min(points, 'x') || 0,
  18003. minY = min(points, 'y') || 0,
  18004. maxX = max(points, 'x') || 0,
  18005. maxY = max(points, 'y') || 0,
  18006. width = (maxX - minX),
  18007. height = (maxY - minY);
  18008. return {
  18009. left: minX,
  18010. top: minY,
  18011. width: width,
  18012. height: height,
  18013. };
  18014. },
  18015. /**
  18016. * Returns object representation of an instance
  18017. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18018. * @return {Object} Object representation of an instance
  18019. */
  18020. toObject: function(propertiesToInclude) {
  18021. return extend(this.callSuper('toObject', propertiesToInclude), {
  18022. points: this.points.concat()
  18023. });
  18024. },
  18025. /* _TO_SVG_START_ */
  18026. /**
  18027. * Returns svg representation of an instance
  18028. * @return {Array} an array of strings with the specific svg representation
  18029. * of the instance
  18030. */
  18031. _toSVG: function() {
  18032. var points = [], diffX = this.pathOffset.x, diffY = this.pathOffset.y,
  18033. NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;
  18034. for (var i = 0, len = this.points.length; i < len; i++) {
  18035. points.push(
  18036. toFixed(this.points[i].x - diffX, NUM_FRACTION_DIGITS), ',',
  18037. toFixed(this.points[i].y - diffY, NUM_FRACTION_DIGITS), ' '
  18038. );
  18039. }
  18040. return [
  18041. '<' + this.type + ' ', 'COMMON_PARTS',
  18042. 'points="', points.join(''),
  18043. '" />\n'
  18044. ];
  18045. },
  18046. /* _TO_SVG_END_ */
  18047. /**
  18048. * @private
  18049. * @param {CanvasRenderingContext2D} ctx Context to render on
  18050. */
  18051. commonRender: function(ctx) {
  18052. var point, len = this.points.length,
  18053. x = this.pathOffset.x,
  18054. y = this.pathOffset.y;
  18055. if (!len || isNaN(this.points[len - 1].y)) {
  18056. // do not draw if no points or odd points
  18057. // NaN comes from parseFloat of a empty string in parser
  18058. return false;
  18059. }
  18060. ctx.beginPath();
  18061. ctx.moveTo(this.points[0].x - x, this.points[0].y - y);
  18062. for (var i = 0; i < len; i++) {
  18063. point = this.points[i];
  18064. ctx.lineTo(point.x - x, point.y - y);
  18065. }
  18066. return true;
  18067. },
  18068. /**
  18069. * @private
  18070. * @param {CanvasRenderingContext2D} ctx Context to render on
  18071. */
  18072. _render: function(ctx) {
  18073. if (!this.commonRender(ctx)) {
  18074. return;
  18075. }
  18076. this._renderPaintInOrder(ctx);
  18077. },
  18078. /**
  18079. * Returns complexity of an instance
  18080. * @return {Number} complexity of this instance
  18081. */
  18082. complexity: function() {
  18083. return this.get('points').length;
  18084. }
  18085. });
  18086. /* _FROM_SVG_START_ */
  18087. /**
  18088. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Polyline.fromElement})
  18089. * @static
  18090. * @memberOf fabric.Polyline
  18091. * @see: http://www.w3.org/TR/SVG/shapes.html#PolylineElement
  18092. */
  18093. fabric.Polyline.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();
  18094. /**
  18095. * Returns fabric.Polyline instance from an SVG element
  18096. * @static
  18097. * @memberOf fabric.Polyline
  18098. * @param {SVGElement} element Element to parser
  18099. * @param {Function} callback callback function invoked after parsing
  18100. * @param {Object} [options] Options object
  18101. */
  18102. fabric.Polyline.fromElementGenerator = function(_class) {
  18103. return function(element, callback, options) {
  18104. if (!element) {
  18105. return callback(null);
  18106. }
  18107. options || (options = { });
  18108. var points = fabric.parsePointsAttribute(element.getAttribute('points')),
  18109. parsedAttributes = fabric.parseAttributes(element, fabric[_class].ATTRIBUTE_NAMES);
  18110. parsedAttributes.fromSVG = true;
  18111. callback(new fabric[_class](points, extend(parsedAttributes, options)));
  18112. };
  18113. };
  18114. fabric.Polyline.fromElement = fabric.Polyline.fromElementGenerator('Polyline');
  18115. /* _FROM_SVG_END_ */
  18116. /**
  18117. * Returns fabric.Polyline instance from an object representation
  18118. * @static
  18119. * @memberOf fabric.Polyline
  18120. * @param {Object} object Object to create an instance from
  18121. * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created
  18122. */
  18123. fabric.Polyline.fromObject = function(object, callback) {
  18124. return fabric.Object._fromObject('Polyline', object, callback, 'points');
  18125. };
  18126. })(typeof exports !== 'undefined' ? exports : this);
  18127. (function(global) {
  18128. 'use strict';
  18129. var fabric = global.fabric || (global.fabric = {}),
  18130. projectStrokeOnPoints = fabric.util.projectStrokeOnPoints;
  18131. if (fabric.Polygon) {
  18132. fabric.warn('fabric.Polygon is already defined');
  18133. return;
  18134. }
  18135. /**
  18136. * Polygon class
  18137. * @class fabric.Polygon
  18138. * @extends fabric.Polyline
  18139. * @see {@link fabric.Polygon#initialize} for constructor definition
  18140. */
  18141. fabric.Polygon = fabric.util.createClass(fabric.Polyline, /** @lends fabric.Polygon.prototype */ {
  18142. /**
  18143. * Type of an object
  18144. * @type String
  18145. * @default
  18146. */
  18147. type: 'polygon',
  18148. /**
  18149. * @private
  18150. */
  18151. _projectStrokeOnPoints: function () {
  18152. return projectStrokeOnPoints(this.points, this);
  18153. },
  18154. /**
  18155. * @private
  18156. * @param {CanvasRenderingContext2D} ctx Context to render on
  18157. */
  18158. _render: function(ctx) {
  18159. if (!this.commonRender(ctx)) {
  18160. return;
  18161. }
  18162. ctx.closePath();
  18163. this._renderPaintInOrder(ctx);
  18164. },
  18165. });
  18166. /* _FROM_SVG_START_ */
  18167. /**
  18168. * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`)
  18169. * @static
  18170. * @memberOf fabric.Polygon
  18171. * @see: http://www.w3.org/TR/SVG/shapes.html#PolygonElement
  18172. */
  18173. fabric.Polygon.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();
  18174. /**
  18175. * Returns {@link fabric.Polygon} instance from an SVG element
  18176. * @static
  18177. * @memberOf fabric.Polygon
  18178. * @param {SVGElement} element Element to parse
  18179. * @param {Function} callback callback function invoked after parsing
  18180. * @param {Object} [options] Options object
  18181. */
  18182. fabric.Polygon.fromElement = fabric.Polyline.fromElementGenerator('Polygon');
  18183. /* _FROM_SVG_END_ */
  18184. /**
  18185. * Returns fabric.Polygon instance from an object representation
  18186. * @static
  18187. * @memberOf fabric.Polygon
  18188. * @param {Object} object Object to create an instance from
  18189. * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created
  18190. * @return {void}
  18191. */
  18192. fabric.Polygon.fromObject = function(object, callback) {
  18193. fabric.Object._fromObject('Polygon', object, callback, 'points');
  18194. };
  18195. })(typeof exports !== 'undefined' ? exports : this);
  18196. (function(global) {
  18197. 'use strict';
  18198. var fabric = global.fabric || (global.fabric = { }),
  18199. min = fabric.util.array.min,
  18200. max = fabric.util.array.max,
  18201. extend = fabric.util.object.extend,
  18202. clone = fabric.util.object.clone,
  18203. toFixed = fabric.util.toFixed;
  18204. if (fabric.Path) {
  18205. fabric.warn('fabric.Path is already defined');
  18206. return;
  18207. }
  18208. /**
  18209. * Path class
  18210. * @class fabric.Path
  18211. * @extends fabric.Object
  18212. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#path_and_pathgroup}
  18213. * @see {@link fabric.Path#initialize} for constructor definition
  18214. */
  18215. fabric.Path = fabric.util.createClass(fabric.Object, /** @lends fabric.Path.prototype */ {
  18216. /**
  18217. * Type of an object
  18218. * @type String
  18219. * @default
  18220. */
  18221. type: 'path',
  18222. /**
  18223. * Array of path points
  18224. * @type Array
  18225. * @default
  18226. */
  18227. path: null,
  18228. cacheProperties: fabric.Object.prototype.cacheProperties.concat('path', 'fillRule'),
  18229. stateProperties: fabric.Object.prototype.stateProperties.concat('path'),
  18230. /**
  18231. * Constructor
  18232. * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens)
  18233. * @param {Object} [options] Options object
  18234. * @return {fabric.Path} thisArg
  18235. */
  18236. initialize: function (path, options) {
  18237. options = clone(options || {});
  18238. delete options.path;
  18239. this.callSuper('initialize', options);
  18240. this._setPath(path || [], options);
  18241. },
  18242. /**
  18243. * @private
  18244. * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens)
  18245. * @param {Object} [options] Options object
  18246. */
  18247. _setPath: function (path, options) {
  18248. this.path = fabric.util.makePathSimpler(
  18249. Array.isArray(path) ? path : fabric.util.parsePath(path)
  18250. );
  18251. fabric.Polyline.prototype._setPositionDimensions.call(this, options || {});
  18252. },
  18253. /**
  18254. * @private
  18255. * @param {CanvasRenderingContext2D} ctx context to render path on
  18256. */
  18257. _renderPathCommands: function(ctx) {
  18258. var current, // current instruction
  18259. subpathStartX = 0,
  18260. subpathStartY = 0,
  18261. x = 0, // current x
  18262. y = 0, // current y
  18263. controlX = 0, // current control point x
  18264. controlY = 0, // current control point y
  18265. l = -this.pathOffset.x,
  18266. t = -this.pathOffset.y;
  18267. ctx.beginPath();
  18268. for (var i = 0, len = this.path.length; i < len; ++i) {
  18269. current = this.path[i];
  18270. switch (current[0]) { // first letter
  18271. case 'L': // lineto, absolute
  18272. x = current[1];
  18273. y = current[2];
  18274. ctx.lineTo(x + l, y + t);
  18275. break;
  18276. case 'M': // moveTo, absolute
  18277. x = current[1];
  18278. y = current[2];
  18279. subpathStartX = x;
  18280. subpathStartY = y;
  18281. ctx.moveTo(x + l, y + t);
  18282. break;
  18283. case 'C': // bezierCurveTo, absolute
  18284. x = current[5];
  18285. y = current[6];
  18286. controlX = current[3];
  18287. controlY = current[4];
  18288. ctx.bezierCurveTo(
  18289. current[1] + l,
  18290. current[2] + t,
  18291. controlX + l,
  18292. controlY + t,
  18293. x + l,
  18294. y + t
  18295. );
  18296. break;
  18297. case 'Q': // quadraticCurveTo, absolute
  18298. ctx.quadraticCurveTo(
  18299. current[1] + l,
  18300. current[2] + t,
  18301. current[3] + l,
  18302. current[4] + t
  18303. );
  18304. x = current[3];
  18305. y = current[4];
  18306. controlX = current[1];
  18307. controlY = current[2];
  18308. break;
  18309. case 'z':
  18310. case 'Z':
  18311. x = subpathStartX;
  18312. y = subpathStartY;
  18313. ctx.closePath();
  18314. break;
  18315. }
  18316. }
  18317. },
  18318. /**
  18319. * @private
  18320. * @param {CanvasRenderingContext2D} ctx context to render path on
  18321. */
  18322. _render: function(ctx) {
  18323. this._renderPathCommands(ctx);
  18324. this._renderPaintInOrder(ctx);
  18325. },
  18326. /**
  18327. * Returns string representation of an instance
  18328. * @return {String} string representation of an instance
  18329. */
  18330. toString: function() {
  18331. return '#<fabric.Path (' + this.complexity() +
  18332. '): { "top": ' + this.top + ', "left": ' + this.left + ' }>';
  18333. },
  18334. /**
  18335. * Returns object representation of an instance
  18336. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18337. * @return {Object} object representation of an instance
  18338. */
  18339. toObject: function(propertiesToInclude) {
  18340. return extend(this.callSuper('toObject', propertiesToInclude), {
  18341. path: this.path.map(function(item) { return item.slice(); }),
  18342. });
  18343. },
  18344. /**
  18345. * Returns dataless object representation of an instance
  18346. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18347. * @return {Object} object representation of an instance
  18348. */
  18349. toDatalessObject: function(propertiesToInclude) {
  18350. var o = this.toObject(['sourcePath'].concat(propertiesToInclude));
  18351. if (o.sourcePath) {
  18352. delete o.path;
  18353. }
  18354. return o;
  18355. },
  18356. /* _TO_SVG_START_ */
  18357. /**
  18358. * Returns svg representation of an instance
  18359. * @return {Array} an array of strings with the specific svg representation
  18360. * of the instance
  18361. */
  18362. _toSVG: function() {
  18363. var path = fabric.util.joinPath(this.path);
  18364. return [
  18365. '<path ', 'COMMON_PARTS',
  18366. 'd="', path,
  18367. '" stroke-linecap="round" ',
  18368. '/>\n'
  18369. ];
  18370. },
  18371. _getOffsetTransform: function() {
  18372. var digits = fabric.Object.NUM_FRACTION_DIGITS;
  18373. return ' translate(' + toFixed(-this.pathOffset.x, digits) + ', ' +
  18374. toFixed(-this.pathOffset.y, digits) + ')';
  18375. },
  18376. /**
  18377. * Returns svg clipPath representation of an instance
  18378. * @param {Function} [reviver] Method for further parsing of svg representation.
  18379. * @return {String} svg representation of an instance
  18380. */
  18381. toClipPathSVG: function(reviver) {
  18382. var additionalTransform = this._getOffsetTransform();
  18383. return '\t' + this._createBaseClipPathSVGMarkup(
  18384. this._toSVG(), { reviver: reviver, additionalTransform: additionalTransform }
  18385. );
  18386. },
  18387. /**
  18388. * Returns svg representation of an instance
  18389. * @param {Function} [reviver] Method for further parsing of svg representation.
  18390. * @return {String} svg representation of an instance
  18391. */
  18392. toSVG: function(reviver) {
  18393. var additionalTransform = this._getOffsetTransform();
  18394. return this._createBaseSVGMarkup(this._toSVG(), { reviver: reviver, additionalTransform: additionalTransform });
  18395. },
  18396. /* _TO_SVG_END_ */
  18397. /**
  18398. * Returns number representation of an instance complexity
  18399. * @return {Number} complexity of this instance
  18400. */
  18401. complexity: function() {
  18402. return this.path.length;
  18403. },
  18404. /**
  18405. * @private
  18406. */
  18407. _calcDimensions: function() {
  18408. var aX = [],
  18409. aY = [],
  18410. current, // current instruction
  18411. subpathStartX = 0,
  18412. subpathStartY = 0,
  18413. x = 0, // current x
  18414. y = 0, // current y
  18415. bounds;
  18416. for (var i = 0, len = this.path.length; i < len; ++i) {
  18417. current = this.path[i];
  18418. switch (current[0]) { // first letter
  18419. case 'L': // lineto, absolute
  18420. x = current[1];
  18421. y = current[2];
  18422. bounds = [];
  18423. break;
  18424. case 'M': // moveTo, absolute
  18425. x = current[1];
  18426. y = current[2];
  18427. subpathStartX = x;
  18428. subpathStartY = y;
  18429. bounds = [];
  18430. break;
  18431. case 'C': // bezierCurveTo, absolute
  18432. bounds = fabric.util.getBoundsOfCurve(x, y,
  18433. current[1],
  18434. current[2],
  18435. current[3],
  18436. current[4],
  18437. current[5],
  18438. current[6]
  18439. );
  18440. x = current[5];
  18441. y = current[6];
  18442. break;
  18443. case 'Q': // quadraticCurveTo, absolute
  18444. bounds = fabric.util.getBoundsOfCurve(x, y,
  18445. current[1],
  18446. current[2],
  18447. current[1],
  18448. current[2],
  18449. current[3],
  18450. current[4]
  18451. );
  18452. x = current[3];
  18453. y = current[4];
  18454. break;
  18455. case 'z':
  18456. case 'Z':
  18457. x = subpathStartX;
  18458. y = subpathStartY;
  18459. break;
  18460. }
  18461. bounds.forEach(function (point) {
  18462. aX.push(point.x);
  18463. aY.push(point.y);
  18464. });
  18465. aX.push(x);
  18466. aY.push(y);
  18467. }
  18468. var minX = min(aX) || 0,
  18469. minY = min(aY) || 0,
  18470. maxX = max(aX) || 0,
  18471. maxY = max(aY) || 0,
  18472. deltaX = maxX - minX,
  18473. deltaY = maxY - minY;
  18474. return {
  18475. left: minX,
  18476. top: minY,
  18477. width: deltaX,
  18478. height: deltaY
  18479. };
  18480. }
  18481. });
  18482. /**
  18483. * Creates an instance of fabric.Path from an object
  18484. * @static
  18485. * @memberOf fabric.Path
  18486. * @param {Object} object
  18487. * @param {Function} [callback] Callback to invoke when an fabric.Path instance is created
  18488. */
  18489. fabric.Path.fromObject = function(object, callback) {
  18490. if (typeof object.sourcePath === 'string') {
  18491. var pathUrl = object.sourcePath;
  18492. fabric.loadSVGFromURL(pathUrl, function (elements) {
  18493. var path = elements[0];
  18494. path.setOptions(object);
  18495. callback && callback(path);
  18496. });
  18497. }
  18498. else {
  18499. fabric.Object._fromObject('Path', object, callback, 'path');
  18500. }
  18501. };
  18502. /* _FROM_SVG_START_ */
  18503. /**
  18504. * List of attribute names to account for when parsing SVG element (used by `fabric.Path.fromElement`)
  18505. * @static
  18506. * @memberOf fabric.Path
  18507. * @see http://www.w3.org/TR/SVG/paths.html#PathElement
  18508. */
  18509. fabric.Path.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(['d']);
  18510. /**
  18511. * Creates an instance of fabric.Path from an SVG <path> element
  18512. * @static
  18513. * @memberOf fabric.Path
  18514. * @param {SVGElement} element to parse
  18515. * @param {Function} callback Callback to invoke when an fabric.Path instance is created
  18516. * @param {Object} [options] Options object
  18517. * @param {Function} [callback] Options callback invoked after parsing is finished
  18518. */
  18519. fabric.Path.fromElement = function(element, callback, options) {
  18520. var parsedAttributes = fabric.parseAttributes(element, fabric.Path.ATTRIBUTE_NAMES);
  18521. parsedAttributes.fromSVG = true;
  18522. callback(new fabric.Path(parsedAttributes.d, extend(parsedAttributes, options)));
  18523. };
  18524. /* _FROM_SVG_END_ */
  18525. })(typeof exports !== 'undefined' ? exports : this);
  18526. (function(global) {
  18527. 'use strict';
  18528. var fabric = global.fabric || (global.fabric = { }),
  18529. min = fabric.util.array.min,
  18530. max = fabric.util.array.max;
  18531. if (fabric.Group) {
  18532. return;
  18533. }
  18534. /**
  18535. * Group class
  18536. * @class fabric.Group
  18537. * @extends fabric.Object
  18538. * @mixes fabric.Collection
  18539. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#groups}
  18540. * @see {@link fabric.Group#initialize} for constructor definition
  18541. */
  18542. fabric.Group = fabric.util.createClass(fabric.Object, fabric.Collection, /** @lends fabric.Group.prototype */ {
  18543. /**
  18544. * Type of an object
  18545. * @type String
  18546. * @default
  18547. */
  18548. type: 'group',
  18549. /**
  18550. * Width of stroke
  18551. * @type Number
  18552. * @default
  18553. */
  18554. strokeWidth: 0,
  18555. /**
  18556. * Indicates if click, mouseover, mouseout events & hoverCursor should also check for subtargets
  18557. * @type Boolean
  18558. * @default
  18559. */
  18560. subTargetCheck: false,
  18561. /**
  18562. * Groups are container, do not render anything on theyr own, ence no cache properties
  18563. * @type Array
  18564. * @default
  18565. */
  18566. cacheProperties: [],
  18567. /**
  18568. * setOnGroup is a method used for TextBox that is no more used since 2.0.0 The behavior is still
  18569. * available setting this boolean to true.
  18570. * @type Boolean
  18571. * @since 2.0.0
  18572. * @default
  18573. */
  18574. useSetOnGroup: false,
  18575. /**
  18576. * Constructor
  18577. * @param {Object} objects Group objects
  18578. * @param {Object} [options] Options object
  18579. * @param {Boolean} [isAlreadyGrouped] if true, objects have been grouped already.
  18580. * @return {Object} thisArg
  18581. */
  18582. initialize: function(objects, options, isAlreadyGrouped) {
  18583. options = options || {};
  18584. this._objects = [];
  18585. // if objects enclosed in a group have been grouped already,
  18586. // we cannot change properties of objects.
  18587. // Thus we need to set options to group without objects,
  18588. isAlreadyGrouped && this.callSuper('initialize', options);
  18589. this._objects = objects || [];
  18590. for (var i = this._objects.length; i--; ) {
  18591. this._objects[i].group = this;
  18592. }
  18593. if (!isAlreadyGrouped) {
  18594. var center = options && options.centerPoint;
  18595. // we want to set origins before calculating the bounding box.
  18596. // so that the topleft can be set with that in mind.
  18597. // if specific top and left are passed, are overwritten later
  18598. // with the callSuper('initialize', options)
  18599. if (options.originX !== undefined) {
  18600. this.originX = options.originX;
  18601. }
  18602. if (options.originY !== undefined) {
  18603. this.originY = options.originY;
  18604. }
  18605. // if coming from svg i do not want to calc bounds.
  18606. // i assume width and height are passed along options
  18607. center || this._calcBounds();
  18608. this._updateObjectsCoords(center);
  18609. delete options.centerPoint;
  18610. this.callSuper('initialize', options);
  18611. }
  18612. else {
  18613. this._updateObjectsACoords();
  18614. }
  18615. this.setCoords();
  18616. },
  18617. /**
  18618. * @private
  18619. */
  18620. _updateObjectsACoords: function() {
  18621. var skipControls = true;
  18622. for (var i = this._objects.length; i--; ){
  18623. this._objects[i].setCoords(skipControls);
  18624. }
  18625. },
  18626. /**
  18627. * @private
  18628. * @param {Boolean} [skipCoordsChange] if true, coordinates of objects enclosed in a group do not change
  18629. */
  18630. _updateObjectsCoords: function(center) {
  18631. var center = center || this.getCenterPoint();
  18632. for (var i = this._objects.length; i--; ){
  18633. this._updateObjectCoords(this._objects[i], center);
  18634. }
  18635. },
  18636. /**
  18637. * @private
  18638. * @param {Object} object
  18639. * @param {fabric.Point} center, current center of group.
  18640. */
  18641. _updateObjectCoords: function(object, center) {
  18642. var objectLeft = object.left,
  18643. objectTop = object.top,
  18644. skipControls = true;
  18645. object.set({
  18646. left: objectLeft - center.x,
  18647. top: objectTop - center.y
  18648. });
  18649. object.group = this;
  18650. object.setCoords(skipControls);
  18651. },
  18652. /**
  18653. * Returns string represenation of a group
  18654. * @return {String}
  18655. */
  18656. toString: function() {
  18657. return '#<fabric.Group: (' + this.complexity() + ')>';
  18658. },
  18659. /**
  18660. * Adds an object to a group; Then recalculates group's dimension, position.
  18661. * @param {Object} object
  18662. * @return {fabric.Group} thisArg
  18663. * @chainable
  18664. */
  18665. addWithUpdate: function(object) {
  18666. var nested = !!this.group;
  18667. this._restoreObjectsState();
  18668. fabric.util.resetObjectTransform(this);
  18669. if (object) {
  18670. if (nested) {
  18671. // if this group is inside another group, we need to pre transform the object
  18672. fabric.util.removeTransformFromObject(object, this.group.calcTransformMatrix());
  18673. }
  18674. this._objects.push(object);
  18675. object.group = this;
  18676. object._set('canvas', this.canvas);
  18677. }
  18678. this._calcBounds();
  18679. this._updateObjectsCoords();
  18680. this.dirty = true;
  18681. if (nested) {
  18682. this.group.addWithUpdate();
  18683. }
  18684. else {
  18685. this.setCoords();
  18686. }
  18687. return this;
  18688. },
  18689. /**
  18690. * Removes an object from a group; Then recalculates group's dimension, position.
  18691. * @param {Object} object
  18692. * @return {fabric.Group} thisArg
  18693. * @chainable
  18694. */
  18695. removeWithUpdate: function(object) {
  18696. this._restoreObjectsState();
  18697. fabric.util.resetObjectTransform(this);
  18698. this.remove(object);
  18699. this._calcBounds();
  18700. this._updateObjectsCoords();
  18701. this.setCoords();
  18702. this.dirty = true;
  18703. return this;
  18704. },
  18705. /**
  18706. * @private
  18707. */
  18708. _onObjectAdded: function(object) {
  18709. this.dirty = true;
  18710. object.group = this;
  18711. object._set('canvas', this.canvas);
  18712. },
  18713. /**
  18714. * @private
  18715. */
  18716. _onObjectRemoved: function(object) {
  18717. this.dirty = true;
  18718. delete object.group;
  18719. },
  18720. /**
  18721. * @private
  18722. */
  18723. _set: function(key, value) {
  18724. var i = this._objects.length;
  18725. if (this.useSetOnGroup) {
  18726. while (i--) {
  18727. this._objects[i].setOnGroup(key, value);
  18728. }
  18729. }
  18730. if (key === 'canvas') {
  18731. while (i--) {
  18732. this._objects[i]._set(key, value);
  18733. }
  18734. }
  18735. fabric.Object.prototype._set.call(this, key, value);
  18736. },
  18737. /**
  18738. * Returns object representation of an instance
  18739. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18740. * @return {Object} object representation of an instance
  18741. */
  18742. toObject: function(propertiesToInclude) {
  18743. var _includeDefaultValues = this.includeDefaultValues;
  18744. var objsToObject = this._objects
  18745. .filter(function (obj) {
  18746. return !obj.excludeFromExport;
  18747. })
  18748. .map(function (obj) {
  18749. var originalDefaults = obj.includeDefaultValues;
  18750. obj.includeDefaultValues = _includeDefaultValues;
  18751. var _obj = obj.toObject(propertiesToInclude);
  18752. obj.includeDefaultValues = originalDefaults;
  18753. return _obj;
  18754. });
  18755. var obj = fabric.Object.prototype.toObject.call(this, propertiesToInclude);
  18756. obj.objects = objsToObject;
  18757. return obj;
  18758. },
  18759. /**
  18760. * Returns object representation of an instance, in dataless mode.
  18761. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18762. * @return {Object} object representation of an instance
  18763. */
  18764. toDatalessObject: function(propertiesToInclude) {
  18765. var objsToObject, sourcePath = this.sourcePath;
  18766. if (sourcePath) {
  18767. objsToObject = sourcePath;
  18768. }
  18769. else {
  18770. var _includeDefaultValues = this.includeDefaultValues;
  18771. objsToObject = this._objects.map(function(obj) {
  18772. var originalDefaults = obj.includeDefaultValues;
  18773. obj.includeDefaultValues = _includeDefaultValues;
  18774. var _obj = obj.toDatalessObject(propertiesToInclude);
  18775. obj.includeDefaultValues = originalDefaults;
  18776. return _obj;
  18777. });
  18778. }
  18779. var obj = fabric.Object.prototype.toDatalessObject.call(this, propertiesToInclude);
  18780. obj.objects = objsToObject;
  18781. return obj;
  18782. },
  18783. /**
  18784. * Renders instance on a given context
  18785. * @param {CanvasRenderingContext2D} ctx context to render instance on
  18786. */
  18787. render: function(ctx) {
  18788. this._transformDone = true;
  18789. this.callSuper('render', ctx);
  18790. this._transformDone = false;
  18791. },
  18792. /**
  18793. * Decide if the object should cache or not. Create its own cache level
  18794. * needsItsOwnCache should be used when the object drawing method requires
  18795. * a cache step. None of the fabric classes requires it.
  18796. * Generally you do not cache objects in groups because the group is already cached.
  18797. * @return {Boolean}
  18798. */
  18799. shouldCache: function() {
  18800. var ownCache = fabric.Object.prototype.shouldCache.call(this);
  18801. if (ownCache) {
  18802. for (var i = 0, len = this._objects.length; i < len; i++) {
  18803. if (this._objects[i].willDrawShadow()) {
  18804. this.ownCaching = false;
  18805. return false;
  18806. }
  18807. }
  18808. }
  18809. return ownCache;
  18810. },
  18811. /**
  18812. * Check if this object or a child object will cast a shadow
  18813. * @return {Boolean}
  18814. */
  18815. willDrawShadow: function() {
  18816. if (fabric.Object.prototype.willDrawShadow.call(this)) {
  18817. return true;
  18818. }
  18819. for (var i = 0, len = this._objects.length; i < len; i++) {
  18820. if (this._objects[i].willDrawShadow()) {
  18821. return true;
  18822. }
  18823. }
  18824. return false;
  18825. },
  18826. /**
  18827. * Check if this group or its parent group are caching, recursively up
  18828. * @return {Boolean}
  18829. */
  18830. isOnACache: function() {
  18831. return this.ownCaching || (this.group && this.group.isOnACache());
  18832. },
  18833. /**
  18834. * Execute the drawing operation for an object on a specified context
  18835. * @param {CanvasRenderingContext2D} ctx Context to render on
  18836. */
  18837. drawObject: function(ctx) {
  18838. for (var i = 0, len = this._objects.length; i < len; i++) {
  18839. this._objects[i].render(ctx);
  18840. }
  18841. this._drawClipPath(ctx, this.clipPath);
  18842. },
  18843. /**
  18844. * Check if cache is dirty
  18845. */
  18846. isCacheDirty: function(skipCanvas) {
  18847. if (this.callSuper('isCacheDirty', skipCanvas)) {
  18848. return true;
  18849. }
  18850. if (!this.statefullCache) {
  18851. return false;
  18852. }
  18853. for (var i = 0, len = this._objects.length; i < len; i++) {
  18854. if (this._objects[i].isCacheDirty(true)) {
  18855. if (this._cacheCanvas) {
  18856. // if this group has not a cache canvas there is nothing to clean
  18857. var x = this.cacheWidth / this.zoomX, y = this.cacheHeight / this.zoomY;
  18858. this._cacheContext.clearRect(-x / 2, -y / 2, x, y);
  18859. }
  18860. return true;
  18861. }
  18862. }
  18863. return false;
  18864. },
  18865. /**
  18866. * Restores original state of each of group objects (original state is that which was before group was created).
  18867. * if the nested boolean is true, the original state will be restored just for the
  18868. * first group and not for all the group chain
  18869. * @private
  18870. * @param {Boolean} nested tell the function to restore object state up to the parent group and not more
  18871. * @return {fabric.Group} thisArg
  18872. * @chainable
  18873. */
  18874. _restoreObjectsState: function() {
  18875. var groupMatrix = this.calcOwnMatrix();
  18876. this._objects.forEach(function(object) {
  18877. // instead of using _this = this;
  18878. fabric.util.addTransformToObject(object, groupMatrix);
  18879. delete object.group;
  18880. object.setCoords();
  18881. });
  18882. return this;
  18883. },
  18884. /**
  18885. * Destroys a group (restoring state of its objects)
  18886. * @return {fabric.Group} thisArg
  18887. * @chainable
  18888. */
  18889. destroy: function() {
  18890. // when group is destroyed objects needs to get a repaint to be eventually
  18891. // displayed on canvas.
  18892. this._objects.forEach(function(object) {
  18893. object.set('dirty', true);
  18894. });
  18895. return this._restoreObjectsState();
  18896. },
  18897. dispose: function () {
  18898. this.callSuper('dispose');
  18899. this.forEachObject(function (object) {
  18900. object.dispose && object.dispose();
  18901. });
  18902. this._objects = [];
  18903. },
  18904. /**
  18905. * make a group an active selection, remove the group from canvas
  18906. * the group has to be on canvas for this to work.
  18907. * @return {fabric.ActiveSelection} thisArg
  18908. * @chainable
  18909. */
  18910. toActiveSelection: function() {
  18911. if (!this.canvas) {
  18912. return;
  18913. }
  18914. var objects = this._objects, canvas = this.canvas;
  18915. this._objects = [];
  18916. var options = this.toObject();
  18917. delete options.objects;
  18918. var activeSelection = new fabric.ActiveSelection([]);
  18919. activeSelection.set(options);
  18920. activeSelection.type = 'activeSelection';
  18921. canvas.remove(this);
  18922. objects.forEach(function(object) {
  18923. object.group = activeSelection;
  18924. object.dirty = true;
  18925. canvas.add(object);
  18926. });
  18927. activeSelection.canvas = canvas;
  18928. activeSelection._objects = objects;
  18929. canvas._activeObject = activeSelection;
  18930. activeSelection.setCoords();
  18931. return activeSelection;
  18932. },
  18933. /**
  18934. * Destroys a group (restoring state of its objects)
  18935. * @return {fabric.Group} thisArg
  18936. * @chainable
  18937. */
  18938. ungroupOnCanvas: function() {
  18939. return this._restoreObjectsState();
  18940. },
  18941. /**
  18942. * Sets coordinates of all objects inside group
  18943. * @return {fabric.Group} thisArg
  18944. * @chainable
  18945. */
  18946. setObjectsCoords: function() {
  18947. var skipControls = true;
  18948. this.forEachObject(function(object) {
  18949. object.setCoords(skipControls);
  18950. });
  18951. return this;
  18952. },
  18953. /**
  18954. * @private
  18955. */
  18956. _calcBounds: function(onlyWidthHeight) {
  18957. var aX = [],
  18958. aY = [],
  18959. o, prop, coords,
  18960. props = ['tr', 'br', 'bl', 'tl'],
  18961. i = 0, iLen = this._objects.length,
  18962. j, jLen = props.length;
  18963. for ( ; i < iLen; ++i) {
  18964. o = this._objects[i];
  18965. coords = o.calcACoords();
  18966. for (j = 0; j < jLen; j++) {
  18967. prop = props[j];
  18968. aX.push(coords[prop].x);
  18969. aY.push(coords[prop].y);
  18970. }
  18971. o.aCoords = coords;
  18972. }
  18973. this._getBounds(aX, aY, onlyWidthHeight);
  18974. },
  18975. /**
  18976. * @private
  18977. */
  18978. _getBounds: function(aX, aY, onlyWidthHeight) {
  18979. var minXY = new fabric.Point(min(aX), min(aY)),
  18980. maxXY = new fabric.Point(max(aX), max(aY)),
  18981. top = minXY.y || 0, left = minXY.x || 0,
  18982. width = (maxXY.x - minXY.x) || 0,
  18983. height = (maxXY.y - minXY.y) || 0;
  18984. this.width = width;
  18985. this.height = height;
  18986. if (!onlyWidthHeight) {
  18987. // the bounding box always finds the topleft most corner.
  18988. // whatever is the group origin, we set up here the left/top position.
  18989. this.setPositionByOrigin({ x: left, y: top }, 'left', 'top');
  18990. }
  18991. },
  18992. /* _TO_SVG_START_ */
  18993. /**
  18994. * Returns svg representation of an instance
  18995. * @param {Function} [reviver] Method for further parsing of svg representation.
  18996. * @return {String} svg representation of an instance
  18997. */
  18998. _toSVG: function(reviver) {
  18999. var svgString = ['<g ', 'COMMON_PARTS', ' >\n'];
  19000. for (var i = 0, len = this._objects.length; i < len; i++) {
  19001. svgString.push('\t\t', this._objects[i].toSVG(reviver));
  19002. }
  19003. svgString.push('</g>\n');
  19004. return svgString;
  19005. },
  19006. /**
  19007. * Returns styles-string for svg-export, specific version for group
  19008. * @return {String}
  19009. */
  19010. getSvgStyles: function() {
  19011. var opacity = typeof this.opacity !== 'undefined' && this.opacity !== 1 ?
  19012. 'opacity: ' + this.opacity + ';' : '',
  19013. visibility = this.visible ? '' : ' visibility: hidden;';
  19014. return [
  19015. opacity,
  19016. this.getSvgFilter(),
  19017. visibility
  19018. ].join('');
  19019. },
  19020. /**
  19021. * Returns svg clipPath representation of an instance
  19022. * @param {Function} [reviver] Method for further parsing of svg representation.
  19023. * @return {String} svg representation of an instance
  19024. */
  19025. toClipPathSVG: function(reviver) {
  19026. var svgString = [];
  19027. for (var i = 0, len = this._objects.length; i < len; i++) {
  19028. svgString.push('\t', this._objects[i].toClipPathSVG(reviver));
  19029. }
  19030. return this._createBaseClipPathSVGMarkup(svgString, { reviver: reviver });
  19031. },
  19032. /* _TO_SVG_END_ */
  19033. });
  19034. /**
  19035. * Returns {@link fabric.Group} instance from an object representation
  19036. * @static
  19037. * @memberOf fabric.Group
  19038. * @param {Object} object Object to create a group from
  19039. * @param {Function} [callback] Callback to invoke when an group instance is created
  19040. */
  19041. fabric.Group.fromObject = function(object, callback) {
  19042. var objects = object.objects,
  19043. options = fabric.util.object.clone(object, true);
  19044. delete options.objects;
  19045. if (typeof objects === 'string') {
  19046. // it has to be an url or something went wrong.
  19047. fabric.loadSVGFromURL(objects, function (elements) {
  19048. var group = fabric.util.groupSVGElements(elements, object, objects);
  19049. group.set(options);
  19050. callback && callback(group);
  19051. });
  19052. return;
  19053. }
  19054. fabric.util.enlivenObjects(objects, function (enlivenedObjects) {
  19055. var options = fabric.util.object.clone(object, true);
  19056. delete options.objects;
  19057. fabric.util.enlivenObjectEnlivables(object, options, function () {
  19058. callback && callback(new fabric.Group(enlivenedObjects, options, true));
  19059. });
  19060. });
  19061. };
  19062. })(typeof exports !== 'undefined' ? exports : this);
  19063. (function(global) {
  19064. 'use strict';
  19065. var fabric = global.fabric || (global.fabric = { });
  19066. if (fabric.ActiveSelection) {
  19067. return;
  19068. }
  19069. /**
  19070. * Group class
  19071. * @class fabric.ActiveSelection
  19072. * @extends fabric.Group
  19073. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3#groups}
  19074. * @see {@link fabric.ActiveSelection#initialize} for constructor definition
  19075. */
  19076. fabric.ActiveSelection = fabric.util.createClass(fabric.Group, /** @lends fabric.ActiveSelection.prototype */ {
  19077. /**
  19078. * Type of an object
  19079. * @type String
  19080. * @default
  19081. */
  19082. type: 'activeSelection',
  19083. /**
  19084. * Constructor
  19085. * @param {Object} objects ActiveSelection objects
  19086. * @param {Object} [options] Options object
  19087. * @return {Object} thisArg
  19088. */
  19089. initialize: function(objects, options) {
  19090. options = options || {};
  19091. this._objects = objects || [];
  19092. for (var i = this._objects.length; i--; ) {
  19093. this._objects[i].group = this;
  19094. }
  19095. if (options.originX) {
  19096. this.originX = options.originX;
  19097. }
  19098. if (options.originY) {
  19099. this.originY = options.originY;
  19100. }
  19101. this._calcBounds();
  19102. this._updateObjectsCoords();
  19103. fabric.Object.prototype.initialize.call(this, options);
  19104. this.setCoords();
  19105. },
  19106. /**
  19107. * Change te activeSelection to a normal group,
  19108. * High level function that automatically adds it to canvas as
  19109. * active object. no events fired.
  19110. * @since 2.0.0
  19111. * @return {fabric.Group}
  19112. */
  19113. toGroup: function() {
  19114. var objects = this._objects.concat();
  19115. this._objects = [];
  19116. var options = fabric.Object.prototype.toObject.call(this);
  19117. var newGroup = new fabric.Group([]);
  19118. delete options.type;
  19119. newGroup.set(options);
  19120. objects.forEach(function(object) {
  19121. object.canvas.remove(object);
  19122. object.group = newGroup;
  19123. });
  19124. newGroup._objects = objects;
  19125. if (!this.canvas) {
  19126. return newGroup;
  19127. }
  19128. var canvas = this.canvas;
  19129. canvas.add(newGroup);
  19130. canvas._activeObject = newGroup;
  19131. newGroup.setCoords();
  19132. return newGroup;
  19133. },
  19134. /**
  19135. * If returns true, deselection is cancelled.
  19136. * @since 2.0.0
  19137. * @return {Boolean} [cancel]
  19138. */
  19139. onDeselect: function() {
  19140. this.destroy();
  19141. return false;
  19142. },
  19143. /**
  19144. * Returns string representation of a group
  19145. * @return {String}
  19146. */
  19147. toString: function() {
  19148. return '#<fabric.ActiveSelection: (' + this.complexity() + ')>';
  19149. },
  19150. /**
  19151. * Decide if the object should cache or not. Create its own cache level
  19152. * objectCaching is a global flag, wins over everything
  19153. * needsItsOwnCache should be used when the object drawing method requires
  19154. * a cache step. None of the fabric classes requires it.
  19155. * Generally you do not cache objects in groups because the group outside is cached.
  19156. * @return {Boolean}
  19157. */
  19158. shouldCache: function() {
  19159. return false;
  19160. },
  19161. /**
  19162. * Check if this group or its parent group are caching, recursively up
  19163. * @return {Boolean}
  19164. */
  19165. isOnACache: function() {
  19166. return false;
  19167. },
  19168. /**
  19169. * Renders controls and borders for the object
  19170. * @param {CanvasRenderingContext2D} ctx Context to render on
  19171. * @param {Object} [styleOverride] properties to override the object style
  19172. * @param {Object} [childrenOverride] properties to override the children overrides
  19173. */
  19174. _renderControls: function(ctx, styleOverride, childrenOverride) {
  19175. ctx.save();
  19176. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  19177. this.callSuper('_renderControls', ctx, styleOverride);
  19178. childrenOverride = childrenOverride || { };
  19179. if (typeof childrenOverride.hasControls === 'undefined') {
  19180. childrenOverride.hasControls = false;
  19181. }
  19182. childrenOverride.forActiveSelection = true;
  19183. for (var i = 0, len = this._objects.length; i < len; i++) {
  19184. this._objects[i]._renderControls(ctx, childrenOverride);
  19185. }
  19186. ctx.restore();
  19187. },
  19188. });
  19189. /**
  19190. * Returns {@link fabric.ActiveSelection} instance from an object representation
  19191. * @static
  19192. * @memberOf fabric.ActiveSelection
  19193. * @param {Object} object Object to create a group from
  19194. * @param {Function} [callback] Callback to invoke when an ActiveSelection instance is created
  19195. */
  19196. fabric.ActiveSelection.fromObject = function(object, callback) {
  19197. fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
  19198. delete object.objects;
  19199. callback && callback(new fabric.ActiveSelection(enlivenedObjects, object, true));
  19200. });
  19201. };
  19202. })(typeof exports !== 'undefined' ? exports : this);
  19203. (function(global) {
  19204. 'use strict';
  19205. var extend = fabric.util.object.extend;
  19206. if (!global.fabric) {
  19207. global.fabric = { };
  19208. }
  19209. if (global.fabric.Image) {
  19210. fabric.warn('fabric.Image is already defined.');
  19211. return;
  19212. }
  19213. /**
  19214. * Image class
  19215. * @class fabric.Image
  19216. * @extends fabric.Object
  19217. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1#images}
  19218. * @see {@link fabric.Image#initialize} for constructor definition
  19219. */
  19220. fabric.Image = fabric.util.createClass(fabric.Object, /** @lends fabric.Image.prototype */ {
  19221. /**
  19222. * Type of an object
  19223. * @type String
  19224. * @default
  19225. */
  19226. type: 'image',
  19227. /**
  19228. * Width of a stroke.
  19229. * For image quality a stroke multiple of 2 gives better results.
  19230. * @type Number
  19231. * @default
  19232. */
  19233. strokeWidth: 0,
  19234. /**
  19235. * When calling {@link fabric.Image.getSrc}, return value from element src with `element.getAttribute('src')`.
  19236. * This allows for relative urls as image src.
  19237. * @since 2.7.0
  19238. * @type Boolean
  19239. * @default
  19240. */
  19241. srcFromAttribute: false,
  19242. /**
  19243. * private
  19244. * contains last value of scaleX to detect
  19245. * if the Image got resized after the last Render
  19246. * @type Number
  19247. */
  19248. _lastScaleX: 1,
  19249. /**
  19250. * private
  19251. * contains last value of scaleY to detect
  19252. * if the Image got resized after the last Render
  19253. * @type Number
  19254. */
  19255. _lastScaleY: 1,
  19256. /**
  19257. * private
  19258. * contains last value of scaling applied by the apply filter chain
  19259. * @type Number
  19260. */
  19261. _filterScalingX: 1,
  19262. /**
  19263. * private
  19264. * contains last value of scaling applied by the apply filter chain
  19265. * @type Number
  19266. */
  19267. _filterScalingY: 1,
  19268. /**
  19269. * minimum scale factor under which any resizeFilter is triggered to resize the image
  19270. * 0 will disable the automatic resize. 1 will trigger automatically always.
  19271. * number bigger than 1 are not implemented yet.
  19272. * @type Number
  19273. */
  19274. minimumScaleTrigger: 0.5,
  19275. /**
  19276. * List of properties to consider when checking if
  19277. * state of an object is changed ({@link fabric.Object#hasStateChanged})
  19278. * as well as for history (undo/redo) purposes
  19279. * @type Array
  19280. */
  19281. stateProperties: fabric.Object.prototype.stateProperties.concat('cropX', 'cropY'),
  19282. /**
  19283. * List of properties to consider when checking if cache needs refresh
  19284. * Those properties are checked by statefullCache ON ( or lazy mode if we want ) or from single
  19285. * calls to Object.set(key, value). If the key is in this list, the object is marked as dirty
  19286. * and refreshed at the next render
  19287. * @type Array
  19288. */
  19289. cacheProperties: fabric.Object.prototype.cacheProperties.concat('cropX', 'cropY'),
  19290. /**
  19291. * key used to retrieve the texture representing this image
  19292. * @since 2.0.0
  19293. * @type String
  19294. * @default
  19295. */
  19296. cacheKey: '',
  19297. /**
  19298. * Image crop in pixels from original image size.
  19299. * @since 2.0.0
  19300. * @type Number
  19301. * @default
  19302. */
  19303. cropX: 0,
  19304. /**
  19305. * Image crop in pixels from original image size.
  19306. * @since 2.0.0
  19307. * @type Number
  19308. * @default
  19309. */
  19310. cropY: 0,
  19311. /**
  19312. * Indicates whether this canvas will use image smoothing when painting this image.
  19313. * Also influence if the cacheCanvas for this image uses imageSmoothing
  19314. * @since 4.0.0-beta.11
  19315. * @type Boolean
  19316. * @default
  19317. */
  19318. imageSmoothing: true,
  19319. /**
  19320. * Constructor
  19321. * Image can be initialized with any canvas drawable or a string.
  19322. * The string should be a url and will be loaded as an image.
  19323. * Canvas and Image element work out of the box, while videos require extra code to work.
  19324. * Please check video element events for seeking.
  19325. * @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | String} element Image element
  19326. * @param {Object} [options] Options object
  19327. * @param {function} [callback] callback function to call after eventual filters applied.
  19328. * @return {fabric.Image} thisArg
  19329. */
  19330. initialize: function(element, options) {
  19331. options || (options = { });
  19332. this.filters = [];
  19333. this.cacheKey = 'texture' + fabric.Object.__uid++;
  19334. this.callSuper('initialize', options);
  19335. this._initElement(element, options);
  19336. },
  19337. /**
  19338. * Returns image element which this instance if based on
  19339. * @return {HTMLImageElement} Image element
  19340. */
  19341. getElement: function() {
  19342. return this._element || {};
  19343. },
  19344. /**
  19345. * Sets image element for this instance to a specified one.
  19346. * If filters defined they are applied to new image.
  19347. * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area.
  19348. * @param {HTMLImageElement} element
  19349. * @param {Object} [options] Options object
  19350. * @return {fabric.Image} thisArg
  19351. * @chainable
  19352. */
  19353. setElement: function(element, options) {
  19354. this.removeTexture(this.cacheKey);
  19355. this.removeTexture(this.cacheKey + '_filtered');
  19356. this._element = element;
  19357. this._originalElement = element;
  19358. this._initConfig(options);
  19359. if (this.filters.length !== 0) {
  19360. this.applyFilters();
  19361. }
  19362. // resizeFilters work on the already filtered copy.
  19363. // we need to apply resizeFilters AFTER normal filters.
  19364. // applyResizeFilters is run more often than normal filters
  19365. // and is triggered by user interactions rather than dev code
  19366. if (this.resizeFilter) {
  19367. this.applyResizeFilters();
  19368. }
  19369. return this;
  19370. },
  19371. /**
  19372. * Delete a single texture if in webgl mode
  19373. */
  19374. removeTexture: function(key) {
  19375. var backend = fabric.filterBackend;
  19376. if (backend && backend.evictCachesForKey) {
  19377. backend.evictCachesForKey(key);
  19378. }
  19379. },
  19380. /**
  19381. * Delete textures, reference to elements and eventually JSDOM cleanup
  19382. */
  19383. dispose: function () {
  19384. this.callSuper('dispose');
  19385. this.removeTexture(this.cacheKey);
  19386. this.removeTexture(this.cacheKey + '_filtered');
  19387. this._cacheContext = undefined;
  19388. ['_originalElement', '_element', '_filteredEl', '_cacheCanvas'].forEach((function(element) {
  19389. fabric.util.cleanUpJsdomNode(this[element]);
  19390. this[element] = undefined;
  19391. }).bind(this));
  19392. },
  19393. /**
  19394. * Get the crossOrigin value (of the corresponding image element)
  19395. */
  19396. getCrossOrigin: function() {
  19397. return this._originalElement && (this._originalElement.crossOrigin || null);
  19398. },
  19399. /**
  19400. * Returns original size of an image
  19401. * @return {Object} Object with "width" and "height" properties
  19402. */
  19403. getOriginalSize: function() {
  19404. var element = this.getElement();
  19405. return {
  19406. width: element.naturalWidth || element.width,
  19407. height: element.naturalHeight || element.height
  19408. };
  19409. },
  19410. /**
  19411. * @private
  19412. * @param {CanvasRenderingContext2D} ctx Context to render on
  19413. */
  19414. _stroke: function(ctx) {
  19415. if (!this.stroke || this.strokeWidth === 0) {
  19416. return;
  19417. }
  19418. var w = this.width / 2, h = this.height / 2;
  19419. ctx.beginPath();
  19420. ctx.moveTo(-w, -h);
  19421. ctx.lineTo(w, -h);
  19422. ctx.lineTo(w, h);
  19423. ctx.lineTo(-w, h);
  19424. ctx.lineTo(-w, -h);
  19425. ctx.closePath();
  19426. },
  19427. /**
  19428. * Returns object representation of an instance
  19429. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  19430. * @return {Object} Object representation of an instance
  19431. */
  19432. toObject: function(propertiesToInclude) {
  19433. var filters = [];
  19434. this.filters.forEach(function(filterObj) {
  19435. if (filterObj) {
  19436. filters.push(filterObj.toObject());
  19437. }
  19438. });
  19439. var object = extend(
  19440. this.callSuper(
  19441. 'toObject',
  19442. ['cropX', 'cropY'].concat(propertiesToInclude)
  19443. ), {
  19444. src: this.getSrc(),
  19445. crossOrigin: this.getCrossOrigin(),
  19446. filters: filters,
  19447. });
  19448. if (this.resizeFilter) {
  19449. object.resizeFilter = this.resizeFilter.toObject();
  19450. }
  19451. return object;
  19452. },
  19453. /**
  19454. * Returns true if an image has crop applied, inspecting values of cropX,cropY,width,height.
  19455. * @return {Boolean}
  19456. */
  19457. hasCrop: function() {
  19458. return this.cropX || this.cropY || this.width < this._element.width || this.height < this._element.height;
  19459. },
  19460. /* _TO_SVG_START_ */
  19461. /**
  19462. * Returns svg representation of an instance
  19463. * @return {Array} an array of strings with the specific svg representation
  19464. * of the instance
  19465. */
  19466. _toSVG: function() {
  19467. var svgString = [], imageMarkup = [], strokeSvg, element = this._element,
  19468. x = -this.width / 2, y = -this.height / 2, clipPath = '', imageRendering = '';
  19469. if (!element) {
  19470. return [];
  19471. }
  19472. if (this.hasCrop()) {
  19473. var clipPathId = fabric.Object.__uid++;
  19474. svgString.push(
  19475. '<clipPath id="imageCrop_' + clipPathId + '">\n',
  19476. '\t<rect x="' + x + '" y="' + y + '" width="' + this.width + '" height="' + this.height + '" />\n',
  19477. '</clipPath>\n'
  19478. );
  19479. clipPath = ' clip-path="url(#imageCrop_' + clipPathId + ')" ';
  19480. }
  19481. if (!this.imageSmoothing) {
  19482. imageRendering = '" image-rendering="optimizeSpeed';
  19483. }
  19484. imageMarkup.push('\t<image ', 'COMMON_PARTS', 'xlink:href="', this.getSvgSrc(true),
  19485. '" x="', x - this.cropX, '" y="', y - this.cropY,
  19486. // we're essentially moving origin of transformation from top/left corner to the center of the shape
  19487. // by wrapping it in container <g> element with actual transformation, then offsetting object to the top/left
  19488. // so that object's center aligns with container's left/top
  19489. '" width="', element.width || element.naturalWidth,
  19490. '" height="', element.height || element.height,
  19491. imageRendering,
  19492. '"', clipPath,
  19493. '></image>\n');
  19494. if (this.stroke || this.strokeDashArray) {
  19495. var origFill = this.fill;
  19496. this.fill = null;
  19497. strokeSvg = [
  19498. '\t<rect ',
  19499. 'x="', x, '" y="', y,
  19500. '" width="', this.width, '" height="', this.height,
  19501. '" style="', this.getSvgStyles(),
  19502. '"/>\n'
  19503. ];
  19504. this.fill = origFill;
  19505. }
  19506. if (this.paintFirst !== 'fill') {
  19507. svgString = svgString.concat(strokeSvg, imageMarkup);
  19508. }
  19509. else {
  19510. svgString = svgString.concat(imageMarkup, strokeSvg);
  19511. }
  19512. return svgString;
  19513. },
  19514. /* _TO_SVG_END_ */
  19515. /**
  19516. * Returns source of an image
  19517. * @param {Boolean} filtered indicates if the src is needed for svg
  19518. * @return {String} Source of an image
  19519. */
  19520. getSrc: function(filtered) {
  19521. var element = filtered ? this._element : this._originalElement;
  19522. if (element) {
  19523. if (element.toDataURL) {
  19524. return element.toDataURL();
  19525. }
  19526. if (this.srcFromAttribute) {
  19527. return element.getAttribute('src');
  19528. }
  19529. else {
  19530. return element.src;
  19531. }
  19532. }
  19533. else {
  19534. return this.src || '';
  19535. }
  19536. },
  19537. /**
  19538. * Sets source of an image
  19539. * @param {String} src Source string (URL)
  19540. * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied)
  19541. * @param {Object} [options] Options object
  19542. * @param {String} [options.crossOrigin] crossOrigin value (one of "", "anonymous", "use-credentials")
  19543. * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
  19544. * @return {fabric.Image} thisArg
  19545. * @chainable
  19546. */
  19547. setSrc: function(src, callback, options) {
  19548. fabric.util.loadImage(src, function(img, isError) {
  19549. this.setElement(img, options);
  19550. this._setWidthHeight();
  19551. callback && callback(this, isError);
  19552. }, this, options && options.crossOrigin);
  19553. return this;
  19554. },
  19555. /**
  19556. * Returns string representation of an instance
  19557. * @return {String} String representation of an instance
  19558. */
  19559. toString: function() {
  19560. return '#<fabric.Image: { src: "' + this.getSrc() + '" }>';
  19561. },
  19562. applyResizeFilters: function() {
  19563. var filter = this.resizeFilter,
  19564. minimumScale = this.minimumScaleTrigger,
  19565. objectScale = this.getTotalObjectScaling(),
  19566. scaleX = objectScale.scaleX,
  19567. scaleY = objectScale.scaleY,
  19568. elementToFilter = this._filteredEl || this._originalElement;
  19569. if (this.group) {
  19570. this.set('dirty', true);
  19571. }
  19572. if (!filter || (scaleX > minimumScale && scaleY > minimumScale)) {
  19573. this._element = elementToFilter;
  19574. this._filterScalingX = 1;
  19575. this._filterScalingY = 1;
  19576. this._lastScaleX = scaleX;
  19577. this._lastScaleY = scaleY;
  19578. return;
  19579. }
  19580. if (!fabric.filterBackend) {
  19581. fabric.filterBackend = fabric.initFilterBackend();
  19582. }
  19583. var canvasEl = fabric.util.createCanvasElement(),
  19584. cacheKey = this._filteredEl ? (this.cacheKey + '_filtered') : this.cacheKey,
  19585. sourceWidth = elementToFilter.width, sourceHeight = elementToFilter.height;
  19586. canvasEl.width = sourceWidth;
  19587. canvasEl.height = sourceHeight;
  19588. this._element = canvasEl;
  19589. this._lastScaleX = filter.scaleX = scaleX;
  19590. this._lastScaleY = filter.scaleY = scaleY;
  19591. fabric.filterBackend.applyFilters(
  19592. [filter], elementToFilter, sourceWidth, sourceHeight, this._element, cacheKey);
  19593. this._filterScalingX = canvasEl.width / this._originalElement.width;
  19594. this._filterScalingY = canvasEl.height / this._originalElement.height;
  19595. },
  19596. /**
  19597. * Applies filters assigned to this image (from "filters" array) or from filter param
  19598. * @method applyFilters
  19599. * @param {Array} filters to be applied
  19600. * @param {Boolean} forResizing specify if the filter operation is a resize operation
  19601. * @return {thisArg} return the fabric.Image object
  19602. * @chainable
  19603. */
  19604. applyFilters: function(filters) {
  19605. filters = filters || this.filters || [];
  19606. filters = filters.filter(function(filter) { return filter && !filter.isNeutralState(); });
  19607. this.set('dirty', true);
  19608. // needs to clear out or WEBGL will not resize correctly
  19609. this.removeTexture(this.cacheKey + '_filtered');
  19610. if (filters.length === 0) {
  19611. this._element = this._originalElement;
  19612. this._filteredEl = null;
  19613. this._filterScalingX = 1;
  19614. this._filterScalingY = 1;
  19615. return this;
  19616. }
  19617. var imgElement = this._originalElement,
  19618. sourceWidth = imgElement.naturalWidth || imgElement.width,
  19619. sourceHeight = imgElement.naturalHeight || imgElement.height;
  19620. if (this._element === this._originalElement) {
  19621. // if the element is the same we need to create a new element
  19622. var canvasEl = fabric.util.createCanvasElement();
  19623. canvasEl.width = sourceWidth;
  19624. canvasEl.height = sourceHeight;
  19625. this._element = canvasEl;
  19626. this._filteredEl = canvasEl;
  19627. }
  19628. else {
  19629. // clear the existing element to get new filter data
  19630. // also dereference the eventual resized _element
  19631. this._element = this._filteredEl;
  19632. this._filteredEl.getContext('2d').clearRect(0, 0, sourceWidth, sourceHeight);
  19633. // we also need to resize again at next renderAll, so remove saved _lastScaleX/Y
  19634. this._lastScaleX = 1;
  19635. this._lastScaleY = 1;
  19636. }
  19637. if (!fabric.filterBackend) {
  19638. fabric.filterBackend = fabric.initFilterBackend();
  19639. }
  19640. fabric.filterBackend.applyFilters(
  19641. filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);
  19642. if (this._originalElement.width !== this._element.width ||
  19643. this._originalElement.height !== this._element.height) {
  19644. this._filterScalingX = this._element.width / this._originalElement.width;
  19645. this._filterScalingY = this._element.height / this._originalElement.height;
  19646. }
  19647. return this;
  19648. },
  19649. /**
  19650. * @private
  19651. * @param {CanvasRenderingContext2D} ctx Context to render on
  19652. */
  19653. _render: function(ctx) {
  19654. fabric.util.setImageSmoothing(ctx, this.imageSmoothing);
  19655. if (this.isMoving !== true && this.resizeFilter && this._needsResize()) {
  19656. this.applyResizeFilters();
  19657. }
  19658. this._stroke(ctx);
  19659. this._renderPaintInOrder(ctx);
  19660. },
  19661. /**
  19662. * Paint the cached copy of the object on the target context.
  19663. * it will set the imageSmoothing for the draw operation
  19664. * @param {CanvasRenderingContext2D} ctx Context to render on
  19665. */
  19666. drawCacheOnCanvas: function(ctx) {
  19667. fabric.util.setImageSmoothing(ctx, this.imageSmoothing);
  19668. fabric.Object.prototype.drawCacheOnCanvas.call(this, ctx);
  19669. },
  19670. /**
  19671. * Decide if the object should cache or not. Create its own cache level
  19672. * needsItsOwnCache should be used when the object drawing method requires
  19673. * a cache step. None of the fabric classes requires it.
  19674. * Generally you do not cache objects in groups because the group outside is cached.
  19675. * This is the special image version where we would like to avoid caching where possible.
  19676. * Essentially images do not benefit from caching. They may require caching, and in that
  19677. * case we do it. Also caching an image usually ends in a loss of details.
  19678. * A full performance audit should be done.
  19679. * @return {Boolean}
  19680. */
  19681. shouldCache: function() {
  19682. return this.needsItsOwnCache();
  19683. },
  19684. _renderFill: function(ctx) {
  19685. var elementToDraw = this._element;
  19686. if (!elementToDraw) {
  19687. return;
  19688. }
  19689. var scaleX = this._filterScalingX, scaleY = this._filterScalingY,
  19690. w = this.width, h = this.height, min = Math.min, max = Math.max,
  19691. // crop values cannot be lesser than 0.
  19692. cropX = max(this.cropX, 0), cropY = max(this.cropY, 0),
  19693. elWidth = elementToDraw.naturalWidth || elementToDraw.width,
  19694. elHeight = elementToDraw.naturalHeight || elementToDraw.height,
  19695. sX = cropX * scaleX,
  19696. sY = cropY * scaleY,
  19697. // the width height cannot exceed element width/height, starting from the crop offset.
  19698. sW = min(w * scaleX, elWidth - sX),
  19699. sH = min(h * scaleY, elHeight - sY),
  19700. x = -w / 2, y = -h / 2,
  19701. maxDestW = min(w, elWidth / scaleX - cropX),
  19702. maxDestH = min(h, elHeight / scaleY - cropY);
  19703. elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);
  19704. },
  19705. /**
  19706. * needed to check if image needs resize
  19707. * @private
  19708. */
  19709. _needsResize: function() {
  19710. var scale = this.getTotalObjectScaling();
  19711. return (scale.scaleX !== this._lastScaleX || scale.scaleY !== this._lastScaleY);
  19712. },
  19713. /**
  19714. * @private
  19715. */
  19716. _resetWidthHeight: function() {
  19717. this.set(this.getOriginalSize());
  19718. },
  19719. /**
  19720. * The Image class's initialization method. This method is automatically
  19721. * called by the constructor.
  19722. * @private
  19723. * @param {HTMLImageElement|String} element The element representing the image
  19724. * @param {Object} [options] Options object
  19725. */
  19726. _initElement: function(element, options) {
  19727. this.setElement(fabric.util.getById(element), options);
  19728. fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);
  19729. },
  19730. /**
  19731. * @private
  19732. * @param {Object} [options] Options object
  19733. */
  19734. _initConfig: function(options) {
  19735. options || (options = { });
  19736. this.setOptions(options);
  19737. this._setWidthHeight(options);
  19738. },
  19739. /**
  19740. * @private
  19741. * @param {Array} filters to be initialized
  19742. * @param {Function} callback Callback to invoke when all fabric.Image.filters instances are created
  19743. */
  19744. _initFilters: function(filters, callback) {
  19745. if (filters && filters.length) {
  19746. fabric.util.enlivenObjects(filters, function(enlivenedObjects) {
  19747. callback && callback(enlivenedObjects);
  19748. }, 'fabric.Image.filters');
  19749. }
  19750. else {
  19751. callback && callback();
  19752. }
  19753. },
  19754. /**
  19755. * @private
  19756. * Set the width and the height of the image object, using the element or the
  19757. * options.
  19758. * @param {Object} [options] Object with width/height properties
  19759. */
  19760. _setWidthHeight: function(options) {
  19761. options || (options = { });
  19762. var el = this.getElement();
  19763. this.width = options.width || el.naturalWidth || el.width || 0;
  19764. this.height = options.height || el.naturalHeight || el.height || 0;
  19765. },
  19766. /**
  19767. * Calculate offset for center and scale factor for the image in order to respect
  19768. * the preserveAspectRatio attribute
  19769. * @private
  19770. * @return {Object}
  19771. */
  19772. parsePreserveAspectRatioAttribute: function() {
  19773. var pAR = fabric.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio || ''),
  19774. rWidth = this._element.width, rHeight = this._element.height,
  19775. scaleX = 1, scaleY = 1, offsetLeft = 0, offsetTop = 0, cropX = 0, cropY = 0,
  19776. offset, pWidth = this.width, pHeight = this.height, parsedAttributes = { width: pWidth, height: pHeight };
  19777. if (pAR && (pAR.alignX !== 'none' || pAR.alignY !== 'none')) {
  19778. if (pAR.meetOrSlice === 'meet') {
  19779. scaleX = scaleY = fabric.util.findScaleToFit(this._element, parsedAttributes);
  19780. offset = (pWidth - rWidth * scaleX) / 2;
  19781. if (pAR.alignX === 'Min') {
  19782. offsetLeft = -offset;
  19783. }
  19784. if (pAR.alignX === 'Max') {
  19785. offsetLeft = offset;
  19786. }
  19787. offset = (pHeight - rHeight * scaleY) / 2;
  19788. if (pAR.alignY === 'Min') {
  19789. offsetTop = -offset;
  19790. }
  19791. if (pAR.alignY === 'Max') {
  19792. offsetTop = offset;
  19793. }
  19794. }
  19795. if (pAR.meetOrSlice === 'slice') {
  19796. scaleX = scaleY = fabric.util.findScaleToCover(this._element, parsedAttributes);
  19797. offset = rWidth - pWidth / scaleX;
  19798. if (pAR.alignX === 'Mid') {
  19799. cropX = offset / 2;
  19800. }
  19801. if (pAR.alignX === 'Max') {
  19802. cropX = offset;
  19803. }
  19804. offset = rHeight - pHeight / scaleY;
  19805. if (pAR.alignY === 'Mid') {
  19806. cropY = offset / 2;
  19807. }
  19808. if (pAR.alignY === 'Max') {
  19809. cropY = offset;
  19810. }
  19811. rWidth = pWidth / scaleX;
  19812. rHeight = pHeight / scaleY;
  19813. }
  19814. }
  19815. else {
  19816. scaleX = pWidth / rWidth;
  19817. scaleY = pHeight / rHeight;
  19818. }
  19819. return {
  19820. width: rWidth,
  19821. height: rHeight,
  19822. scaleX: scaleX,
  19823. scaleY: scaleY,
  19824. offsetLeft: offsetLeft,
  19825. offsetTop: offsetTop,
  19826. cropX: cropX,
  19827. cropY: cropY
  19828. };
  19829. }
  19830. });
  19831. /**
  19832. * Default CSS class name for canvas
  19833. * @static
  19834. * @type String
  19835. * @default
  19836. */
  19837. fabric.Image.CSS_CANVAS = 'canvas-img';
  19838. /**
  19839. * Alias for getSrc
  19840. * @static
  19841. */
  19842. fabric.Image.prototype.getSvgSrc = fabric.Image.prototype.getSrc;
  19843. /**
  19844. * Creates an instance of fabric.Image from its object representation
  19845. * @static
  19846. * @param {Object} object Object to create an instance from
  19847. * @param {Function} callback Callback to invoke when an image instance is created
  19848. */
  19849. fabric.Image.fromObject = function(_object, callback) {
  19850. var object = fabric.util.object.clone(_object);
  19851. fabric.util.loadImage(object.src, function(img, isError) {
  19852. if (isError) {
  19853. callback && callback(null, true);
  19854. return;
  19855. }
  19856. fabric.Image.prototype._initFilters.call(object, object.filters, function(filters) {
  19857. object.filters = filters || [];
  19858. fabric.Image.prototype._initFilters.call(object, [object.resizeFilter], function(resizeFilters) {
  19859. object.resizeFilter = resizeFilters[0];
  19860. fabric.util.enlivenObjectEnlivables(object, object, function () {
  19861. var image = new fabric.Image(img, object);
  19862. callback(image, false);
  19863. });
  19864. });
  19865. });
  19866. }, null, object.crossOrigin);
  19867. };
  19868. /**
  19869. * Creates an instance of fabric.Image from an URL string
  19870. * @static
  19871. * @param {String} url URL to create an image from
  19872. * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument). Second argument is a boolean indicating if an error occurred or not.
  19873. * @param {Object} [imgOptions] Options object
  19874. */
  19875. fabric.Image.fromURL = function(url, callback, imgOptions) {
  19876. fabric.util.loadImage(url, function(img, isError) {
  19877. callback && callback(new fabric.Image(img, imgOptions), isError);
  19878. }, null, imgOptions && imgOptions.crossOrigin);
  19879. };
  19880. /* _FROM_SVG_START_ */
  19881. /**
  19882. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Image.fromElement})
  19883. * @static
  19884. * @see {@link http://www.w3.org/TR/SVG/struct.html#ImageElement}
  19885. */
  19886. fabric.Image.ATTRIBUTE_NAMES =
  19887. fabric.SHARED_ATTRIBUTES.concat(
  19888. 'x y width height preserveAspectRatio xlink:href crossOrigin image-rendering'.split(' ')
  19889. );
  19890. /**
  19891. * Returns {@link fabric.Image} instance from an SVG element
  19892. * @static
  19893. * @param {SVGElement} element Element to parse
  19894. * @param {Object} [options] Options object
  19895. * @param {Function} callback Callback to execute when fabric.Image object is created
  19896. * @return {fabric.Image} Instance of fabric.Image
  19897. */
  19898. fabric.Image.fromElement = function(element, callback, options) {
  19899. var parsedAttributes = fabric.parseAttributes(element, fabric.Image.ATTRIBUTE_NAMES);
  19900. fabric.Image.fromURL(parsedAttributes['xlink:href'], callback,
  19901. extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));
  19902. };
  19903. /* _FROM_SVG_END_ */
  19904. })(typeof exports !== 'undefined' ? exports : this);
  19905. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  19906. /**
  19907. * @private
  19908. * @return {Number} angle value
  19909. */
  19910. _getAngleValueForStraighten: function() {
  19911. var angle = this.angle % 360;
  19912. if (angle > 0) {
  19913. return Math.round((angle - 1) / 90) * 90;
  19914. }
  19915. return Math.round(angle / 90) * 90;
  19916. },
  19917. /**
  19918. * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer)
  19919. * @return {fabric.Object} thisArg
  19920. * @chainable
  19921. */
  19922. straighten: function() {
  19923. return this.rotate(this._getAngleValueForStraighten());
  19924. },
  19925. /**
  19926. * Same as {@link fabric.Object.prototype.straighten} but with animation
  19927. * @param {Object} callbacks Object with callback functions
  19928. * @param {Function} [callbacks.onComplete] Invoked on completion
  19929. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  19930. * @return {fabric.Object} thisArg
  19931. */
  19932. fxStraighten: function(callbacks) {
  19933. callbacks = callbacks || { };
  19934. var empty = function() { },
  19935. onComplete = callbacks.onComplete || empty,
  19936. onChange = callbacks.onChange || empty,
  19937. _this = this;
  19938. return fabric.util.animate({
  19939. target: this,
  19940. startValue: this.get('angle'),
  19941. endValue: this._getAngleValueForStraighten(),
  19942. duration: this.FX_DURATION,
  19943. onChange: function(value) {
  19944. _this.rotate(value);
  19945. onChange();
  19946. },
  19947. onComplete: function() {
  19948. _this.setCoords();
  19949. onComplete();
  19950. },
  19951. });
  19952. }
  19953. });
  19954. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  19955. /**
  19956. * Straightens object, then rerenders canvas
  19957. * @param {fabric.Object} object Object to straighten
  19958. * @return {fabric.Canvas} thisArg
  19959. * @chainable
  19960. */
  19961. straightenObject: function (object) {
  19962. object.straighten();
  19963. this.requestRenderAll();
  19964. return this;
  19965. },
  19966. /**
  19967. * Same as {@link fabric.Canvas.prototype.straightenObject}, but animated
  19968. * @param {fabric.Object} object Object to straighten
  19969. * @return {fabric.Canvas} thisArg
  19970. */
  19971. fxStraightenObject: function (object) {
  19972. return object.fxStraighten({
  19973. onChange: this.requestRenderAllBound
  19974. });
  19975. }
  19976. });
  19977. (function() {
  19978. 'use strict';
  19979. /**
  19980. * Tests if webgl supports certain precision
  19981. * @param {WebGL} Canvas WebGL context to test on
  19982. * @param {String} Precision to test can be any of following: 'lowp', 'mediump', 'highp'
  19983. * @returns {Boolean} Whether the user's browser WebGL supports given precision.
  19984. */
  19985. function testPrecision(gl, precision){
  19986. var fragmentSource = 'precision ' + precision + ' float;\nvoid main(){}';
  19987. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  19988. gl.shaderSource(fragmentShader, fragmentSource);
  19989. gl.compileShader(fragmentShader);
  19990. if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
  19991. return false;
  19992. }
  19993. return true;
  19994. }
  19995. /**
  19996. * Indicate whether this filtering backend is supported by the user's browser.
  19997. * @param {Number} tileSize check if the tileSize is supported
  19998. * @returns {Boolean} Whether the user's browser supports WebGL.
  19999. */
  20000. fabric.isWebglSupported = function(tileSize) {
  20001. if (fabric.isLikelyNode) {
  20002. return false;
  20003. }
  20004. tileSize = tileSize || fabric.WebglFilterBackend.prototype.tileSize;
  20005. var canvas = document.createElement('canvas');
  20006. var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
  20007. var isSupported = false;
  20008. // eslint-disable-next-line
  20009. if (gl) {
  20010. fabric.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  20011. isSupported = fabric.maxTextureSize >= tileSize;
  20012. var precisions = ['highp', 'mediump', 'lowp'];
  20013. for (var i = 0; i < 3; i++){
  20014. if (testPrecision(gl, precisions[i])){
  20015. fabric.webGlPrecision = precisions[i];
  20016. break;
  20017. };
  20018. }
  20019. }
  20020. this.isSupported = isSupported;
  20021. return isSupported;
  20022. };
  20023. fabric.WebglFilterBackend = WebglFilterBackend;
  20024. /**
  20025. * WebGL filter backend.
  20026. */
  20027. function WebglFilterBackend(options) {
  20028. if (options && options.tileSize) {
  20029. this.tileSize = options.tileSize;
  20030. }
  20031. this.setupGLContext(this.tileSize, this.tileSize);
  20032. this.captureGPUInfo();
  20033. };
  20034. WebglFilterBackend.prototype = /** @lends fabric.WebglFilterBackend.prototype */ {
  20035. tileSize: 2048,
  20036. /**
  20037. * Experimental. This object is a sort of repository of help layers used to avoid
  20038. * of recreating them during frequent filtering. If you are previewing a filter with
  20039. * a slider you probably do not want to create help layers every filter step.
  20040. * in this object there will be appended some canvases, created once, resized sometimes
  20041. * cleared never. Clearing is left to the developer.
  20042. **/
  20043. resources: {
  20044. },
  20045. /**
  20046. * Setup a WebGL context suitable for filtering, and bind any needed event handlers.
  20047. */
  20048. setupGLContext: function(width, height) {
  20049. this.dispose();
  20050. this.createWebGLCanvas(width, height);
  20051. // eslint-disable-next-line
  20052. this.aPosition = new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]);
  20053. this.chooseFastestCopyGLTo2DMethod(width, height);
  20054. },
  20055. /**
  20056. * Pick a method to copy data from GL context to 2d canvas. In some browsers using
  20057. * putImageData is faster than drawImage for that specific operation.
  20058. */
  20059. chooseFastestCopyGLTo2DMethod: function(width, height) {
  20060. var canMeasurePerf = typeof window.performance !== 'undefined', canUseImageData;
  20061. try {
  20062. new ImageData(1, 1);
  20063. canUseImageData = true;
  20064. }
  20065. catch (e) {
  20066. canUseImageData = false;
  20067. }
  20068. // eslint-disable-next-line no-undef
  20069. var canUseArrayBuffer = typeof ArrayBuffer !== 'undefined';
  20070. // eslint-disable-next-line no-undef
  20071. var canUseUint8Clamped = typeof Uint8ClampedArray !== 'undefined';
  20072. if (!(canMeasurePerf && canUseImageData && canUseArrayBuffer && canUseUint8Clamped)) {
  20073. return;
  20074. }
  20075. var targetCanvas = fabric.util.createCanvasElement();
  20076. // eslint-disable-next-line no-undef
  20077. var imageBuffer = new ArrayBuffer(width * height * 4);
  20078. if (fabric.forceGLPutImageData) {
  20079. this.imageBuffer = imageBuffer;
  20080. this.copyGLTo2D = copyGLTo2DPutImageData;
  20081. return;
  20082. }
  20083. var testContext = {
  20084. imageBuffer: imageBuffer,
  20085. destinationWidth: width,
  20086. destinationHeight: height,
  20087. targetCanvas: targetCanvas
  20088. };
  20089. var startTime, drawImageTime, putImageDataTime;
  20090. targetCanvas.width = width;
  20091. targetCanvas.height = height;
  20092. startTime = window.performance.now();
  20093. copyGLTo2DDrawImage.call(testContext, this.gl, testContext);
  20094. drawImageTime = window.performance.now() - startTime;
  20095. startTime = window.performance.now();
  20096. copyGLTo2DPutImageData.call(testContext, this.gl, testContext);
  20097. putImageDataTime = window.performance.now() - startTime;
  20098. if (drawImageTime > putImageDataTime) {
  20099. this.imageBuffer = imageBuffer;
  20100. this.copyGLTo2D = copyGLTo2DPutImageData;
  20101. }
  20102. else {
  20103. this.copyGLTo2D = copyGLTo2DDrawImage;
  20104. }
  20105. },
  20106. /**
  20107. * Create a canvas element and associated WebGL context and attaches them as
  20108. * class properties to the GLFilterBackend class.
  20109. */
  20110. createWebGLCanvas: function(width, height) {
  20111. var canvas = fabric.util.createCanvasElement();
  20112. canvas.width = width;
  20113. canvas.height = height;
  20114. var glOptions = {
  20115. alpha: true,
  20116. premultipliedAlpha: false,
  20117. depth: false,
  20118. stencil: false,
  20119. antialias: false
  20120. },
  20121. gl = canvas.getContext('webgl', glOptions);
  20122. if (!gl) {
  20123. gl = canvas.getContext('experimental-webgl', glOptions);
  20124. }
  20125. if (!gl) {
  20126. return;
  20127. }
  20128. gl.clearColor(0, 0, 0, 0);
  20129. // this canvas can fire webglcontextlost and webglcontextrestored
  20130. this.canvas = canvas;
  20131. this.gl = gl;
  20132. },
  20133. /**
  20134. * Attempts to apply the requested filters to the source provided, drawing the filtered output
  20135. * to the provided target canvas.
  20136. *
  20137. * @param {Array} filters The filters to apply.
  20138. * @param {HTMLImageElement|HTMLCanvasElement} source The source to be filtered.
  20139. * @param {Number} width The width of the source input.
  20140. * @param {Number} height The height of the source input.
  20141. * @param {HTMLCanvasElement} targetCanvas The destination for filtered output to be drawn.
  20142. * @param {String|undefined} cacheKey A key used to cache resources related to the source. If
  20143. * omitted, caching will be skipped.
  20144. */
  20145. applyFilters: function(filters, source, width, height, targetCanvas, cacheKey) {
  20146. var gl = this.gl;
  20147. var cachedTexture;
  20148. if (cacheKey) {
  20149. cachedTexture = this.getCachedTexture(cacheKey, source);
  20150. }
  20151. var pipelineState = {
  20152. originalWidth: source.width || source.originalWidth,
  20153. originalHeight: source.height || source.originalHeight,
  20154. sourceWidth: width,
  20155. sourceHeight: height,
  20156. destinationWidth: width,
  20157. destinationHeight: height,
  20158. context: gl,
  20159. sourceTexture: this.createTexture(gl, width, height, !cachedTexture && source),
  20160. targetTexture: this.createTexture(gl, width, height),
  20161. originalTexture: cachedTexture ||
  20162. this.createTexture(gl, width, height, !cachedTexture && source),
  20163. passes: filters.length,
  20164. webgl: true,
  20165. aPosition: this.aPosition,
  20166. programCache: this.programCache,
  20167. pass: 0,
  20168. filterBackend: this,
  20169. targetCanvas: targetCanvas
  20170. };
  20171. var tempFbo = gl.createFramebuffer();
  20172. gl.bindFramebuffer(gl.FRAMEBUFFER, tempFbo);
  20173. filters.forEach(function(filter) { filter && filter.applyTo(pipelineState); });
  20174. resizeCanvasIfNeeded(pipelineState);
  20175. this.copyGLTo2D(gl, pipelineState);
  20176. gl.bindTexture(gl.TEXTURE_2D, null);
  20177. gl.deleteTexture(pipelineState.sourceTexture);
  20178. gl.deleteTexture(pipelineState.targetTexture);
  20179. gl.deleteFramebuffer(tempFbo);
  20180. targetCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);
  20181. return pipelineState;
  20182. },
  20183. /**
  20184. * Detach event listeners, remove references, and clean up caches.
  20185. */
  20186. dispose: function() {
  20187. if (this.canvas) {
  20188. this.canvas = null;
  20189. this.gl = null;
  20190. }
  20191. this.clearWebGLCaches();
  20192. },
  20193. /**
  20194. * Wipe out WebGL-related caches.
  20195. */
  20196. clearWebGLCaches: function() {
  20197. this.programCache = {};
  20198. this.textureCache = {};
  20199. },
  20200. /**
  20201. * Create a WebGL texture object.
  20202. *
  20203. * Accepts specific dimensions to initialize the texture to or a source image.
  20204. *
  20205. * @param {WebGLRenderingContext} gl The GL context to use for creating the texture.
  20206. * @param {Number} width The width to initialize the texture at.
  20207. * @param {Number} height The height to initialize the texture.
  20208. * @param {HTMLImageElement|HTMLCanvasElement} textureImageSource A source for the texture data.
  20209. * @returns {WebGLTexture}
  20210. */
  20211. createTexture: function(gl, width, height, textureImageSource) {
  20212. var texture = gl.createTexture();
  20213. gl.bindTexture(gl.TEXTURE_2D, texture);
  20214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  20215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  20216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  20217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  20218. if (textureImageSource) {
  20219. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImageSource);
  20220. }
  20221. else {
  20222. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  20223. }
  20224. return texture;
  20225. },
  20226. /**
  20227. * Can be optionally used to get a texture from the cache array
  20228. *
  20229. * If an existing texture is not found, a new texture is created and cached.
  20230. *
  20231. * @param {String} uniqueId A cache key to use to find an existing texture.
  20232. * @param {HTMLImageElement|HTMLCanvasElement} textureImageSource A source to use to create the
  20233. * texture cache entry if one does not already exist.
  20234. */
  20235. getCachedTexture: function(uniqueId, textureImageSource) {
  20236. if (this.textureCache[uniqueId]) {
  20237. return this.textureCache[uniqueId];
  20238. }
  20239. else {
  20240. var texture = this.createTexture(
  20241. this.gl, textureImageSource.width, textureImageSource.height, textureImageSource);
  20242. this.textureCache[uniqueId] = texture;
  20243. return texture;
  20244. }
  20245. },
  20246. /**
  20247. * Clear out cached resources related to a source image that has been
  20248. * filtered previously.
  20249. *
  20250. * @param {String} cacheKey The cache key provided when the source image was filtered.
  20251. */
  20252. evictCachesForKey: function(cacheKey) {
  20253. if (this.textureCache[cacheKey]) {
  20254. this.gl.deleteTexture(this.textureCache[cacheKey]);
  20255. delete this.textureCache[cacheKey];
  20256. }
  20257. },
  20258. copyGLTo2D: copyGLTo2DDrawImage,
  20259. /**
  20260. * Attempt to extract GPU information strings from a WebGL context.
  20261. *
  20262. * Useful information when debugging or blacklisting specific GPUs.
  20263. *
  20264. * @returns {Object} A GPU info object with renderer and vendor strings.
  20265. */
  20266. captureGPUInfo: function() {
  20267. if (this.gpuInfo) {
  20268. return this.gpuInfo;
  20269. }
  20270. var gl = this.gl, gpuInfo = { renderer: '', vendor: '' };
  20271. if (!gl) {
  20272. return gpuInfo;
  20273. }
  20274. var ext = gl.getExtension('WEBGL_debug_renderer_info');
  20275. if (ext) {
  20276. var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
  20277. var vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);
  20278. if (renderer) {
  20279. gpuInfo.renderer = renderer.toLowerCase();
  20280. }
  20281. if (vendor) {
  20282. gpuInfo.vendor = vendor.toLowerCase();
  20283. }
  20284. }
  20285. this.gpuInfo = gpuInfo;
  20286. return gpuInfo;
  20287. },
  20288. };
  20289. })();
  20290. function resizeCanvasIfNeeded(pipelineState) {
  20291. var targetCanvas = pipelineState.targetCanvas,
  20292. width = targetCanvas.width, height = targetCanvas.height,
  20293. dWidth = pipelineState.destinationWidth,
  20294. dHeight = pipelineState.destinationHeight;
  20295. if (width !== dWidth || height !== dHeight) {
  20296. targetCanvas.width = dWidth;
  20297. targetCanvas.height = dHeight;
  20298. }
  20299. }
  20300. /**
  20301. * Copy an input WebGL canvas on to an output 2D canvas.
  20302. *
  20303. * The WebGL canvas is assumed to be upside down, with the top-left pixel of the
  20304. * desired output image appearing in the bottom-left corner of the WebGL canvas.
  20305. *
  20306. * @param {WebGLRenderingContext} sourceContext The WebGL context to copy from.
  20307. * @param {HTMLCanvasElement} targetCanvas The 2D target canvas to copy on to.
  20308. * @param {Object} pipelineState The 2D target canvas to copy on to.
  20309. */
  20310. function copyGLTo2DDrawImage(gl, pipelineState) {
  20311. var glCanvas = gl.canvas, targetCanvas = pipelineState.targetCanvas,
  20312. ctx = targetCanvas.getContext('2d');
  20313. ctx.translate(0, targetCanvas.height); // move it down again
  20314. ctx.scale(1, -1); // vertical flip
  20315. // where is my image on the big glcanvas?
  20316. var sourceY = glCanvas.height - targetCanvas.height;
  20317. ctx.drawImage(glCanvas, 0, sourceY, targetCanvas.width, targetCanvas.height, 0, 0,
  20318. targetCanvas.width, targetCanvas.height);
  20319. }
  20320. /**
  20321. * Copy an input WebGL canvas on to an output 2D canvas using 2d canvas' putImageData
  20322. * API. Measurably faster than using ctx.drawImage in Firefox (version 54 on OSX Sierra).
  20323. *
  20324. * @param {WebGLRenderingContext} sourceContext The WebGL context to copy from.
  20325. * @param {HTMLCanvasElement} targetCanvas The 2D target canvas to copy on to.
  20326. * @param {Object} pipelineState The 2D target canvas to copy on to.
  20327. */
  20328. function copyGLTo2DPutImageData(gl, pipelineState) {
  20329. var targetCanvas = pipelineState.targetCanvas, ctx = targetCanvas.getContext('2d'),
  20330. dWidth = pipelineState.destinationWidth,
  20331. dHeight = pipelineState.destinationHeight,
  20332. numBytes = dWidth * dHeight * 4;
  20333. // eslint-disable-next-line no-undef
  20334. var u8 = new Uint8Array(this.imageBuffer, 0, numBytes);
  20335. // eslint-disable-next-line no-undef
  20336. var u8Clamped = new Uint8ClampedArray(this.imageBuffer, 0, numBytes);
  20337. gl.readPixels(0, 0, dWidth, dHeight, gl.RGBA, gl.UNSIGNED_BYTE, u8);
  20338. var imgData = new ImageData(u8Clamped, dWidth, dHeight);
  20339. ctx.putImageData(imgData, 0, 0);
  20340. }
  20341. (function() {
  20342. 'use strict';
  20343. var noop = function() {};
  20344. fabric.Canvas2dFilterBackend = Canvas2dFilterBackend;
  20345. /**
  20346. * Canvas 2D filter backend.
  20347. */
  20348. function Canvas2dFilterBackend() {};
  20349. Canvas2dFilterBackend.prototype = /** @lends fabric.Canvas2dFilterBackend.prototype */ {
  20350. evictCachesForKey: noop,
  20351. dispose: noop,
  20352. clearWebGLCaches: noop,
  20353. /**
  20354. * Experimental. This object is a sort of repository of help layers used to avoid
  20355. * of recreating them during frequent filtering. If you are previewing a filter with
  20356. * a slider you probably do not want to create help layers every filter step.
  20357. * in this object there will be appended some canvases, created once, resized sometimes
  20358. * cleared never. Clearing is left to the developer.
  20359. **/
  20360. resources: {
  20361. },
  20362. /**
  20363. * Apply a set of filters against a source image and draw the filtered output
  20364. * to the provided destination canvas.
  20365. *
  20366. * @param {EnhancedFilter} filters The filter to apply.
  20367. * @param {HTMLImageElement|HTMLCanvasElement} sourceElement The source to be filtered.
  20368. * @param {Number} sourceWidth The width of the source input.
  20369. * @param {Number} sourceHeight The height of the source input.
  20370. * @param {HTMLCanvasElement} targetCanvas The destination for filtered output to be drawn.
  20371. */
  20372. applyFilters: function(filters, sourceElement, sourceWidth, sourceHeight, targetCanvas) {
  20373. var ctx = targetCanvas.getContext('2d');
  20374. ctx.drawImage(sourceElement, 0, 0, sourceWidth, sourceHeight);
  20375. var imageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);
  20376. var originalImageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);
  20377. var pipelineState = {
  20378. sourceWidth: sourceWidth,
  20379. sourceHeight: sourceHeight,
  20380. imageData: imageData,
  20381. originalEl: sourceElement,
  20382. originalImageData: originalImageData,
  20383. canvasEl: targetCanvas,
  20384. ctx: ctx,
  20385. filterBackend: this,
  20386. };
  20387. filters.forEach(function(filter) { filter.applyTo(pipelineState); });
  20388. if (pipelineState.imageData.width !== sourceWidth || pipelineState.imageData.height !== sourceHeight) {
  20389. targetCanvas.width = pipelineState.imageData.width;
  20390. targetCanvas.height = pipelineState.imageData.height;
  20391. }
  20392. ctx.putImageData(pipelineState.imageData, 0, 0);
  20393. return pipelineState;
  20394. },
  20395. };
  20396. })();
  20397. /**
  20398. * @namespace fabric.Image.filters
  20399. * @memberOf fabric.Image
  20400. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#image_filters}
  20401. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20402. */
  20403. fabric.Image = fabric.Image || { };
  20404. fabric.Image.filters = fabric.Image.filters || { };
  20405. /**
  20406. * Root filter class from which all filter classes inherit from
  20407. * @class fabric.Image.filters.BaseFilter
  20408. * @memberOf fabric.Image.filters
  20409. */
  20410. fabric.Image.filters.BaseFilter = fabric.util.createClass(/** @lends fabric.Image.filters.BaseFilter.prototype */ {
  20411. /**
  20412. * Filter type
  20413. * @param {String} type
  20414. * @default
  20415. */
  20416. type: 'BaseFilter',
  20417. /**
  20418. * Array of attributes to send with buffers. do not modify
  20419. * @private
  20420. */
  20421. vertexSource: 'attribute vec2 aPosition;\n' +
  20422. 'varying vec2 vTexCoord;\n' +
  20423. 'void main() {\n' +
  20424. 'vTexCoord = aPosition;\n' +
  20425. 'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n' +
  20426. '}',
  20427. fragmentSource: 'precision highp float;\n' +
  20428. 'varying vec2 vTexCoord;\n' +
  20429. 'uniform sampler2D uTexture;\n' +
  20430. 'void main() {\n' +
  20431. 'gl_FragColor = texture2D(uTexture, vTexCoord);\n' +
  20432. '}',
  20433. /**
  20434. * Constructor
  20435. * @param {Object} [options] Options object
  20436. */
  20437. initialize: function(options) {
  20438. if (options) {
  20439. this.setOptions(options);
  20440. }
  20441. },
  20442. /**
  20443. * Sets filter's properties from options
  20444. * @param {Object} [options] Options object
  20445. */
  20446. setOptions: function(options) {
  20447. for (var prop in options) {
  20448. this[prop] = options[prop];
  20449. }
  20450. },
  20451. /**
  20452. * Compile this filter's shader program.
  20453. *
  20454. * @param {WebGLRenderingContext} gl The GL canvas context to use for shader compilation.
  20455. * @param {String} fragmentSource fragmentShader source for compilation
  20456. * @param {String} vertexSource vertexShader source for compilation
  20457. */
  20458. createProgram: function(gl, fragmentSource, vertexSource) {
  20459. fragmentSource = fragmentSource || this.fragmentSource;
  20460. vertexSource = vertexSource || this.vertexSource;
  20461. if (fabric.webGlPrecision !== 'highp'){
  20462. fragmentSource = fragmentSource.replace(
  20463. /precision highp float/g,
  20464. 'precision ' + fabric.webGlPrecision + ' float'
  20465. );
  20466. }
  20467. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  20468. gl.shaderSource(vertexShader, vertexSource);
  20469. gl.compileShader(vertexShader);
  20470. if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
  20471. throw new Error(
  20472. // eslint-disable-next-line prefer-template
  20473. 'Vertex shader compile error for ' + this.type + ': ' +
  20474. gl.getShaderInfoLog(vertexShader)
  20475. );
  20476. }
  20477. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  20478. gl.shaderSource(fragmentShader, fragmentSource);
  20479. gl.compileShader(fragmentShader);
  20480. if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
  20481. throw new Error(
  20482. // eslint-disable-next-line prefer-template
  20483. 'Fragment shader compile error for ' + this.type + ': ' +
  20484. gl.getShaderInfoLog(fragmentShader)
  20485. );
  20486. }
  20487. var program = gl.createProgram();
  20488. gl.attachShader(program, vertexShader);
  20489. gl.attachShader(program, fragmentShader);
  20490. gl.linkProgram(program);
  20491. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  20492. throw new Error(
  20493. // eslint-disable-next-line prefer-template
  20494. 'Shader link error for "${this.type}" ' +
  20495. gl.getProgramInfoLog(program)
  20496. );
  20497. }
  20498. var attributeLocations = this.getAttributeLocations(gl, program);
  20499. var uniformLocations = this.getUniformLocations(gl, program) || { };
  20500. uniformLocations.uStepW = gl.getUniformLocation(program, 'uStepW');
  20501. uniformLocations.uStepH = gl.getUniformLocation(program, 'uStepH');
  20502. return {
  20503. program: program,
  20504. attributeLocations: attributeLocations,
  20505. uniformLocations: uniformLocations
  20506. };
  20507. },
  20508. /**
  20509. * Return a map of attribute names to WebGLAttributeLocation objects.
  20510. *
  20511. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  20512. * @param {WebGLShaderProgram} program The shader program from which to take attribute locations.
  20513. * @returns {Object} A map of attribute names to attribute locations.
  20514. */
  20515. getAttributeLocations: function(gl, program) {
  20516. return {
  20517. aPosition: gl.getAttribLocation(program, 'aPosition'),
  20518. };
  20519. },
  20520. /**
  20521. * Return a map of uniform names to WebGLUniformLocation objects.
  20522. *
  20523. * Intended to be overridden by subclasses.
  20524. *
  20525. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  20526. * @param {WebGLShaderProgram} program The shader program from which to take uniform locations.
  20527. * @returns {Object} A map of uniform names to uniform locations.
  20528. */
  20529. getUniformLocations: function (/* gl, program */) {
  20530. // in case i do not need any special uniform i need to return an empty object
  20531. return { };
  20532. },
  20533. /**
  20534. * Send attribute data from this filter to its shader program on the GPU.
  20535. *
  20536. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  20537. * @param {Object} attributeLocations A map of shader attribute names to their locations.
  20538. */
  20539. sendAttributeData: function(gl, attributeLocations, aPositionData) {
  20540. var attributeLocation = attributeLocations.aPosition;
  20541. var buffer = gl.createBuffer();
  20542. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  20543. gl.enableVertexAttribArray(attributeLocation);
  20544. gl.vertexAttribPointer(attributeLocation, 2, gl.FLOAT, false, 0, 0);
  20545. gl.bufferData(gl.ARRAY_BUFFER, aPositionData, gl.STATIC_DRAW);
  20546. },
  20547. _setupFrameBuffer: function(options) {
  20548. var gl = options.context, width, height;
  20549. if (options.passes > 1) {
  20550. width = options.destinationWidth;
  20551. height = options.destinationHeight;
  20552. if (options.sourceWidth !== width || options.sourceHeight !== height) {
  20553. gl.deleteTexture(options.targetTexture);
  20554. options.targetTexture = options.filterBackend.createTexture(gl, width, height);
  20555. }
  20556. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D,
  20557. options.targetTexture, 0);
  20558. }
  20559. else {
  20560. // draw last filter on canvas and not to framebuffer.
  20561. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  20562. gl.finish();
  20563. }
  20564. },
  20565. _swapTextures: function(options) {
  20566. options.passes--;
  20567. options.pass++;
  20568. var temp = options.targetTexture;
  20569. options.targetTexture = options.sourceTexture;
  20570. options.sourceTexture = temp;
  20571. },
  20572. /**
  20573. * Generic isNeutral implementation for one parameter based filters.
  20574. * Used only in image applyFilters to discard filters that will not have an effect
  20575. * on the image
  20576. * Other filters may need their own version ( ColorMatrix, HueRotation, gamma, ComposedFilter )
  20577. * @param {Object} options
  20578. **/
  20579. isNeutralState: function(/* options */) {
  20580. var main = this.mainParameter,
  20581. _class = fabric.Image.filters[this.type].prototype;
  20582. if (main) {
  20583. if (Array.isArray(_class[main])) {
  20584. for (var i = _class[main].length; i--;) {
  20585. if (this[main][i] !== _class[main][i]) {
  20586. return false;
  20587. }
  20588. }
  20589. return true;
  20590. }
  20591. else {
  20592. return _class[main] === this[main];
  20593. }
  20594. }
  20595. else {
  20596. return false;
  20597. }
  20598. },
  20599. /**
  20600. * Apply this filter to the input image data provided.
  20601. *
  20602. * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
  20603. *
  20604. * @param {Object} options
  20605. * @param {Number} options.passes The number of filters remaining to be executed
  20606. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  20607. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  20608. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  20609. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  20610. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  20611. */
  20612. applyTo: function(options) {
  20613. if (options.webgl) {
  20614. this._setupFrameBuffer(options);
  20615. this.applyToWebGL(options);
  20616. this._swapTextures(options);
  20617. }
  20618. else {
  20619. this.applyTo2d(options);
  20620. }
  20621. },
  20622. /**
  20623. * Retrieves the cached shader.
  20624. * @param {Object} options
  20625. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  20626. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  20627. */
  20628. retrieveShader: function(options) {
  20629. if (!options.programCache.hasOwnProperty(this.type)) {
  20630. options.programCache[this.type] = this.createProgram(options.context);
  20631. }
  20632. return options.programCache[this.type];
  20633. },
  20634. /**
  20635. * Apply this filter using webgl.
  20636. *
  20637. * @param {Object} options
  20638. * @param {Number} options.passes The number of filters remaining to be executed
  20639. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  20640. * @param {WebGLTexture} options.originalTexture The texture of the original input image.
  20641. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  20642. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  20643. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  20644. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  20645. */
  20646. applyToWebGL: function(options) {
  20647. var gl = options.context;
  20648. var shader = this.retrieveShader(options);
  20649. if (options.pass === 0 && options.originalTexture) {
  20650. gl.bindTexture(gl.TEXTURE_2D, options.originalTexture);
  20651. }
  20652. else {
  20653. gl.bindTexture(gl.TEXTURE_2D, options.sourceTexture);
  20654. }
  20655. gl.useProgram(shader.program);
  20656. this.sendAttributeData(gl, shader.attributeLocations, options.aPosition);
  20657. gl.uniform1f(shader.uniformLocations.uStepW, 1 / options.sourceWidth);
  20658. gl.uniform1f(shader.uniformLocations.uStepH, 1 / options.sourceHeight);
  20659. this.sendUniformData(gl, shader.uniformLocations);
  20660. gl.viewport(0, 0, options.destinationWidth, options.destinationHeight);
  20661. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  20662. },
  20663. bindAdditionalTexture: function(gl, texture, textureUnit) {
  20664. gl.activeTexture(textureUnit);
  20665. gl.bindTexture(gl.TEXTURE_2D, texture);
  20666. // reset active texture to 0 as usual
  20667. gl.activeTexture(gl.TEXTURE0);
  20668. },
  20669. unbindAdditionalTexture: function(gl, textureUnit) {
  20670. gl.activeTexture(textureUnit);
  20671. gl.bindTexture(gl.TEXTURE_2D, null);
  20672. gl.activeTexture(gl.TEXTURE0);
  20673. },
  20674. getMainParameter: function() {
  20675. return this[this.mainParameter];
  20676. },
  20677. setMainParameter: function(value) {
  20678. this[this.mainParameter] = value;
  20679. },
  20680. /**
  20681. * Send uniform data from this filter to its shader program on the GPU.
  20682. *
  20683. * Intended to be overridden by subclasses.
  20684. *
  20685. * @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
  20686. * @param {Object} uniformLocations A map of shader uniform names to their locations.
  20687. */
  20688. sendUniformData: function(/* gl, uniformLocations */) {
  20689. // Intentionally left blank. Override me in subclasses.
  20690. },
  20691. /**
  20692. * If needed by a 2d filter, this functions can create an helper canvas to be used
  20693. * remember that options.targetCanvas is available for use till end of chain.
  20694. */
  20695. createHelpLayer: function(options) {
  20696. if (!options.helpLayer) {
  20697. var helpLayer = document.createElement('canvas');
  20698. helpLayer.width = options.sourceWidth;
  20699. helpLayer.height = options.sourceHeight;
  20700. options.helpLayer = helpLayer;
  20701. }
  20702. },
  20703. /**
  20704. * Returns object representation of an instance
  20705. * @return {Object} Object representation of an instance
  20706. */
  20707. toObject: function() {
  20708. var object = { type: this.type }, mainP = this.mainParameter;
  20709. if (mainP) {
  20710. object[mainP] = this[mainP];
  20711. }
  20712. return object;
  20713. },
  20714. /**
  20715. * Returns a JSON representation of an instance
  20716. * @return {Object} JSON
  20717. */
  20718. toJSON: function() {
  20719. // delegate, not alias
  20720. return this.toObject();
  20721. }
  20722. });
  20723. fabric.Image.filters.BaseFilter.fromObject = function(object, callback) {
  20724. var filter = new fabric.Image.filters[object.type](object);
  20725. callback && callback(filter);
  20726. return filter;
  20727. };
  20728. (function(global) {
  20729. 'use strict';
  20730. var fabric = global.fabric || (global.fabric = { }),
  20731. filters = fabric.Image.filters,
  20732. createClass = fabric.util.createClass;
  20733. /**
  20734. * Color Matrix filter class
  20735. * @class fabric.Image.filters.ColorMatrix
  20736. * @memberOf fabric.Image.filters
  20737. * @extends fabric.Image.filters.BaseFilter
  20738. * @see {@link fabric.Image.filters.ColorMatrix#initialize} for constructor definition
  20739. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20740. * @see {@Link http://www.webwasp.co.uk/tutorials/219/Color_Matrix_Filter.php}
  20741. * @see {@Link http://phoboslab.org/log/2013/11/fast-image-filters-with-webgl}
  20742. * @example <caption>Kodachrome filter</caption>
  20743. * var filter = new fabric.Image.filters.ColorMatrix({
  20744. * matrix: [
  20745. 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,
  20746. -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,
  20747. -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,
  20748. 0, 0, 0, 1, 0
  20749. ]
  20750. * });
  20751. * object.filters.push(filter);
  20752. * object.applyFilters();
  20753. */
  20754. filters.ColorMatrix = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.ColorMatrix.prototype */ {
  20755. /**
  20756. * Filter type
  20757. * @param {String} type
  20758. * @default
  20759. */
  20760. type: 'ColorMatrix',
  20761. fragmentSource: 'precision highp float;\n' +
  20762. 'uniform sampler2D uTexture;\n' +
  20763. 'varying vec2 vTexCoord;\n' +
  20764. 'uniform mat4 uColorMatrix;\n' +
  20765. 'uniform vec4 uConstants;\n' +
  20766. 'void main() {\n' +
  20767. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  20768. 'color *= uColorMatrix;\n' +
  20769. 'color += uConstants;\n' +
  20770. 'gl_FragColor = color;\n' +
  20771. '}',
  20772. /**
  20773. * Colormatrix for pixels.
  20774. * array of 20 floats. Numbers in positions 4, 9, 14, 19 loose meaning
  20775. * outside the -1, 1 range.
  20776. * 0.0039215686 is the part of 1 that get translated to 1 in 2d
  20777. * @param {Array} matrix array of 20 numbers.
  20778. * @default
  20779. */
  20780. matrix: [
  20781. 1, 0, 0, 0, 0,
  20782. 0, 1, 0, 0, 0,
  20783. 0, 0, 1, 0, 0,
  20784. 0, 0, 0, 1, 0
  20785. ],
  20786. mainParameter: 'matrix',
  20787. /**
  20788. * Lock the colormatrix on the color part, skipping alpha, mainly for non webgl scenario
  20789. * to save some calculation
  20790. * @type Boolean
  20791. * @default true
  20792. */
  20793. colorsOnly: true,
  20794. /**
  20795. * Constructor
  20796. * @param {Object} [options] Options object
  20797. */
  20798. initialize: function(options) {
  20799. this.callSuper('initialize', options);
  20800. // create a new array instead mutating the prototype with push
  20801. this.matrix = this.matrix.slice(0);
  20802. },
  20803. /**
  20804. * Apply the ColorMatrix operation to a Uint8Array representing the pixels of an image.
  20805. *
  20806. * @param {Object} options
  20807. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  20808. */
  20809. applyTo2d: function(options) {
  20810. var imageData = options.imageData,
  20811. data = imageData.data,
  20812. iLen = data.length,
  20813. m = this.matrix,
  20814. r, g, b, a, i, colorsOnly = this.colorsOnly;
  20815. for (i = 0; i < iLen; i += 4) {
  20816. r = data[i];
  20817. g = data[i + 1];
  20818. b = data[i + 2];
  20819. if (colorsOnly) {
  20820. data[i] = r * m[0] + g * m[1] + b * m[2] + m[4] * 255;
  20821. data[i + 1] = r * m[5] + g * m[6] + b * m[7] + m[9] * 255;
  20822. data[i + 2] = r * m[10] + g * m[11] + b * m[12] + m[14] * 255;
  20823. }
  20824. else {
  20825. a = data[i + 3];
  20826. data[i] = r * m[0] + g * m[1] + b * m[2] + a * m[3] + m[4] * 255;
  20827. data[i + 1] = r * m[5] + g * m[6] + b * m[7] + a * m[8] + m[9] * 255;
  20828. data[i + 2] = r * m[10] + g * m[11] + b * m[12] + a * m[13] + m[14] * 255;
  20829. data[i + 3] = r * m[15] + g * m[16] + b * m[17] + a * m[18] + m[19] * 255;
  20830. }
  20831. }
  20832. },
  20833. /**
  20834. * Return WebGL uniform locations for this filter's shader.
  20835. *
  20836. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20837. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20838. */
  20839. getUniformLocations: function(gl, program) {
  20840. return {
  20841. uColorMatrix: gl.getUniformLocation(program, 'uColorMatrix'),
  20842. uConstants: gl.getUniformLocation(program, 'uConstants'),
  20843. };
  20844. },
  20845. /**
  20846. * Send data from this filter to its shader program's uniforms.
  20847. *
  20848. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20849. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20850. */
  20851. sendUniformData: function(gl, uniformLocations) {
  20852. var m = this.matrix,
  20853. matrix = [
  20854. m[0], m[1], m[2], m[3],
  20855. m[5], m[6], m[7], m[8],
  20856. m[10], m[11], m[12], m[13],
  20857. m[15], m[16], m[17], m[18]
  20858. ],
  20859. constants = [m[4], m[9], m[14], m[19]];
  20860. gl.uniformMatrix4fv(uniformLocations.uColorMatrix, false, matrix);
  20861. gl.uniform4fv(uniformLocations.uConstants, constants);
  20862. },
  20863. });
  20864. /**
  20865. * Returns filter instance from an object representation
  20866. * @static
  20867. * @param {Object} object Object to create an instance from
  20868. * @param {function} [callback] function to invoke after filter creation
  20869. * @return {fabric.Image.filters.ColorMatrix} Instance of fabric.Image.filters.ColorMatrix
  20870. */
  20871. fabric.Image.filters.ColorMatrix.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20872. })(typeof exports !== 'undefined' ? exports : this);
  20873. (function(global) {
  20874. 'use strict';
  20875. var fabric = global.fabric || (global.fabric = { }),
  20876. filters = fabric.Image.filters,
  20877. createClass = fabric.util.createClass;
  20878. /**
  20879. * Brightness filter class
  20880. * @class fabric.Image.filters.Brightness
  20881. * @memberOf fabric.Image.filters
  20882. * @extends fabric.Image.filters.BaseFilter
  20883. * @see {@link fabric.Image.filters.Brightness#initialize} for constructor definition
  20884. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20885. * @example
  20886. * var filter = new fabric.Image.filters.Brightness({
  20887. * brightness: 0.05
  20888. * });
  20889. * object.filters.push(filter);
  20890. * object.applyFilters();
  20891. */
  20892. filters.Brightness = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ {
  20893. /**
  20894. * Filter type
  20895. * @param {String} type
  20896. * @default
  20897. */
  20898. type: 'Brightness',
  20899. /**
  20900. * Fragment source for the brightness program
  20901. */
  20902. fragmentSource: 'precision highp float;\n' +
  20903. 'uniform sampler2D uTexture;\n' +
  20904. 'uniform float uBrightness;\n' +
  20905. 'varying vec2 vTexCoord;\n' +
  20906. 'void main() {\n' +
  20907. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  20908. 'color.rgb += uBrightness;\n' +
  20909. 'gl_FragColor = color;\n' +
  20910. '}',
  20911. /**
  20912. * Brightness value, from -1 to 1.
  20913. * translated to -255 to 255 for 2d
  20914. * 0.0039215686 is the part of 1 that get translated to 1 in 2d
  20915. * @param {Number} brightness
  20916. * @default
  20917. */
  20918. brightness: 0,
  20919. /**
  20920. * Describe the property that is the filter parameter
  20921. * @param {String} m
  20922. * @default
  20923. */
  20924. mainParameter: 'brightness',
  20925. /**
  20926. * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.
  20927. *
  20928. * @param {Object} options
  20929. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  20930. */
  20931. applyTo2d: function(options) {
  20932. if (this.brightness === 0) {
  20933. return;
  20934. }
  20935. var imageData = options.imageData,
  20936. data = imageData.data, i, len = data.length,
  20937. brightness = Math.round(this.brightness * 255);
  20938. for (i = 0; i < len; i += 4) {
  20939. data[i] = data[i] + brightness;
  20940. data[i + 1] = data[i + 1] + brightness;
  20941. data[i + 2] = data[i + 2] + brightness;
  20942. }
  20943. },
  20944. /**
  20945. * Return WebGL uniform locations for this filter's shader.
  20946. *
  20947. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20948. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  20949. */
  20950. getUniformLocations: function(gl, program) {
  20951. return {
  20952. uBrightness: gl.getUniformLocation(program, 'uBrightness'),
  20953. };
  20954. },
  20955. /**
  20956. * Send data from this filter to its shader program's uniforms.
  20957. *
  20958. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  20959. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  20960. */
  20961. sendUniformData: function(gl, uniformLocations) {
  20962. gl.uniform1f(uniformLocations.uBrightness, this.brightness);
  20963. },
  20964. });
  20965. /**
  20966. * Returns filter instance from an object representation
  20967. * @static
  20968. * @param {Object} object Object to create an instance from
  20969. * @param {function} [callback] to be invoked after filter creation
  20970. * @return {fabric.Image.filters.Brightness} Instance of fabric.Image.filters.Brightness
  20971. */
  20972. fabric.Image.filters.Brightness.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  20973. })(typeof exports !== 'undefined' ? exports : this);
  20974. (function(global) {
  20975. 'use strict';
  20976. var fabric = global.fabric || (global.fabric = { }),
  20977. extend = fabric.util.object.extend,
  20978. filters = fabric.Image.filters,
  20979. createClass = fabric.util.createClass;
  20980. /**
  20981. * Adapted from <a href="http://www.html5rocks.com/en/tutorials/canvas/imagefilters/">html5rocks article</a>
  20982. * @class fabric.Image.filters.Convolute
  20983. * @memberOf fabric.Image.filters
  20984. * @extends fabric.Image.filters.BaseFilter
  20985. * @see {@link fabric.Image.filters.Convolute#initialize} for constructor definition
  20986. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  20987. * @example <caption>Sharpen filter</caption>
  20988. * var filter = new fabric.Image.filters.Convolute({
  20989. * matrix: [ 0, -1, 0,
  20990. * -1, 5, -1,
  20991. * 0, -1, 0 ]
  20992. * });
  20993. * object.filters.push(filter);
  20994. * object.applyFilters();
  20995. * canvas.renderAll();
  20996. * @example <caption>Blur filter</caption>
  20997. * var filter = new fabric.Image.filters.Convolute({
  20998. * matrix: [ 1/9, 1/9, 1/9,
  20999. * 1/9, 1/9, 1/9,
  21000. * 1/9, 1/9, 1/9 ]
  21001. * });
  21002. * object.filters.push(filter);
  21003. * object.applyFilters();
  21004. * canvas.renderAll();
  21005. * @example <caption>Emboss filter</caption>
  21006. * var filter = new fabric.Image.filters.Convolute({
  21007. * matrix: [ 1, 1, 1,
  21008. * 1, 0.7, -1,
  21009. * -1, -1, -1 ]
  21010. * });
  21011. * object.filters.push(filter);
  21012. * object.applyFilters();
  21013. * canvas.renderAll();
  21014. * @example <caption>Emboss filter with opaqueness</caption>
  21015. * var filter = new fabric.Image.filters.Convolute({
  21016. * opaque: true,
  21017. * matrix: [ 1, 1, 1,
  21018. * 1, 0.7, -1,
  21019. * -1, -1, -1 ]
  21020. * });
  21021. * object.filters.push(filter);
  21022. * object.applyFilters();
  21023. * canvas.renderAll();
  21024. */
  21025. filters.Convolute = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Convolute.prototype */ {
  21026. /**
  21027. * Filter type
  21028. * @param {String} type
  21029. * @default
  21030. */
  21031. type: 'Convolute',
  21032. /*
  21033. * Opaque value (true/false)
  21034. */
  21035. opaque: false,
  21036. /*
  21037. * matrix for the filter, max 9x9
  21038. */
  21039. matrix: [0, 0, 0, 0, 1, 0, 0, 0, 0],
  21040. /**
  21041. * Fragment source for the brightness program
  21042. */
  21043. fragmentSource: {
  21044. Convolute_3_1: 'precision highp float;\n' +
  21045. 'uniform sampler2D uTexture;\n' +
  21046. 'uniform float uMatrix[9];\n' +
  21047. 'uniform float uStepW;\n' +
  21048. 'uniform float uStepH;\n' +
  21049. 'varying vec2 vTexCoord;\n' +
  21050. 'void main() {\n' +
  21051. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  21052. 'for (float h = 0.0; h < 3.0; h+=1.0) {\n' +
  21053. 'for (float w = 0.0; w < 3.0; w+=1.0) {\n' +
  21054. 'vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\n' +
  21055. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n' +
  21056. '}\n' +
  21057. '}\n' +
  21058. 'gl_FragColor = color;\n' +
  21059. '}',
  21060. Convolute_3_0: 'precision highp float;\n' +
  21061. 'uniform sampler2D uTexture;\n' +
  21062. 'uniform float uMatrix[9];\n' +
  21063. 'uniform float uStepW;\n' +
  21064. 'uniform float uStepH;\n' +
  21065. 'varying vec2 vTexCoord;\n' +
  21066. 'void main() {\n' +
  21067. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  21068. 'for (float h = 0.0; h < 3.0; h+=1.0) {\n' +
  21069. 'for (float w = 0.0; w < 3.0; w+=1.0) {\n' +
  21070. 'vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\n' +
  21071. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n' +
  21072. '}\n' +
  21073. '}\n' +
  21074. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  21075. 'gl_FragColor = color;\n' +
  21076. 'gl_FragColor.a = alpha;\n' +
  21077. '}',
  21078. Convolute_5_1: 'precision highp float;\n' +
  21079. 'uniform sampler2D uTexture;\n' +
  21080. 'uniform float uMatrix[25];\n' +
  21081. 'uniform float uStepW;\n' +
  21082. 'uniform float uStepH;\n' +
  21083. 'varying vec2 vTexCoord;\n' +
  21084. 'void main() {\n' +
  21085. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  21086. 'for (float h = 0.0; h < 5.0; h+=1.0) {\n' +
  21087. 'for (float w = 0.0; w < 5.0; w+=1.0) {\n' +
  21088. 'vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n' +
  21089. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n' +
  21090. '}\n' +
  21091. '}\n' +
  21092. 'gl_FragColor = color;\n' +
  21093. '}',
  21094. Convolute_5_0: 'precision highp float;\n' +
  21095. 'uniform sampler2D uTexture;\n' +
  21096. 'uniform float uMatrix[25];\n' +
  21097. 'uniform float uStepW;\n' +
  21098. 'uniform float uStepH;\n' +
  21099. 'varying vec2 vTexCoord;\n' +
  21100. 'void main() {\n' +
  21101. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  21102. 'for (float h = 0.0; h < 5.0; h+=1.0) {\n' +
  21103. 'for (float w = 0.0; w < 5.0; w+=1.0) {\n' +
  21104. 'vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n' +
  21105. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n' +
  21106. '}\n' +
  21107. '}\n' +
  21108. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  21109. 'gl_FragColor = color;\n' +
  21110. 'gl_FragColor.a = alpha;\n' +
  21111. '}',
  21112. Convolute_7_1: 'precision highp float;\n' +
  21113. 'uniform sampler2D uTexture;\n' +
  21114. 'uniform float uMatrix[49];\n' +
  21115. 'uniform float uStepW;\n' +
  21116. 'uniform float uStepH;\n' +
  21117. 'varying vec2 vTexCoord;\n' +
  21118. 'void main() {\n' +
  21119. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  21120. 'for (float h = 0.0; h < 7.0; h+=1.0) {\n' +
  21121. 'for (float w = 0.0; w < 7.0; w+=1.0) {\n' +
  21122. 'vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n' +
  21123. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n' +
  21124. '}\n' +
  21125. '}\n' +
  21126. 'gl_FragColor = color;\n' +
  21127. '}',
  21128. Convolute_7_0: 'precision highp float;\n' +
  21129. 'uniform sampler2D uTexture;\n' +
  21130. 'uniform float uMatrix[49];\n' +
  21131. 'uniform float uStepW;\n' +
  21132. 'uniform float uStepH;\n' +
  21133. 'varying vec2 vTexCoord;\n' +
  21134. 'void main() {\n' +
  21135. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  21136. 'for (float h = 0.0; h < 7.0; h+=1.0) {\n' +
  21137. 'for (float w = 0.0; w < 7.0; w+=1.0) {\n' +
  21138. 'vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n' +
  21139. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n' +
  21140. '}\n' +
  21141. '}\n' +
  21142. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  21143. 'gl_FragColor = color;\n' +
  21144. 'gl_FragColor.a = alpha;\n' +
  21145. '}',
  21146. Convolute_9_1: 'precision highp float;\n' +
  21147. 'uniform sampler2D uTexture;\n' +
  21148. 'uniform float uMatrix[81];\n' +
  21149. 'uniform float uStepW;\n' +
  21150. 'uniform float uStepH;\n' +
  21151. 'varying vec2 vTexCoord;\n' +
  21152. 'void main() {\n' +
  21153. 'vec4 color = vec4(0, 0, 0, 0);\n' +
  21154. 'for (float h = 0.0; h < 9.0; h+=1.0) {\n' +
  21155. 'for (float w = 0.0; w < 9.0; w+=1.0) {\n' +
  21156. 'vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n' +
  21157. 'color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n' +
  21158. '}\n' +
  21159. '}\n' +
  21160. 'gl_FragColor = color;\n' +
  21161. '}',
  21162. Convolute_9_0: 'precision highp float;\n' +
  21163. 'uniform sampler2D uTexture;\n' +
  21164. 'uniform float uMatrix[81];\n' +
  21165. 'uniform float uStepW;\n' +
  21166. 'uniform float uStepH;\n' +
  21167. 'varying vec2 vTexCoord;\n' +
  21168. 'void main() {\n' +
  21169. 'vec4 color = vec4(0, 0, 0, 1);\n' +
  21170. 'for (float h = 0.0; h < 9.0; h+=1.0) {\n' +
  21171. 'for (float w = 0.0; w < 9.0; w+=1.0) {\n' +
  21172. 'vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n' +
  21173. 'color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n' +
  21174. '}\n' +
  21175. '}\n' +
  21176. 'float alpha = texture2D(uTexture, vTexCoord).a;\n' +
  21177. 'gl_FragColor = color;\n' +
  21178. 'gl_FragColor.a = alpha;\n' +
  21179. '}',
  21180. },
  21181. /**
  21182. * Constructor
  21183. * @memberOf fabric.Image.filters.Convolute.prototype
  21184. * @param {Object} [options] Options object
  21185. * @param {Boolean} [options.opaque=false] Opaque value (true/false)
  21186. * @param {Array} [options.matrix] Filter matrix
  21187. */
  21188. /**
  21189. * Retrieves the cached shader.
  21190. * @param {Object} options
  21191. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21192. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21193. */
  21194. retrieveShader: function(options) {
  21195. var size = Math.sqrt(this.matrix.length);
  21196. var cacheKey = this.type + '_' + size + '_' + (this.opaque ? 1 : 0);
  21197. var shaderSource = this.fragmentSource[cacheKey];
  21198. if (!options.programCache.hasOwnProperty(cacheKey)) {
  21199. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  21200. }
  21201. return options.programCache[cacheKey];
  21202. },
  21203. /**
  21204. * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.
  21205. *
  21206. * @param {Object} options
  21207. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  21208. */
  21209. applyTo2d: function(options) {
  21210. var imageData = options.imageData,
  21211. data = imageData.data,
  21212. weights = this.matrix,
  21213. side = Math.round(Math.sqrt(weights.length)),
  21214. halfSide = Math.floor(side / 2),
  21215. sw = imageData.width,
  21216. sh = imageData.height,
  21217. output = options.ctx.createImageData(sw, sh),
  21218. dst = output.data,
  21219. // go through the destination image pixels
  21220. alphaFac = this.opaque ? 1 : 0,
  21221. r, g, b, a, dstOff,
  21222. scx, scy, srcOff, wt,
  21223. x, y, cx, cy;
  21224. for (y = 0; y < sh; y++) {
  21225. for (x = 0; x < sw; x++) {
  21226. dstOff = (y * sw + x) * 4;
  21227. // calculate the weighed sum of the source image pixels that
  21228. // fall under the convolution matrix
  21229. r = 0; g = 0; b = 0; a = 0;
  21230. for (cy = 0; cy < side; cy++) {
  21231. for (cx = 0; cx < side; cx++) {
  21232. scy = y + cy - halfSide;
  21233. scx = x + cx - halfSide;
  21234. // eslint-disable-next-line max-depth
  21235. if (scy < 0 || scy >= sh || scx < 0 || scx >= sw) {
  21236. continue;
  21237. }
  21238. srcOff = (scy * sw + scx) * 4;
  21239. wt = weights[cy * side + cx];
  21240. r += data[srcOff] * wt;
  21241. g += data[srcOff + 1] * wt;
  21242. b += data[srcOff + 2] * wt;
  21243. // eslint-disable-next-line max-depth
  21244. if (!alphaFac) {
  21245. a += data[srcOff + 3] * wt;
  21246. }
  21247. }
  21248. }
  21249. dst[dstOff] = r;
  21250. dst[dstOff + 1] = g;
  21251. dst[dstOff + 2] = b;
  21252. if (!alphaFac) {
  21253. dst[dstOff + 3] = a;
  21254. }
  21255. else {
  21256. dst[dstOff + 3] = data[dstOff + 3];
  21257. }
  21258. }
  21259. }
  21260. options.imageData = output;
  21261. },
  21262. /**
  21263. * Return WebGL uniform locations for this filter's shader.
  21264. *
  21265. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21266. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21267. */
  21268. getUniformLocations: function(gl, program) {
  21269. return {
  21270. uMatrix: gl.getUniformLocation(program, 'uMatrix'),
  21271. uOpaque: gl.getUniformLocation(program, 'uOpaque'),
  21272. uHalfSize: gl.getUniformLocation(program, 'uHalfSize'),
  21273. uSize: gl.getUniformLocation(program, 'uSize'),
  21274. };
  21275. },
  21276. /**
  21277. * Send data from this filter to its shader program's uniforms.
  21278. *
  21279. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21280. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21281. */
  21282. sendUniformData: function(gl, uniformLocations) {
  21283. gl.uniform1fv(uniformLocations.uMatrix, this.matrix);
  21284. },
  21285. /**
  21286. * Returns object representation of an instance
  21287. * @return {Object} Object representation of an instance
  21288. */
  21289. toObject: function() {
  21290. return extend(this.callSuper('toObject'), {
  21291. opaque: this.opaque,
  21292. matrix: this.matrix
  21293. });
  21294. }
  21295. });
  21296. /**
  21297. * Returns filter instance from an object representation
  21298. * @static
  21299. * @param {Object} object Object to create an instance from
  21300. * @param {function} [callback] to be invoked after filter creation
  21301. * @return {fabric.Image.filters.Convolute} Instance of fabric.Image.filters.Convolute
  21302. */
  21303. fabric.Image.filters.Convolute.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21304. })(typeof exports !== 'undefined' ? exports : this);
  21305. (function(global) {
  21306. 'use strict';
  21307. var fabric = global.fabric || (global.fabric = { }),
  21308. filters = fabric.Image.filters,
  21309. createClass = fabric.util.createClass;
  21310. /**
  21311. * Grayscale image filter class
  21312. * @class fabric.Image.filters.Grayscale
  21313. * @memberOf fabric.Image.filters
  21314. * @extends fabric.Image.filters.BaseFilter
  21315. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21316. * @example
  21317. * var filter = new fabric.Image.filters.Grayscale();
  21318. * object.filters.push(filter);
  21319. * object.applyFilters();
  21320. */
  21321. filters.Grayscale = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Grayscale.prototype */ {
  21322. /**
  21323. * Filter type
  21324. * @param {String} type
  21325. * @default
  21326. */
  21327. type: 'Grayscale',
  21328. fragmentSource: {
  21329. average: 'precision highp float;\n' +
  21330. 'uniform sampler2D uTexture;\n' +
  21331. 'varying vec2 vTexCoord;\n' +
  21332. 'void main() {\n' +
  21333. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21334. 'float average = (color.r + color.b + color.g) / 3.0;\n' +
  21335. 'gl_FragColor = vec4(average, average, average, color.a);\n' +
  21336. '}',
  21337. lightness: 'precision highp float;\n' +
  21338. 'uniform sampler2D uTexture;\n' +
  21339. 'uniform int uMode;\n' +
  21340. 'varying vec2 vTexCoord;\n' +
  21341. 'void main() {\n' +
  21342. 'vec4 col = texture2D(uTexture, vTexCoord);\n' +
  21343. 'float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\n' +
  21344. 'gl_FragColor = vec4(average, average, average, col.a);\n' +
  21345. '}',
  21346. luminosity: 'precision highp float;\n' +
  21347. 'uniform sampler2D uTexture;\n' +
  21348. 'uniform int uMode;\n' +
  21349. 'varying vec2 vTexCoord;\n' +
  21350. 'void main() {\n' +
  21351. 'vec4 col = texture2D(uTexture, vTexCoord);\n' +
  21352. 'float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\n' +
  21353. 'gl_FragColor = vec4(average, average, average, col.a);\n' +
  21354. '}',
  21355. },
  21356. /**
  21357. * Grayscale mode, between 'average', 'lightness', 'luminosity'
  21358. * @param {String} type
  21359. * @default
  21360. */
  21361. mode: 'average',
  21362. mainParameter: 'mode',
  21363. /**
  21364. * Apply the Grayscale operation to a Uint8Array representing the pixels of an image.
  21365. *
  21366. * @param {Object} options
  21367. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  21368. */
  21369. applyTo2d: function(options) {
  21370. var imageData = options.imageData,
  21371. data = imageData.data, i,
  21372. len = data.length, value,
  21373. mode = this.mode;
  21374. for (i = 0; i < len; i += 4) {
  21375. if (mode === 'average') {
  21376. value = (data[i] + data[i + 1] + data[i + 2]) / 3;
  21377. }
  21378. else if (mode === 'lightness') {
  21379. value = (Math.min(data[i], data[i + 1], data[i + 2]) +
  21380. Math.max(data[i], data[i + 1], data[i + 2])) / 2;
  21381. }
  21382. else if (mode === 'luminosity') {
  21383. value = 0.21 * data[i] + 0.72 * data[i + 1] + 0.07 * data[i + 2];
  21384. }
  21385. data[i] = value;
  21386. data[i + 1] = value;
  21387. data[i + 2] = value;
  21388. }
  21389. },
  21390. /**
  21391. * Retrieves the cached shader.
  21392. * @param {Object} options
  21393. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  21394. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  21395. */
  21396. retrieveShader: function(options) {
  21397. var cacheKey = this.type + '_' + this.mode;
  21398. if (!options.programCache.hasOwnProperty(cacheKey)) {
  21399. var shaderSource = this.fragmentSource[this.mode];
  21400. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  21401. }
  21402. return options.programCache[cacheKey];
  21403. },
  21404. /**
  21405. * Return WebGL uniform locations for this filter's shader.
  21406. *
  21407. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21408. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21409. */
  21410. getUniformLocations: function(gl, program) {
  21411. return {
  21412. uMode: gl.getUniformLocation(program, 'uMode'),
  21413. };
  21414. },
  21415. /**
  21416. * Send data from this filter to its shader program's uniforms.
  21417. *
  21418. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21419. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21420. */
  21421. sendUniformData: function(gl, uniformLocations) {
  21422. // default average mode.
  21423. var mode = 1;
  21424. gl.uniform1i(uniformLocations.uMode, mode);
  21425. },
  21426. /**
  21427. * Grayscale filter isNeutralState implementation
  21428. * The filter is never neutral
  21429. * on the image
  21430. **/
  21431. isNeutralState: function() {
  21432. return false;
  21433. },
  21434. });
  21435. /**
  21436. * Returns filter instance from an object representation
  21437. * @static
  21438. * @param {Object} object Object to create an instance from
  21439. * @param {function} [callback] to be invoked after filter creation
  21440. * @return {fabric.Image.filters.Grayscale} Instance of fabric.Image.filters.Grayscale
  21441. */
  21442. fabric.Image.filters.Grayscale.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21443. })(typeof exports !== 'undefined' ? exports : this);
  21444. (function(global) {
  21445. 'use strict';
  21446. var fabric = global.fabric || (global.fabric = { }),
  21447. filters = fabric.Image.filters,
  21448. createClass = fabric.util.createClass;
  21449. /**
  21450. * Invert filter class
  21451. * @class fabric.Image.filters.Invert
  21452. * @memberOf fabric.Image.filters
  21453. * @extends fabric.Image.filters.BaseFilter
  21454. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21455. * @example
  21456. * var filter = new fabric.Image.filters.Invert();
  21457. * object.filters.push(filter);
  21458. * object.applyFilters(canvas.renderAll.bind(canvas));
  21459. */
  21460. filters.Invert = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Invert.prototype */ {
  21461. /**
  21462. * Filter type
  21463. * @param {String} type
  21464. * @default
  21465. */
  21466. type: 'Invert',
  21467. fragmentSource: 'precision highp float;\n' +
  21468. 'uniform sampler2D uTexture;\n' +
  21469. 'uniform int uInvert;\n' +
  21470. 'varying vec2 vTexCoord;\n' +
  21471. 'void main() {\n' +
  21472. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21473. 'if (uInvert == 1) {\n' +
  21474. 'gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n' +
  21475. '} else {\n' +
  21476. 'gl_FragColor = color;\n' +
  21477. '}\n' +
  21478. '}',
  21479. /**
  21480. * Filter invert. if false, does nothing
  21481. * @param {Boolean} invert
  21482. * @default
  21483. */
  21484. invert: true,
  21485. mainParameter: 'invert',
  21486. /**
  21487. * Apply the Invert operation to a Uint8Array representing the pixels of an image.
  21488. *
  21489. * @param {Object} options
  21490. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  21491. */
  21492. applyTo2d: function(options) {
  21493. var imageData = options.imageData,
  21494. data = imageData.data, i,
  21495. len = data.length;
  21496. for (i = 0; i < len; i += 4) {
  21497. data[i] = 255 - data[i];
  21498. data[i + 1] = 255 - data[i + 1];
  21499. data[i + 2] = 255 - data[i + 2];
  21500. }
  21501. },
  21502. /**
  21503. * Invert filter isNeutralState implementation
  21504. * Used only in image applyFilters to discard filters that will not have an effect
  21505. * on the image
  21506. * @param {Object} options
  21507. **/
  21508. isNeutralState: function() {
  21509. return !this.invert;
  21510. },
  21511. /**
  21512. * Return WebGL uniform locations for this filter's shader.
  21513. *
  21514. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21515. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21516. */
  21517. getUniformLocations: function(gl, program) {
  21518. return {
  21519. uInvert: gl.getUniformLocation(program, 'uInvert'),
  21520. };
  21521. },
  21522. /**
  21523. * Send data from this filter to its shader program's uniforms.
  21524. *
  21525. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21526. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21527. */
  21528. sendUniformData: function(gl, uniformLocations) {
  21529. gl.uniform1i(uniformLocations.uInvert, this.invert);
  21530. },
  21531. });
  21532. /**
  21533. * Returns filter instance from an object representation
  21534. * @static
  21535. * @param {Object} object Object to create an instance from
  21536. * @param {function} [callback] to be invoked after filter creation
  21537. * @return {fabric.Image.filters.Invert} Instance of fabric.Image.filters.Invert
  21538. */
  21539. fabric.Image.filters.Invert.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21540. })(typeof exports !== 'undefined' ? exports : this);
  21541. (function(global) {
  21542. 'use strict';
  21543. var fabric = global.fabric || (global.fabric = { }),
  21544. extend = fabric.util.object.extend,
  21545. filters = fabric.Image.filters,
  21546. createClass = fabric.util.createClass;
  21547. /**
  21548. * Noise filter class
  21549. * @class fabric.Image.filters.Noise
  21550. * @memberOf fabric.Image.filters
  21551. * @extends fabric.Image.filters.BaseFilter
  21552. * @see {@link fabric.Image.filters.Noise#initialize} for constructor definition
  21553. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21554. * @example
  21555. * var filter = new fabric.Image.filters.Noise({
  21556. * noise: 700
  21557. * });
  21558. * object.filters.push(filter);
  21559. * object.applyFilters();
  21560. * canvas.renderAll();
  21561. */
  21562. filters.Noise = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Noise.prototype */ {
  21563. /**
  21564. * Filter type
  21565. * @param {String} type
  21566. * @default
  21567. */
  21568. type: 'Noise',
  21569. /**
  21570. * Fragment source for the noise program
  21571. */
  21572. fragmentSource: 'precision highp float;\n' +
  21573. 'uniform sampler2D uTexture;\n' +
  21574. 'uniform float uStepH;\n' +
  21575. 'uniform float uNoise;\n' +
  21576. 'uniform float uSeed;\n' +
  21577. 'varying vec2 vTexCoord;\n' +
  21578. 'float rand(vec2 co, float seed, float vScale) {\n' +
  21579. 'return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n' +
  21580. '}\n' +
  21581. 'void main() {\n' +
  21582. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  21583. 'color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\n' +
  21584. 'gl_FragColor = color;\n' +
  21585. '}',
  21586. /**
  21587. * Describe the property that is the filter parameter
  21588. * @param {String} m
  21589. * @default
  21590. */
  21591. mainParameter: 'noise',
  21592. /**
  21593. * Noise value, from
  21594. * @param {Number} noise
  21595. * @default
  21596. */
  21597. noise: 0,
  21598. /**
  21599. * Apply the Brightness operation to a Uint8ClampedArray representing the pixels of an image.
  21600. *
  21601. * @param {Object} options
  21602. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  21603. */
  21604. applyTo2d: function(options) {
  21605. if (this.noise === 0) {
  21606. return;
  21607. }
  21608. var imageData = options.imageData,
  21609. data = imageData.data, i, len = data.length,
  21610. noise = this.noise, rand;
  21611. for (i = 0, len = data.length; i < len; i += 4) {
  21612. rand = (0.5 - Math.random()) * noise;
  21613. data[i] += rand;
  21614. data[i + 1] += rand;
  21615. data[i + 2] += rand;
  21616. }
  21617. },
  21618. /**
  21619. * Return WebGL uniform locations for this filter's shader.
  21620. *
  21621. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21622. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21623. */
  21624. getUniformLocations: function(gl, program) {
  21625. return {
  21626. uNoise: gl.getUniformLocation(program, 'uNoise'),
  21627. uSeed: gl.getUniformLocation(program, 'uSeed'),
  21628. };
  21629. },
  21630. /**
  21631. * Send data from this filter to its shader program's uniforms.
  21632. *
  21633. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21634. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21635. */
  21636. sendUniformData: function(gl, uniformLocations) {
  21637. gl.uniform1f(uniformLocations.uNoise, this.noise / 255);
  21638. gl.uniform1f(uniformLocations.uSeed, Math.random());
  21639. },
  21640. /**
  21641. * Returns object representation of an instance
  21642. * @return {Object} Object representation of an instance
  21643. */
  21644. toObject: function() {
  21645. return extend(this.callSuper('toObject'), {
  21646. noise: this.noise
  21647. });
  21648. }
  21649. });
  21650. /**
  21651. * Returns filter instance from an object representation
  21652. * @static
  21653. * @param {Object} object Object to create an instance from
  21654. * @param {Function} [callback] to be invoked after filter creation
  21655. * @return {fabric.Image.filters.Noise} Instance of fabric.Image.filters.Noise
  21656. */
  21657. fabric.Image.filters.Noise.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21658. })(typeof exports !== 'undefined' ? exports : this);
  21659. (function(global) {
  21660. 'use strict';
  21661. var fabric = global.fabric || (global.fabric = { }),
  21662. filters = fabric.Image.filters,
  21663. createClass = fabric.util.createClass;
  21664. /**
  21665. * Pixelate filter class
  21666. * @class fabric.Image.filters.Pixelate
  21667. * @memberOf fabric.Image.filters
  21668. * @extends fabric.Image.filters.BaseFilter
  21669. * @see {@link fabric.Image.filters.Pixelate#initialize} for constructor definition
  21670. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21671. * @example
  21672. * var filter = new fabric.Image.filters.Pixelate({
  21673. * blocksize: 8
  21674. * });
  21675. * object.filters.push(filter);
  21676. * object.applyFilters();
  21677. */
  21678. filters.Pixelate = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Pixelate.prototype */ {
  21679. /**
  21680. * Filter type
  21681. * @param {String} type
  21682. * @default
  21683. */
  21684. type: 'Pixelate',
  21685. blocksize: 4,
  21686. mainParameter: 'blocksize',
  21687. /**
  21688. * Fragment source for the Pixelate program
  21689. */
  21690. fragmentSource: 'precision highp float;\n' +
  21691. 'uniform sampler2D uTexture;\n' +
  21692. 'uniform float uBlocksize;\n' +
  21693. 'uniform float uStepW;\n' +
  21694. 'uniform float uStepH;\n' +
  21695. 'varying vec2 vTexCoord;\n' +
  21696. 'void main() {\n' +
  21697. 'float blockW = uBlocksize * uStepW;\n' +
  21698. 'float blockH = uBlocksize * uStepW;\n' +
  21699. 'int posX = int(vTexCoord.x / blockW);\n' +
  21700. 'int posY = int(vTexCoord.y / blockH);\n' +
  21701. 'float fposX = float(posX);\n' +
  21702. 'float fposY = float(posY);\n' +
  21703. 'vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\n' +
  21704. 'vec4 color = texture2D(uTexture, squareCoords);\n' +
  21705. 'gl_FragColor = color;\n' +
  21706. '}',
  21707. /**
  21708. * Apply the Pixelate operation to a Uint8ClampedArray representing the pixels of an image.
  21709. *
  21710. * @param {Object} options
  21711. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  21712. */
  21713. applyTo2d: function(options) {
  21714. var imageData = options.imageData,
  21715. data = imageData.data,
  21716. iLen = imageData.height,
  21717. jLen = imageData.width,
  21718. index, i, j, r, g, b, a,
  21719. _i, _j, _iLen, _jLen;
  21720. for (i = 0; i < iLen; i += this.blocksize) {
  21721. for (j = 0; j < jLen; j += this.blocksize) {
  21722. index = (i * 4) * jLen + (j * 4);
  21723. r = data[index];
  21724. g = data[index + 1];
  21725. b = data[index + 2];
  21726. a = data[index + 3];
  21727. _iLen = Math.min(i + this.blocksize, iLen);
  21728. _jLen = Math.min(j + this.blocksize, jLen);
  21729. for (_i = i; _i < _iLen; _i++) {
  21730. for (_j = j; _j < _jLen; _j++) {
  21731. index = (_i * 4) * jLen + (_j * 4);
  21732. data[index] = r;
  21733. data[index + 1] = g;
  21734. data[index + 2] = b;
  21735. data[index + 3] = a;
  21736. }
  21737. }
  21738. }
  21739. }
  21740. },
  21741. /**
  21742. * Indicate when the filter is not gonna apply changes to the image
  21743. **/
  21744. isNeutralState: function() {
  21745. return this.blocksize === 1;
  21746. },
  21747. /**
  21748. * Return WebGL uniform locations for this filter's shader.
  21749. *
  21750. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21751. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21752. */
  21753. getUniformLocations: function(gl, program) {
  21754. return {
  21755. uBlocksize: gl.getUniformLocation(program, 'uBlocksize'),
  21756. uStepW: gl.getUniformLocation(program, 'uStepW'),
  21757. uStepH: gl.getUniformLocation(program, 'uStepH'),
  21758. };
  21759. },
  21760. /**
  21761. * Send data from this filter to its shader program's uniforms.
  21762. *
  21763. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21764. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21765. */
  21766. sendUniformData: function(gl, uniformLocations) {
  21767. gl.uniform1f(uniformLocations.uBlocksize, this.blocksize);
  21768. },
  21769. });
  21770. /**
  21771. * Returns filter instance from an object representation
  21772. * @static
  21773. * @param {Object} object Object to create an instance from
  21774. * @param {Function} [callback] to be invoked after filter creation
  21775. * @return {fabric.Image.filters.Pixelate} Instance of fabric.Image.filters.Pixelate
  21776. */
  21777. fabric.Image.filters.Pixelate.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21778. })(typeof exports !== 'undefined' ? exports : this);
  21779. (function(global) {
  21780. 'use strict';
  21781. var fabric = global.fabric || (global.fabric = { }),
  21782. extend = fabric.util.object.extend,
  21783. filters = fabric.Image.filters,
  21784. createClass = fabric.util.createClass;
  21785. /**
  21786. * Remove white filter class
  21787. * @class fabric.Image.filters.RemoveColor
  21788. * @memberOf fabric.Image.filters
  21789. * @extends fabric.Image.filters.BaseFilter
  21790. * @see {@link fabric.Image.filters.RemoveColor#initialize} for constructor definition
  21791. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  21792. * @example
  21793. * var filter = new fabric.Image.filters.RemoveColor({
  21794. * threshold: 0.2,
  21795. * });
  21796. * object.filters.push(filter);
  21797. * object.applyFilters();
  21798. * canvas.renderAll();
  21799. */
  21800. filters.RemoveColor = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.RemoveColor.prototype */ {
  21801. /**
  21802. * Filter type
  21803. * @param {String} type
  21804. * @default
  21805. */
  21806. type: 'RemoveColor',
  21807. /**
  21808. * Color to remove, in any format understood by fabric.Color.
  21809. * @param {String} type
  21810. * @default
  21811. */
  21812. color: '#FFFFFF',
  21813. /**
  21814. * Fragment source for the brightness program
  21815. */
  21816. fragmentSource: 'precision highp float;\n' +
  21817. 'uniform sampler2D uTexture;\n' +
  21818. 'uniform vec4 uLow;\n' +
  21819. 'uniform vec4 uHigh;\n' +
  21820. 'varying vec2 vTexCoord;\n' +
  21821. 'void main() {\n' +
  21822. 'gl_FragColor = texture2D(uTexture, vTexCoord);\n' +
  21823. 'if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\n' +
  21824. 'gl_FragColor.a = 0.0;\n' +
  21825. '}\n' +
  21826. '}',
  21827. /**
  21828. * distance to actual color, as value up or down from each r,g,b
  21829. * between 0 and 1
  21830. **/
  21831. distance: 0.02,
  21832. /**
  21833. * For color to remove inside distance, use alpha channel for a smoother deletion
  21834. * NOT IMPLEMENTED YET
  21835. **/
  21836. useAlpha: false,
  21837. /**
  21838. * Constructor
  21839. * @memberOf fabric.Image.filters.RemoveWhite.prototype
  21840. * @param {Object} [options] Options object
  21841. * @param {Number} [options.color=#RRGGBB] Threshold value
  21842. * @param {Number} [options.distance=10] Distance value
  21843. */
  21844. /**
  21845. * Applies filter to canvas element
  21846. * @param {Object} canvasEl Canvas element to apply filter to
  21847. */
  21848. applyTo2d: function(options) {
  21849. var imageData = options.imageData,
  21850. data = imageData.data, i,
  21851. distance = this.distance * 255,
  21852. r, g, b,
  21853. source = new fabric.Color(this.color).getSource(),
  21854. lowC = [
  21855. source[0] - distance,
  21856. source[1] - distance,
  21857. source[2] - distance,
  21858. ],
  21859. highC = [
  21860. source[0] + distance,
  21861. source[1] + distance,
  21862. source[2] + distance,
  21863. ];
  21864. for (i = 0; i < data.length; i += 4) {
  21865. r = data[i];
  21866. g = data[i + 1];
  21867. b = data[i + 2];
  21868. if (r > lowC[0] &&
  21869. g > lowC[1] &&
  21870. b > lowC[2] &&
  21871. r < highC[0] &&
  21872. g < highC[1] &&
  21873. b < highC[2]) {
  21874. data[i + 3] = 0;
  21875. }
  21876. }
  21877. },
  21878. /**
  21879. * Return WebGL uniform locations for this filter's shader.
  21880. *
  21881. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21882. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  21883. */
  21884. getUniformLocations: function(gl, program) {
  21885. return {
  21886. uLow: gl.getUniformLocation(program, 'uLow'),
  21887. uHigh: gl.getUniformLocation(program, 'uHigh'),
  21888. };
  21889. },
  21890. /**
  21891. * Send data from this filter to its shader program's uniforms.
  21892. *
  21893. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  21894. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  21895. */
  21896. sendUniformData: function(gl, uniformLocations) {
  21897. var source = new fabric.Color(this.color).getSource(),
  21898. distance = parseFloat(this.distance),
  21899. lowC = [
  21900. 0 + source[0] / 255 - distance,
  21901. 0 + source[1] / 255 - distance,
  21902. 0 + source[2] / 255 - distance,
  21903. 1
  21904. ],
  21905. highC = [
  21906. source[0] / 255 + distance,
  21907. source[1] / 255 + distance,
  21908. source[2] / 255 + distance,
  21909. 1
  21910. ];
  21911. gl.uniform4fv(uniformLocations.uLow, lowC);
  21912. gl.uniform4fv(uniformLocations.uHigh, highC);
  21913. },
  21914. /**
  21915. * Returns object representation of an instance
  21916. * @return {Object} Object representation of an instance
  21917. */
  21918. toObject: function() {
  21919. return extend(this.callSuper('toObject'), {
  21920. color: this.color,
  21921. distance: this.distance
  21922. });
  21923. }
  21924. });
  21925. /**
  21926. * Returns filter instance from an object representation
  21927. * @static
  21928. * @param {Object} object Object to create an instance from
  21929. * @param {Function} [callback] to be invoked after filter creation
  21930. * @return {fabric.Image.filters.RemoveColor} Instance of fabric.Image.filters.RemoveWhite
  21931. */
  21932. fabric.Image.filters.RemoveColor.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  21933. })(typeof exports !== 'undefined' ? exports : this);
  21934. (function(global) {
  21935. 'use strict';
  21936. var fabric = global.fabric || (global.fabric = { }),
  21937. filters = fabric.Image.filters,
  21938. createClass = fabric.util.createClass;
  21939. var matrices = {
  21940. Brownie: [
  21941. 0.59970,0.34553,-0.27082,0,0.186,
  21942. -0.03770,0.86095,0.15059,0,-0.1449,
  21943. 0.24113,-0.07441,0.44972,0,-0.02965,
  21944. 0,0,0,1,0
  21945. ],
  21946. Vintage: [
  21947. 0.62793,0.32021,-0.03965,0,0.03784,
  21948. 0.02578,0.64411,0.03259,0,0.02926,
  21949. 0.04660,-0.08512,0.52416,0,0.02023,
  21950. 0,0,0,1,0
  21951. ],
  21952. Kodachrome: [
  21953. 1.12855,-0.39673,-0.03992,0,0.24991,
  21954. -0.16404,1.08352,-0.05498,0,0.09698,
  21955. -0.16786,-0.56034,1.60148,0,0.13972,
  21956. 0,0,0,1,0
  21957. ],
  21958. Technicolor: [
  21959. 1.91252,-0.85453,-0.09155,0,0.04624,
  21960. -0.30878,1.76589,-0.10601,0,-0.27589,
  21961. -0.23110,-0.75018,1.84759,0,0.12137,
  21962. 0,0,0,1,0
  21963. ],
  21964. Polaroid: [
  21965. 1.438,-0.062,-0.062,0,0,
  21966. -0.122,1.378,-0.122,0,0,
  21967. -0.016,-0.016,1.483,0,0,
  21968. 0,0,0,1,0
  21969. ],
  21970. Sepia: [
  21971. 0.393, 0.769, 0.189, 0, 0,
  21972. 0.349, 0.686, 0.168, 0, 0,
  21973. 0.272, 0.534, 0.131, 0, 0,
  21974. 0, 0, 0, 1, 0
  21975. ],
  21976. BlackWhite: [
  21977. 1.5, 1.5, 1.5, 0, -1,
  21978. 1.5, 1.5, 1.5, 0, -1,
  21979. 1.5, 1.5, 1.5, 0, -1,
  21980. 0, 0, 0, 1, 0,
  21981. ]
  21982. };
  21983. for (var key in matrices) {
  21984. filters[key] = createClass(filters.ColorMatrix, /** @lends fabric.Image.filters.Sepia.prototype */ {
  21985. /**
  21986. * Filter type
  21987. * @param {String} type
  21988. * @default
  21989. */
  21990. type: key,
  21991. /**
  21992. * Colormatrix for the effect
  21993. * array of 20 floats. Numbers in positions 4, 9, 14, 19 loose meaning
  21994. * outside the -1, 1 range.
  21995. * @param {Array} matrix array of 20 numbers.
  21996. * @default
  21997. */
  21998. matrix: matrices[key],
  21999. /**
  22000. * Lock the matrix export for this kind of static, parameter less filters.
  22001. */
  22002. mainParameter: false,
  22003. /**
  22004. * Lock the colormatrix on the color part, skipping alpha
  22005. */
  22006. colorsOnly: true,
  22007. });
  22008. fabric.Image.filters[key].fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22009. }
  22010. })(typeof exports !== 'undefined' ? exports : this);
  22011. (function(global) {
  22012. 'use strict';
  22013. var fabric = global.fabric,
  22014. filters = fabric.Image.filters,
  22015. createClass = fabric.util.createClass;
  22016. /**
  22017. * Color Blend filter class
  22018. * @class fabric.Image.filter.BlendColor
  22019. * @memberOf fabric.Image.filters
  22020. * @extends fabric.Image.filters.BaseFilter
  22021. * @example
  22022. * var filter = new fabric.Image.filters.BlendColor({
  22023. * color: '#000',
  22024. * mode: 'multiply'
  22025. * });
  22026. *
  22027. * var filter = new fabric.Image.filters.BlendImage({
  22028. * image: fabricImageObject,
  22029. * mode: 'multiply',
  22030. * alpha: 0.5
  22031. * });
  22032. * object.filters.push(filter);
  22033. * object.applyFilters();
  22034. * canvas.renderAll();
  22035. */
  22036. filters.BlendColor = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Blend.prototype */ {
  22037. type: 'BlendColor',
  22038. /**
  22039. * Color to make the blend operation with. default to a reddish color since black or white
  22040. * gives always strong result.
  22041. * @type String
  22042. * @default
  22043. **/
  22044. color: '#F95C63',
  22045. /**
  22046. * Blend mode for the filter: one of multiply, add, diff, screen, subtract,
  22047. * darken, lighten, overlay, exclusion, tint.
  22048. * @type String
  22049. * @default
  22050. **/
  22051. mode: 'multiply',
  22052. /**
  22053. * alpha value. represent the strength of the blend color operation.
  22054. * @type Number
  22055. * @default
  22056. **/
  22057. alpha: 1,
  22058. /**
  22059. * Fragment source for the Multiply program
  22060. */
  22061. fragmentSource: {
  22062. multiply: 'gl_FragColor.rgb *= uColor.rgb;\n',
  22063. screen: 'gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n',
  22064. add: 'gl_FragColor.rgb += uColor.rgb;\n',
  22065. diff: 'gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n',
  22066. subtract: 'gl_FragColor.rgb -= uColor.rgb;\n',
  22067. lighten: 'gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n',
  22068. darken: 'gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n',
  22069. exclusion: 'gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n',
  22070. overlay: 'if (uColor.r < 0.5) {\n' +
  22071. 'gl_FragColor.r *= 2.0 * uColor.r;\n' +
  22072. '} else {\n' +
  22073. 'gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n' +
  22074. '}\n' +
  22075. 'if (uColor.g < 0.5) {\n' +
  22076. 'gl_FragColor.g *= 2.0 * uColor.g;\n' +
  22077. '} else {\n' +
  22078. 'gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n' +
  22079. '}\n' +
  22080. 'if (uColor.b < 0.5) {\n' +
  22081. 'gl_FragColor.b *= 2.0 * uColor.b;\n' +
  22082. '} else {\n' +
  22083. 'gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n' +
  22084. '}\n',
  22085. tint: 'gl_FragColor.rgb *= (1.0 - uColor.a);\n' +
  22086. 'gl_FragColor.rgb += uColor.rgb;\n',
  22087. },
  22088. /**
  22089. * build the fragment source for the filters, joining the common part with
  22090. * the specific one.
  22091. * @param {String} mode the mode of the filter, a key of this.fragmentSource
  22092. * @return {String} the source to be compiled
  22093. * @private
  22094. */
  22095. buildSource: function(mode) {
  22096. return 'precision highp float;\n' +
  22097. 'uniform sampler2D uTexture;\n' +
  22098. 'uniform vec4 uColor;\n' +
  22099. 'varying vec2 vTexCoord;\n' +
  22100. 'void main() {\n' +
  22101. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  22102. 'gl_FragColor = color;\n' +
  22103. 'if (color.a > 0.0) {\n' +
  22104. this.fragmentSource[mode] +
  22105. '}\n' +
  22106. '}';
  22107. },
  22108. /**
  22109. * Retrieves the cached shader.
  22110. * @param {Object} options
  22111. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  22112. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  22113. */
  22114. retrieveShader: function(options) {
  22115. var cacheKey = this.type + '_' + this.mode, shaderSource;
  22116. if (!options.programCache.hasOwnProperty(cacheKey)) {
  22117. shaderSource = this.buildSource(this.mode);
  22118. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  22119. }
  22120. return options.programCache[cacheKey];
  22121. },
  22122. /**
  22123. * Apply the Blend operation to a Uint8ClampedArray representing the pixels of an image.
  22124. *
  22125. * @param {Object} options
  22126. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  22127. */
  22128. applyTo2d: function(options) {
  22129. var imageData = options.imageData,
  22130. data = imageData.data, iLen = data.length,
  22131. tr, tg, tb,
  22132. r, g, b,
  22133. source, alpha1 = 1 - this.alpha;
  22134. source = new fabric.Color(this.color).getSource();
  22135. tr = source[0] * this.alpha;
  22136. tg = source[1] * this.alpha;
  22137. tb = source[2] * this.alpha;
  22138. for (var i = 0; i < iLen; i += 4) {
  22139. r = data[i];
  22140. g = data[i + 1];
  22141. b = data[i + 2];
  22142. switch (this.mode) {
  22143. case 'multiply':
  22144. data[i] = r * tr / 255;
  22145. data[i + 1] = g * tg / 255;
  22146. data[i + 2] = b * tb / 255;
  22147. break;
  22148. case 'screen':
  22149. data[i] = 255 - (255 - r) * (255 - tr) / 255;
  22150. data[i + 1] = 255 - (255 - g) * (255 - tg) / 255;
  22151. data[i + 2] = 255 - (255 - b) * (255 - tb) / 255;
  22152. break;
  22153. case 'add':
  22154. data[i] = r + tr;
  22155. data[i + 1] = g + tg;
  22156. data[i + 2] = b + tb;
  22157. break;
  22158. case 'diff':
  22159. case 'difference':
  22160. data[i] = Math.abs(r - tr);
  22161. data[i + 1] = Math.abs(g - tg);
  22162. data[i + 2] = Math.abs(b - tb);
  22163. break;
  22164. case 'subtract':
  22165. data[i] = r - tr;
  22166. data[i + 1] = g - tg;
  22167. data[i + 2] = b - tb;
  22168. break;
  22169. case 'darken':
  22170. data[i] = Math.min(r, tr);
  22171. data[i + 1] = Math.min(g, tg);
  22172. data[i + 2] = Math.min(b, tb);
  22173. break;
  22174. case 'lighten':
  22175. data[i] = Math.max(r, tr);
  22176. data[i + 1] = Math.max(g, tg);
  22177. data[i + 2] = Math.max(b, tb);
  22178. break;
  22179. case 'overlay':
  22180. data[i] = tr < 128 ? (2 * r * tr / 255) : (255 - 2 * (255 - r) * (255 - tr) / 255);
  22181. data[i + 1] = tg < 128 ? (2 * g * tg / 255) : (255 - 2 * (255 - g) * (255 - tg) / 255);
  22182. data[i + 2] = tb < 128 ? (2 * b * tb / 255) : (255 - 2 * (255 - b) * (255 - tb) / 255);
  22183. break;
  22184. case 'exclusion':
  22185. data[i] = tr + r - ((2 * tr * r) / 255);
  22186. data[i + 1] = tg + g - ((2 * tg * g) / 255);
  22187. data[i + 2] = tb + b - ((2 * tb * b) / 255);
  22188. break;
  22189. case 'tint':
  22190. data[i] = tr + r * alpha1;
  22191. data[i + 1] = tg + g * alpha1;
  22192. data[i + 2] = tb + b * alpha1;
  22193. }
  22194. }
  22195. },
  22196. /**
  22197. * Return WebGL uniform locations for this filter's shader.
  22198. *
  22199. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22200. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22201. */
  22202. getUniformLocations: function(gl, program) {
  22203. return {
  22204. uColor: gl.getUniformLocation(program, 'uColor'),
  22205. };
  22206. },
  22207. /**
  22208. * Send data from this filter to its shader program's uniforms.
  22209. *
  22210. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22211. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  22212. */
  22213. sendUniformData: function(gl, uniformLocations) {
  22214. var source = new fabric.Color(this.color).getSource();
  22215. source[0] = this.alpha * source[0] / 255;
  22216. source[1] = this.alpha * source[1] / 255;
  22217. source[2] = this.alpha * source[2] / 255;
  22218. source[3] = this.alpha;
  22219. gl.uniform4fv(uniformLocations.uColor, source);
  22220. },
  22221. /**
  22222. * Returns object representation of an instance
  22223. * @return {Object} Object representation of an instance
  22224. */
  22225. toObject: function() {
  22226. return {
  22227. type: this.type,
  22228. color: this.color,
  22229. mode: this.mode,
  22230. alpha: this.alpha
  22231. };
  22232. }
  22233. });
  22234. /**
  22235. * Returns filter instance from an object representation
  22236. * @static
  22237. * @param {Object} object Object to create an instance from
  22238. * @param {function} [callback] to be invoked after filter creation
  22239. * @return {fabric.Image.filters.BlendColor} Instance of fabric.Image.filters.BlendColor
  22240. */
  22241. fabric.Image.filters.BlendColor.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22242. })(typeof exports !== 'undefined' ? exports : this);
  22243. (function(global) {
  22244. 'use strict';
  22245. var fabric = global.fabric,
  22246. filters = fabric.Image.filters,
  22247. createClass = fabric.util.createClass;
  22248. /**
  22249. * Image Blend filter class
  22250. * @class fabric.Image.filter.BlendImage
  22251. * @memberOf fabric.Image.filters
  22252. * @extends fabric.Image.filters.BaseFilter
  22253. * @example
  22254. * var filter = new fabric.Image.filters.BlendColor({
  22255. * color: '#000',
  22256. * mode: 'multiply'
  22257. * });
  22258. *
  22259. * var filter = new fabric.Image.filters.BlendImage({
  22260. * image: fabricImageObject,
  22261. * mode: 'multiply',
  22262. * alpha: 0.5
  22263. * });
  22264. * object.filters.push(filter);
  22265. * object.applyFilters();
  22266. * canvas.renderAll();
  22267. */
  22268. filters.BlendImage = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.BlendImage.prototype */ {
  22269. type: 'BlendImage',
  22270. /**
  22271. * Color to make the blend operation with. default to a reddish color since black or white
  22272. * gives always strong result.
  22273. **/
  22274. image: null,
  22275. /**
  22276. * Blend mode for the filter (one of "multiply", "mask")
  22277. * @type String
  22278. * @default
  22279. **/
  22280. mode: 'multiply',
  22281. /**
  22282. * alpha value. represent the strength of the blend image operation.
  22283. * not implemented.
  22284. **/
  22285. alpha: 1,
  22286. vertexSource: 'attribute vec2 aPosition;\n' +
  22287. 'varying vec2 vTexCoord;\n' +
  22288. 'varying vec2 vTexCoord2;\n' +
  22289. 'uniform mat3 uTransformMatrix;\n' +
  22290. 'void main() {\n' +
  22291. 'vTexCoord = aPosition;\n' +
  22292. 'vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\n' +
  22293. 'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n' +
  22294. '}',
  22295. /**
  22296. * Fragment source for the Multiply program
  22297. */
  22298. fragmentSource: {
  22299. multiply: 'precision highp float;\n' +
  22300. 'uniform sampler2D uTexture;\n' +
  22301. 'uniform sampler2D uImage;\n' +
  22302. 'uniform vec4 uColor;\n' +
  22303. 'varying vec2 vTexCoord;\n' +
  22304. 'varying vec2 vTexCoord2;\n' +
  22305. 'void main() {\n' +
  22306. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  22307. 'vec4 color2 = texture2D(uImage, vTexCoord2);\n' +
  22308. 'color.rgba *= color2.rgba;\n' +
  22309. 'gl_FragColor = color;\n' +
  22310. '}',
  22311. mask: 'precision highp float;\n' +
  22312. 'uniform sampler2D uTexture;\n' +
  22313. 'uniform sampler2D uImage;\n' +
  22314. 'uniform vec4 uColor;\n' +
  22315. 'varying vec2 vTexCoord;\n' +
  22316. 'varying vec2 vTexCoord2;\n' +
  22317. 'void main() {\n' +
  22318. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  22319. 'vec4 color2 = texture2D(uImage, vTexCoord2);\n' +
  22320. 'color.a = color2.a;\n' +
  22321. 'gl_FragColor = color;\n' +
  22322. '}',
  22323. },
  22324. /**
  22325. * Retrieves the cached shader.
  22326. * @param {Object} options
  22327. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  22328. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  22329. */
  22330. retrieveShader: function(options) {
  22331. var cacheKey = this.type + '_' + this.mode;
  22332. var shaderSource = this.fragmentSource[this.mode];
  22333. if (!options.programCache.hasOwnProperty(cacheKey)) {
  22334. options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
  22335. }
  22336. return options.programCache[cacheKey];
  22337. },
  22338. applyToWebGL: function(options) {
  22339. // load texture to blend.
  22340. var gl = options.context,
  22341. texture = this.createTexture(options.filterBackend, this.image);
  22342. this.bindAdditionalTexture(gl, texture, gl.TEXTURE1);
  22343. this.callSuper('applyToWebGL', options);
  22344. this.unbindAdditionalTexture(gl, gl.TEXTURE1);
  22345. },
  22346. createTexture: function(backend, image) {
  22347. return backend.getCachedTexture(image.cacheKey, image._element);
  22348. },
  22349. /**
  22350. * Calculate a transformMatrix to adapt the image to blend over
  22351. * @param {Object} options
  22352. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  22353. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  22354. */
  22355. calculateMatrix: function() {
  22356. var image = this.image,
  22357. width = image._element.width,
  22358. height = image._element.height;
  22359. return [
  22360. 1 / image.scaleX, 0, 0,
  22361. 0, 1 / image.scaleY, 0,
  22362. -image.left / width, -image.top / height, 1
  22363. ];
  22364. },
  22365. /**
  22366. * Apply the Blend operation to a Uint8ClampedArray representing the pixels of an image.
  22367. *
  22368. * @param {Object} options
  22369. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  22370. */
  22371. applyTo2d: function(options) {
  22372. var imageData = options.imageData,
  22373. resources = options.filterBackend.resources,
  22374. data = imageData.data, iLen = data.length,
  22375. width = imageData.width,
  22376. height = imageData.height,
  22377. tr, tg, tb, ta,
  22378. r, g, b, a,
  22379. canvas1, context, image = this.image, blendData;
  22380. if (!resources.blendImage) {
  22381. resources.blendImage = fabric.util.createCanvasElement();
  22382. }
  22383. canvas1 = resources.blendImage;
  22384. context = canvas1.getContext('2d');
  22385. if (canvas1.width !== width || canvas1.height !== height) {
  22386. canvas1.width = width;
  22387. canvas1.height = height;
  22388. }
  22389. else {
  22390. context.clearRect(0, 0, width, height);
  22391. }
  22392. context.setTransform(image.scaleX, 0, 0, image.scaleY, image.left, image.top);
  22393. context.drawImage(image._element, 0, 0, width, height);
  22394. blendData = context.getImageData(0, 0, width, height).data;
  22395. for (var i = 0; i < iLen; i += 4) {
  22396. r = data[i];
  22397. g = data[i + 1];
  22398. b = data[i + 2];
  22399. a = data[i + 3];
  22400. tr = blendData[i];
  22401. tg = blendData[i + 1];
  22402. tb = blendData[i + 2];
  22403. ta = blendData[i + 3];
  22404. switch (this.mode) {
  22405. case 'multiply':
  22406. data[i] = r * tr / 255;
  22407. data[i + 1] = g * tg / 255;
  22408. data[i + 2] = b * tb / 255;
  22409. data[i + 3] = a * ta / 255;
  22410. break;
  22411. case 'mask':
  22412. data[i + 3] = ta;
  22413. break;
  22414. }
  22415. }
  22416. },
  22417. /**
  22418. * Return WebGL uniform locations for this filter's shader.
  22419. *
  22420. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22421. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22422. */
  22423. getUniformLocations: function(gl, program) {
  22424. return {
  22425. uTransformMatrix: gl.getUniformLocation(program, 'uTransformMatrix'),
  22426. uImage: gl.getUniformLocation(program, 'uImage'),
  22427. };
  22428. },
  22429. /**
  22430. * Send data from this filter to its shader program's uniforms.
  22431. *
  22432. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22433. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  22434. */
  22435. sendUniformData: function(gl, uniformLocations) {
  22436. var matrix = this.calculateMatrix();
  22437. gl.uniform1i(uniformLocations.uImage, 1); // texture unit 1.
  22438. gl.uniformMatrix3fv(uniformLocations.uTransformMatrix, false, matrix);
  22439. },
  22440. /**
  22441. * Returns object representation of an instance
  22442. * @return {Object} Object representation of an instance
  22443. */
  22444. toObject: function() {
  22445. return {
  22446. type: this.type,
  22447. image: this.image && this.image.toObject(),
  22448. mode: this.mode,
  22449. alpha: this.alpha
  22450. };
  22451. }
  22452. });
  22453. /**
  22454. * Returns filter instance from an object representation
  22455. * @static
  22456. * @param {Object} object Object to create an instance from
  22457. * @param {function} callback to be invoked after filter creation
  22458. * @return {fabric.Image.filters.BlendImage} Instance of fabric.Image.filters.BlendImage
  22459. */
  22460. fabric.Image.filters.BlendImage.fromObject = function(object, callback) {
  22461. fabric.Image.fromObject(object.image, function(image) {
  22462. var options = fabric.util.object.clone(object);
  22463. options.image = image;
  22464. callback(new fabric.Image.filters.BlendImage(options));
  22465. });
  22466. };
  22467. })(typeof exports !== 'undefined' ? exports : this);
  22468. (function(global) {
  22469. 'use strict';
  22470. var fabric = global.fabric || (global.fabric = { }), pow = Math.pow, floor = Math.floor,
  22471. sqrt = Math.sqrt, abs = Math.abs, round = Math.round, sin = Math.sin,
  22472. ceil = Math.ceil,
  22473. filters = fabric.Image.filters,
  22474. createClass = fabric.util.createClass;
  22475. /**
  22476. * Resize image filter class
  22477. * @class fabric.Image.filters.Resize
  22478. * @memberOf fabric.Image.filters
  22479. * @extends fabric.Image.filters.BaseFilter
  22480. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  22481. * @example
  22482. * var filter = new fabric.Image.filters.Resize();
  22483. * object.filters.push(filter);
  22484. * object.applyFilters(canvas.renderAll.bind(canvas));
  22485. */
  22486. filters.Resize = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Resize.prototype */ {
  22487. /**
  22488. * Filter type
  22489. * @param {String} type
  22490. * @default
  22491. */
  22492. type: 'Resize',
  22493. /**
  22494. * Resize type
  22495. * for webgl resizeType is just lanczos, for canvas2d can be:
  22496. * bilinear, hermite, sliceHack, lanczos.
  22497. * @param {String} resizeType
  22498. * @default
  22499. */
  22500. resizeType: 'hermite',
  22501. /**
  22502. * Scale factor for resizing, x axis
  22503. * @param {Number} scaleX
  22504. * @default
  22505. */
  22506. scaleX: 1,
  22507. /**
  22508. * Scale factor for resizing, y axis
  22509. * @param {Number} scaleY
  22510. * @default
  22511. */
  22512. scaleY: 1,
  22513. /**
  22514. * LanczosLobes parameter for lanczos filter, valid for resizeType lanczos
  22515. * @param {Number} lanczosLobes
  22516. * @default
  22517. */
  22518. lanczosLobes: 3,
  22519. /**
  22520. * Return WebGL uniform locations for this filter's shader.
  22521. *
  22522. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22523. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22524. */
  22525. getUniformLocations: function(gl, program) {
  22526. return {
  22527. uDelta: gl.getUniformLocation(program, 'uDelta'),
  22528. uTaps: gl.getUniformLocation(program, 'uTaps'),
  22529. };
  22530. },
  22531. /**
  22532. * Send data from this filter to its shader program's uniforms.
  22533. *
  22534. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22535. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  22536. */
  22537. sendUniformData: function(gl, uniformLocations) {
  22538. gl.uniform2fv(uniformLocations.uDelta, this.horizontal ? [1 / this.width, 0] : [0, 1 / this.height]);
  22539. gl.uniform1fv(uniformLocations.uTaps, this.taps);
  22540. },
  22541. /**
  22542. * Retrieves the cached shader.
  22543. * @param {Object} options
  22544. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  22545. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  22546. */
  22547. retrieveShader: function(options) {
  22548. var filterWindow = this.getFilterWindow(), cacheKey = this.type + '_' + filterWindow;
  22549. if (!options.programCache.hasOwnProperty(cacheKey)) {
  22550. var fragmentShader = this.generateShader(filterWindow);
  22551. options.programCache[cacheKey] = this.createProgram(options.context, fragmentShader);
  22552. }
  22553. return options.programCache[cacheKey];
  22554. },
  22555. getFilterWindow: function() {
  22556. var scale = this.tempScale;
  22557. return Math.ceil(this.lanczosLobes / scale);
  22558. },
  22559. getTaps: function() {
  22560. var lobeFunction = this.lanczosCreate(this.lanczosLobes), scale = this.tempScale,
  22561. filterWindow = this.getFilterWindow(), taps = new Array(filterWindow);
  22562. for (var i = 1; i <= filterWindow; i++) {
  22563. taps[i - 1] = lobeFunction(i * scale);
  22564. }
  22565. return taps;
  22566. },
  22567. /**
  22568. * Generate vertex and shader sources from the necessary steps numbers
  22569. * @param {Number} filterWindow
  22570. */
  22571. generateShader: function(filterWindow) {
  22572. var offsets = new Array(filterWindow),
  22573. fragmentShader = this.fragmentSourceTOP, filterWindow;
  22574. for (var i = 1; i <= filterWindow; i++) {
  22575. offsets[i - 1] = i + '.0 * uDelta';
  22576. }
  22577. fragmentShader += 'uniform float uTaps[' + filterWindow + '];\n';
  22578. fragmentShader += 'void main() {\n';
  22579. fragmentShader += ' vec4 color = texture2D(uTexture, vTexCoord);\n';
  22580. fragmentShader += ' float sum = 1.0;\n';
  22581. offsets.forEach(function(offset, i) {
  22582. fragmentShader += ' color += texture2D(uTexture, vTexCoord + ' + offset + ') * uTaps[' + i + '];\n';
  22583. fragmentShader += ' color += texture2D(uTexture, vTexCoord - ' + offset + ') * uTaps[' + i + '];\n';
  22584. fragmentShader += ' sum += 2.0 * uTaps[' + i + '];\n';
  22585. });
  22586. fragmentShader += ' gl_FragColor = color / sum;\n';
  22587. fragmentShader += '}';
  22588. return fragmentShader;
  22589. },
  22590. fragmentSourceTOP: 'precision highp float;\n' +
  22591. 'uniform sampler2D uTexture;\n' +
  22592. 'uniform vec2 uDelta;\n' +
  22593. 'varying vec2 vTexCoord;\n',
  22594. /**
  22595. * Apply the resize filter to the image
  22596. * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
  22597. *
  22598. * @param {Object} options
  22599. * @param {Number} options.passes The number of filters remaining to be executed
  22600. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  22601. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  22602. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  22603. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  22604. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  22605. */
  22606. applyTo: function(options) {
  22607. if (options.webgl) {
  22608. options.passes++;
  22609. this.width = options.sourceWidth;
  22610. this.horizontal = true;
  22611. this.dW = Math.round(this.width * this.scaleX);
  22612. this.dH = options.sourceHeight;
  22613. this.tempScale = this.dW / this.width;
  22614. this.taps = this.getTaps();
  22615. options.destinationWidth = this.dW;
  22616. this._setupFrameBuffer(options);
  22617. this.applyToWebGL(options);
  22618. this._swapTextures(options);
  22619. options.sourceWidth = options.destinationWidth;
  22620. this.height = options.sourceHeight;
  22621. this.horizontal = false;
  22622. this.dH = Math.round(this.height * this.scaleY);
  22623. this.tempScale = this.dH / this.height;
  22624. this.taps = this.getTaps();
  22625. options.destinationHeight = this.dH;
  22626. this._setupFrameBuffer(options);
  22627. this.applyToWebGL(options);
  22628. this._swapTextures(options);
  22629. options.sourceHeight = options.destinationHeight;
  22630. }
  22631. else {
  22632. this.applyTo2d(options);
  22633. }
  22634. },
  22635. isNeutralState: function() {
  22636. return this.scaleX === 1 && this.scaleY === 1;
  22637. },
  22638. lanczosCreate: function(lobes) {
  22639. return function(x) {
  22640. if (x >= lobes || x <= -lobes) {
  22641. return 0.0;
  22642. }
  22643. if (x < 1.19209290E-07 && x > -1.19209290E-07) {
  22644. return 1.0;
  22645. }
  22646. x *= Math.PI;
  22647. var xx = x / lobes;
  22648. return (sin(x) / x) * sin(xx) / xx;
  22649. };
  22650. },
  22651. /**
  22652. * Applies filter to canvas element
  22653. * @memberOf fabric.Image.filters.Resize.prototype
  22654. * @param {Object} canvasEl Canvas element to apply filter to
  22655. * @param {Number} scaleX
  22656. * @param {Number} scaleY
  22657. */
  22658. applyTo2d: function(options) {
  22659. var imageData = options.imageData,
  22660. scaleX = this.scaleX,
  22661. scaleY = this.scaleY;
  22662. this.rcpScaleX = 1 / scaleX;
  22663. this.rcpScaleY = 1 / scaleY;
  22664. var oW = imageData.width, oH = imageData.height,
  22665. dW = round(oW * scaleX), dH = round(oH * scaleY),
  22666. newData;
  22667. if (this.resizeType === 'sliceHack') {
  22668. newData = this.sliceByTwo(options, oW, oH, dW, dH);
  22669. }
  22670. else if (this.resizeType === 'hermite') {
  22671. newData = this.hermiteFastResize(options, oW, oH, dW, dH);
  22672. }
  22673. else if (this.resizeType === 'bilinear') {
  22674. newData = this.bilinearFiltering(options, oW, oH, dW, dH);
  22675. }
  22676. else if (this.resizeType === 'lanczos') {
  22677. newData = this.lanczosResize(options, oW, oH, dW, dH);
  22678. }
  22679. options.imageData = newData;
  22680. },
  22681. /**
  22682. * Filter sliceByTwo
  22683. * @param {Object} canvasEl Canvas element to apply filter to
  22684. * @param {Number} oW Original Width
  22685. * @param {Number} oH Original Height
  22686. * @param {Number} dW Destination Width
  22687. * @param {Number} dH Destination Height
  22688. * @returns {ImageData}
  22689. */
  22690. sliceByTwo: function(options, oW, oH, dW, dH) {
  22691. var imageData = options.imageData,
  22692. mult = 0.5, doneW = false, doneH = false, stepW = oW * mult,
  22693. stepH = oH * mult, resources = fabric.filterBackend.resources,
  22694. tmpCanvas, ctx, sX = 0, sY = 0, dX = oW, dY = 0;
  22695. if (!resources.sliceByTwo) {
  22696. resources.sliceByTwo = document.createElement('canvas');
  22697. }
  22698. tmpCanvas = resources.sliceByTwo;
  22699. if (tmpCanvas.width < oW * 1.5 || tmpCanvas.height < oH) {
  22700. tmpCanvas.width = oW * 1.5;
  22701. tmpCanvas.height = oH;
  22702. }
  22703. ctx = tmpCanvas.getContext('2d');
  22704. ctx.clearRect(0, 0, oW * 1.5, oH);
  22705. ctx.putImageData(imageData, 0, 0);
  22706. dW = floor(dW);
  22707. dH = floor(dH);
  22708. while (!doneW || !doneH) {
  22709. oW = stepW;
  22710. oH = stepH;
  22711. if (dW < floor(stepW * mult)) {
  22712. stepW = floor(stepW * mult);
  22713. }
  22714. else {
  22715. stepW = dW;
  22716. doneW = true;
  22717. }
  22718. if (dH < floor(stepH * mult)) {
  22719. stepH = floor(stepH * mult);
  22720. }
  22721. else {
  22722. stepH = dH;
  22723. doneH = true;
  22724. }
  22725. ctx.drawImage(tmpCanvas, sX, sY, oW, oH, dX, dY, stepW, stepH);
  22726. sX = dX;
  22727. sY = dY;
  22728. dY += stepH;
  22729. }
  22730. return ctx.getImageData(sX, sY, dW, dH);
  22731. },
  22732. /**
  22733. * Filter lanczosResize
  22734. * @param {Object} canvasEl Canvas element to apply filter to
  22735. * @param {Number} oW Original Width
  22736. * @param {Number} oH Original Height
  22737. * @param {Number} dW Destination Width
  22738. * @param {Number} dH Destination Height
  22739. * @returns {ImageData}
  22740. */
  22741. lanczosResize: function(options, oW, oH, dW, dH) {
  22742. function process(u) {
  22743. var v, i, weight, idx, a, red, green,
  22744. blue, alpha, fX, fY;
  22745. center.x = (u + 0.5) * ratioX;
  22746. icenter.x = floor(center.x);
  22747. for (v = 0; v < dH; v++) {
  22748. center.y = (v + 0.5) * ratioY;
  22749. icenter.y = floor(center.y);
  22750. a = 0; red = 0; green = 0; blue = 0; alpha = 0;
  22751. for (i = icenter.x - range2X; i <= icenter.x + range2X; i++) {
  22752. if (i < 0 || i >= oW) {
  22753. continue;
  22754. }
  22755. fX = floor(1000 * abs(i - center.x));
  22756. if (!cacheLanc[fX]) {
  22757. cacheLanc[fX] = { };
  22758. }
  22759. for (var j = icenter.y - range2Y; j <= icenter.y + range2Y; j++) {
  22760. if (j < 0 || j >= oH) {
  22761. continue;
  22762. }
  22763. fY = floor(1000 * abs(j - center.y));
  22764. if (!cacheLanc[fX][fY]) {
  22765. cacheLanc[fX][fY] = lanczos(sqrt(pow(fX * rcpRatioX, 2) + pow(fY * rcpRatioY, 2)) / 1000);
  22766. }
  22767. weight = cacheLanc[fX][fY];
  22768. if (weight > 0) {
  22769. idx = (j * oW + i) * 4;
  22770. a += weight;
  22771. red += weight * srcData[idx];
  22772. green += weight * srcData[idx + 1];
  22773. blue += weight * srcData[idx + 2];
  22774. alpha += weight * srcData[idx + 3];
  22775. }
  22776. }
  22777. }
  22778. idx = (v * dW + u) * 4;
  22779. destData[idx] = red / a;
  22780. destData[idx + 1] = green / a;
  22781. destData[idx + 2] = blue / a;
  22782. destData[idx + 3] = alpha / a;
  22783. }
  22784. if (++u < dW) {
  22785. return process(u);
  22786. }
  22787. else {
  22788. return destImg;
  22789. }
  22790. }
  22791. var srcData = options.imageData.data,
  22792. destImg = options.ctx.createImageData(dW, dH),
  22793. destData = destImg.data,
  22794. lanczos = this.lanczosCreate(this.lanczosLobes),
  22795. ratioX = this.rcpScaleX, ratioY = this.rcpScaleY,
  22796. rcpRatioX = 2 / this.rcpScaleX, rcpRatioY = 2 / this.rcpScaleY,
  22797. range2X = ceil(ratioX * this.lanczosLobes / 2),
  22798. range2Y = ceil(ratioY * this.lanczosLobes / 2),
  22799. cacheLanc = { }, center = { }, icenter = { };
  22800. return process(0);
  22801. },
  22802. /**
  22803. * bilinearFiltering
  22804. * @param {Object} canvasEl Canvas element to apply filter to
  22805. * @param {Number} oW Original Width
  22806. * @param {Number} oH Original Height
  22807. * @param {Number} dW Destination Width
  22808. * @param {Number} dH Destination Height
  22809. * @returns {ImageData}
  22810. */
  22811. bilinearFiltering: function(options, oW, oH, dW, dH) {
  22812. var a, b, c, d, x, y, i, j, xDiff, yDiff, chnl,
  22813. color, offset = 0, origPix, ratioX = this.rcpScaleX,
  22814. ratioY = this.rcpScaleY,
  22815. w4 = 4 * (oW - 1), img = options.imageData,
  22816. pixels = img.data, destImage = options.ctx.createImageData(dW, dH),
  22817. destPixels = destImage.data;
  22818. for (i = 0; i < dH; i++) {
  22819. for (j = 0; j < dW; j++) {
  22820. x = floor(ratioX * j);
  22821. y = floor(ratioY * i);
  22822. xDiff = ratioX * j - x;
  22823. yDiff = ratioY * i - y;
  22824. origPix = 4 * (y * oW + x);
  22825. for (chnl = 0; chnl < 4; chnl++) {
  22826. a = pixels[origPix + chnl];
  22827. b = pixels[origPix + 4 + chnl];
  22828. c = pixels[origPix + w4 + chnl];
  22829. d = pixels[origPix + w4 + 4 + chnl];
  22830. color = a * (1 - xDiff) * (1 - yDiff) + b * xDiff * (1 - yDiff) +
  22831. c * yDiff * (1 - xDiff) + d * xDiff * yDiff;
  22832. destPixels[offset++] = color;
  22833. }
  22834. }
  22835. }
  22836. return destImage;
  22837. },
  22838. /**
  22839. * hermiteFastResize
  22840. * @param {Object} canvasEl Canvas element to apply filter to
  22841. * @param {Number} oW Original Width
  22842. * @param {Number} oH Original Height
  22843. * @param {Number} dW Destination Width
  22844. * @param {Number} dH Destination Height
  22845. * @returns {ImageData}
  22846. */
  22847. hermiteFastResize: function(options, oW, oH, dW, dH) {
  22848. var ratioW = this.rcpScaleX, ratioH = this.rcpScaleY,
  22849. ratioWHalf = ceil(ratioW / 2),
  22850. ratioHHalf = ceil(ratioH / 2),
  22851. img = options.imageData, data = img.data,
  22852. img2 = options.ctx.createImageData(dW, dH), data2 = img2.data;
  22853. for (var j = 0; j < dH; j++) {
  22854. for (var i = 0; i < dW; i++) {
  22855. var x2 = (i + j * dW) * 4, weight = 0, weights = 0, weightsAlpha = 0,
  22856. gxR = 0, gxG = 0, gxB = 0, gxA = 0, centerY = (j + 0.5) * ratioH;
  22857. for (var yy = floor(j * ratioH); yy < (j + 1) * ratioH; yy++) {
  22858. var dy = abs(centerY - (yy + 0.5)) / ratioHHalf,
  22859. centerX = (i + 0.5) * ratioW, w0 = dy * dy;
  22860. for (var xx = floor(i * ratioW); xx < (i + 1) * ratioW; xx++) {
  22861. var dx = abs(centerX - (xx + 0.5)) / ratioWHalf,
  22862. w = sqrt(w0 + dx * dx);
  22863. /* eslint-disable max-depth */
  22864. if (w > 1 && w < -1) {
  22865. continue;
  22866. }
  22867. //hermite filter
  22868. weight = 2 * w * w * w - 3 * w * w + 1;
  22869. if (weight > 0) {
  22870. dx = 4 * (xx + yy * oW);
  22871. //alpha
  22872. gxA += weight * data[dx + 3];
  22873. weightsAlpha += weight;
  22874. //colors
  22875. if (data[dx + 3] < 255) {
  22876. weight = weight * data[dx + 3] / 250;
  22877. }
  22878. gxR += weight * data[dx];
  22879. gxG += weight * data[dx + 1];
  22880. gxB += weight * data[dx + 2];
  22881. weights += weight;
  22882. }
  22883. /* eslint-enable max-depth */
  22884. }
  22885. }
  22886. data2[x2] = gxR / weights;
  22887. data2[x2 + 1] = gxG / weights;
  22888. data2[x2 + 2] = gxB / weights;
  22889. data2[x2 + 3] = gxA / weightsAlpha;
  22890. }
  22891. }
  22892. return img2;
  22893. },
  22894. /**
  22895. * Returns object representation of an instance
  22896. * @return {Object} Object representation of an instance
  22897. */
  22898. toObject: function() {
  22899. return {
  22900. type: this.type,
  22901. scaleX: this.scaleX,
  22902. scaleY: this.scaleY,
  22903. resizeType: this.resizeType,
  22904. lanczosLobes: this.lanczosLobes
  22905. };
  22906. }
  22907. });
  22908. /**
  22909. * Returns filter instance from an object representation
  22910. * @static
  22911. * @param {Object} object Object to create an instance from
  22912. * @param {Function} [callback] to be invoked after filter creation
  22913. * @return {fabric.Image.filters.Resize} Instance of fabric.Image.filters.Resize
  22914. */
  22915. fabric.Image.filters.Resize.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  22916. })(typeof exports !== 'undefined' ? exports : this);
  22917. (function(global) {
  22918. 'use strict';
  22919. var fabric = global.fabric || (global.fabric = { }),
  22920. filters = fabric.Image.filters,
  22921. createClass = fabric.util.createClass;
  22922. /**
  22923. * Contrast filter class
  22924. * @class fabric.Image.filters.Contrast
  22925. * @memberOf fabric.Image.filters
  22926. * @extends fabric.Image.filters.BaseFilter
  22927. * @see {@link fabric.Image.filters.Contrast#initialize} for constructor definition
  22928. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  22929. * @example
  22930. * var filter = new fabric.Image.filters.Contrast({
  22931. * contrast: 0.25
  22932. * });
  22933. * object.filters.push(filter);
  22934. * object.applyFilters();
  22935. */
  22936. filters.Contrast = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Contrast.prototype */ {
  22937. /**
  22938. * Filter type
  22939. * @param {String} type
  22940. * @default
  22941. */
  22942. type: 'Contrast',
  22943. fragmentSource: 'precision highp float;\n' +
  22944. 'uniform sampler2D uTexture;\n' +
  22945. 'uniform float uContrast;\n' +
  22946. 'varying vec2 vTexCoord;\n' +
  22947. 'void main() {\n' +
  22948. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  22949. 'float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\n' +
  22950. 'color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\n' +
  22951. 'gl_FragColor = color;\n' +
  22952. '}',
  22953. /**
  22954. * contrast value, range from -1 to 1.
  22955. * @param {Number} contrast
  22956. * @default 0
  22957. */
  22958. contrast: 0,
  22959. mainParameter: 'contrast',
  22960. /**
  22961. * Constructor
  22962. * @memberOf fabric.Image.filters.Contrast.prototype
  22963. * @param {Object} [options] Options object
  22964. * @param {Number} [options.contrast=0] Value to contrast the image up (-1...1)
  22965. */
  22966. /**
  22967. * Apply the Contrast operation to a Uint8Array representing the pixels of an image.
  22968. *
  22969. * @param {Object} options
  22970. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  22971. */
  22972. applyTo2d: function(options) {
  22973. if (this.contrast === 0) {
  22974. return;
  22975. }
  22976. var imageData = options.imageData, i, len,
  22977. data = imageData.data, len = data.length,
  22978. contrast = Math.floor(this.contrast * 255),
  22979. contrastF = 259 * (contrast + 255) / (255 * (259 - contrast));
  22980. for (i = 0; i < len; i += 4) {
  22981. data[i] = contrastF * (data[i] - 128) + 128;
  22982. data[i + 1] = contrastF * (data[i + 1] - 128) + 128;
  22983. data[i + 2] = contrastF * (data[i + 2] - 128) + 128;
  22984. }
  22985. },
  22986. /**
  22987. * Return WebGL uniform locations for this filter's shader.
  22988. *
  22989. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  22990. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  22991. */
  22992. getUniformLocations: function(gl, program) {
  22993. return {
  22994. uContrast: gl.getUniformLocation(program, 'uContrast'),
  22995. };
  22996. },
  22997. /**
  22998. * Send data from this filter to its shader program's uniforms.
  22999. *
  23000. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23001. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  23002. */
  23003. sendUniformData: function(gl, uniformLocations) {
  23004. gl.uniform1f(uniformLocations.uContrast, this.contrast);
  23005. },
  23006. });
  23007. /**
  23008. * Returns filter instance from an object representation
  23009. * @static
  23010. * @param {Object} object Object to create an instance from
  23011. * @param {function} [callback] to be invoked after filter creation
  23012. * @return {fabric.Image.filters.Contrast} Instance of fabric.Image.filters.Contrast
  23013. */
  23014. fabric.Image.filters.Contrast.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  23015. })(typeof exports !== 'undefined' ? exports : this);
  23016. (function(global) {
  23017. 'use strict';
  23018. var fabric = global.fabric || (global.fabric = { }),
  23019. filters = fabric.Image.filters,
  23020. createClass = fabric.util.createClass;
  23021. /**
  23022. * Saturate filter class
  23023. * @class fabric.Image.filters.Saturation
  23024. * @memberOf fabric.Image.filters
  23025. * @extends fabric.Image.filters.BaseFilter
  23026. * @see {@link fabric.Image.filters.Saturation#initialize} for constructor definition
  23027. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  23028. * @example
  23029. * var filter = new fabric.Image.filters.Saturation({
  23030. * saturation: 1
  23031. * });
  23032. * object.filters.push(filter);
  23033. * object.applyFilters();
  23034. */
  23035. filters.Saturation = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Saturation.prototype */ {
  23036. /**
  23037. * Filter type
  23038. * @param {String} type
  23039. * @default
  23040. */
  23041. type: 'Saturation',
  23042. fragmentSource: 'precision highp float;\n' +
  23043. 'uniform sampler2D uTexture;\n' +
  23044. 'uniform float uSaturation;\n' +
  23045. 'varying vec2 vTexCoord;\n' +
  23046. 'void main() {\n' +
  23047. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  23048. 'float rgMax = max(color.r, color.g);\n' +
  23049. 'float rgbMax = max(rgMax, color.b);\n' +
  23050. 'color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\n' +
  23051. 'color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\n' +
  23052. 'color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\n' +
  23053. 'gl_FragColor = color;\n' +
  23054. '}',
  23055. /**
  23056. * Saturation value, from -1 to 1.
  23057. * Increases/decreases the color saturation.
  23058. * A value of 0 has no effect.
  23059. *
  23060. * @param {Number} saturation
  23061. * @default
  23062. */
  23063. saturation: 0,
  23064. mainParameter: 'saturation',
  23065. /**
  23066. * Constructor
  23067. * @memberOf fabric.Image.filters.Saturate.prototype
  23068. * @param {Object} [options] Options object
  23069. * @param {Number} [options.saturate=0] Value to saturate the image (-1...1)
  23070. */
  23071. /**
  23072. * Apply the Saturation operation to a Uint8ClampedArray representing the pixels of an image.
  23073. *
  23074. * @param {Object} options
  23075. * @param {ImageData} options.imageData The Uint8ClampedArray to be filtered.
  23076. */
  23077. applyTo2d: function(options) {
  23078. if (this.saturation === 0) {
  23079. return;
  23080. }
  23081. var imageData = options.imageData,
  23082. data = imageData.data, len = data.length,
  23083. adjust = -this.saturation, i, max;
  23084. for (i = 0; i < len; i += 4) {
  23085. max = Math.max(data[i], data[i + 1], data[i + 2]);
  23086. data[i] += max !== data[i] ? (max - data[i]) * adjust : 0;
  23087. data[i + 1] += max !== data[i + 1] ? (max - data[i + 1]) * adjust : 0;
  23088. data[i + 2] += max !== data[i + 2] ? (max - data[i + 2]) * adjust : 0;
  23089. }
  23090. },
  23091. /**
  23092. * Return WebGL uniform locations for this filter's shader.
  23093. *
  23094. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23095. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  23096. */
  23097. getUniformLocations: function(gl, program) {
  23098. return {
  23099. uSaturation: gl.getUniformLocation(program, 'uSaturation'),
  23100. };
  23101. },
  23102. /**
  23103. * Send data from this filter to its shader program's uniforms.
  23104. *
  23105. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23106. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  23107. */
  23108. sendUniformData: function(gl, uniformLocations) {
  23109. gl.uniform1f(uniformLocations.uSaturation, -this.saturation);
  23110. },
  23111. });
  23112. /**
  23113. * Returns filter instance from an object representation
  23114. * @static
  23115. * @param {Object} object Object to create an instance from
  23116. * @param {Function} [callback] to be invoked after filter creation
  23117. * @return {fabric.Image.filters.Saturation} Instance of fabric.Image.filters.Saturate
  23118. */
  23119. fabric.Image.filters.Saturation.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  23120. })(typeof exports !== 'undefined' ? exports : this);
  23121. (function(global) {
  23122. 'use strict';
  23123. var fabric = global.fabric || (global.fabric = { }),
  23124. filters = fabric.Image.filters,
  23125. createClass = fabric.util.createClass;
  23126. /**
  23127. * Blur filter class
  23128. * @class fabric.Image.filters.Blur
  23129. * @memberOf fabric.Image.filters
  23130. * @extends fabric.Image.filters.BaseFilter
  23131. * @see {@link fabric.Image.filters.Blur#initialize} for constructor definition
  23132. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  23133. * @example
  23134. * var filter = new fabric.Image.filters.Blur({
  23135. * blur: 0.5
  23136. * });
  23137. * object.filters.push(filter);
  23138. * object.applyFilters();
  23139. * canvas.renderAll();
  23140. */
  23141. filters.Blur = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Blur.prototype */ {
  23142. type: 'Blur',
  23143. /*
  23144. 'gl_FragColor = vec4(0.0);',
  23145. 'gl_FragColor += texture2D(texture, vTexCoord + -7 * uDelta)*0.0044299121055113265;',
  23146. 'gl_FragColor += texture2D(texture, vTexCoord + -6 * uDelta)*0.00895781211794;',
  23147. 'gl_FragColor += texture2D(texture, vTexCoord + -5 * uDelta)*0.0215963866053;',
  23148. 'gl_FragColor += texture2D(texture, vTexCoord + -4 * uDelta)*0.0443683338718;',
  23149. 'gl_FragColor += texture2D(texture, vTexCoord + -3 * uDelta)*0.0776744219933;',
  23150. 'gl_FragColor += texture2D(texture, vTexCoord + -2 * uDelta)*0.115876621105;',
  23151. 'gl_FragColor += texture2D(texture, vTexCoord + -1 * uDelta)*0.147308056121;',
  23152. 'gl_FragColor += texture2D(texture, vTexCoord )*0.159576912161;',
  23153. 'gl_FragColor += texture2D(texture, vTexCoord + 1 * uDelta)*0.147308056121;',
  23154. 'gl_FragColor += texture2D(texture, vTexCoord + 2 * uDelta)*0.115876621105;',
  23155. 'gl_FragColor += texture2D(texture, vTexCoord + 3 * uDelta)*0.0776744219933;',
  23156. 'gl_FragColor += texture2D(texture, vTexCoord + 4 * uDelta)*0.0443683338718;',
  23157. 'gl_FragColor += texture2D(texture, vTexCoord + 5 * uDelta)*0.0215963866053;',
  23158. 'gl_FragColor += texture2D(texture, vTexCoord + 6 * uDelta)*0.00895781211794;',
  23159. 'gl_FragColor += texture2D(texture, vTexCoord + 7 * uDelta)*0.0044299121055113265;',
  23160. */
  23161. /* eslint-disable max-len */
  23162. fragmentSource: 'precision highp float;\n' +
  23163. 'uniform sampler2D uTexture;\n' +
  23164. 'uniform vec2 uDelta;\n' +
  23165. 'varying vec2 vTexCoord;\n' +
  23166. 'const float nSamples = 15.0;\n' +
  23167. 'vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\n' +
  23168. 'float random(vec3 scale) {\n' +
  23169. /* use the fragment position for a different seed per-pixel */
  23170. 'return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n' +
  23171. '}\n' +
  23172. 'void main() {\n' +
  23173. 'vec4 color = vec4(0.0);\n' +
  23174. 'float total = 0.0;\n' +
  23175. 'float offset = random(v3offset);\n' +
  23176. 'for (float t = -nSamples; t <= nSamples; t++) {\n' +
  23177. 'float percent = (t + offset - 0.5) / nSamples;\n' +
  23178. 'float weight = 1.0 - abs(percent);\n' +
  23179. 'color += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\n' +
  23180. 'total += weight;\n' +
  23181. '}\n' +
  23182. 'gl_FragColor = color / total;\n' +
  23183. '}',
  23184. /* eslint-enable max-len */
  23185. /**
  23186. * blur value, in percentage of image dimensions.
  23187. * specific to keep the image blur constant at different resolutions
  23188. * range between 0 and 1.
  23189. * @type Number
  23190. * @default
  23191. */
  23192. blur: 0,
  23193. mainParameter: 'blur',
  23194. applyTo: function(options) {
  23195. if (options.webgl) {
  23196. // this aspectRatio is used to give the same blur to vertical and horizontal
  23197. this.aspectRatio = options.sourceWidth / options.sourceHeight;
  23198. options.passes++;
  23199. this._setupFrameBuffer(options);
  23200. this.horizontal = true;
  23201. this.applyToWebGL(options);
  23202. this._swapTextures(options);
  23203. this._setupFrameBuffer(options);
  23204. this.horizontal = false;
  23205. this.applyToWebGL(options);
  23206. this._swapTextures(options);
  23207. }
  23208. else {
  23209. this.applyTo2d(options);
  23210. }
  23211. },
  23212. applyTo2d: function(options) {
  23213. // paint canvasEl with current image data.
  23214. //options.ctx.putImageData(options.imageData, 0, 0);
  23215. options.imageData = this.simpleBlur(options);
  23216. },
  23217. simpleBlur: function(options) {
  23218. var resources = options.filterBackend.resources, canvas1, canvas2,
  23219. width = options.imageData.width,
  23220. height = options.imageData.height;
  23221. if (!resources.blurLayer1) {
  23222. resources.blurLayer1 = fabric.util.createCanvasElement();
  23223. resources.blurLayer2 = fabric.util.createCanvasElement();
  23224. }
  23225. canvas1 = resources.blurLayer1;
  23226. canvas2 = resources.blurLayer2;
  23227. if (canvas1.width !== width || canvas1.height !== height) {
  23228. canvas2.width = canvas1.width = width;
  23229. canvas2.height = canvas1.height = height;
  23230. }
  23231. var ctx1 = canvas1.getContext('2d'),
  23232. ctx2 = canvas2.getContext('2d'),
  23233. nSamples = 15,
  23234. random, percent, j, i,
  23235. blur = this.blur * 0.06 * 0.5;
  23236. // load first canvas
  23237. ctx1.putImageData(options.imageData, 0, 0);
  23238. ctx2.clearRect(0, 0, width, height);
  23239. for (i = -nSamples; i <= nSamples; i++) {
  23240. random = (Math.random() - 0.5) / 4;
  23241. percent = i / nSamples;
  23242. j = blur * percent * width + random;
  23243. ctx2.globalAlpha = 1 - Math.abs(percent);
  23244. ctx2.drawImage(canvas1, j, random);
  23245. ctx1.drawImage(canvas2, 0, 0);
  23246. ctx2.globalAlpha = 1;
  23247. ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  23248. }
  23249. for (i = -nSamples; i <= nSamples; i++) {
  23250. random = (Math.random() - 0.5) / 4;
  23251. percent = i / nSamples;
  23252. j = blur * percent * height + random;
  23253. ctx2.globalAlpha = 1 - Math.abs(percent);
  23254. ctx2.drawImage(canvas1, random, j);
  23255. ctx1.drawImage(canvas2, 0, 0);
  23256. ctx2.globalAlpha = 1;
  23257. ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  23258. }
  23259. options.ctx.drawImage(canvas1, 0, 0);
  23260. var newImageData = options.ctx.getImageData(0, 0, canvas1.width, canvas1.height);
  23261. ctx1.globalAlpha = 1;
  23262. ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
  23263. return newImageData;
  23264. },
  23265. /**
  23266. * Return WebGL uniform locations for this filter's shader.
  23267. *
  23268. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23269. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  23270. */
  23271. getUniformLocations: function(gl, program) {
  23272. return {
  23273. delta: gl.getUniformLocation(program, 'uDelta'),
  23274. };
  23275. },
  23276. /**
  23277. * Send data from this filter to its shader program's uniforms.
  23278. *
  23279. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23280. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  23281. */
  23282. sendUniformData: function(gl, uniformLocations) {
  23283. var delta = this.chooseRightDelta();
  23284. gl.uniform2fv(uniformLocations.delta, delta);
  23285. },
  23286. /**
  23287. * choose right value of image percentage to blur with
  23288. * @returns {Array} a numeric array with delta values
  23289. */
  23290. chooseRightDelta: function() {
  23291. var blurScale = 1, delta = [0, 0], blur;
  23292. if (this.horizontal) {
  23293. if (this.aspectRatio > 1) {
  23294. // image is wide, i want to shrink radius horizontal
  23295. blurScale = 1 / this.aspectRatio;
  23296. }
  23297. }
  23298. else {
  23299. if (this.aspectRatio < 1) {
  23300. // image is tall, i want to shrink radius vertical
  23301. blurScale = this.aspectRatio;
  23302. }
  23303. }
  23304. blur = blurScale * this.blur * 0.12;
  23305. if (this.horizontal) {
  23306. delta[0] = blur;
  23307. }
  23308. else {
  23309. delta[1] = blur;
  23310. }
  23311. return delta;
  23312. },
  23313. });
  23314. /**
  23315. * Deserialize a JSON definition of a BlurFilter into a concrete instance.
  23316. */
  23317. filters.Blur.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  23318. })(typeof exports !== 'undefined' ? exports : this);
  23319. (function(global) {
  23320. 'use strict';
  23321. var fabric = global.fabric || (global.fabric = { }),
  23322. filters = fabric.Image.filters,
  23323. createClass = fabric.util.createClass;
  23324. /**
  23325. * Gamma filter class
  23326. * @class fabric.Image.filters.Gamma
  23327. * @memberOf fabric.Image.filters
  23328. * @extends fabric.Image.filters.BaseFilter
  23329. * @see {@link fabric.Image.filters.Gamma#initialize} for constructor definition
  23330. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  23331. * @example
  23332. * var filter = new fabric.Image.filters.Gamma({
  23333. * gamma: [1, 0.5, 2.1]
  23334. * });
  23335. * object.filters.push(filter);
  23336. * object.applyFilters();
  23337. */
  23338. filters.Gamma = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Gamma.prototype */ {
  23339. /**
  23340. * Filter type
  23341. * @param {String} type
  23342. * @default
  23343. */
  23344. type: 'Gamma',
  23345. fragmentSource: 'precision highp float;\n' +
  23346. 'uniform sampler2D uTexture;\n' +
  23347. 'uniform vec3 uGamma;\n' +
  23348. 'varying vec2 vTexCoord;\n' +
  23349. 'void main() {\n' +
  23350. 'vec4 color = texture2D(uTexture, vTexCoord);\n' +
  23351. 'vec3 correction = (1.0 / uGamma);\n' +
  23352. 'color.r = pow(color.r, correction.r);\n' +
  23353. 'color.g = pow(color.g, correction.g);\n' +
  23354. 'color.b = pow(color.b, correction.b);\n' +
  23355. 'gl_FragColor = color;\n' +
  23356. 'gl_FragColor.rgb *= color.a;\n' +
  23357. '}',
  23358. /**
  23359. * Gamma array value, from 0.01 to 2.2.
  23360. * @param {Array} gamma
  23361. * @default
  23362. */
  23363. gamma: [1, 1, 1],
  23364. /**
  23365. * Describe the property that is the filter parameter
  23366. * @param {String} m
  23367. * @default
  23368. */
  23369. mainParameter: 'gamma',
  23370. /**
  23371. * Constructor
  23372. * @param {Object} [options] Options object
  23373. */
  23374. initialize: function(options) {
  23375. this.gamma = [1, 1, 1];
  23376. filters.BaseFilter.prototype.initialize.call(this, options);
  23377. },
  23378. /**
  23379. * Apply the Gamma operation to a Uint8Array representing the pixels of an image.
  23380. *
  23381. * @param {Object} options
  23382. * @param {ImageData} options.imageData The Uint8Array to be filtered.
  23383. */
  23384. applyTo2d: function(options) {
  23385. var imageData = options.imageData, data = imageData.data,
  23386. gamma = this.gamma, len = data.length,
  23387. rInv = 1 / gamma[0], gInv = 1 / gamma[1],
  23388. bInv = 1 / gamma[2], i;
  23389. if (!this.rVals) {
  23390. // eslint-disable-next-line
  23391. this.rVals = new Uint8Array(256);
  23392. // eslint-disable-next-line
  23393. this.gVals = new Uint8Array(256);
  23394. // eslint-disable-next-line
  23395. this.bVals = new Uint8Array(256);
  23396. }
  23397. // This is an optimization - pre-compute a look-up table for each color channel
  23398. // instead of performing these pow calls for each pixel in the image.
  23399. for (i = 0, len = 256; i < len; i++) {
  23400. this.rVals[i] = Math.pow(i / 255, rInv) * 255;
  23401. this.gVals[i] = Math.pow(i / 255, gInv) * 255;
  23402. this.bVals[i] = Math.pow(i / 255, bInv) * 255;
  23403. }
  23404. for (i = 0, len = data.length; i < len; i += 4) {
  23405. data[i] = this.rVals[data[i]];
  23406. data[i + 1] = this.gVals[data[i + 1]];
  23407. data[i + 2] = this.bVals[data[i + 2]];
  23408. }
  23409. },
  23410. /**
  23411. * Return WebGL uniform locations for this filter's shader.
  23412. *
  23413. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23414. * @param {WebGLShaderProgram} program This filter's compiled shader program.
  23415. */
  23416. getUniformLocations: function(gl, program) {
  23417. return {
  23418. uGamma: gl.getUniformLocation(program, 'uGamma'),
  23419. };
  23420. },
  23421. /**
  23422. * Send data from this filter to its shader program's uniforms.
  23423. *
  23424. * @param {WebGLRenderingContext} gl The GL canvas context used to compile this filter's shader.
  23425. * @param {Object} uniformLocations A map of string uniform names to WebGLUniformLocation objects
  23426. */
  23427. sendUniformData: function(gl, uniformLocations) {
  23428. gl.uniform3fv(uniformLocations.uGamma, this.gamma);
  23429. },
  23430. });
  23431. /**
  23432. * Returns filter instance from an object representation
  23433. * @static
  23434. * @param {Object} object Object to create an instance from
  23435. * @param {function} [callback] to be invoked after filter creation
  23436. * @return {fabric.Image.filters.Gamma} Instance of fabric.Image.filters.Gamma
  23437. */
  23438. fabric.Image.filters.Gamma.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  23439. })(typeof exports !== 'undefined' ? exports : this);
  23440. (function(global) {
  23441. 'use strict';
  23442. var fabric = global.fabric || (global.fabric = { }),
  23443. filters = fabric.Image.filters,
  23444. createClass = fabric.util.createClass;
  23445. /**
  23446. * A container class that knows how to apply a sequence of filters to an input image.
  23447. */
  23448. filters.Composed = createClass(filters.BaseFilter, /** @lends fabric.Image.filters.Composed.prototype */ {
  23449. type: 'Composed',
  23450. /**
  23451. * A non sparse array of filters to apply
  23452. */
  23453. subFilters: [],
  23454. /**
  23455. * Constructor
  23456. * @param {Object} [options] Options object
  23457. */
  23458. initialize: function(options) {
  23459. this.callSuper('initialize', options);
  23460. // create a new array instead mutating the prototype with push
  23461. this.subFilters = this.subFilters.slice(0);
  23462. },
  23463. /**
  23464. * Apply this container's filters to the input image provided.
  23465. *
  23466. * @param {Object} options
  23467. * @param {Number} options.passes The number of filters remaining to be applied.
  23468. */
  23469. applyTo: function(options) {
  23470. options.passes += this.subFilters.length - 1;
  23471. this.subFilters.forEach(function(filter) {
  23472. filter.applyTo(options);
  23473. });
  23474. },
  23475. /**
  23476. * Serialize this filter into JSON.
  23477. *
  23478. * @returns {Object} A JSON representation of this filter.
  23479. */
  23480. toObject: function() {
  23481. return fabric.util.object.extend(this.callSuper('toObject'), {
  23482. subFilters: this.subFilters.map(function(filter) { return filter.toObject(); }),
  23483. });
  23484. },
  23485. isNeutralState: function() {
  23486. return !this.subFilters.some(function(filter) { return !filter.isNeutralState(); });
  23487. }
  23488. });
  23489. /**
  23490. * Deserialize a JSON definition of a ComposedFilter into a concrete instance.
  23491. */
  23492. fabric.Image.filters.Composed.fromObject = function(object, callback) {
  23493. var filters = object.subFilters || [],
  23494. subFilters = filters.map(function(filter) {
  23495. return new fabric.Image.filters[filter.type](filter);
  23496. }),
  23497. instance = new fabric.Image.filters.Composed({ subFilters: subFilters });
  23498. callback && callback(instance);
  23499. return instance;
  23500. };
  23501. })(typeof exports !== 'undefined' ? exports : this);
  23502. (function(global) {
  23503. 'use strict';
  23504. var fabric = global.fabric || (global.fabric = { }),
  23505. filters = fabric.Image.filters,
  23506. createClass = fabric.util.createClass;
  23507. /**
  23508. * HueRotation filter class
  23509. * @class fabric.Image.filters.HueRotation
  23510. * @memberOf fabric.Image.filters
  23511. * @extends fabric.Image.filters.BaseFilter
  23512. * @see {@link fabric.Image.filters.HueRotation#initialize} for constructor definition
  23513. * @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
  23514. * @example
  23515. * var filter = new fabric.Image.filters.HueRotation({
  23516. * rotation: -0.5
  23517. * });
  23518. * object.filters.push(filter);
  23519. * object.applyFilters();
  23520. */
  23521. filters.HueRotation = createClass(filters.ColorMatrix, /** @lends fabric.Image.filters.HueRotation.prototype */ {
  23522. /**
  23523. * Filter type
  23524. * @param {String} type
  23525. * @default
  23526. */
  23527. type: 'HueRotation',
  23528. /**
  23529. * HueRotation value, from -1 to 1.
  23530. * the unit is radians
  23531. * @param {Number} myParameter
  23532. * @default
  23533. */
  23534. rotation: 0,
  23535. /**
  23536. * Describe the property that is the filter parameter
  23537. * @param {String} m
  23538. * @default
  23539. */
  23540. mainParameter: 'rotation',
  23541. calculateMatrix: function() {
  23542. var rad = this.rotation * Math.PI, cos = fabric.util.cos(rad), sin = fabric.util.sin(rad),
  23543. aThird = 1 / 3, aThirdSqtSin = Math.sqrt(aThird) * sin, OneMinusCos = 1 - cos;
  23544. this.matrix = [
  23545. 1, 0, 0, 0, 0,
  23546. 0, 1, 0, 0, 0,
  23547. 0, 0, 1, 0, 0,
  23548. 0, 0, 0, 1, 0
  23549. ];
  23550. this.matrix[0] = cos + OneMinusCos / 3;
  23551. this.matrix[1] = aThird * OneMinusCos - aThirdSqtSin;
  23552. this.matrix[2] = aThird * OneMinusCos + aThirdSqtSin;
  23553. this.matrix[5] = aThird * OneMinusCos + aThirdSqtSin;
  23554. this.matrix[6] = cos + aThird * OneMinusCos;
  23555. this.matrix[7] = aThird * OneMinusCos - aThirdSqtSin;
  23556. this.matrix[10] = aThird * OneMinusCos - aThirdSqtSin;
  23557. this.matrix[11] = aThird * OneMinusCos + aThirdSqtSin;
  23558. this.matrix[12] = cos + aThird * OneMinusCos;
  23559. },
  23560. /**
  23561. * HueRotation isNeutralState implementation
  23562. * Used only in image applyFilters to discard filters that will not have an effect
  23563. * on the image
  23564. * @param {Object} options
  23565. **/
  23566. isNeutralState: function(options) {
  23567. this.calculateMatrix();
  23568. return filters.BaseFilter.prototype.isNeutralState.call(this, options);
  23569. },
  23570. /**
  23571. * Apply this filter to the input image data provided.
  23572. *
  23573. * Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
  23574. *
  23575. * @param {Object} options
  23576. * @param {Number} options.passes The number of filters remaining to be executed
  23577. * @param {Boolean} options.webgl Whether to use webgl to render the filter.
  23578. * @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
  23579. * @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
  23580. * @param {WebGLRenderingContext} options.context The GL context used for rendering.
  23581. * @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
  23582. */
  23583. applyTo: function(options) {
  23584. this.calculateMatrix();
  23585. filters.BaseFilter.prototype.applyTo.call(this, options);
  23586. },
  23587. });
  23588. /**
  23589. * Returns filter instance from an object representation
  23590. * @static
  23591. * @param {Object} object Object to create an instance from
  23592. * @param {function} [callback] to be invoked after filter creation
  23593. * @return {fabric.Image.filters.HueRotation} Instance of fabric.Image.filters.HueRotation
  23594. */
  23595. fabric.Image.filters.HueRotation.fromObject = fabric.Image.filters.BaseFilter.fromObject;
  23596. })(typeof exports !== 'undefined' ? exports : this);
  23597. (function(global) {
  23598. 'use strict';
  23599. var fabric = global.fabric || (global.fabric = { }),
  23600. clone = fabric.util.object.clone;
  23601. if (fabric.Text) {
  23602. fabric.warn('fabric.Text is already defined');
  23603. return;
  23604. }
  23605. var additionalProps =
  23606. ('fontFamily fontWeight fontSize text underline overline linethrough' +
  23607. ' textAlign fontStyle lineHeight textBackgroundColor charSpacing styles' +
  23608. ' direction path pathStartOffset pathSide pathAlign').split(' ');
  23609. /**
  23610. * Text class
  23611. * @class fabric.Text
  23612. * @extends fabric.Object
  23613. * @return {fabric.Text} thisArg
  23614. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2#text}
  23615. * @see {@link fabric.Text#initialize} for constructor definition
  23616. */
  23617. fabric.Text = fabric.util.createClass(fabric.Object, /** @lends fabric.Text.prototype */ {
  23618. /**
  23619. * Properties which when set cause object to change dimensions
  23620. * @type Array
  23621. * @private
  23622. */
  23623. _dimensionAffectingProps: [
  23624. 'fontSize',
  23625. 'fontWeight',
  23626. 'fontFamily',
  23627. 'fontStyle',
  23628. 'lineHeight',
  23629. 'text',
  23630. 'charSpacing',
  23631. 'textAlign',
  23632. 'styles',
  23633. 'path',
  23634. 'pathStartOffset',
  23635. 'pathSide',
  23636. 'pathAlign'
  23637. ],
  23638. /**
  23639. * @private
  23640. */
  23641. _reNewline: /\r?\n/,
  23642. /**
  23643. * Use this regular expression to filter for whitespaces that is not a new line.
  23644. * Mostly used when text is 'justify' aligned.
  23645. * @private
  23646. */
  23647. _reSpacesAndTabs: /[ \t\r]/g,
  23648. /**
  23649. * Use this regular expression to filter for whitespace that is not a new line.
  23650. * Mostly used when text is 'justify' aligned.
  23651. * @private
  23652. */
  23653. _reSpaceAndTab: /[ \t\r]/,
  23654. /**
  23655. * Use this regular expression to filter consecutive groups of non spaces.
  23656. * Mostly used when text is 'justify' aligned.
  23657. * @private
  23658. */
  23659. _reWords: /\S+/g,
  23660. /**
  23661. * Type of an object
  23662. * @type String
  23663. * @default
  23664. */
  23665. type: 'text',
  23666. /**
  23667. * Font size (in pixels)
  23668. * @type Number
  23669. * @default
  23670. */
  23671. fontSize: 40,
  23672. /**
  23673. * Font weight (e.g. bold, normal, 400, 600, 800)
  23674. * @type {(Number|String)}
  23675. * @default
  23676. */
  23677. fontWeight: 'normal',
  23678. /**
  23679. * Font family
  23680. * @type String
  23681. * @default
  23682. */
  23683. fontFamily: 'Times New Roman',
  23684. /**
  23685. * Text decoration underline.
  23686. * @type Boolean
  23687. * @default
  23688. */
  23689. underline: false,
  23690. /**
  23691. * Text decoration overline.
  23692. * @type Boolean
  23693. * @default
  23694. */
  23695. overline: false,
  23696. /**
  23697. * Text decoration linethrough.
  23698. * @type Boolean
  23699. * @default
  23700. */
  23701. linethrough: false,
  23702. /**
  23703. * Text alignment. Possible values: "left", "center", "right", "justify",
  23704. * "justify-left", "justify-center" or "justify-right".
  23705. * @type String
  23706. * @default
  23707. */
  23708. textAlign: 'left',
  23709. /**
  23710. * Font style . Possible values: "", "normal", "italic" or "oblique".
  23711. * @type String
  23712. * @default
  23713. */
  23714. fontStyle: 'normal',
  23715. /**
  23716. * Line height
  23717. * @type Number
  23718. * @default
  23719. */
  23720. lineHeight: 1.16,
  23721. /**
  23722. * Superscript schema object (minimum overlap)
  23723. * @type {Object}
  23724. * @default
  23725. */
  23726. superscript: {
  23727. size: 0.60, // fontSize factor
  23728. baseline: -0.35 // baseline-shift factor (upwards)
  23729. },
  23730. /**
  23731. * Subscript schema object (minimum overlap)
  23732. * @type {Object}
  23733. * @default
  23734. */
  23735. subscript: {
  23736. size: 0.60, // fontSize factor
  23737. baseline: 0.11 // baseline-shift factor (downwards)
  23738. },
  23739. /**
  23740. * Background color of text lines
  23741. * @type String
  23742. * @default
  23743. */
  23744. textBackgroundColor: '',
  23745. /**
  23746. * List of properties to consider when checking if
  23747. * state of an object is changed ({@link fabric.Object#hasStateChanged})
  23748. * as well as for history (undo/redo) purposes
  23749. * @type Array
  23750. */
  23751. stateProperties: fabric.Object.prototype.stateProperties.concat(additionalProps),
  23752. /**
  23753. * List of properties to consider when checking if cache needs refresh
  23754. * @type Array
  23755. */
  23756. cacheProperties: fabric.Object.prototype.cacheProperties.concat(additionalProps),
  23757. /**
  23758. * When defined, an object is rendered via stroke and this property specifies its color.
  23759. * <b>Backwards incompatibility note:</b> This property was named "strokeStyle" until v1.1.6
  23760. * @type String
  23761. * @default
  23762. */
  23763. stroke: null,
  23764. /**
  23765. * Shadow object representing shadow of this shape.
  23766. * <b>Backwards incompatibility note:</b> This property was named "textShadow" (String) until v1.2.11
  23767. * @type fabric.Shadow
  23768. * @default
  23769. */
  23770. shadow: null,
  23771. /**
  23772. * fabric.Path that the text should follow.
  23773. * since 4.6.0 the path will be drawn automatically.
  23774. * if you want to make the path visible, give it a stroke and strokeWidth or fill value
  23775. * if you want it to be hidden, assign visible = false to the path.
  23776. * This feature is in BETA, and SVG import/export is not yet supported.
  23777. * @type fabric.Path
  23778. * @example
  23779. * var textPath = new fabric.Text('Text on a path', {
  23780. * top: 150,
  23781. * left: 150,
  23782. * textAlign: 'center',
  23783. * charSpacing: -50,
  23784. * path: new fabric.Path('M 0 0 C 50 -100 150 -100 200 0', {
  23785. * strokeWidth: 1,
  23786. * visible: false
  23787. * }),
  23788. * pathSide: 'left',
  23789. * pathStartOffset: 0
  23790. * });
  23791. * @default
  23792. */
  23793. path: null,
  23794. /**
  23795. * Offset amount for text path starting position
  23796. * Only used when text has a path
  23797. * @type Number
  23798. * @default
  23799. */
  23800. pathStartOffset: 0,
  23801. /**
  23802. * Which side of the path the text should be drawn on.
  23803. * Only used when text has a path
  23804. * @type {String} 'left|right'
  23805. * @default
  23806. */
  23807. pathSide: 'left',
  23808. /**
  23809. * How text is aligned to the path. This property determines
  23810. * the perpendicular position of each character relative to the path.
  23811. * (one of "baseline", "center", "ascender", "descender")
  23812. * This feature is in BETA, and its behavior may change
  23813. * @type String
  23814. * @default
  23815. */
  23816. pathAlign: 'baseline',
  23817. /**
  23818. * @private
  23819. */
  23820. _fontSizeFraction: 0.222,
  23821. /**
  23822. * @private
  23823. */
  23824. offsets: {
  23825. underline: 0.10,
  23826. linethrough: -0.315,
  23827. overline: -0.88
  23828. },
  23829. /**
  23830. * Text Line proportion to font Size (in pixels)
  23831. * @type Number
  23832. * @default
  23833. */
  23834. _fontSizeMult: 1.13,
  23835. /**
  23836. * additional space between characters
  23837. * expressed in thousands of em unit
  23838. * @type Number
  23839. * @default
  23840. */
  23841. charSpacing: 0,
  23842. /**
  23843. * Object containing character styles - top-level properties -> line numbers,
  23844. * 2nd-level properties - character numbers
  23845. * @type Object
  23846. * @default
  23847. */
  23848. styles: null,
  23849. /**
  23850. * Reference to a context to measure text char or couple of chars
  23851. * the cacheContext of the canvas will be used or a freshly created one if the object is not on canvas
  23852. * once created it will be referenced on fabric._measuringContext to avoid creating a canvas for every
  23853. * text object created.
  23854. * @type {CanvasRenderingContext2D}
  23855. * @default
  23856. */
  23857. _measuringContext: null,
  23858. /**
  23859. * Baseline shift, styles only, keep at 0 for the main text object
  23860. * @type {Number}
  23861. * @default
  23862. */
  23863. deltaY: 0,
  23864. /**
  23865. * WARNING: EXPERIMENTAL. NOT SUPPORTED YET
  23866. * determine the direction of the text.
  23867. * This has to be set manually together with textAlign and originX for proper
  23868. * experience.
  23869. * some interesting link for the future
  23870. * https://www.w3.org/International/questions/qa-bidi-unicode-controls
  23871. * @since 4.5.0
  23872. * @type {String} 'ltr|rtl'
  23873. * @default
  23874. */
  23875. direction: 'ltr',
  23876. /**
  23877. * Array of properties that define a style unit (of 'styles').
  23878. * @type {Array}
  23879. * @default
  23880. */
  23881. _styleProperties: [
  23882. 'stroke',
  23883. 'strokeWidth',
  23884. 'fill',
  23885. 'fontFamily',
  23886. 'fontSize',
  23887. 'fontWeight',
  23888. 'fontStyle',
  23889. 'underline',
  23890. 'overline',
  23891. 'linethrough',
  23892. 'deltaY',
  23893. 'textBackgroundColor',
  23894. ],
  23895. /**
  23896. * contains characters bounding boxes
  23897. */
  23898. __charBounds: [],
  23899. /**
  23900. * use this size when measuring text. To avoid IE11 rounding errors
  23901. * @type {Number}
  23902. * @default
  23903. * @readonly
  23904. * @private
  23905. */
  23906. CACHE_FONT_SIZE: 400,
  23907. /**
  23908. * contains the min text width to avoid getting 0
  23909. * @type {Number}
  23910. * @default
  23911. */
  23912. MIN_TEXT_WIDTH: 2,
  23913. /**
  23914. * Constructor
  23915. * @param {String} text Text string
  23916. * @param {Object} [options] Options object
  23917. * @return {fabric.Text} thisArg
  23918. */
  23919. initialize: function(text, options) {
  23920. this.styles = options ? (options.styles || { }) : { };
  23921. this.text = text;
  23922. this.__skipDimension = true;
  23923. this.callSuper('initialize', options);
  23924. if (this.path) {
  23925. this.setPathInfo();
  23926. }
  23927. this.__skipDimension = false;
  23928. this.initDimensions();
  23929. this.setCoords();
  23930. this.setupState({ propertySet: '_dimensionAffectingProps' });
  23931. },
  23932. /**
  23933. * If text has a path, it will add the extra information needed
  23934. * for path and text calculations
  23935. * @return {fabric.Text} thisArg
  23936. */
  23937. setPathInfo: function() {
  23938. var path = this.path;
  23939. if (path) {
  23940. path.segmentsInfo = fabric.util.getPathSegmentsInfo(path.path);
  23941. }
  23942. },
  23943. /**
  23944. * Return a context for measurement of text string.
  23945. * if created it gets stored for reuse
  23946. * this is for internal use, please do not use it
  23947. * @private
  23948. * @param {String} text Text string
  23949. * @param {Object} [options] Options object
  23950. * @return {fabric.Text} thisArg
  23951. */
  23952. getMeasuringContext: function() {
  23953. // if we did not return we have to measure something.
  23954. if (!fabric._measuringContext) {
  23955. fabric._measuringContext = this.canvas && this.canvas.contextCache ||
  23956. fabric.util.createCanvasElement().getContext('2d');
  23957. }
  23958. return fabric._measuringContext;
  23959. },
  23960. /**
  23961. * @private
  23962. * Divides text into lines of text and lines of graphemes.
  23963. */
  23964. _splitText: function() {
  23965. var newLines = this._splitTextIntoLines(this.text);
  23966. this.textLines = newLines.lines;
  23967. this._textLines = newLines.graphemeLines;
  23968. this._unwrappedTextLines = newLines._unwrappedLines;
  23969. this._text = newLines.graphemeText;
  23970. return newLines;
  23971. },
  23972. /**
  23973. * Initialize or update text dimensions.
  23974. * Updates this.width and this.height with the proper values.
  23975. * Does not return dimensions.
  23976. */
  23977. initDimensions: function() {
  23978. if (this.__skipDimension) {
  23979. return;
  23980. }
  23981. this._splitText();
  23982. this._clearCache();
  23983. if (this.path) {
  23984. this.width = this.path.width;
  23985. this.height = this.path.height;
  23986. }
  23987. else {
  23988. this.width = this.calcTextWidth() || this.cursorWidth || this.MIN_TEXT_WIDTH;
  23989. this.height = this.calcTextHeight();
  23990. }
  23991. if (this.textAlign.indexOf('justify') !== -1) {
  23992. // once text is measured we need to make space fatter to make justified text.
  23993. this.enlargeSpaces();
  23994. }
  23995. this.saveState({ propertySet: '_dimensionAffectingProps' });
  23996. },
  23997. /**
  23998. * Enlarge space boxes and shift the others
  23999. */
  24000. enlargeSpaces: function() {
  24001. var diffSpace, currentLineWidth, numberOfSpaces, accumulatedSpace, line, charBound, spaces;
  24002. for (var i = 0, len = this._textLines.length; i < len; i++) {
  24003. if (this.textAlign !== 'justify' && (i === len - 1 || this.isEndOfWrapping(i))) {
  24004. continue;
  24005. }
  24006. accumulatedSpace = 0;
  24007. line = this._textLines[i];
  24008. currentLineWidth = this.getLineWidth(i);
  24009. if (currentLineWidth < this.width && (spaces = this.textLines[i].match(this._reSpacesAndTabs))) {
  24010. numberOfSpaces = spaces.length;
  24011. diffSpace = (this.width - currentLineWidth) / numberOfSpaces;
  24012. for (var j = 0, jlen = line.length; j <= jlen; j++) {
  24013. charBound = this.__charBounds[i][j];
  24014. if (this._reSpaceAndTab.test(line[j])) {
  24015. charBound.width += diffSpace;
  24016. charBound.kernedWidth += diffSpace;
  24017. charBound.left += accumulatedSpace;
  24018. accumulatedSpace += diffSpace;
  24019. }
  24020. else {
  24021. charBound.left += accumulatedSpace;
  24022. }
  24023. }
  24024. }
  24025. }
  24026. },
  24027. /**
  24028. * Detect if the text line is ended with an hard break
  24029. * text and itext do not have wrapping, return false
  24030. * @return {Boolean}
  24031. */
  24032. isEndOfWrapping: function(lineIndex) {
  24033. return lineIndex === this._textLines.length - 1;
  24034. },
  24035. /**
  24036. * Detect if a line has a linebreak and so we need to account for it when moving
  24037. * and counting style.
  24038. * It return always for text and Itext.
  24039. * @return Number
  24040. */
  24041. missingNewlineOffset: function() {
  24042. return 1;
  24043. },
  24044. /**
  24045. * Returns string representation of an instance
  24046. * @return {String} String representation of text object
  24047. */
  24048. toString: function() {
  24049. return '#<fabric.Text (' + this.complexity() +
  24050. '): { "text": "' + this.text + '", "fontFamily": "' + this.fontFamily + '" }>';
  24051. },
  24052. /**
  24053. * Return the dimension and the zoom level needed to create a cache canvas
  24054. * big enough to host the object to be cached.
  24055. * @private
  24056. * @param {Object} dim.x width of object to be cached
  24057. * @param {Object} dim.y height of object to be cached
  24058. * @return {Object}.width width of canvas
  24059. * @return {Object}.height height of canvas
  24060. * @return {Object}.zoomX zoomX zoom value to unscale the canvas before drawing cache
  24061. * @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
  24062. */
  24063. _getCacheCanvasDimensions: function() {
  24064. var dims = this.callSuper('_getCacheCanvasDimensions');
  24065. var fontSize = this.fontSize;
  24066. dims.width += fontSize * dims.zoomX;
  24067. dims.height += fontSize * dims.zoomY;
  24068. return dims;
  24069. },
  24070. /**
  24071. * @private
  24072. * @param {CanvasRenderingContext2D} ctx Context to render on
  24073. */
  24074. _render: function(ctx) {
  24075. var path = this.path;
  24076. path && !path.isNotVisible() && path._render(ctx);
  24077. this._setTextStyles(ctx);
  24078. this._renderTextLinesBackground(ctx);
  24079. this._renderTextDecoration(ctx, 'underline');
  24080. this._renderText(ctx);
  24081. this._renderTextDecoration(ctx, 'overline');
  24082. this._renderTextDecoration(ctx, 'linethrough');
  24083. },
  24084. /**
  24085. * @private
  24086. * @param {CanvasRenderingContext2D} ctx Context to render on
  24087. */
  24088. _renderText: function(ctx) {
  24089. if (this.paintFirst === 'stroke') {
  24090. this._renderTextStroke(ctx);
  24091. this._renderTextFill(ctx);
  24092. }
  24093. else {
  24094. this._renderTextFill(ctx);
  24095. this._renderTextStroke(ctx);
  24096. }
  24097. },
  24098. /**
  24099. * Set the font parameter of the context with the object properties or with charStyle
  24100. * @private
  24101. * @param {CanvasRenderingContext2D} ctx Context to render on
  24102. * @param {Object} [charStyle] object with font style properties
  24103. * @param {String} [charStyle.fontFamily] Font Family
  24104. * @param {Number} [charStyle.fontSize] Font size in pixels. ( without px suffix )
  24105. * @param {String} [charStyle.fontWeight] Font weight
  24106. * @param {String} [charStyle.fontStyle] Font style (italic|normal)
  24107. */
  24108. _setTextStyles: function(ctx, charStyle, forMeasuring) {
  24109. ctx.textBaseline = 'alphabetical';
  24110. if (this.path) {
  24111. switch (this.pathAlign) {
  24112. case 'center':
  24113. ctx.textBaseline = 'middle';
  24114. break;
  24115. case 'ascender':
  24116. ctx.textBaseline = 'top';
  24117. break;
  24118. case 'descender':
  24119. ctx.textBaseline = 'bottom';
  24120. break;
  24121. }
  24122. }
  24123. ctx.font = this._getFontDeclaration(charStyle, forMeasuring);
  24124. },
  24125. /**
  24126. * calculate and return the text Width measuring each line.
  24127. * @private
  24128. * @param {CanvasRenderingContext2D} ctx Context to render on
  24129. * @return {Number} Maximum width of fabric.Text object
  24130. */
  24131. calcTextWidth: function() {
  24132. var maxWidth = this.getLineWidth(0);
  24133. for (var i = 1, len = this._textLines.length; i < len; i++) {
  24134. var currentLineWidth = this.getLineWidth(i);
  24135. if (currentLineWidth > maxWidth) {
  24136. maxWidth = currentLineWidth;
  24137. }
  24138. }
  24139. return maxWidth;
  24140. },
  24141. /**
  24142. * @private
  24143. * @param {String} method Method name ("fillText" or "strokeText")
  24144. * @param {CanvasRenderingContext2D} ctx Context to render on
  24145. * @param {String} line Text to render
  24146. * @param {Number} left Left position of text
  24147. * @param {Number} top Top position of text
  24148. * @param {Number} lineIndex Index of a line in a text
  24149. */
  24150. _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
  24151. this._renderChars(method, ctx, line, left, top, lineIndex);
  24152. },
  24153. /**
  24154. * Renders the text background for lines, taking care of style
  24155. * @private
  24156. * @param {CanvasRenderingContext2D} ctx Context to render on
  24157. */
  24158. _renderTextLinesBackground: function(ctx) {
  24159. if (!this.textBackgroundColor && !this.styleHas('textBackgroundColor')) {
  24160. return;
  24161. }
  24162. var heightOfLine,
  24163. lineLeftOffset, originalFill = ctx.fillStyle,
  24164. line, lastColor,
  24165. leftOffset = this._getLeftOffset(),
  24166. lineTopOffset = this._getTopOffset(),
  24167. boxStart = 0, boxWidth = 0, charBox, currentColor, path = this.path,
  24168. drawStart;
  24169. for (var i = 0, len = this._textLines.length; i < len; i++) {
  24170. heightOfLine = this.getHeightOfLine(i);
  24171. if (!this.textBackgroundColor && !this.styleHas('textBackgroundColor', i)) {
  24172. lineTopOffset += heightOfLine;
  24173. continue;
  24174. }
  24175. line = this._textLines[i];
  24176. lineLeftOffset = this._getLineLeftOffset(i);
  24177. boxWidth = 0;
  24178. boxStart = 0;
  24179. lastColor = this.getValueOfPropertyAt(i, 0, 'textBackgroundColor');
  24180. for (var j = 0, jlen = line.length; j < jlen; j++) {
  24181. charBox = this.__charBounds[i][j];
  24182. currentColor = this.getValueOfPropertyAt(i, j, 'textBackgroundColor');
  24183. if (path) {
  24184. ctx.save();
  24185. ctx.translate(charBox.renderLeft, charBox.renderTop);
  24186. ctx.rotate(charBox.angle);
  24187. ctx.fillStyle = currentColor;
  24188. currentColor && ctx.fillRect(
  24189. -charBox.width / 2,
  24190. -heightOfLine / this.lineHeight * (1 - this._fontSizeFraction),
  24191. charBox.width,
  24192. heightOfLine / this.lineHeight
  24193. );
  24194. ctx.restore();
  24195. }
  24196. else if (currentColor !== lastColor) {
  24197. drawStart = leftOffset + lineLeftOffset + boxStart;
  24198. if (this.direction === 'rtl') {
  24199. drawStart = this.width - drawStart - boxWidth;
  24200. }
  24201. ctx.fillStyle = lastColor;
  24202. lastColor && ctx.fillRect(
  24203. drawStart,
  24204. lineTopOffset,
  24205. boxWidth,
  24206. heightOfLine / this.lineHeight
  24207. );
  24208. boxStart = charBox.left;
  24209. boxWidth = charBox.width;
  24210. lastColor = currentColor;
  24211. }
  24212. else {
  24213. boxWidth += charBox.kernedWidth;
  24214. }
  24215. }
  24216. if (currentColor && !path) {
  24217. drawStart = leftOffset + lineLeftOffset + boxStart;
  24218. if (this.direction === 'rtl') {
  24219. drawStart = this.width - drawStart - boxWidth;
  24220. }
  24221. ctx.fillStyle = currentColor;
  24222. ctx.fillRect(
  24223. drawStart,
  24224. lineTopOffset,
  24225. boxWidth,
  24226. heightOfLine / this.lineHeight
  24227. );
  24228. }
  24229. lineTopOffset += heightOfLine;
  24230. }
  24231. ctx.fillStyle = originalFill;
  24232. // if there is text background color no
  24233. // other shadows should be casted
  24234. this._removeShadow(ctx);
  24235. },
  24236. /**
  24237. * @private
  24238. * @param {Object} decl style declaration for cache
  24239. * @param {String} decl.fontFamily fontFamily
  24240. * @param {String} decl.fontStyle fontStyle
  24241. * @param {String} decl.fontWeight fontWeight
  24242. * @return {Object} reference to cache
  24243. */
  24244. getFontCache: function(decl) {
  24245. var fontFamily = decl.fontFamily.toLowerCase();
  24246. if (!fabric.charWidthsCache[fontFamily]) {
  24247. fabric.charWidthsCache[fontFamily] = { };
  24248. }
  24249. var cache = fabric.charWidthsCache[fontFamily],
  24250. cacheProp = decl.fontStyle.toLowerCase() + '_' + (decl.fontWeight + '').toLowerCase();
  24251. if (!cache[cacheProp]) {
  24252. cache[cacheProp] = { };
  24253. }
  24254. return cache[cacheProp];
  24255. },
  24256. /**
  24257. * measure and return the width of a single character.
  24258. * possibly overridden to accommodate different measure logic or
  24259. * to hook some external lib for character measurement
  24260. * @private
  24261. * @param {String} _char, char to be measured
  24262. * @param {Object} charStyle style of char to be measured
  24263. * @param {String} [previousChar] previous char
  24264. * @param {Object} [prevCharStyle] style of previous char
  24265. */
  24266. _measureChar: function(_char, charStyle, previousChar, prevCharStyle) {
  24267. // first i try to return from cache
  24268. var fontCache = this.getFontCache(charStyle), fontDeclaration = this._getFontDeclaration(charStyle),
  24269. previousFontDeclaration = this._getFontDeclaration(prevCharStyle), couple = previousChar + _char,
  24270. stylesAreEqual = fontDeclaration === previousFontDeclaration, width, coupleWidth, previousWidth,
  24271. fontMultiplier = charStyle.fontSize / this.CACHE_FONT_SIZE, kernedWidth;
  24272. if (previousChar && fontCache[previousChar] !== undefined) {
  24273. previousWidth = fontCache[previousChar];
  24274. }
  24275. if (fontCache[_char] !== undefined) {
  24276. kernedWidth = width = fontCache[_char];
  24277. }
  24278. if (stylesAreEqual && fontCache[couple] !== undefined) {
  24279. coupleWidth = fontCache[couple];
  24280. kernedWidth = coupleWidth - previousWidth;
  24281. }
  24282. if (width === undefined || previousWidth === undefined || coupleWidth === undefined) {
  24283. var ctx = this.getMeasuringContext();
  24284. // send a TRUE to specify measuring font size CACHE_FONT_SIZE
  24285. this._setTextStyles(ctx, charStyle, true);
  24286. }
  24287. if (width === undefined) {
  24288. kernedWidth = width = ctx.measureText(_char).width;
  24289. fontCache[_char] = width;
  24290. }
  24291. if (previousWidth === undefined && stylesAreEqual && previousChar) {
  24292. previousWidth = ctx.measureText(previousChar).width;
  24293. fontCache[previousChar] = previousWidth;
  24294. }
  24295. if (stylesAreEqual && coupleWidth === undefined) {
  24296. // we can measure the kerning couple and subtract the width of the previous character
  24297. coupleWidth = ctx.measureText(couple).width;
  24298. fontCache[couple] = coupleWidth;
  24299. kernedWidth = coupleWidth - previousWidth;
  24300. }
  24301. return { width: width * fontMultiplier, kernedWidth: kernedWidth * fontMultiplier };
  24302. },
  24303. /**
  24304. * Computes height of character at given position
  24305. * @param {Number} line the line index number
  24306. * @param {Number} _char the character index number
  24307. * @return {Number} fontSize of the character
  24308. */
  24309. getHeightOfChar: function(line, _char) {
  24310. return this.getValueOfPropertyAt(line, _char, 'fontSize');
  24311. },
  24312. /**
  24313. * measure a text line measuring all characters.
  24314. * @param {Number} lineIndex line number
  24315. * @return {Number} Line width
  24316. */
  24317. measureLine: function(lineIndex) {
  24318. var lineInfo = this._measureLine(lineIndex);
  24319. if (this.charSpacing !== 0) {
  24320. lineInfo.width -= this._getWidthOfCharSpacing();
  24321. }
  24322. if (lineInfo.width < 0) {
  24323. lineInfo.width = 0;
  24324. }
  24325. return lineInfo;
  24326. },
  24327. /**
  24328. * measure every grapheme of a line, populating __charBounds
  24329. * @param {Number} lineIndex
  24330. * @return {Object} object.width total width of characters
  24331. * @return {Object} object.widthOfSpaces length of chars that match this._reSpacesAndTabs
  24332. */
  24333. _measureLine: function(lineIndex) {
  24334. var width = 0, i, grapheme, line = this._textLines[lineIndex], prevGrapheme,
  24335. graphemeInfo, numOfSpaces = 0, lineBounds = new Array(line.length),
  24336. positionInPath = 0, startingPoint, totalPathLength, path = this.path,
  24337. reverse = this.pathSide === 'right';
  24338. this.__charBounds[lineIndex] = lineBounds;
  24339. for (i = 0; i < line.length; i++) {
  24340. grapheme = line[i];
  24341. graphemeInfo = this._getGraphemeBox(grapheme, lineIndex, i, prevGrapheme);
  24342. lineBounds[i] = graphemeInfo;
  24343. width += graphemeInfo.kernedWidth;
  24344. prevGrapheme = grapheme;
  24345. }
  24346. // this latest bound box represent the last character of the line
  24347. // to simplify cursor handling in interactive mode.
  24348. lineBounds[i] = {
  24349. left: graphemeInfo ? graphemeInfo.left + graphemeInfo.width : 0,
  24350. width: 0,
  24351. kernedWidth: 0,
  24352. height: this.fontSize
  24353. };
  24354. if (path) {
  24355. totalPathLength = path.segmentsInfo[path.segmentsInfo.length - 1].length;
  24356. startingPoint = fabric.util.getPointOnPath(path.path, 0, path.segmentsInfo);
  24357. startingPoint.x += path.pathOffset.x;
  24358. startingPoint.y += path.pathOffset.y;
  24359. switch (this.textAlign) {
  24360. case 'left':
  24361. positionInPath = reverse ? (totalPathLength - width) : 0;
  24362. break;
  24363. case 'center':
  24364. positionInPath = (totalPathLength - width) / 2;
  24365. break;
  24366. case 'right':
  24367. positionInPath = reverse ? 0 : (totalPathLength - width);
  24368. break;
  24369. //todo - add support for justify
  24370. }
  24371. positionInPath += this.pathStartOffset * (reverse ? -1 : 1);
  24372. for (i = reverse ? line.length - 1 : 0;
  24373. reverse ? i >= 0 : i < line.length;
  24374. reverse ? i-- : i++) {
  24375. graphemeInfo = lineBounds[i];
  24376. if (positionInPath > totalPathLength) {
  24377. positionInPath %= totalPathLength;
  24378. }
  24379. else if (positionInPath < 0) {
  24380. positionInPath += totalPathLength;
  24381. }
  24382. // it would probably much faster to send all the grapheme position for a line
  24383. // and calculate path position/angle at once.
  24384. this._setGraphemeOnPath(positionInPath, graphemeInfo, startingPoint);
  24385. positionInPath += graphemeInfo.kernedWidth;
  24386. }
  24387. }
  24388. return { width: width, numOfSpaces: numOfSpaces };
  24389. },
  24390. /**
  24391. * Calculate the angle and the left,top position of the char that follow a path.
  24392. * It appends it to graphemeInfo to be reused later at rendering
  24393. * @private
  24394. * @param {Number} positionInPath to be measured
  24395. * @param {Object} graphemeInfo current grapheme box information
  24396. * @param {Object} startingPoint position of the point
  24397. */
  24398. _setGraphemeOnPath: function(positionInPath, graphemeInfo, startingPoint) {
  24399. var centerPosition = positionInPath + graphemeInfo.kernedWidth / 2,
  24400. path = this.path;
  24401. // we are at currentPositionOnPath. we want to know what point on the path is.
  24402. var info = fabric.util.getPointOnPath(path.path, centerPosition, path.segmentsInfo);
  24403. graphemeInfo.renderLeft = info.x - startingPoint.x;
  24404. graphemeInfo.renderTop = info.y - startingPoint.y;
  24405. graphemeInfo.angle = info.angle + (this.pathSide === 'right' ? Math.PI : 0);
  24406. },
  24407. /**
  24408. * Measure and return the info of a single grapheme.
  24409. * needs the the info of previous graphemes already filled
  24410. * @private
  24411. * @param {String} grapheme to be measured
  24412. * @param {Number} lineIndex index of the line where the char is
  24413. * @param {Number} charIndex position in the line
  24414. * @param {String} [prevGrapheme] character preceding the one to be measured
  24415. */
  24416. _getGraphemeBox: function(grapheme, lineIndex, charIndex, prevGrapheme, skipLeft) {
  24417. var style = this.getCompleteStyleDeclaration(lineIndex, charIndex),
  24418. prevStyle = prevGrapheme ? this.getCompleteStyleDeclaration(lineIndex, charIndex - 1) : { },
  24419. info = this._measureChar(grapheme, style, prevGrapheme, prevStyle),
  24420. kernedWidth = info.kernedWidth,
  24421. width = info.width, charSpacing;
  24422. if (this.charSpacing !== 0) {
  24423. charSpacing = this._getWidthOfCharSpacing();
  24424. width += charSpacing;
  24425. kernedWidth += charSpacing;
  24426. }
  24427. var box = {
  24428. width: width,
  24429. left: 0,
  24430. height: style.fontSize,
  24431. kernedWidth: kernedWidth,
  24432. deltaY: style.deltaY,
  24433. };
  24434. if (charIndex > 0 && !skipLeft) {
  24435. var previousBox = this.__charBounds[lineIndex][charIndex - 1];
  24436. box.left = previousBox.left + previousBox.width + info.kernedWidth - info.width;
  24437. }
  24438. return box;
  24439. },
  24440. /**
  24441. * Calculate height of line at 'lineIndex'
  24442. * @param {Number} lineIndex index of line to calculate
  24443. * @return {Number}
  24444. */
  24445. getHeightOfLine: function(lineIndex) {
  24446. if (this.__lineHeights[lineIndex]) {
  24447. return this.__lineHeights[lineIndex];
  24448. }
  24449. var line = this._textLines[lineIndex],
  24450. // char 0 is measured before the line cycle because it nneds to char
  24451. // emptylines
  24452. maxHeight = this.getHeightOfChar(lineIndex, 0);
  24453. for (var i = 1, len = line.length; i < len; i++) {
  24454. maxHeight = Math.max(this.getHeightOfChar(lineIndex, i), maxHeight);
  24455. }
  24456. return this.__lineHeights[lineIndex] = maxHeight * this.lineHeight * this._fontSizeMult;
  24457. },
  24458. /**
  24459. * Calculate text box height
  24460. */
  24461. calcTextHeight: function() {
  24462. var lineHeight, height = 0;
  24463. for (var i = 0, len = this._textLines.length; i < len; i++) {
  24464. lineHeight = this.getHeightOfLine(i);
  24465. height += (i === len - 1 ? lineHeight / this.lineHeight : lineHeight);
  24466. }
  24467. return height;
  24468. },
  24469. /**
  24470. * @private
  24471. * @return {Number} Left offset
  24472. */
  24473. _getLeftOffset: function() {
  24474. return this.direction === 'ltr' ? -this.width / 2 : this.width / 2;
  24475. },
  24476. /**
  24477. * @private
  24478. * @return {Number} Top offset
  24479. */
  24480. _getTopOffset: function() {
  24481. return -this.height / 2;
  24482. },
  24483. /**
  24484. * @private
  24485. * @param {CanvasRenderingContext2D} ctx Context to render on
  24486. * @param {String} method Method name ("fillText" or "strokeText")
  24487. */
  24488. _renderTextCommon: function(ctx, method) {
  24489. ctx.save();
  24490. var lineHeights = 0, left = this._getLeftOffset(), top = this._getTopOffset();
  24491. for (var i = 0, len = this._textLines.length; i < len; i++) {
  24492. var heightOfLine = this.getHeightOfLine(i),
  24493. maxHeight = heightOfLine / this.lineHeight,
  24494. leftOffset = this._getLineLeftOffset(i);
  24495. this._renderTextLine(
  24496. method,
  24497. ctx,
  24498. this._textLines[i],
  24499. left + leftOffset,
  24500. top + lineHeights + maxHeight,
  24501. i
  24502. );
  24503. lineHeights += heightOfLine;
  24504. }
  24505. ctx.restore();
  24506. },
  24507. /**
  24508. * @private
  24509. * @param {CanvasRenderingContext2D} ctx Context to render on
  24510. */
  24511. _renderTextFill: function(ctx) {
  24512. if (!this.fill && !this.styleHas('fill')) {
  24513. return;
  24514. }
  24515. this._renderTextCommon(ctx, 'fillText');
  24516. },
  24517. /**
  24518. * @private
  24519. * @param {CanvasRenderingContext2D} ctx Context to render on
  24520. */
  24521. _renderTextStroke: function(ctx) {
  24522. if ((!this.stroke || this.strokeWidth === 0) && this.isEmptyStyles()) {
  24523. return;
  24524. }
  24525. if (this.shadow && !this.shadow.affectStroke) {
  24526. this._removeShadow(ctx);
  24527. }
  24528. ctx.save();
  24529. this._setLineDash(ctx, this.strokeDashArray);
  24530. ctx.beginPath();
  24531. this._renderTextCommon(ctx, 'strokeText');
  24532. ctx.closePath();
  24533. ctx.restore();
  24534. },
  24535. /**
  24536. * @private
  24537. * @param {String} method fillText or strokeText.
  24538. * @param {CanvasRenderingContext2D} ctx Context to render on
  24539. * @param {Array} line Content of the line, splitted in an array by grapheme
  24540. * @param {Number} left
  24541. * @param {Number} top
  24542. * @param {Number} lineIndex
  24543. */
  24544. _renderChars: function(method, ctx, line, left, top, lineIndex) {
  24545. // set proper line offset
  24546. var lineHeight = this.getHeightOfLine(lineIndex),
  24547. isJustify = this.textAlign.indexOf('justify') !== -1,
  24548. actualStyle,
  24549. nextStyle,
  24550. charsToRender = '',
  24551. charBox,
  24552. boxWidth = 0,
  24553. timeToRender,
  24554. path = this.path,
  24555. shortCut = !isJustify && this.charSpacing === 0 && this.isEmptyStyles(lineIndex) && !path,
  24556. isLtr = this.direction === 'ltr', sign = this.direction === 'ltr' ? 1 : -1,
  24557. drawingLeft, currentDirection = ctx.canvas.getAttribute('dir');
  24558. ctx.save();
  24559. if (currentDirection !== this.direction) {
  24560. ctx.canvas.setAttribute('dir', isLtr ? 'ltr' : 'rtl');
  24561. ctx.direction = isLtr ? 'ltr' : 'rtl';
  24562. ctx.textAlign = isLtr ? 'left' : 'right';
  24563. }
  24564. top -= lineHeight * this._fontSizeFraction / this.lineHeight;
  24565. if (shortCut) {
  24566. // render all the line in one pass without checking
  24567. // drawingLeft = isLtr ? left : left - this.getLineWidth(lineIndex);
  24568. this._renderChar(method, ctx, lineIndex, 0, line.join(''), left, top, lineHeight);
  24569. ctx.restore();
  24570. return;
  24571. }
  24572. for (var i = 0, len = line.length - 1; i <= len; i++) {
  24573. timeToRender = i === len || this.charSpacing || path;
  24574. charsToRender += line[i];
  24575. charBox = this.__charBounds[lineIndex][i];
  24576. if (boxWidth === 0) {
  24577. left += sign * (charBox.kernedWidth - charBox.width);
  24578. boxWidth += charBox.width;
  24579. }
  24580. else {
  24581. boxWidth += charBox.kernedWidth;
  24582. }
  24583. if (isJustify && !timeToRender) {
  24584. if (this._reSpaceAndTab.test(line[i])) {
  24585. timeToRender = true;
  24586. }
  24587. }
  24588. if (!timeToRender) {
  24589. // if we have charSpacing, we render char by char
  24590. actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i);
  24591. nextStyle = this.getCompleteStyleDeclaration(lineIndex, i + 1);
  24592. timeToRender = fabric.util.hasStyleChanged(actualStyle, nextStyle, false);
  24593. }
  24594. if (timeToRender) {
  24595. if (path) {
  24596. ctx.save();
  24597. ctx.translate(charBox.renderLeft, charBox.renderTop);
  24598. ctx.rotate(charBox.angle);
  24599. this._renderChar(method, ctx, lineIndex, i, charsToRender, -boxWidth / 2, 0, lineHeight);
  24600. ctx.restore();
  24601. }
  24602. else {
  24603. drawingLeft = left;
  24604. this._renderChar(method, ctx, lineIndex, i, charsToRender, drawingLeft, top, lineHeight);
  24605. }
  24606. charsToRender = '';
  24607. actualStyle = nextStyle;
  24608. left += sign * boxWidth;
  24609. boxWidth = 0;
  24610. }
  24611. }
  24612. ctx.restore();
  24613. },
  24614. /**
  24615. * This function try to patch the missing gradientTransform on canvas gradients.
  24616. * transforming a context to transform the gradient, is going to transform the stroke too.
  24617. * we want to transform the gradient but not the stroke operation, so we create
  24618. * a transformed gradient on a pattern and then we use the pattern instead of the gradient.
  24619. * this method has drawbacks: is slow, is in low resolution, needs a patch for when the size
  24620. * is limited.
  24621. * @private
  24622. * @param {fabric.Gradient} filler a fabric gradient instance
  24623. * @return {CanvasPattern} a pattern to use as fill/stroke style
  24624. */
  24625. _applyPatternGradientTransformText: function(filler) {
  24626. var pCanvas = fabric.util.createCanvasElement(), pCtx,
  24627. // TODO: verify compatibility with strokeUniform
  24628. width = this.width + this.strokeWidth, height = this.height + this.strokeWidth;
  24629. pCanvas.width = width;
  24630. pCanvas.height = height;
  24631. pCtx = pCanvas.getContext('2d');
  24632. pCtx.beginPath(); pCtx.moveTo(0, 0); pCtx.lineTo(width, 0); pCtx.lineTo(width, height);
  24633. pCtx.lineTo(0, height); pCtx.closePath();
  24634. pCtx.translate(width / 2, height / 2);
  24635. pCtx.fillStyle = filler.toLive(pCtx);
  24636. this._applyPatternGradientTransform(pCtx, filler);
  24637. pCtx.fill();
  24638. return pCtx.createPattern(pCanvas, 'no-repeat');
  24639. },
  24640. handleFiller: function(ctx, property, filler) {
  24641. var offsetX, offsetY;
  24642. if (filler.toLive) {
  24643. if (filler.gradientUnits === 'percentage' || filler.gradientTransform || filler.patternTransform) {
  24644. // need to transform gradient in a pattern.
  24645. // this is a slow process. If you are hitting this codepath, and the object
  24646. // is not using caching, you should consider switching it on.
  24647. // we need a canvas as big as the current object caching canvas.
  24648. offsetX = -this.width / 2;
  24649. offsetY = -this.height / 2;
  24650. ctx.translate(offsetX, offsetY);
  24651. ctx[property] = this._applyPatternGradientTransformText(filler);
  24652. return { offsetX: offsetX, offsetY: offsetY };
  24653. }
  24654. else {
  24655. // is a simple gradient or pattern
  24656. ctx[property] = filler.toLive(ctx, this);
  24657. return this._applyPatternGradientTransform(ctx, filler);
  24658. }
  24659. }
  24660. else {
  24661. // is a color
  24662. ctx[property] = filler;
  24663. }
  24664. return { offsetX: 0, offsetY: 0 };
  24665. },
  24666. _setStrokeStyles: function(ctx, decl) {
  24667. ctx.lineWidth = decl.strokeWidth;
  24668. ctx.lineCap = this.strokeLineCap;
  24669. ctx.lineDashOffset = this.strokeDashOffset;
  24670. ctx.lineJoin = this.strokeLineJoin;
  24671. ctx.miterLimit = this.strokeMiterLimit;
  24672. return this.handleFiller(ctx, 'strokeStyle', decl.stroke);
  24673. },
  24674. _setFillStyles: function(ctx, decl) {
  24675. return this.handleFiller(ctx, 'fillStyle', decl.fill);
  24676. },
  24677. /**
  24678. * @private
  24679. * @param {String} method
  24680. * @param {CanvasRenderingContext2D} ctx Context to render on
  24681. * @param {Number} lineIndex
  24682. * @param {Number} charIndex
  24683. * @param {String} _char
  24684. * @param {Number} left Left coordinate
  24685. * @param {Number} top Top coordinate
  24686. * @param {Number} lineHeight Height of the line
  24687. */
  24688. _renderChar: function(method, ctx, lineIndex, charIndex, _char, left, top) {
  24689. var decl = this._getStyleDeclaration(lineIndex, charIndex),
  24690. fullDecl = this.getCompleteStyleDeclaration(lineIndex, charIndex),
  24691. shouldFill = method === 'fillText' && fullDecl.fill,
  24692. shouldStroke = method === 'strokeText' && fullDecl.stroke && fullDecl.strokeWidth,
  24693. fillOffsets, strokeOffsets;
  24694. if (!shouldStroke && !shouldFill) {
  24695. return;
  24696. }
  24697. ctx.save();
  24698. shouldFill && (fillOffsets = this._setFillStyles(ctx, fullDecl));
  24699. shouldStroke && (strokeOffsets = this._setStrokeStyles(ctx, fullDecl));
  24700. ctx.font = this._getFontDeclaration(fullDecl);
  24701. if (decl && decl.textBackgroundColor) {
  24702. this._removeShadow(ctx);
  24703. }
  24704. if (decl && decl.deltaY) {
  24705. top += decl.deltaY;
  24706. }
  24707. shouldFill && ctx.fillText(_char, left - fillOffsets.offsetX, top - fillOffsets.offsetY);
  24708. shouldStroke && ctx.strokeText(_char, left - strokeOffsets.offsetX, top - strokeOffsets.offsetY);
  24709. ctx.restore();
  24710. },
  24711. /**
  24712. * Turns the character into a 'superior figure' (i.e. 'superscript')
  24713. * @param {Number} start selection start
  24714. * @param {Number} end selection end
  24715. * @returns {fabric.Text} thisArg
  24716. * @chainable
  24717. */
  24718. setSuperscript: function(start, end) {
  24719. return this._setScript(start, end, this.superscript);
  24720. },
  24721. /**
  24722. * Turns the character into an 'inferior figure' (i.e. 'subscript')
  24723. * @param {Number} start selection start
  24724. * @param {Number} end selection end
  24725. * @returns {fabric.Text} thisArg
  24726. * @chainable
  24727. */
  24728. setSubscript: function(start, end) {
  24729. return this._setScript(start, end, this.subscript);
  24730. },
  24731. /**
  24732. * Applies 'schema' at given position
  24733. * @private
  24734. * @param {Number} start selection start
  24735. * @param {Number} end selection end
  24736. * @param {Number} schema
  24737. * @returns {fabric.Text} thisArg
  24738. * @chainable
  24739. */
  24740. _setScript: function(start, end, schema) {
  24741. var loc = this.get2DCursorLocation(start, true),
  24742. fontSize = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, 'fontSize'),
  24743. dy = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, 'deltaY'),
  24744. style = { fontSize: fontSize * schema.size, deltaY: dy + fontSize * schema.baseline };
  24745. this.setSelectionStyles(style, start, end);
  24746. return this;
  24747. },
  24748. /**
  24749. * @private
  24750. * @param {Number} lineIndex index text line
  24751. * @return {Number} Line left offset
  24752. */
  24753. _getLineLeftOffset: function(lineIndex) {
  24754. var lineWidth = this.getLineWidth(lineIndex),
  24755. lineDiff = this.width - lineWidth, textAlign = this.textAlign, direction = this.direction,
  24756. isEndOfWrapping, leftOffset = 0, isEndOfWrapping = this.isEndOfWrapping(lineIndex);
  24757. if (textAlign === 'justify'
  24758. || (textAlign === 'justify-center' && !isEndOfWrapping)
  24759. || (textAlign === 'justify-right' && !isEndOfWrapping)
  24760. || (textAlign === 'justify-left' && !isEndOfWrapping)
  24761. ) {
  24762. return 0;
  24763. }
  24764. if (textAlign === 'center') {
  24765. leftOffset = lineDiff / 2;
  24766. }
  24767. if (textAlign === 'right') {
  24768. leftOffset = lineDiff;
  24769. }
  24770. if (textAlign === 'justify-center') {
  24771. leftOffset = lineDiff / 2;
  24772. }
  24773. if (textAlign === 'justify-right') {
  24774. leftOffset = lineDiff;
  24775. }
  24776. if (direction === 'rtl') {
  24777. leftOffset -= lineDiff;
  24778. }
  24779. return leftOffset;
  24780. },
  24781. /**
  24782. * @private
  24783. */
  24784. _clearCache: function() {
  24785. this.__lineWidths = [];
  24786. this.__lineHeights = [];
  24787. this.__charBounds = [];
  24788. },
  24789. /**
  24790. * @private
  24791. */
  24792. _shouldClearDimensionCache: function() {
  24793. var shouldClear = this._forceClearCache;
  24794. shouldClear || (shouldClear = this.hasStateChanged('_dimensionAffectingProps'));
  24795. if (shouldClear) {
  24796. this.dirty = true;
  24797. this._forceClearCache = false;
  24798. }
  24799. return shouldClear;
  24800. },
  24801. /**
  24802. * Measure a single line given its index. Used to calculate the initial
  24803. * text bounding box. The values are calculated and stored in __lineWidths cache.
  24804. * @private
  24805. * @param {Number} lineIndex line number
  24806. * @return {Number} Line width
  24807. */
  24808. getLineWidth: function(lineIndex) {
  24809. if (this.__lineWidths[lineIndex] !== undefined) {
  24810. return this.__lineWidths[lineIndex];
  24811. }
  24812. var lineInfo = this.measureLine(lineIndex);
  24813. var width = lineInfo.width;
  24814. this.__lineWidths[lineIndex] = width;
  24815. return width;
  24816. },
  24817. _getWidthOfCharSpacing: function() {
  24818. if (this.charSpacing !== 0) {
  24819. return this.fontSize * this.charSpacing / 1000;
  24820. }
  24821. return 0;
  24822. },
  24823. /**
  24824. * Retrieves the value of property at given character position
  24825. * @param {Number} lineIndex the line number
  24826. * @param {Number} charIndex the character number
  24827. * @param {String} property the property name
  24828. * @returns the value of 'property'
  24829. */
  24830. getValueOfPropertyAt: function(lineIndex, charIndex, property) {
  24831. var charStyle = this._getStyleDeclaration(lineIndex, charIndex);
  24832. if (charStyle && typeof charStyle[property] !== 'undefined') {
  24833. return charStyle[property];
  24834. }
  24835. return this[property];
  24836. },
  24837. /**
  24838. * @private
  24839. * @param {CanvasRenderingContext2D} ctx Context to render on
  24840. */
  24841. _renderTextDecoration: function(ctx, type) {
  24842. if (!this[type] && !this.styleHas(type)) {
  24843. return;
  24844. }
  24845. var heightOfLine, size, _size,
  24846. lineLeftOffset, dy, _dy,
  24847. line, lastDecoration,
  24848. leftOffset = this._getLeftOffset(),
  24849. topOffset = this._getTopOffset(), top,
  24850. boxStart, boxWidth, charBox, currentDecoration,
  24851. maxHeight, currentFill, lastFill, path = this.path,
  24852. charSpacing = this._getWidthOfCharSpacing(),
  24853. offsetY = this.offsets[type];
  24854. for (var i = 0, len = this._textLines.length; i < len; i++) {
  24855. heightOfLine = this.getHeightOfLine(i);
  24856. if (!this[type] && !this.styleHas(type, i)) {
  24857. topOffset += heightOfLine;
  24858. continue;
  24859. }
  24860. line = this._textLines[i];
  24861. maxHeight = heightOfLine / this.lineHeight;
  24862. lineLeftOffset = this._getLineLeftOffset(i);
  24863. boxStart = 0;
  24864. boxWidth = 0;
  24865. lastDecoration = this.getValueOfPropertyAt(i, 0, type);
  24866. lastFill = this.getValueOfPropertyAt(i, 0, 'fill');
  24867. top = topOffset + maxHeight * (1 - this._fontSizeFraction);
  24868. size = this.getHeightOfChar(i, 0);
  24869. dy = this.getValueOfPropertyAt(i, 0, 'deltaY');
  24870. for (var j = 0, jlen = line.length; j < jlen; j++) {
  24871. charBox = this.__charBounds[i][j];
  24872. currentDecoration = this.getValueOfPropertyAt(i, j, type);
  24873. currentFill = this.getValueOfPropertyAt(i, j, 'fill');
  24874. _size = this.getHeightOfChar(i, j);
  24875. _dy = this.getValueOfPropertyAt(i, j, 'deltaY');
  24876. if (path && currentDecoration && currentFill) {
  24877. ctx.save();
  24878. ctx.fillStyle = lastFill;
  24879. ctx.translate(charBox.renderLeft, charBox.renderTop);
  24880. ctx.rotate(charBox.angle);
  24881. ctx.fillRect(
  24882. -charBox.kernedWidth / 2,
  24883. offsetY * _size + _dy,
  24884. charBox.kernedWidth,
  24885. this.fontSize / 15
  24886. );
  24887. ctx.restore();
  24888. }
  24889. else if (
  24890. (currentDecoration !== lastDecoration || currentFill !== lastFill || _size !== size || _dy !== dy)
  24891. && boxWidth > 0
  24892. ) {
  24893. var drawStart = leftOffset + lineLeftOffset + boxStart;
  24894. if (this.direction === 'rtl') {
  24895. drawStart = this.width - drawStart - boxWidth;
  24896. }
  24897. if (lastDecoration && lastFill) {
  24898. ctx.fillStyle = lastFill;
  24899. ctx.fillRect(
  24900. drawStart,
  24901. top + offsetY * size + dy,
  24902. boxWidth,
  24903. this.fontSize / 15
  24904. );
  24905. }
  24906. boxStart = charBox.left;
  24907. boxWidth = charBox.width;
  24908. lastDecoration = currentDecoration;
  24909. lastFill = currentFill;
  24910. size = _size;
  24911. dy = _dy;
  24912. }
  24913. else {
  24914. boxWidth += charBox.kernedWidth;
  24915. }
  24916. }
  24917. var drawStart = leftOffset + lineLeftOffset + boxStart;
  24918. if (this.direction === 'rtl') {
  24919. drawStart = this.width - drawStart - boxWidth;
  24920. }
  24921. ctx.fillStyle = currentFill;
  24922. currentDecoration && currentFill && ctx.fillRect(
  24923. drawStart,
  24924. top + offsetY * size + dy,
  24925. boxWidth - charSpacing,
  24926. this.fontSize / 15
  24927. );
  24928. topOffset += heightOfLine;
  24929. }
  24930. // if there is text background color no
  24931. // other shadows should be casted
  24932. this._removeShadow(ctx);
  24933. },
  24934. /**
  24935. * return font declaration string for canvas context
  24936. * @param {Object} [styleObject] object
  24937. * @returns {String} font declaration formatted for canvas context.
  24938. */
  24939. _getFontDeclaration: function(styleObject, forMeasuring) {
  24940. var style = styleObject || this, family = this.fontFamily,
  24941. fontIsGeneric = fabric.Text.genericFonts.indexOf(family.toLowerCase()) > -1;
  24942. var fontFamily = family === undefined ||
  24943. family.indexOf('\'') > -1 || family.indexOf(',') > -1 ||
  24944. family.indexOf('"') > -1 || fontIsGeneric
  24945. ? style.fontFamily : '"' + style.fontFamily + '"';
  24946. return [
  24947. // node-canvas needs "weight style", while browsers need "style weight"
  24948. // verify if this can be fixed in JSDOM
  24949. (fabric.isLikelyNode ? style.fontWeight : style.fontStyle),
  24950. (fabric.isLikelyNode ? style.fontStyle : style.fontWeight),
  24951. forMeasuring ? this.CACHE_FONT_SIZE + 'px' : style.fontSize + 'px',
  24952. fontFamily
  24953. ].join(' ');
  24954. },
  24955. /**
  24956. * Renders text instance on a specified context
  24957. * @param {CanvasRenderingContext2D} ctx Context to render on
  24958. */
  24959. render: function(ctx) {
  24960. // do not render if object is not visible
  24961. if (!this.visible) {
  24962. return;
  24963. }
  24964. if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {
  24965. return;
  24966. }
  24967. if (this._shouldClearDimensionCache()) {
  24968. this.initDimensions();
  24969. }
  24970. this.callSuper('render', ctx);
  24971. },
  24972. /**
  24973. * Returns the text as an array of lines.
  24974. * @param {String} text text to split
  24975. * @returns {Array} Lines in the text
  24976. */
  24977. _splitTextIntoLines: function(text) {
  24978. var lines = text.split(this._reNewline),
  24979. newLines = new Array(lines.length),
  24980. newLine = ['\n'],
  24981. newText = [];
  24982. for (var i = 0; i < lines.length; i++) {
  24983. newLines[i] = fabric.util.string.graphemeSplit(lines[i]);
  24984. newText = newText.concat(newLines[i], newLine);
  24985. }
  24986. newText.pop();
  24987. return { _unwrappedLines: newLines, lines: lines, graphemeText: newText, graphemeLines: newLines };
  24988. },
  24989. /**
  24990. * Returns object representation of an instance
  24991. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  24992. * @return {Object} Object representation of an instance
  24993. */
  24994. toObject: function(propertiesToInclude) {
  24995. var allProperties = additionalProps.concat(propertiesToInclude);
  24996. var obj = this.callSuper('toObject', allProperties);
  24997. obj.styles = fabric.util.stylesToArray(this.styles, this.text);
  24998. if (obj.path) {
  24999. obj.path = this.path.toObject();
  25000. }
  25001. return obj;
  25002. },
  25003. /**
  25004. * 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()`.
  25005. * @param {String|Object} key Property name or object (if object, iterate over the object properties)
  25006. * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
  25007. * @return {fabric.Object} thisArg
  25008. * @chainable
  25009. */
  25010. set: function(key, value) {
  25011. this.callSuper('set', key, value);
  25012. var needsDims = false;
  25013. var isAddingPath = false;
  25014. if (typeof key === 'object') {
  25015. for (var _key in key) {
  25016. if (_key === 'path') {
  25017. this.setPathInfo();
  25018. }
  25019. needsDims = needsDims || this._dimensionAffectingProps.indexOf(_key) !== -1;
  25020. isAddingPath = isAddingPath || _key === 'path';
  25021. }
  25022. }
  25023. else {
  25024. needsDims = this._dimensionAffectingProps.indexOf(key) !== -1;
  25025. isAddingPath = key === 'path';
  25026. }
  25027. if (isAddingPath) {
  25028. this.setPathInfo();
  25029. }
  25030. if (needsDims) {
  25031. this.initDimensions();
  25032. this.setCoords();
  25033. }
  25034. return this;
  25035. },
  25036. /**
  25037. * Returns complexity of an instance
  25038. * @return {Number} complexity
  25039. */
  25040. complexity: function() {
  25041. return 1;
  25042. }
  25043. });
  25044. /* _FROM_SVG_START_ */
  25045. /**
  25046. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Text.fromElement})
  25047. * @static
  25048. * @memberOf fabric.Text
  25049. * @see: http://www.w3.org/TR/SVG/text.html#TextElement
  25050. */
  25051. fabric.Text.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(
  25052. 'x y dx dy font-family font-style font-weight font-size letter-spacing text-decoration text-anchor'.split(' '));
  25053. /**
  25054. * Default SVG font size
  25055. * @static
  25056. * @memberOf fabric.Text
  25057. */
  25058. fabric.Text.DEFAULT_SVG_FONT_SIZE = 16;
  25059. /**
  25060. * Returns fabric.Text instance from an SVG element (<b>not yet implemented</b>)
  25061. * @static
  25062. * @memberOf fabric.Text
  25063. * @param {SVGElement} element Element to parse
  25064. * @param {Function} callback callback function invoked after parsing
  25065. * @param {Object} [options] Options object
  25066. */
  25067. fabric.Text.fromElement = function(element, callback, options) {
  25068. if (!element) {
  25069. return callback(null);
  25070. }
  25071. var parsedAttributes = fabric.parseAttributes(element, fabric.Text.ATTRIBUTE_NAMES),
  25072. parsedAnchor = parsedAttributes.textAnchor || 'left';
  25073. options = fabric.util.object.extend((options ? clone(options) : { }), parsedAttributes);
  25074. options.top = options.top || 0;
  25075. options.left = options.left || 0;
  25076. if (parsedAttributes.textDecoration) {
  25077. var textDecoration = parsedAttributes.textDecoration;
  25078. if (textDecoration.indexOf('underline') !== -1) {
  25079. options.underline = true;
  25080. }
  25081. if (textDecoration.indexOf('overline') !== -1) {
  25082. options.overline = true;
  25083. }
  25084. if (textDecoration.indexOf('line-through') !== -1) {
  25085. options.linethrough = true;
  25086. }
  25087. delete options.textDecoration;
  25088. }
  25089. if ('dx' in parsedAttributes) {
  25090. options.left += parsedAttributes.dx;
  25091. }
  25092. if ('dy' in parsedAttributes) {
  25093. options.top += parsedAttributes.dy;
  25094. }
  25095. if (!('fontSize' in options)) {
  25096. options.fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
  25097. }
  25098. var textContent = '';
  25099. // The XML is not properly parsed in IE9 so a workaround to get
  25100. // textContent is through firstChild.data. Another workaround would be
  25101. // to convert XML loaded from a file to be converted using DOMParser (same way loadSVGFromString() does)
  25102. if (!('textContent' in element)) {
  25103. if ('firstChild' in element && element.firstChild !== null) {
  25104. if ('data' in element.firstChild && element.firstChild.data !== null) {
  25105. textContent = element.firstChild.data;
  25106. }
  25107. }
  25108. }
  25109. else {
  25110. textContent = element.textContent;
  25111. }
  25112. textContent = textContent.replace(/^\s+|\s+$|\n+/g, '').replace(/\s+/g, ' ');
  25113. var originalStrokeWidth = options.strokeWidth;
  25114. options.strokeWidth = 0;
  25115. var text = new fabric.Text(textContent, options),
  25116. textHeightScaleFactor = text.getScaledHeight() / text.height,
  25117. lineHeightDiff = (text.height + text.strokeWidth) * text.lineHeight - text.height,
  25118. scaledDiff = lineHeightDiff * textHeightScaleFactor,
  25119. textHeight = text.getScaledHeight() + scaledDiff,
  25120. offX = 0;
  25121. /*
  25122. Adjust positioning:
  25123. x/y attributes in SVG correspond to the bottom-left corner of text bounding box
  25124. fabric output by default at top, left.
  25125. */
  25126. if (parsedAnchor === 'center') {
  25127. offX = text.getScaledWidth() / 2;
  25128. }
  25129. if (parsedAnchor === 'right') {
  25130. offX = text.getScaledWidth();
  25131. }
  25132. text.set({
  25133. left: text.left - offX,
  25134. top: text.top - (textHeight - text.fontSize * (0.07 + text._fontSizeFraction)) / text.lineHeight,
  25135. strokeWidth: typeof originalStrokeWidth !== 'undefined' ? originalStrokeWidth : 1,
  25136. });
  25137. callback(text);
  25138. };
  25139. /* _FROM_SVG_END_ */
  25140. /**
  25141. * Returns fabric.Text instance from an object representation
  25142. * @static
  25143. * @memberOf fabric.Text
  25144. * @param {Object} object plain js Object to create an instance from
  25145. * @param {Function} [callback] Callback to invoke when an fabric.Text instance is created
  25146. */
  25147. fabric.Text.fromObject = function(object, callback) {
  25148. var objectCopy = clone(object), path = object.path;
  25149. delete objectCopy.path;
  25150. return fabric.Object._fromObject('Text', objectCopy, function(textInstance) {
  25151. textInstance.styles = fabric.util.stylesFromArray(object.styles, object.text);
  25152. if (path) {
  25153. fabric.Object._fromObject('Path', path, function(pathInstance) {
  25154. textInstance.set('path', pathInstance);
  25155. callback(textInstance);
  25156. }, 'path');
  25157. }
  25158. else {
  25159. callback(textInstance);
  25160. }
  25161. }, 'text');
  25162. };
  25163. fabric.Text.genericFonts = ['sans-serif', 'serif', 'cursive', 'fantasy', 'monospace'];
  25164. fabric.util.createAccessors && fabric.util.createAccessors(fabric.Text);
  25165. })(typeof exports !== 'undefined' ? exports : this);
  25166. (function() {
  25167. fabric.util.object.extend(fabric.Text.prototype, /** @lends fabric.Text.prototype */ {
  25168. /**
  25169. * Returns true if object has no styling or no styling in a line
  25170. * @param {Number} lineIndex , lineIndex is on wrapped lines.
  25171. * @return {Boolean}
  25172. */
  25173. isEmptyStyles: function(lineIndex) {
  25174. if (!this.styles) {
  25175. return true;
  25176. }
  25177. if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {
  25178. return true;
  25179. }
  25180. var obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };
  25181. for (var p1 in obj) {
  25182. for (var p2 in obj[p1]) {
  25183. // eslint-disable-next-line no-unused-vars
  25184. for (var p3 in obj[p1][p2]) {
  25185. return false;
  25186. }
  25187. }
  25188. }
  25189. return true;
  25190. },
  25191. /**
  25192. * Returns true if object has a style property or has it ina specified line
  25193. * This function is used to detect if a text will use a particular property or not.
  25194. * @param {String} property to check for
  25195. * @param {Number} lineIndex to check the style on
  25196. * @return {Boolean}
  25197. */
  25198. styleHas: function(property, lineIndex) {
  25199. if (!this.styles || !property || property === '') {
  25200. return false;
  25201. }
  25202. if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {
  25203. return false;
  25204. }
  25205. var obj = typeof lineIndex === 'undefined' ? this.styles : { 0: this.styles[lineIndex] };
  25206. // eslint-disable-next-line
  25207. for (var p1 in obj) {
  25208. // eslint-disable-next-line
  25209. for (var p2 in obj[p1]) {
  25210. if (typeof obj[p1][p2][property] !== 'undefined') {
  25211. return true;
  25212. }
  25213. }
  25214. }
  25215. return false;
  25216. },
  25217. /**
  25218. * Check if characters in a text have a value for a property
  25219. * whose value matches the textbox's value for that property. If so,
  25220. * the character-level property is deleted. If the character
  25221. * has no other properties, then it is also deleted. Finally,
  25222. * if the line containing that character has no other characters
  25223. * then it also is deleted.
  25224. *
  25225. * @param {string} property The property to compare between characters and text.
  25226. */
  25227. cleanStyle: function(property) {
  25228. if (!this.styles || !property || property === '') {
  25229. return false;
  25230. }
  25231. var obj = this.styles, stylesCount = 0, letterCount, stylePropertyValue,
  25232. allStyleObjectPropertiesMatch = true, graphemeCount = 0, styleObject;
  25233. // eslint-disable-next-line
  25234. for (var p1 in obj) {
  25235. letterCount = 0;
  25236. // eslint-disable-next-line
  25237. for (var p2 in obj[p1]) {
  25238. var styleObject = obj[p1][p2],
  25239. stylePropertyHasBeenSet = styleObject.hasOwnProperty(property);
  25240. stylesCount++;
  25241. if (stylePropertyHasBeenSet) {
  25242. if (!stylePropertyValue) {
  25243. stylePropertyValue = styleObject[property];
  25244. }
  25245. else if (styleObject[property] !== stylePropertyValue) {
  25246. allStyleObjectPropertiesMatch = false;
  25247. }
  25248. if (styleObject[property] === this[property]) {
  25249. delete styleObject[property];
  25250. }
  25251. }
  25252. else {
  25253. allStyleObjectPropertiesMatch = false;
  25254. }
  25255. if (Object.keys(styleObject).length !== 0) {
  25256. letterCount++;
  25257. }
  25258. else {
  25259. delete obj[p1][p2];
  25260. }
  25261. }
  25262. if (letterCount === 0) {
  25263. delete obj[p1];
  25264. }
  25265. }
  25266. // if every grapheme has the same style set then
  25267. // delete those styles and set it on the parent
  25268. for (var i = 0; i < this._textLines.length; i++) {
  25269. graphemeCount += this._textLines[i].length;
  25270. }
  25271. if (allStyleObjectPropertiesMatch && stylesCount === graphemeCount) {
  25272. this[property] = stylePropertyValue;
  25273. this.removeStyle(property);
  25274. }
  25275. },
  25276. /**
  25277. * Remove a style property or properties from all individual character styles
  25278. * in a text object. Deletes the character style object if it contains no other style
  25279. * props. Deletes a line style object if it contains no other character styles.
  25280. *
  25281. * @param {String} props The property to remove from character styles.
  25282. */
  25283. removeStyle: function(property) {
  25284. if (!this.styles || !property || property === '') {
  25285. return;
  25286. }
  25287. var obj = this.styles, line, lineNum, charNum;
  25288. for (lineNum in obj) {
  25289. line = obj[lineNum];
  25290. for (charNum in line) {
  25291. delete line[charNum][property];
  25292. if (Object.keys(line[charNum]).length === 0) {
  25293. delete line[charNum];
  25294. }
  25295. }
  25296. if (Object.keys(line).length === 0) {
  25297. delete obj[lineNum];
  25298. }
  25299. }
  25300. },
  25301. /**
  25302. * @private
  25303. */
  25304. _extendStyles: function(index, styles) {
  25305. var loc = this.get2DCursorLocation(index);
  25306. if (!this._getLineStyle(loc.lineIndex)) {
  25307. this._setLineStyle(loc.lineIndex);
  25308. }
  25309. if (!this._getStyleDeclaration(loc.lineIndex, loc.charIndex)) {
  25310. this._setStyleDeclaration(loc.lineIndex, loc.charIndex, {});
  25311. }
  25312. fabric.util.object.extend(this._getStyleDeclaration(loc.lineIndex, loc.charIndex), styles);
  25313. },
  25314. /**
  25315. * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start)
  25316. * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used.
  25317. * @param {Boolean} [skipWrapping] consider the location for unwrapped lines. useful to manage styles.
  25318. */
  25319. get2DCursorLocation: function(selectionStart, skipWrapping) {
  25320. if (typeof selectionStart === 'undefined') {
  25321. selectionStart = this.selectionStart;
  25322. }
  25323. var lines = skipWrapping ? this._unwrappedTextLines : this._textLines,
  25324. len = lines.length;
  25325. for (var i = 0; i < len; i++) {
  25326. if (selectionStart <= lines[i].length) {
  25327. return {
  25328. lineIndex: i,
  25329. charIndex: selectionStart
  25330. };
  25331. }
  25332. selectionStart -= lines[i].length + this.missingNewlineOffset(i);
  25333. }
  25334. return {
  25335. lineIndex: i - 1,
  25336. charIndex: lines[i - 1].length < selectionStart ? lines[i - 1].length : selectionStart
  25337. };
  25338. },
  25339. /**
  25340. * Gets style of a current selection/cursor (at the start position)
  25341. * if startIndex or endIndex are not provided, selectionStart or selectionEnd will be used.
  25342. * @param {Number} [startIndex] Start index to get styles at
  25343. * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1
  25344. * @param {Boolean} [complete] get full style or not
  25345. * @return {Array} styles an array with one, zero or more Style objects
  25346. */
  25347. getSelectionStyles: function(startIndex, endIndex, complete) {
  25348. if (typeof startIndex === 'undefined') {
  25349. startIndex = this.selectionStart || 0;
  25350. }
  25351. if (typeof endIndex === 'undefined') {
  25352. endIndex = this.selectionEnd || startIndex;
  25353. }
  25354. var styles = [];
  25355. for (var i = startIndex; i < endIndex; i++) {
  25356. styles.push(this.getStyleAtPosition(i, complete));
  25357. }
  25358. return styles;
  25359. },
  25360. /**
  25361. * Gets style of a current selection/cursor position
  25362. * @param {Number} position to get styles at
  25363. * @param {Boolean} [complete] full style if true
  25364. * @return {Object} style Style object at a specified index
  25365. * @private
  25366. */
  25367. getStyleAtPosition: function(position, complete) {
  25368. var loc = this.get2DCursorLocation(position),
  25369. style = complete ? this.getCompleteStyleDeclaration(loc.lineIndex, loc.charIndex) :
  25370. this._getStyleDeclaration(loc.lineIndex, loc.charIndex);
  25371. return style || {};
  25372. },
  25373. /**
  25374. * Sets style of a current selection, if no selection exist, do not set anything.
  25375. * @param {Object} [styles] Styles object
  25376. * @param {Number} [startIndex] Start index to get styles at
  25377. * @param {Number} [endIndex] End index to get styles at, if not specified selectionEnd or startIndex + 1
  25378. * @return {fabric.IText} thisArg
  25379. * @chainable
  25380. */
  25381. setSelectionStyles: function(styles, startIndex, endIndex) {
  25382. if (typeof startIndex === 'undefined') {
  25383. startIndex = this.selectionStart || 0;
  25384. }
  25385. if (typeof endIndex === 'undefined') {
  25386. endIndex = this.selectionEnd || startIndex;
  25387. }
  25388. for (var i = startIndex; i < endIndex; i++) {
  25389. this._extendStyles(i, styles);
  25390. }
  25391. /* not included in _extendStyles to avoid clearing cache more than once */
  25392. this._forceClearCache = true;
  25393. return this;
  25394. },
  25395. /**
  25396. * get the reference, not a clone, of the style object for a given character
  25397. * @param {Number} lineIndex
  25398. * @param {Number} charIndex
  25399. * @return {Object} style object
  25400. */
  25401. _getStyleDeclaration: function(lineIndex, charIndex) {
  25402. var lineStyle = this.styles && this.styles[lineIndex];
  25403. if (!lineStyle) {
  25404. return null;
  25405. }
  25406. return lineStyle[charIndex];
  25407. },
  25408. /**
  25409. * return a new object that contains all the style property for a character
  25410. * the object returned is newly created
  25411. * @param {Number} lineIndex of the line where the character is
  25412. * @param {Number} charIndex position of the character on the line
  25413. * @return {Object} style object
  25414. */
  25415. getCompleteStyleDeclaration: function(lineIndex, charIndex) {
  25416. var style = this._getStyleDeclaration(lineIndex, charIndex) || { },
  25417. styleObject = { }, prop;
  25418. for (var i = 0; i < this._styleProperties.length; i++) {
  25419. prop = this._styleProperties[i];
  25420. styleObject[prop] = typeof style[prop] === 'undefined' ? this[prop] : style[prop];
  25421. }
  25422. return styleObject;
  25423. },
  25424. /**
  25425. * @param {Number} lineIndex
  25426. * @param {Number} charIndex
  25427. * @param {Object} style
  25428. * @private
  25429. */
  25430. _setStyleDeclaration: function(lineIndex, charIndex, style) {
  25431. this.styles[lineIndex][charIndex] = style;
  25432. },
  25433. /**
  25434. *
  25435. * @param {Number} lineIndex
  25436. * @param {Number} charIndex
  25437. * @private
  25438. */
  25439. _deleteStyleDeclaration: function(lineIndex, charIndex) {
  25440. delete this.styles[lineIndex][charIndex];
  25441. },
  25442. /**
  25443. * @param {Number} lineIndex
  25444. * @return {Boolean} if the line exists or not
  25445. * @private
  25446. */
  25447. _getLineStyle: function(lineIndex) {
  25448. return !!this.styles[lineIndex];
  25449. },
  25450. /**
  25451. * Set the line style to an empty object so that is initialized
  25452. * @param {Number} lineIndex
  25453. * @private
  25454. */
  25455. _setLineStyle: function(lineIndex) {
  25456. this.styles[lineIndex] = {};
  25457. },
  25458. /**
  25459. * @param {Number} lineIndex
  25460. * @private
  25461. */
  25462. _deleteLineStyle: function(lineIndex) {
  25463. delete this.styles[lineIndex];
  25464. }
  25465. });
  25466. })();
  25467. (function() {
  25468. function parseDecoration(object) {
  25469. if (object.textDecoration) {
  25470. object.textDecoration.indexOf('underline') > -1 && (object.underline = true);
  25471. object.textDecoration.indexOf('line-through') > -1 && (object.linethrough = true);
  25472. object.textDecoration.indexOf('overline') > -1 && (object.overline = true);
  25473. delete object.textDecoration;
  25474. }
  25475. }
  25476. /**
  25477. * IText class (introduced in <b>v1.4</b>) Events are also fired with "text:"
  25478. * prefix when observing canvas.
  25479. * @class fabric.IText
  25480. * @extends fabric.Text
  25481. * @mixes fabric.Observable
  25482. *
  25483. * @fires changed
  25484. * @fires selection:changed
  25485. * @fires editing:entered
  25486. * @fires editing:exited
  25487. *
  25488. * @return {fabric.IText} thisArg
  25489. * @see {@link fabric.IText#initialize} for constructor definition
  25490. *
  25491. * <p>Supported key combinations:</p>
  25492. * <pre>
  25493. * Move cursor: left, right, up, down
  25494. * Select character: shift + left, shift + right
  25495. * Select text vertically: shift + up, shift + down
  25496. * Move cursor by word: alt + left, alt + right
  25497. * Select words: shift + alt + left, shift + alt + right
  25498. * Move cursor to line start/end: cmd + left, cmd + right or home, end
  25499. * Select till start/end of line: cmd + shift + left, cmd + shift + right or shift + home, shift + end
  25500. * Jump to start/end of text: cmd + up, cmd + down
  25501. * Select till start/end of text: cmd + shift + up, cmd + shift + down or shift + pgUp, shift + pgDown
  25502. * Delete character: backspace
  25503. * Delete word: alt + backspace
  25504. * Delete line: cmd + backspace
  25505. * Forward delete: delete
  25506. * Copy text: ctrl/cmd + c
  25507. * Paste text: ctrl/cmd + v
  25508. * Cut text: ctrl/cmd + x
  25509. * Select entire text: ctrl/cmd + a
  25510. * Quit editing tab or esc
  25511. * </pre>
  25512. *
  25513. * <p>Supported mouse/touch combination</p>
  25514. * <pre>
  25515. * Position cursor: click/touch
  25516. * Create selection: click/touch & drag
  25517. * Create selection: click & shift + click
  25518. * Select word: double click
  25519. * Select line: triple click
  25520. * </pre>
  25521. */
  25522. fabric.IText = fabric.util.createClass(fabric.Text, fabric.Observable, /** @lends fabric.IText.prototype */ {
  25523. /**
  25524. * Type of an object
  25525. * @type String
  25526. * @default
  25527. */
  25528. type: 'i-text',
  25529. /**
  25530. * Index where text selection starts (or where cursor is when there is no selection)
  25531. * @type Number
  25532. * @default
  25533. */
  25534. selectionStart: 0,
  25535. /**
  25536. * Index where text selection ends
  25537. * @type Number
  25538. * @default
  25539. */
  25540. selectionEnd: 0,
  25541. /**
  25542. * Color of text selection
  25543. * @type String
  25544. * @default
  25545. */
  25546. selectionColor: 'rgba(17,119,255,0.3)',
  25547. /**
  25548. * Indicates whether text is in editing mode
  25549. * @type Boolean
  25550. * @default
  25551. */
  25552. isEditing: false,
  25553. /**
  25554. * Indicates whether a text can be edited
  25555. * @type Boolean
  25556. * @default
  25557. */
  25558. editable: true,
  25559. /**
  25560. * Border color of text object while it's in editing mode
  25561. * @type String
  25562. * @default
  25563. */
  25564. editingBorderColor: 'rgba(102,153,255,0.25)',
  25565. /**
  25566. * Width of cursor (in px)
  25567. * @type Number
  25568. * @default
  25569. */
  25570. cursorWidth: 2,
  25571. /**
  25572. * Color of text cursor color in editing mode.
  25573. * if not set (default) will take color from the text.
  25574. * if set to a color value that fabric can understand, it will
  25575. * be used instead of the color of the text at the current position.
  25576. * @type String
  25577. * @default
  25578. */
  25579. cursorColor: '',
  25580. /**
  25581. * Delay between cursor blink (in ms)
  25582. * @type Number
  25583. * @default
  25584. */
  25585. cursorDelay: 1000,
  25586. /**
  25587. * Duration of cursor fadein (in ms)
  25588. * @type Number
  25589. * @default
  25590. */
  25591. cursorDuration: 600,
  25592. /**
  25593. * Indicates whether internal text char widths can be cached
  25594. * @type Boolean
  25595. * @default
  25596. */
  25597. caching: true,
  25598. /**
  25599. * DOM container to append the hiddenTextarea.
  25600. * An alternative to attaching to the document.body.
  25601. * Useful to reduce laggish redraw of the full document.body tree and
  25602. * also with modals event capturing that won't let the textarea take focus.
  25603. * @type HTMLElement
  25604. * @default
  25605. */
  25606. hiddenTextareaContainer: null,
  25607. /**
  25608. * @private
  25609. */
  25610. _reSpace: /\s|\n/,
  25611. /**
  25612. * @private
  25613. */
  25614. _currentCursorOpacity: 0,
  25615. /**
  25616. * @private
  25617. */
  25618. _selectionDirection: null,
  25619. /**
  25620. * @private
  25621. */
  25622. _abortCursorAnimation: false,
  25623. /**
  25624. * @private
  25625. */
  25626. __widthOfSpace: [],
  25627. /**
  25628. * Helps determining when the text is in composition, so that the cursor
  25629. * rendering is altered.
  25630. */
  25631. inCompositionMode: false,
  25632. /**
  25633. * Constructor
  25634. * @param {String} text Text string
  25635. * @param {Object} [options] Options object
  25636. * @return {fabric.IText} thisArg
  25637. */
  25638. initialize: function(text, options) {
  25639. this.callSuper('initialize', text, options);
  25640. this.initBehavior();
  25641. },
  25642. /**
  25643. * Sets selection start (left boundary of a selection)
  25644. * @param {Number} index Index to set selection start to
  25645. */
  25646. setSelectionStart: function(index) {
  25647. index = Math.max(index, 0);
  25648. this._updateAndFire('selectionStart', index);
  25649. },
  25650. /**
  25651. * Sets selection end (right boundary of a selection)
  25652. * @param {Number} index Index to set selection end to
  25653. */
  25654. setSelectionEnd: function(index) {
  25655. index = Math.min(index, this.text.length);
  25656. this._updateAndFire('selectionEnd', index);
  25657. },
  25658. /**
  25659. * @private
  25660. * @param {String} property 'selectionStart' or 'selectionEnd'
  25661. * @param {Number} index new position of property
  25662. */
  25663. _updateAndFire: function(property, index) {
  25664. if (this[property] !== index) {
  25665. this._fireSelectionChanged();
  25666. this[property] = index;
  25667. }
  25668. this._updateTextarea();
  25669. },
  25670. /**
  25671. * Fires the even of selection changed
  25672. * @private
  25673. */
  25674. _fireSelectionChanged: function() {
  25675. this.fire('selection:changed');
  25676. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  25677. },
  25678. /**
  25679. * Initialize text dimensions. Render all text on given context
  25680. * or on a offscreen canvas to get the text width with measureText.
  25681. * Updates this.width and this.height with the proper values.
  25682. * Does not return dimensions.
  25683. * @private
  25684. */
  25685. initDimensions: function() {
  25686. this.isEditing && this.initDelayedCursor();
  25687. this.clearContextTop();
  25688. this.callSuper('initDimensions');
  25689. },
  25690. /**
  25691. * @private
  25692. * @param {CanvasRenderingContext2D} ctx Context to render on
  25693. */
  25694. render: function(ctx) {
  25695. this.clearContextTop();
  25696. this.callSuper('render', ctx);
  25697. // clear the cursorOffsetCache, so we ensure to calculate once per renderCursor
  25698. // the correct position but not at every cursor animation.
  25699. this.cursorOffsetCache = { };
  25700. this.renderCursorOrSelection();
  25701. },
  25702. /**
  25703. * @private
  25704. * @param {CanvasRenderingContext2D} ctx Context to render on
  25705. */
  25706. _render: function(ctx) {
  25707. this.callSuper('_render', ctx);
  25708. },
  25709. /**
  25710. * Prepare and clean the contextTop
  25711. */
  25712. clearContextTop: function(skipRestore) {
  25713. if (!this.isEditing || !this.canvas || !this.canvas.contextTop) {
  25714. return;
  25715. }
  25716. var ctx = this.canvas.contextTop, v = this.canvas.viewportTransform;
  25717. ctx.save();
  25718. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  25719. this.transform(ctx);
  25720. this._clearTextArea(ctx);
  25721. skipRestore || ctx.restore();
  25722. },
  25723. /**
  25724. * Renders cursor or selection (depending on what exists)
  25725. * it does on the contextTop. If contextTop is not available, do nothing.
  25726. */
  25727. renderCursorOrSelection: function() {
  25728. if (!this.isEditing || !this.canvas || !this.canvas.contextTop) {
  25729. return;
  25730. }
  25731. var boundaries = this._getCursorBoundaries(),
  25732. ctx = this.canvas.contextTop;
  25733. this.clearContextTop(true);
  25734. if (this.selectionStart === this.selectionEnd) {
  25735. this.renderCursor(boundaries, ctx);
  25736. }
  25737. else {
  25738. this.renderSelection(boundaries, ctx);
  25739. }
  25740. ctx.restore();
  25741. },
  25742. _clearTextArea: function(ctx) {
  25743. // we add 4 pixel, to be sure to do not leave any pixel out
  25744. var width = this.width + 4, height = this.height + 4;
  25745. ctx.clearRect(-width / 2, -height / 2, width, height);
  25746. },
  25747. /**
  25748. * Returns cursor boundaries (left, top, leftOffset, topOffset)
  25749. * @private
  25750. * @param {Array} chars Array of characters
  25751. * @param {String} typeOfBoundaries
  25752. */
  25753. _getCursorBoundaries: function(position) {
  25754. // left/top are left/top of entire text box
  25755. // leftOffset/topOffset are offset from that left/top point of a text box
  25756. if (typeof position === 'undefined') {
  25757. position = this.selectionStart;
  25758. }
  25759. var left = this._getLeftOffset(),
  25760. top = this._getTopOffset(),
  25761. offsets = this._getCursorBoundariesOffsets(position);
  25762. return {
  25763. left: left,
  25764. top: top,
  25765. leftOffset: offsets.left,
  25766. topOffset: offsets.top
  25767. };
  25768. },
  25769. /**
  25770. * @private
  25771. */
  25772. _getCursorBoundariesOffsets: function(position) {
  25773. if (this.cursorOffsetCache && 'top' in this.cursorOffsetCache) {
  25774. return this.cursorOffsetCache;
  25775. }
  25776. var lineLeftOffset,
  25777. lineIndex,
  25778. charIndex,
  25779. topOffset = 0,
  25780. leftOffset = 0,
  25781. boundaries,
  25782. cursorPosition = this.get2DCursorLocation(position);
  25783. charIndex = cursorPosition.charIndex;
  25784. lineIndex = cursorPosition.lineIndex;
  25785. for (var i = 0; i < lineIndex; i++) {
  25786. topOffset += this.getHeightOfLine(i);
  25787. }
  25788. lineLeftOffset = this._getLineLeftOffset(lineIndex);
  25789. var bound = this.__charBounds[lineIndex][charIndex];
  25790. bound && (leftOffset = bound.left);
  25791. if (this.charSpacing !== 0 && charIndex === this._textLines[lineIndex].length) {
  25792. leftOffset -= this._getWidthOfCharSpacing();
  25793. }
  25794. boundaries = {
  25795. top: topOffset,
  25796. left: lineLeftOffset + (leftOffset > 0 ? leftOffset : 0),
  25797. };
  25798. if (this.direction === 'rtl') {
  25799. boundaries.left *= -1;
  25800. }
  25801. this.cursorOffsetCache = boundaries;
  25802. return this.cursorOffsetCache;
  25803. },
  25804. /**
  25805. * Renders cursor
  25806. * @param {Object} boundaries
  25807. * @param {CanvasRenderingContext2D} ctx transformed context to draw on
  25808. */
  25809. renderCursor: function(boundaries, ctx) {
  25810. var cursorLocation = this.get2DCursorLocation(),
  25811. lineIndex = cursorLocation.lineIndex,
  25812. charIndex = cursorLocation.charIndex > 0 ? cursorLocation.charIndex - 1 : 0,
  25813. charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, 'fontSize'),
  25814. multiplier = this.scaleX * this.canvas.getZoom(),
  25815. cursorWidth = this.cursorWidth / multiplier,
  25816. topOffset = boundaries.topOffset,
  25817. dy = this.getValueOfPropertyAt(lineIndex, charIndex, 'deltaY');
  25818. topOffset += (1 - this._fontSizeFraction) * this.getHeightOfLine(lineIndex) / this.lineHeight
  25819. - charHeight * (1 - this._fontSizeFraction);
  25820. if (this.inCompositionMode) {
  25821. this.renderSelection(boundaries, ctx);
  25822. }
  25823. ctx.fillStyle = this.cursorColor || this.getValueOfPropertyAt(lineIndex, charIndex, 'fill');
  25824. ctx.globalAlpha = this.__isMousedown ? 1 : this._currentCursorOpacity;
  25825. ctx.fillRect(
  25826. boundaries.left + boundaries.leftOffset - cursorWidth / 2,
  25827. topOffset + boundaries.top + dy,
  25828. cursorWidth,
  25829. charHeight);
  25830. },
  25831. /**
  25832. * Renders text selection
  25833. * @param {Object} boundaries Object with left/top/leftOffset/topOffset
  25834. * @param {CanvasRenderingContext2D} ctx transformed context to draw on
  25835. */
  25836. renderSelection: function(boundaries, ctx) {
  25837. var selectionStart = this.inCompositionMode ? this.hiddenTextarea.selectionStart : this.selectionStart,
  25838. selectionEnd = this.inCompositionMode ? this.hiddenTextarea.selectionEnd : this.selectionEnd,
  25839. isJustify = this.textAlign.indexOf('justify') !== -1,
  25840. start = this.get2DCursorLocation(selectionStart),
  25841. end = this.get2DCursorLocation(selectionEnd),
  25842. startLine = start.lineIndex,
  25843. endLine = end.lineIndex,
  25844. startChar = start.charIndex < 0 ? 0 : start.charIndex,
  25845. endChar = end.charIndex < 0 ? 0 : end.charIndex;
  25846. for (var i = startLine; i <= endLine; i++) {
  25847. var lineOffset = this._getLineLeftOffset(i) || 0,
  25848. lineHeight = this.getHeightOfLine(i),
  25849. realLineHeight = 0, boxStart = 0, boxEnd = 0;
  25850. if (i === startLine) {
  25851. boxStart = this.__charBounds[startLine][startChar].left;
  25852. }
  25853. if (i >= startLine && i < endLine) {
  25854. boxEnd = isJustify && !this.isEndOfWrapping(i) ? this.width : this.getLineWidth(i) || 5; // WTF is this 5?
  25855. }
  25856. else if (i === endLine) {
  25857. if (endChar === 0) {
  25858. boxEnd = this.__charBounds[endLine][endChar].left;
  25859. }
  25860. else {
  25861. var charSpacing = this._getWidthOfCharSpacing();
  25862. boxEnd = this.__charBounds[endLine][endChar - 1].left
  25863. + this.__charBounds[endLine][endChar - 1].width - charSpacing;
  25864. }
  25865. }
  25866. realLineHeight = lineHeight;
  25867. if (this.lineHeight < 1 || (i === endLine && this.lineHeight > 1)) {
  25868. lineHeight /= this.lineHeight;
  25869. }
  25870. var drawStart = boundaries.left + lineOffset + boxStart,
  25871. drawWidth = boxEnd - boxStart,
  25872. drawHeight = lineHeight, extraTop = 0;
  25873. if (this.inCompositionMode) {
  25874. ctx.fillStyle = this.compositionColor || 'black';
  25875. drawHeight = 1;
  25876. extraTop = lineHeight;
  25877. }
  25878. else {
  25879. ctx.fillStyle = this.selectionColor;
  25880. }
  25881. if (this.direction === 'rtl') {
  25882. drawStart = this.width - drawStart - drawWidth;
  25883. }
  25884. ctx.fillRect(
  25885. drawStart,
  25886. boundaries.top + boundaries.topOffset + extraTop,
  25887. drawWidth,
  25888. drawHeight);
  25889. boundaries.topOffset += realLineHeight;
  25890. }
  25891. },
  25892. /**
  25893. * High level function to know the height of the cursor.
  25894. * the currentChar is the one that precedes the cursor
  25895. * Returns fontSize of char at the current cursor
  25896. * Unused from the library, is for the end user
  25897. * @return {Number} Character font size
  25898. */
  25899. getCurrentCharFontSize: function() {
  25900. var cp = this._getCurrentCharIndex();
  25901. return this.getValueOfPropertyAt(cp.l, cp.c, 'fontSize');
  25902. },
  25903. /**
  25904. * High level function to know the color of the cursor.
  25905. * the currentChar is the one that precedes the cursor
  25906. * Returns color (fill) of char at the current cursor
  25907. * if the text object has a pattern or gradient for filler, it will return that.
  25908. * Unused by the library, is for the end user
  25909. * @return {String | fabric.Gradient | fabric.Pattern} Character color (fill)
  25910. */
  25911. getCurrentCharColor: function() {
  25912. var cp = this._getCurrentCharIndex();
  25913. return this.getValueOfPropertyAt(cp.l, cp.c, 'fill');
  25914. },
  25915. /**
  25916. * Returns the cursor position for the getCurrent.. functions
  25917. * @private
  25918. */
  25919. _getCurrentCharIndex: function() {
  25920. var cursorPosition = this.get2DCursorLocation(this.selectionStart, true),
  25921. charIndex = cursorPosition.charIndex > 0 ? cursorPosition.charIndex - 1 : 0;
  25922. return { l: cursorPosition.lineIndex, c: charIndex };
  25923. }
  25924. });
  25925. /**
  25926. * Returns fabric.IText instance from an object representation
  25927. * @static
  25928. * @memberOf fabric.IText
  25929. * @param {Object} object Object to create an instance from
  25930. * @param {function} [callback] invoked with new instance as argument
  25931. */
  25932. fabric.IText.fromObject = function(object, callback) {
  25933. object.styles = fabric.util.stylesFromArray(object.styles, object.text);
  25934. parseDecoration(object);
  25935. if (object.styles) {
  25936. for (var i in object.styles) {
  25937. for (var j in object.styles[i]) {
  25938. parseDecoration(object.styles[i][j]);
  25939. }
  25940. }
  25941. }
  25942. fabric.Object._fromObject('IText', object, callback, 'text');
  25943. };
  25944. })();
  25945. (function() {
  25946. var clone = fabric.util.object.clone;
  25947. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  25948. /**
  25949. * Initializes all the interactive behavior of IText
  25950. */
  25951. initBehavior: function() {
  25952. this.initAddedHandler();
  25953. this.initRemovedHandler();
  25954. this.initCursorSelectionHandlers();
  25955. this.initDoubleClickSimulation();
  25956. this.mouseMoveHandler = this.mouseMoveHandler.bind(this);
  25957. },
  25958. onDeselect: function() {
  25959. this.isEditing && this.exitEditing();
  25960. this.selected = false;
  25961. },
  25962. /**
  25963. * Initializes "added" event handler
  25964. */
  25965. initAddedHandler: function() {
  25966. var _this = this;
  25967. this.on('added', function() {
  25968. var canvas = _this.canvas;
  25969. if (canvas) {
  25970. if (!canvas._hasITextHandlers) {
  25971. canvas._hasITextHandlers = true;
  25972. _this._initCanvasHandlers(canvas);
  25973. }
  25974. canvas._iTextInstances = canvas._iTextInstances || [];
  25975. canvas._iTextInstances.push(_this);
  25976. }
  25977. });
  25978. },
  25979. initRemovedHandler: function() {
  25980. var _this = this;
  25981. this.on('removed', function() {
  25982. var canvas = _this.canvas;
  25983. if (canvas) {
  25984. canvas._iTextInstances = canvas._iTextInstances || [];
  25985. fabric.util.removeFromArray(canvas._iTextInstances, _this);
  25986. if (canvas._iTextInstances.length === 0) {
  25987. canvas._hasITextHandlers = false;
  25988. _this._removeCanvasHandlers(canvas);
  25989. }
  25990. }
  25991. });
  25992. },
  25993. /**
  25994. * register canvas event to manage exiting on other instances
  25995. * @private
  25996. */
  25997. _initCanvasHandlers: function(canvas) {
  25998. canvas._mouseUpITextHandler = function() {
  25999. if (canvas._iTextInstances) {
  26000. canvas._iTextInstances.forEach(function(obj) {
  26001. obj.__isMousedown = false;
  26002. });
  26003. }
  26004. };
  26005. canvas.on('mouse:up', canvas._mouseUpITextHandler);
  26006. },
  26007. /**
  26008. * remove canvas event to manage exiting on other instances
  26009. * @private
  26010. */
  26011. _removeCanvasHandlers: function(canvas) {
  26012. canvas.off('mouse:up', canvas._mouseUpITextHandler);
  26013. },
  26014. /**
  26015. * @private
  26016. */
  26017. _tick: function() {
  26018. this._currentTickState = this._animateCursor(this, 1, this.cursorDuration, '_onTickComplete');
  26019. },
  26020. /**
  26021. * @private
  26022. */
  26023. _animateCursor: function(obj, targetOpacity, duration, completeMethod) {
  26024. var tickState;
  26025. tickState = {
  26026. isAborted: false,
  26027. abort: function() {
  26028. this.isAborted = true;
  26029. },
  26030. };
  26031. obj.animate('_currentCursorOpacity', targetOpacity, {
  26032. duration: duration,
  26033. onComplete: function() {
  26034. if (!tickState.isAborted) {
  26035. obj[completeMethod]();
  26036. }
  26037. },
  26038. onChange: function() {
  26039. // we do not want to animate a selection, only cursor
  26040. if (obj.canvas && obj.selectionStart === obj.selectionEnd) {
  26041. obj.renderCursorOrSelection();
  26042. }
  26043. },
  26044. abort: function() {
  26045. return tickState.isAborted;
  26046. }
  26047. });
  26048. return tickState;
  26049. },
  26050. /**
  26051. * @private
  26052. */
  26053. _onTickComplete: function() {
  26054. var _this = this;
  26055. if (this._cursorTimeout1) {
  26056. clearTimeout(this._cursorTimeout1);
  26057. }
  26058. this._cursorTimeout1 = setTimeout(function() {
  26059. _this._currentTickCompleteState = _this._animateCursor(_this, 0, this.cursorDuration / 2, '_tick');
  26060. }, 100);
  26061. },
  26062. /**
  26063. * Initializes delayed cursor
  26064. */
  26065. initDelayedCursor: function(restart) {
  26066. var _this = this,
  26067. delay = restart ? 0 : this.cursorDelay;
  26068. this.abortCursorAnimation();
  26069. this._currentCursorOpacity = 1;
  26070. this._cursorTimeout2 = setTimeout(function() {
  26071. _this._tick();
  26072. }, delay);
  26073. },
  26074. /**
  26075. * Aborts cursor animation and clears all timeouts
  26076. */
  26077. abortCursorAnimation: function() {
  26078. var shouldClear = this._currentTickState || this._currentTickCompleteState,
  26079. canvas = this.canvas;
  26080. this._currentTickState && this._currentTickState.abort();
  26081. this._currentTickCompleteState && this._currentTickCompleteState.abort();
  26082. clearTimeout(this._cursorTimeout1);
  26083. clearTimeout(this._cursorTimeout2);
  26084. this._currentCursorOpacity = 0;
  26085. // to clear just itext area we need to transform the context
  26086. // it may not be worth it
  26087. if (shouldClear && canvas) {
  26088. canvas.clearContext(canvas.contextTop || canvas.contextContainer);
  26089. }
  26090. },
  26091. /**
  26092. * Selects entire text
  26093. * @return {fabric.IText} thisArg
  26094. * @chainable
  26095. */
  26096. selectAll: function() {
  26097. this.selectionStart = 0;
  26098. this.selectionEnd = this._text.length;
  26099. this._fireSelectionChanged();
  26100. this._updateTextarea();
  26101. return this;
  26102. },
  26103. /**
  26104. * Returns selected text
  26105. * @return {String}
  26106. */
  26107. getSelectedText: function() {
  26108. return this._text.slice(this.selectionStart, this.selectionEnd).join('');
  26109. },
  26110. /**
  26111. * Find new selection index representing start of current word according to current selection index
  26112. * @param {Number} startFrom Current selection index
  26113. * @return {Number} New selection index
  26114. */
  26115. findWordBoundaryLeft: function(startFrom) {
  26116. var offset = 0, index = startFrom - 1;
  26117. // remove space before cursor first
  26118. if (this._reSpace.test(this._text[index])) {
  26119. while (this._reSpace.test(this._text[index])) {
  26120. offset++;
  26121. index--;
  26122. }
  26123. }
  26124. while (/\S/.test(this._text[index]) && index > -1) {
  26125. offset++;
  26126. index--;
  26127. }
  26128. return startFrom - offset;
  26129. },
  26130. /**
  26131. * Find new selection index representing end of current word according to current selection index
  26132. * @param {Number} startFrom Current selection index
  26133. * @return {Number} New selection index
  26134. */
  26135. findWordBoundaryRight: function(startFrom) {
  26136. var offset = 0, index = startFrom;
  26137. // remove space after cursor first
  26138. if (this._reSpace.test(this._text[index])) {
  26139. while (this._reSpace.test(this._text[index])) {
  26140. offset++;
  26141. index++;
  26142. }
  26143. }
  26144. while (/\S/.test(this._text[index]) && index < this._text.length) {
  26145. offset++;
  26146. index++;
  26147. }
  26148. return startFrom + offset;
  26149. },
  26150. /**
  26151. * Find new selection index representing start of current line according to current selection index
  26152. * @param {Number} startFrom Current selection index
  26153. * @return {Number} New selection index
  26154. */
  26155. findLineBoundaryLeft: function(startFrom) {
  26156. var offset = 0, index = startFrom - 1;
  26157. while (!/\n/.test(this._text[index]) && index > -1) {
  26158. offset++;
  26159. index--;
  26160. }
  26161. return startFrom - offset;
  26162. },
  26163. /**
  26164. * Find new selection index representing end of current line according to current selection index
  26165. * @param {Number} startFrom Current selection index
  26166. * @return {Number} New selection index
  26167. */
  26168. findLineBoundaryRight: function(startFrom) {
  26169. var offset = 0, index = startFrom;
  26170. while (!/\n/.test(this._text[index]) && index < this._text.length) {
  26171. offset++;
  26172. index++;
  26173. }
  26174. return startFrom + offset;
  26175. },
  26176. /**
  26177. * Finds index corresponding to beginning or end of a word
  26178. * @param {Number} selectionStart Index of a character
  26179. * @param {Number} direction 1 or -1
  26180. * @return {Number} Index of the beginning or end of a word
  26181. */
  26182. searchWordBoundary: function(selectionStart, direction) {
  26183. var text = this._text,
  26184. index = this._reSpace.test(text[selectionStart]) ? selectionStart - 1 : selectionStart,
  26185. _char = text[index],
  26186. // wrong
  26187. reNonWord = fabric.reNonWord;
  26188. while (!reNonWord.test(_char) && index > 0 && index < text.length) {
  26189. index += direction;
  26190. _char = text[index];
  26191. }
  26192. if (reNonWord.test(_char)) {
  26193. index += direction === 1 ? 0 : 1;
  26194. }
  26195. return index;
  26196. },
  26197. /**
  26198. * Selects a word based on the index
  26199. * @param {Number} selectionStart Index of a character
  26200. */
  26201. selectWord: function(selectionStart) {
  26202. selectionStart = selectionStart || this.selectionStart;
  26203. var newSelectionStart = this.searchWordBoundary(selectionStart, -1), /* search backwards */
  26204. newSelectionEnd = this.searchWordBoundary(selectionStart, 1); /* search forward */
  26205. this.selectionStart = newSelectionStart;
  26206. this.selectionEnd = newSelectionEnd;
  26207. this._fireSelectionChanged();
  26208. this._updateTextarea();
  26209. this.renderCursorOrSelection();
  26210. },
  26211. /**
  26212. * Selects a line based on the index
  26213. * @param {Number} selectionStart Index of a character
  26214. * @return {fabric.IText} thisArg
  26215. * @chainable
  26216. */
  26217. selectLine: function(selectionStart) {
  26218. selectionStart = selectionStart || this.selectionStart;
  26219. var newSelectionStart = this.findLineBoundaryLeft(selectionStart),
  26220. newSelectionEnd = this.findLineBoundaryRight(selectionStart);
  26221. this.selectionStart = newSelectionStart;
  26222. this.selectionEnd = newSelectionEnd;
  26223. this._fireSelectionChanged();
  26224. this._updateTextarea();
  26225. return this;
  26226. },
  26227. /**
  26228. * Enters editing state
  26229. * @return {fabric.IText} thisArg
  26230. * @chainable
  26231. */
  26232. enterEditing: function(e) {
  26233. if (this.isEditing || !this.editable) {
  26234. return;
  26235. }
  26236. if (this.canvas) {
  26237. this.canvas.calcOffset();
  26238. this.exitEditingOnOthers(this.canvas);
  26239. }
  26240. this.isEditing = true;
  26241. this.initHiddenTextarea(e);
  26242. this.hiddenTextarea.focus();
  26243. this.hiddenTextarea.value = this.text;
  26244. this._updateTextarea();
  26245. this._saveEditingProps();
  26246. this._setEditingProps();
  26247. this._textBeforeEdit = this.text;
  26248. this._tick();
  26249. this.fire('editing:entered');
  26250. this._fireSelectionChanged();
  26251. if (!this.canvas) {
  26252. return this;
  26253. }
  26254. this.canvas.fire('text:editing:entered', { target: this });
  26255. this.initMouseMoveHandler();
  26256. this.canvas.requestRenderAll();
  26257. return this;
  26258. },
  26259. exitEditingOnOthers: function(canvas) {
  26260. if (canvas._iTextInstances) {
  26261. canvas._iTextInstances.forEach(function(obj) {
  26262. obj.selected = false;
  26263. if (obj.isEditing) {
  26264. obj.exitEditing();
  26265. }
  26266. });
  26267. }
  26268. },
  26269. /**
  26270. * Initializes "mousemove" event handler
  26271. */
  26272. initMouseMoveHandler: function() {
  26273. this.canvas.on('mouse:move', this.mouseMoveHandler);
  26274. },
  26275. /**
  26276. * @private
  26277. */
  26278. mouseMoveHandler: function(options) {
  26279. if (!this.__isMousedown || !this.isEditing) {
  26280. return;
  26281. }
  26282. var newSelectionStart = this.getSelectionStartFromPointer(options.e),
  26283. currentStart = this.selectionStart,
  26284. currentEnd = this.selectionEnd;
  26285. if (
  26286. (newSelectionStart !== this.__selectionStartOnMouseDown || currentStart === currentEnd)
  26287. &&
  26288. (currentStart === newSelectionStart || currentEnd === newSelectionStart)
  26289. ) {
  26290. return;
  26291. }
  26292. if (newSelectionStart > this.__selectionStartOnMouseDown) {
  26293. this.selectionStart = this.__selectionStartOnMouseDown;
  26294. this.selectionEnd = newSelectionStart;
  26295. }
  26296. else {
  26297. this.selectionStart = newSelectionStart;
  26298. this.selectionEnd = this.__selectionStartOnMouseDown;
  26299. }
  26300. if (this.selectionStart !== currentStart || this.selectionEnd !== currentEnd) {
  26301. this.restartCursorIfNeeded();
  26302. this._fireSelectionChanged();
  26303. this._updateTextarea();
  26304. this.renderCursorOrSelection();
  26305. }
  26306. },
  26307. /**
  26308. * @private
  26309. */
  26310. _setEditingProps: function() {
  26311. this.hoverCursor = 'text';
  26312. if (this.canvas) {
  26313. this.canvas.defaultCursor = this.canvas.moveCursor = 'text';
  26314. }
  26315. this.borderColor = this.editingBorderColor;
  26316. this.hasControls = this.selectable = false;
  26317. this.lockMovementX = this.lockMovementY = true;
  26318. },
  26319. /**
  26320. * convert from textarea to grapheme indexes
  26321. */
  26322. fromStringToGraphemeSelection: function(start, end, text) {
  26323. var smallerTextStart = text.slice(0, start),
  26324. graphemeStart = fabric.util.string.graphemeSplit(smallerTextStart).length;
  26325. if (start === end) {
  26326. return { selectionStart: graphemeStart, selectionEnd: graphemeStart };
  26327. }
  26328. var smallerTextEnd = text.slice(start, end),
  26329. graphemeEnd = fabric.util.string.graphemeSplit(smallerTextEnd).length;
  26330. return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };
  26331. },
  26332. /**
  26333. * convert from fabric to textarea values
  26334. */
  26335. fromGraphemeToStringSelection: function(start, end, _text) {
  26336. var smallerTextStart = _text.slice(0, start),
  26337. graphemeStart = smallerTextStart.join('').length;
  26338. if (start === end) {
  26339. return { selectionStart: graphemeStart, selectionEnd: graphemeStart };
  26340. }
  26341. var smallerTextEnd = _text.slice(start, end),
  26342. graphemeEnd = smallerTextEnd.join('').length;
  26343. return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };
  26344. },
  26345. /**
  26346. * @private
  26347. */
  26348. _updateTextarea: function() {
  26349. this.cursorOffsetCache = { };
  26350. if (!this.hiddenTextarea) {
  26351. return;
  26352. }
  26353. if (!this.inCompositionMode) {
  26354. var newSelection = this.fromGraphemeToStringSelection(this.selectionStart, this.selectionEnd, this._text);
  26355. this.hiddenTextarea.selectionStart = newSelection.selectionStart;
  26356. this.hiddenTextarea.selectionEnd = newSelection.selectionEnd;
  26357. }
  26358. this.updateTextareaPosition();
  26359. },
  26360. /**
  26361. * @private
  26362. */
  26363. updateFromTextArea: function() {
  26364. if (!this.hiddenTextarea) {
  26365. return;
  26366. }
  26367. this.cursorOffsetCache = { };
  26368. this.text = this.hiddenTextarea.value;
  26369. if (this._shouldClearDimensionCache()) {
  26370. this.initDimensions();
  26371. this.setCoords();
  26372. }
  26373. var newSelection = this.fromStringToGraphemeSelection(
  26374. this.hiddenTextarea.selectionStart, this.hiddenTextarea.selectionEnd, this.hiddenTextarea.value);
  26375. this.selectionEnd = this.selectionStart = newSelection.selectionEnd;
  26376. if (!this.inCompositionMode) {
  26377. this.selectionStart = newSelection.selectionStart;
  26378. }
  26379. this.updateTextareaPosition();
  26380. },
  26381. /**
  26382. * @private
  26383. */
  26384. updateTextareaPosition: function() {
  26385. if (this.selectionStart === this.selectionEnd) {
  26386. var style = this._calcTextareaPosition();
  26387. this.hiddenTextarea.style.left = style.left;
  26388. this.hiddenTextarea.style.top = style.top;
  26389. }
  26390. },
  26391. /**
  26392. * @private
  26393. * @return {Object} style contains style for hiddenTextarea
  26394. */
  26395. _calcTextareaPosition: function() {
  26396. if (!this.canvas) {
  26397. return { x: 1, y: 1 };
  26398. }
  26399. var desiredPosition = this.inCompositionMode ? this.compositionStart : this.selectionStart,
  26400. boundaries = this._getCursorBoundaries(desiredPosition),
  26401. cursorLocation = this.get2DCursorLocation(desiredPosition),
  26402. lineIndex = cursorLocation.lineIndex,
  26403. charIndex = cursorLocation.charIndex,
  26404. charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, 'fontSize') * this.lineHeight,
  26405. leftOffset = boundaries.leftOffset,
  26406. m = this.calcTransformMatrix(),
  26407. p = {
  26408. x: boundaries.left + leftOffset,
  26409. y: boundaries.top + boundaries.topOffset + charHeight
  26410. },
  26411. retinaScaling = this.canvas.getRetinaScaling(),
  26412. upperCanvas = this.canvas.upperCanvasEl,
  26413. upperCanvasWidth = upperCanvas.width / retinaScaling,
  26414. upperCanvasHeight = upperCanvas.height / retinaScaling,
  26415. maxWidth = upperCanvasWidth - charHeight,
  26416. maxHeight = upperCanvasHeight - charHeight,
  26417. scaleX = upperCanvas.clientWidth / upperCanvasWidth,
  26418. scaleY = upperCanvas.clientHeight / upperCanvasHeight;
  26419. p = fabric.util.transformPoint(p, m);
  26420. p = fabric.util.transformPoint(p, this.canvas.viewportTransform);
  26421. p.x *= scaleX;
  26422. p.y *= scaleY;
  26423. if (p.x < 0) {
  26424. p.x = 0;
  26425. }
  26426. if (p.x > maxWidth) {
  26427. p.x = maxWidth;
  26428. }
  26429. if (p.y < 0) {
  26430. p.y = 0;
  26431. }
  26432. if (p.y > maxHeight) {
  26433. p.y = maxHeight;
  26434. }
  26435. // add canvas offset on document
  26436. p.x += this.canvas._offset.left;
  26437. p.y += this.canvas._offset.top;
  26438. return { left: p.x + 'px', top: p.y + 'px', fontSize: charHeight + 'px', charHeight: charHeight };
  26439. },
  26440. /**
  26441. * @private
  26442. */
  26443. _saveEditingProps: function() {
  26444. this._savedProps = {
  26445. hasControls: this.hasControls,
  26446. borderColor: this.borderColor,
  26447. lockMovementX: this.lockMovementX,
  26448. lockMovementY: this.lockMovementY,
  26449. hoverCursor: this.hoverCursor,
  26450. selectable: this.selectable,
  26451. defaultCursor: this.canvas && this.canvas.defaultCursor,
  26452. moveCursor: this.canvas && this.canvas.moveCursor
  26453. };
  26454. },
  26455. /**
  26456. * @private
  26457. */
  26458. _restoreEditingProps: function() {
  26459. if (!this._savedProps) {
  26460. return;
  26461. }
  26462. this.hoverCursor = this._savedProps.hoverCursor;
  26463. this.hasControls = this._savedProps.hasControls;
  26464. this.borderColor = this._savedProps.borderColor;
  26465. this.selectable = this._savedProps.selectable;
  26466. this.lockMovementX = this._savedProps.lockMovementX;
  26467. this.lockMovementY = this._savedProps.lockMovementY;
  26468. if (this.canvas) {
  26469. this.canvas.defaultCursor = this._savedProps.defaultCursor;
  26470. this.canvas.moveCursor = this._savedProps.moveCursor;
  26471. }
  26472. },
  26473. /**
  26474. * Exits from editing state
  26475. * @return {fabric.IText} thisArg
  26476. * @chainable
  26477. */
  26478. exitEditing: function() {
  26479. var isTextChanged = (this._textBeforeEdit !== this.text);
  26480. var hiddenTextarea = this.hiddenTextarea;
  26481. this.selected = false;
  26482. this.isEditing = false;
  26483. this.selectionEnd = this.selectionStart;
  26484. if (hiddenTextarea) {
  26485. hiddenTextarea.blur && hiddenTextarea.blur();
  26486. hiddenTextarea.parentNode && hiddenTextarea.parentNode.removeChild(hiddenTextarea);
  26487. }
  26488. this.hiddenTextarea = null;
  26489. this.abortCursorAnimation();
  26490. this._restoreEditingProps();
  26491. this._currentCursorOpacity = 0;
  26492. if (this._shouldClearDimensionCache()) {
  26493. this.initDimensions();
  26494. this.setCoords();
  26495. }
  26496. this.fire('editing:exited');
  26497. isTextChanged && this.fire('modified');
  26498. if (this.canvas) {
  26499. this.canvas.off('mouse:move', this.mouseMoveHandler);
  26500. this.canvas.fire('text:editing:exited', { target: this });
  26501. isTextChanged && this.canvas.fire('object:modified', { target: this });
  26502. }
  26503. return this;
  26504. },
  26505. /**
  26506. * @private
  26507. */
  26508. _removeExtraneousStyles: function() {
  26509. for (var prop in this.styles) {
  26510. if (!this._textLines[prop]) {
  26511. delete this.styles[prop];
  26512. }
  26513. }
  26514. },
  26515. /**
  26516. * remove and reflow a style block from start to end.
  26517. * @param {Number} start linear start position for removal (included in removal)
  26518. * @param {Number} end linear end position for removal ( excluded from removal )
  26519. */
  26520. removeStyleFromTo: function(start, end) {
  26521. var cursorStart = this.get2DCursorLocation(start, true),
  26522. cursorEnd = this.get2DCursorLocation(end, true),
  26523. lineStart = cursorStart.lineIndex,
  26524. charStart = cursorStart.charIndex,
  26525. lineEnd = cursorEnd.lineIndex,
  26526. charEnd = cursorEnd.charIndex,
  26527. i, styleObj;
  26528. if (lineStart !== lineEnd) {
  26529. // step1 remove the trailing of lineStart
  26530. if (this.styles[lineStart]) {
  26531. for (i = charStart; i < this._unwrappedTextLines[lineStart].length; i++) {
  26532. delete this.styles[lineStart][i];
  26533. }
  26534. }
  26535. // step2 move the trailing of lineEnd to lineStart if needed
  26536. if (this.styles[lineEnd]) {
  26537. for (i = charEnd; i < this._unwrappedTextLines[lineEnd].length; i++) {
  26538. styleObj = this.styles[lineEnd][i];
  26539. if (styleObj) {
  26540. this.styles[lineStart] || (this.styles[lineStart] = { });
  26541. this.styles[lineStart][charStart + i - charEnd] = styleObj;
  26542. }
  26543. }
  26544. }
  26545. // step3 detects lines will be completely removed.
  26546. for (i = lineStart + 1; i <= lineEnd; i++) {
  26547. delete this.styles[i];
  26548. }
  26549. // step4 shift remaining lines.
  26550. this.shiftLineStyles(lineEnd, lineStart - lineEnd);
  26551. }
  26552. else {
  26553. // remove and shift left on the same line
  26554. if (this.styles[lineStart]) {
  26555. styleObj = this.styles[lineStart];
  26556. var diff = charEnd - charStart, numericChar, _char;
  26557. for (i = charStart; i < charEnd; i++) {
  26558. delete styleObj[i];
  26559. }
  26560. for (_char in this.styles[lineStart]) {
  26561. numericChar = parseInt(_char, 10);
  26562. if (numericChar >= charEnd) {
  26563. styleObj[numericChar - diff] = styleObj[_char];
  26564. delete styleObj[_char];
  26565. }
  26566. }
  26567. }
  26568. }
  26569. },
  26570. /**
  26571. * Shifts line styles up or down
  26572. * @param {Number} lineIndex Index of a line
  26573. * @param {Number} offset Can any number?
  26574. */
  26575. shiftLineStyles: function(lineIndex, offset) {
  26576. // shift all line styles by offset upward or downward
  26577. // do not clone deep. we need new array, not new style objects
  26578. var clonedStyles = clone(this.styles);
  26579. for (var line in this.styles) {
  26580. var numericLine = parseInt(line, 10);
  26581. if (numericLine > lineIndex) {
  26582. this.styles[numericLine + offset] = clonedStyles[numericLine];
  26583. if (!clonedStyles[numericLine - offset]) {
  26584. delete this.styles[numericLine];
  26585. }
  26586. }
  26587. }
  26588. },
  26589. restartCursorIfNeeded: function() {
  26590. if (!this._currentTickState || this._currentTickState.isAborted
  26591. || !this._currentTickCompleteState || this._currentTickCompleteState.isAborted
  26592. ) {
  26593. this.initDelayedCursor();
  26594. }
  26595. },
  26596. /**
  26597. * Handle insertion of more consecutive style lines for when one or more
  26598. * newlines gets added to the text. Since current style needs to be shifted
  26599. * first we shift the current style of the number lines needed, then we add
  26600. * new lines from the last to the first.
  26601. * @param {Number} lineIndex Index of a line
  26602. * @param {Number} charIndex Index of a char
  26603. * @param {Number} qty number of lines to add
  26604. * @param {Array} copiedStyle Array of objects styles
  26605. */
  26606. insertNewlineStyleObject: function(lineIndex, charIndex, qty, copiedStyle) {
  26607. var currentCharStyle,
  26608. newLineStyles = {},
  26609. somethingAdded = false,
  26610. isEndOfLine = this._unwrappedTextLines[lineIndex].length === charIndex;
  26611. qty || (qty = 1);
  26612. this.shiftLineStyles(lineIndex, qty);
  26613. if (this.styles[lineIndex]) {
  26614. currentCharStyle = this.styles[lineIndex][charIndex === 0 ? charIndex : charIndex - 1];
  26615. }
  26616. // we clone styles of all chars
  26617. // after cursor onto the current line
  26618. for (var index in this.styles[lineIndex]) {
  26619. var numIndex = parseInt(index, 10);
  26620. if (numIndex >= charIndex) {
  26621. somethingAdded = true;
  26622. newLineStyles[numIndex - charIndex] = this.styles[lineIndex][index];
  26623. // remove lines from the previous line since they're on a new line now
  26624. if (!(isEndOfLine && charIndex === 0)) {
  26625. delete this.styles[lineIndex][index];
  26626. }
  26627. }
  26628. }
  26629. var styleCarriedOver = false;
  26630. if (somethingAdded && !isEndOfLine) {
  26631. // if is end of line, the extra style we copied
  26632. // is probably not something we want
  26633. this.styles[lineIndex + qty] = newLineStyles;
  26634. styleCarriedOver = true;
  26635. }
  26636. if (styleCarriedOver) {
  26637. // skip the last line of since we already prepared it.
  26638. qty--;
  26639. }
  26640. // for the all the lines or all the other lines
  26641. // we clone current char style onto the next (otherwise empty) line
  26642. while (qty > 0) {
  26643. if (copiedStyle && copiedStyle[qty - 1]) {
  26644. this.styles[lineIndex + qty] = { 0: clone(copiedStyle[qty - 1]) };
  26645. }
  26646. else if (currentCharStyle) {
  26647. this.styles[lineIndex + qty] = { 0: clone(currentCharStyle) };
  26648. }
  26649. else {
  26650. delete this.styles[lineIndex + qty];
  26651. }
  26652. qty--;
  26653. }
  26654. this._forceClearCache = true;
  26655. },
  26656. /**
  26657. * Inserts style object for a given line/char index
  26658. * @param {Number} lineIndex Index of a line
  26659. * @param {Number} charIndex Index of a char
  26660. * @param {Number} quantity number Style object to insert, if given
  26661. * @param {Array} copiedStyle array of style objects
  26662. */
  26663. insertCharStyleObject: function(lineIndex, charIndex, quantity, copiedStyle) {
  26664. if (!this.styles) {
  26665. this.styles = {};
  26666. }
  26667. var currentLineStyles = this.styles[lineIndex],
  26668. currentLineStylesCloned = currentLineStyles ? clone(currentLineStyles) : {};
  26669. quantity || (quantity = 1);
  26670. // shift all char styles by quantity forward
  26671. // 0,1,2,3 -> (charIndex=2) -> 0,1,3,4 -> (insert 2) -> 0,1,2,3,4
  26672. for (var index in currentLineStylesCloned) {
  26673. var numericIndex = parseInt(index, 10);
  26674. if (numericIndex >= charIndex) {
  26675. currentLineStyles[numericIndex + quantity] = currentLineStylesCloned[numericIndex];
  26676. // only delete the style if there was nothing moved there
  26677. if (!currentLineStylesCloned[numericIndex - quantity]) {
  26678. delete currentLineStyles[numericIndex];
  26679. }
  26680. }
  26681. }
  26682. this._forceClearCache = true;
  26683. if (copiedStyle) {
  26684. while (quantity--) {
  26685. if (!Object.keys(copiedStyle[quantity]).length) {
  26686. continue;
  26687. }
  26688. if (!this.styles[lineIndex]) {
  26689. this.styles[lineIndex] = {};
  26690. }
  26691. this.styles[lineIndex][charIndex + quantity] = clone(copiedStyle[quantity]);
  26692. }
  26693. return;
  26694. }
  26695. if (!currentLineStyles) {
  26696. return;
  26697. }
  26698. var newStyle = currentLineStyles[charIndex ? charIndex - 1 : 1];
  26699. while (newStyle && quantity--) {
  26700. this.styles[lineIndex][charIndex + quantity] = clone(newStyle);
  26701. }
  26702. },
  26703. /**
  26704. * Inserts style object(s)
  26705. * @param {Array} insertedText Characters at the location where style is inserted
  26706. * @param {Number} start cursor index for inserting style
  26707. * @param {Array} [copiedStyle] array of style objects to insert.
  26708. */
  26709. insertNewStyleBlock: function(insertedText, start, copiedStyle) {
  26710. var cursorLoc = this.get2DCursorLocation(start, true),
  26711. addedLines = [0], linesLength = 0;
  26712. // get an array of how many char per lines are being added.
  26713. for (var i = 0; i < insertedText.length; i++) {
  26714. if (insertedText[i] === '\n') {
  26715. linesLength++;
  26716. addedLines[linesLength] = 0;
  26717. }
  26718. else {
  26719. addedLines[linesLength]++;
  26720. }
  26721. }
  26722. // for the first line copy the style from the current char position.
  26723. if (addedLines[0] > 0) {
  26724. this.insertCharStyleObject(cursorLoc.lineIndex, cursorLoc.charIndex, addedLines[0], copiedStyle);
  26725. copiedStyle = copiedStyle && copiedStyle.slice(addedLines[0] + 1);
  26726. }
  26727. linesLength && this.insertNewlineStyleObject(
  26728. cursorLoc.lineIndex, cursorLoc.charIndex + addedLines[0], linesLength);
  26729. for (var i = 1; i < linesLength; i++) {
  26730. if (addedLines[i] > 0) {
  26731. this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);
  26732. }
  26733. else if (copiedStyle) {
  26734. // this test is required in order to close #6841
  26735. // when a pasted buffer begins with a newline then
  26736. // this.styles[cursorLoc.lineIndex + i] and copiedStyle[0]
  26737. // may be undefined for some reason
  26738. if (this.styles[cursorLoc.lineIndex + i] && copiedStyle[0]) {
  26739. this.styles[cursorLoc.lineIndex + i][0] = copiedStyle[0];
  26740. }
  26741. }
  26742. copiedStyle = copiedStyle && copiedStyle.slice(addedLines[i] + 1);
  26743. }
  26744. // we use i outside the loop to get it like linesLength
  26745. if (addedLines[i] > 0) {
  26746. this.insertCharStyleObject(cursorLoc.lineIndex + i, 0, addedLines[i], copiedStyle);
  26747. }
  26748. },
  26749. /**
  26750. * Set the selectionStart and selectionEnd according to the new position of cursor
  26751. * mimic the key - mouse navigation when shift is pressed.
  26752. */
  26753. setSelectionStartEndWithShift: function(start, end, newSelection) {
  26754. if (newSelection <= start) {
  26755. if (end === start) {
  26756. this._selectionDirection = 'left';
  26757. }
  26758. else if (this._selectionDirection === 'right') {
  26759. this._selectionDirection = 'left';
  26760. this.selectionEnd = start;
  26761. }
  26762. this.selectionStart = newSelection;
  26763. }
  26764. else if (newSelection > start && newSelection < end) {
  26765. if (this._selectionDirection === 'right') {
  26766. this.selectionEnd = newSelection;
  26767. }
  26768. else {
  26769. this.selectionStart = newSelection;
  26770. }
  26771. }
  26772. else {
  26773. // newSelection is > selection start and end
  26774. if (end === start) {
  26775. this._selectionDirection = 'right';
  26776. }
  26777. else if (this._selectionDirection === 'left') {
  26778. this._selectionDirection = 'right';
  26779. this.selectionStart = end;
  26780. }
  26781. this.selectionEnd = newSelection;
  26782. }
  26783. },
  26784. setSelectionInBoundaries: function() {
  26785. var length = this.text.length;
  26786. if (this.selectionStart > length) {
  26787. this.selectionStart = length;
  26788. }
  26789. else if (this.selectionStart < 0) {
  26790. this.selectionStart = 0;
  26791. }
  26792. if (this.selectionEnd > length) {
  26793. this.selectionEnd = length;
  26794. }
  26795. else if (this.selectionEnd < 0) {
  26796. this.selectionEnd = 0;
  26797. }
  26798. }
  26799. });
  26800. })();
  26801. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  26802. /**
  26803. * Initializes "dbclick" event handler
  26804. */
  26805. initDoubleClickSimulation: function() {
  26806. // for double click
  26807. this.__lastClickTime = +new Date();
  26808. // for triple click
  26809. this.__lastLastClickTime = +new Date();
  26810. this.__lastPointer = { };
  26811. this.on('mousedown', this.onMouseDown);
  26812. },
  26813. /**
  26814. * Default event handler to simulate triple click
  26815. * @private
  26816. */
  26817. onMouseDown: function(options) {
  26818. if (!this.canvas) {
  26819. return;
  26820. }
  26821. this.__newClickTime = +new Date();
  26822. var newPointer = options.pointer;
  26823. if (this.isTripleClick(newPointer)) {
  26824. this.fire('tripleclick', options);
  26825. this._stopEvent(options.e);
  26826. }
  26827. this.__lastLastClickTime = this.__lastClickTime;
  26828. this.__lastClickTime = this.__newClickTime;
  26829. this.__lastPointer = newPointer;
  26830. this.__lastIsEditing = this.isEditing;
  26831. this.__lastSelected = this.selected;
  26832. },
  26833. isTripleClick: function(newPointer) {
  26834. return this.__newClickTime - this.__lastClickTime < 500 &&
  26835. this.__lastClickTime - this.__lastLastClickTime < 500 &&
  26836. this.__lastPointer.x === newPointer.x &&
  26837. this.__lastPointer.y === newPointer.y;
  26838. },
  26839. /**
  26840. * @private
  26841. */
  26842. _stopEvent: function(e) {
  26843. e.preventDefault && e.preventDefault();
  26844. e.stopPropagation && e.stopPropagation();
  26845. },
  26846. /**
  26847. * Initializes event handlers related to cursor or selection
  26848. */
  26849. initCursorSelectionHandlers: function() {
  26850. this.initMousedownHandler();
  26851. this.initMouseupHandler();
  26852. this.initClicks();
  26853. },
  26854. /**
  26855. * Default handler for double click, select a word
  26856. */
  26857. doubleClickHandler: function(options) {
  26858. if (!this.isEditing) {
  26859. return;
  26860. }
  26861. this.selectWord(this.getSelectionStartFromPointer(options.e));
  26862. },
  26863. /**
  26864. * Default handler for triple click, select a line
  26865. */
  26866. tripleClickHandler: function(options) {
  26867. if (!this.isEditing) {
  26868. return;
  26869. }
  26870. this.selectLine(this.getSelectionStartFromPointer(options.e));
  26871. },
  26872. /**
  26873. * Initializes double and triple click event handlers
  26874. */
  26875. initClicks: function() {
  26876. this.on('mousedblclick', this.doubleClickHandler);
  26877. this.on('tripleclick', this.tripleClickHandler);
  26878. },
  26879. /**
  26880. * Default event handler for the basic functionalities needed on _mouseDown
  26881. * can be overridden to do something different.
  26882. * Scope of this implementation is: find the click position, set selectionStart
  26883. * find selectionEnd, initialize the drawing of either cursor or selection area
  26884. * initializing a mousedDown on a text area will cancel fabricjs knowledge of
  26885. * current compositionMode. It will be set to false.
  26886. */
  26887. _mouseDownHandler: function(options) {
  26888. if (!this.canvas || !this.editable || (options.e.button && options.e.button !== 1)) {
  26889. return;
  26890. }
  26891. this.__isMousedown = true;
  26892. if (this.selected) {
  26893. this.inCompositionMode = false;
  26894. this.setCursorByClick(options.e);
  26895. }
  26896. if (this.isEditing) {
  26897. this.__selectionStartOnMouseDown = this.selectionStart;
  26898. if (this.selectionStart === this.selectionEnd) {
  26899. this.abortCursorAnimation();
  26900. }
  26901. this.renderCursorOrSelection();
  26902. }
  26903. },
  26904. /**
  26905. * Default event handler for the basic functionalities needed on mousedown:before
  26906. * can be overridden to do something different.
  26907. * Scope of this implementation is: verify the object is already selected when mousing down
  26908. */
  26909. _mouseDownHandlerBefore: function(options) {
  26910. if (!this.canvas || !this.editable || (options.e.button && options.e.button !== 1)) {
  26911. return;
  26912. }
  26913. // we want to avoid that an object that was selected and then becomes unselectable,
  26914. // may trigger editing mode in some way.
  26915. this.selected = this === this.canvas._activeObject;
  26916. },
  26917. /**
  26918. * Initializes "mousedown" event handler
  26919. */
  26920. initMousedownHandler: function() {
  26921. this.on('mousedown', this._mouseDownHandler);
  26922. this.on('mousedown:before', this._mouseDownHandlerBefore);
  26923. },
  26924. /**
  26925. * Initializes "mouseup" event handler
  26926. */
  26927. initMouseupHandler: function() {
  26928. this.on('mouseup', this.mouseUpHandler);
  26929. },
  26930. /**
  26931. * standard handler for mouse up, overridable
  26932. * @private
  26933. */
  26934. mouseUpHandler: function(options) {
  26935. this.__isMousedown = false;
  26936. if (!this.editable || this.group ||
  26937. (options.transform && options.transform.actionPerformed) ||
  26938. (options.e.button && options.e.button !== 1)) {
  26939. return;
  26940. }
  26941. if (this.canvas) {
  26942. var currentActive = this.canvas._activeObject;
  26943. if (currentActive && currentActive !== this) {
  26944. // avoid running this logic when there is an active object
  26945. // this because is possible with shift click and fast clicks,
  26946. // to rapidly deselect and reselect this object and trigger an enterEdit
  26947. return;
  26948. }
  26949. }
  26950. if (this.__lastSelected && !this.__corner) {
  26951. this.selected = false;
  26952. this.__lastSelected = false;
  26953. this.enterEditing(options.e);
  26954. if (this.selectionStart === this.selectionEnd) {
  26955. this.initDelayedCursor(true);
  26956. }
  26957. else {
  26958. this.renderCursorOrSelection();
  26959. }
  26960. }
  26961. else {
  26962. this.selected = true;
  26963. }
  26964. },
  26965. /**
  26966. * Changes cursor location in a text depending on passed pointer (x/y) object
  26967. * @param {Event} e Event object
  26968. */
  26969. setCursorByClick: function(e) {
  26970. var newSelection = this.getSelectionStartFromPointer(e),
  26971. start = this.selectionStart, end = this.selectionEnd;
  26972. if (e.shiftKey) {
  26973. this.setSelectionStartEndWithShift(start, end, newSelection);
  26974. }
  26975. else {
  26976. this.selectionStart = newSelection;
  26977. this.selectionEnd = newSelection;
  26978. }
  26979. if (this.isEditing) {
  26980. this._fireSelectionChanged();
  26981. this._updateTextarea();
  26982. }
  26983. },
  26984. /**
  26985. * Returns index of a character corresponding to where an object was clicked
  26986. * @param {Event} e Event object
  26987. * @return {Number} Index of a character
  26988. */
  26989. getSelectionStartFromPointer: function(e) {
  26990. var mouseOffset = this.getLocalPointer(e),
  26991. prevWidth = 0,
  26992. width = 0,
  26993. height = 0,
  26994. charIndex = 0,
  26995. lineIndex = 0,
  26996. lineLeftOffset,
  26997. line;
  26998. for (var i = 0, len = this._textLines.length; i < len; i++) {
  26999. if (height <= mouseOffset.y) {
  27000. height += this.getHeightOfLine(i) * this.scaleY;
  27001. lineIndex = i;
  27002. if (i > 0) {
  27003. charIndex += this._textLines[i - 1].length + this.missingNewlineOffset(i - 1);
  27004. }
  27005. }
  27006. else {
  27007. break;
  27008. }
  27009. }
  27010. lineLeftOffset = this._getLineLeftOffset(lineIndex);
  27011. width = lineLeftOffset * this.scaleX;
  27012. line = this._textLines[lineIndex];
  27013. // handling of RTL: in order to get things work correctly,
  27014. // we assume RTL writing is mirrored compared to LTR writing.
  27015. // so in position detection we mirror the X offset, and when is time
  27016. // of rendering it, we mirror it again.
  27017. if (this.direction === 'rtl') {
  27018. mouseOffset.x = this.width * this.scaleX - mouseOffset.x + width;
  27019. }
  27020. for (var j = 0, jlen = line.length; j < jlen; j++) {
  27021. prevWidth = width;
  27022. // i removed something about flipX here, check.
  27023. width += this.__charBounds[lineIndex][j].kernedWidth * this.scaleX;
  27024. if (width <= mouseOffset.x) {
  27025. charIndex++;
  27026. }
  27027. else {
  27028. break;
  27029. }
  27030. }
  27031. return this._getNewSelectionStartFromOffset(mouseOffset, prevWidth, width, charIndex, jlen);
  27032. },
  27033. /**
  27034. * @private
  27035. */
  27036. _getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index, jlen) {
  27037. // we need Math.abs because when width is after the last char, the offset is given as 1, while is 0
  27038. var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth,
  27039. distanceBtwNextCharAndCursor = width - mouseOffset.x,
  27040. offset = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor ||
  27041. distanceBtwNextCharAndCursor < 0 ? 0 : 1,
  27042. newSelectionStart = index + offset;
  27043. // if object is horizontally flipped, mirror cursor location from the end
  27044. if (this.flipX) {
  27045. newSelectionStart = jlen - newSelectionStart;
  27046. }
  27047. if (newSelectionStart > this._text.length) {
  27048. newSelectionStart = this._text.length;
  27049. }
  27050. return newSelectionStart;
  27051. }
  27052. });
  27053. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  27054. /**
  27055. * Initializes hidden textarea (needed to bring up keyboard in iOS)
  27056. */
  27057. initHiddenTextarea: function() {
  27058. this.hiddenTextarea = fabric.document.createElement('textarea');
  27059. this.hiddenTextarea.setAttribute('autocapitalize', 'off');
  27060. this.hiddenTextarea.setAttribute('autocorrect', 'off');
  27061. this.hiddenTextarea.setAttribute('autocomplete', 'off');
  27062. this.hiddenTextarea.setAttribute('spellcheck', 'false');
  27063. this.hiddenTextarea.setAttribute('data-fabric-hiddentextarea', '');
  27064. this.hiddenTextarea.setAttribute('wrap', 'off');
  27065. var style = this._calcTextareaPosition();
  27066. // line-height: 1px; was removed from the style to fix this:
  27067. // https://bugs.chromium.org/p/chromium/issues/detail?id=870966
  27068. this.hiddenTextarea.style.cssText = 'position: absolute; top: ' + style.top +
  27069. '; left: ' + style.left + '; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px;' +
  27070. ' paddingーtop: ' + style.fontSize + ';';
  27071. if (this.hiddenTextareaContainer) {
  27072. this.hiddenTextareaContainer.appendChild(this.hiddenTextarea);
  27073. }
  27074. else {
  27075. fabric.document.body.appendChild(this.hiddenTextarea);
  27076. }
  27077. fabric.util.addListener(this.hiddenTextarea, 'keydown', this.onKeyDown.bind(this));
  27078. fabric.util.addListener(this.hiddenTextarea, 'keyup', this.onKeyUp.bind(this));
  27079. fabric.util.addListener(this.hiddenTextarea, 'input', this.onInput.bind(this));
  27080. fabric.util.addListener(this.hiddenTextarea, 'copy', this.copy.bind(this));
  27081. fabric.util.addListener(this.hiddenTextarea, 'cut', this.copy.bind(this));
  27082. fabric.util.addListener(this.hiddenTextarea, 'paste', this.paste.bind(this));
  27083. fabric.util.addListener(this.hiddenTextarea, 'compositionstart', this.onCompositionStart.bind(this));
  27084. fabric.util.addListener(this.hiddenTextarea, 'compositionupdate', this.onCompositionUpdate.bind(this));
  27085. fabric.util.addListener(this.hiddenTextarea, 'compositionend', this.onCompositionEnd.bind(this));
  27086. if (!this._clickHandlerInitialized && this.canvas) {
  27087. fabric.util.addListener(this.canvas.upperCanvasEl, 'click', this.onClick.bind(this));
  27088. this._clickHandlerInitialized = true;
  27089. }
  27090. },
  27091. /**
  27092. * For functionalities on keyDown
  27093. * Map a special key to a function of the instance/prototype
  27094. * If you need different behaviour for ESC or TAB or arrows, you have to change
  27095. * this map setting the name of a function that you build on the fabric.Itext or
  27096. * your prototype.
  27097. * the map change will affect all Instances unless you need for only some text Instances
  27098. * in that case you have to clone this object and assign your Instance.
  27099. * this.keysMap = fabric.util.object.clone(this.keysMap);
  27100. * The function must be in fabric.Itext.prototype.myFunction And will receive event as args[0]
  27101. */
  27102. keysMap: {
  27103. 9: 'exitEditing',
  27104. 27: 'exitEditing',
  27105. 33: 'moveCursorUp',
  27106. 34: 'moveCursorDown',
  27107. 35: 'moveCursorRight',
  27108. 36: 'moveCursorLeft',
  27109. 37: 'moveCursorLeft',
  27110. 38: 'moveCursorUp',
  27111. 39: 'moveCursorRight',
  27112. 40: 'moveCursorDown',
  27113. },
  27114. keysMapRtl: {
  27115. 9: 'exitEditing',
  27116. 27: 'exitEditing',
  27117. 33: 'moveCursorUp',
  27118. 34: 'moveCursorDown',
  27119. 35: 'moveCursorLeft',
  27120. 36: 'moveCursorRight',
  27121. 37: 'moveCursorRight',
  27122. 38: 'moveCursorUp',
  27123. 39: 'moveCursorLeft',
  27124. 40: 'moveCursorDown',
  27125. },
  27126. /**
  27127. * For functionalities on keyUp + ctrl || cmd
  27128. */
  27129. ctrlKeysMapUp: {
  27130. 67: 'copy',
  27131. 88: 'cut'
  27132. },
  27133. /**
  27134. * For functionalities on keyDown + ctrl || cmd
  27135. */
  27136. ctrlKeysMapDown: {
  27137. 65: 'selectAll'
  27138. },
  27139. onClick: function() {
  27140. // No need to trigger click event here, focus is enough to have the keyboard appear on Android
  27141. this.hiddenTextarea && this.hiddenTextarea.focus();
  27142. },
  27143. /**
  27144. * Handles keydown event
  27145. * only used for arrows and combination of modifier keys.
  27146. * @param {Event} e Event object
  27147. */
  27148. onKeyDown: function(e) {
  27149. if (!this.isEditing) {
  27150. return;
  27151. }
  27152. var keyMap = this.direction === 'rtl' ? this.keysMapRtl : this.keysMap;
  27153. if (e.keyCode in keyMap) {
  27154. this[keyMap[e.keyCode]](e);
  27155. }
  27156. else if ((e.keyCode in this.ctrlKeysMapDown) && (e.ctrlKey || e.metaKey)) {
  27157. this[this.ctrlKeysMapDown[e.keyCode]](e);
  27158. }
  27159. else {
  27160. return;
  27161. }
  27162. e.stopImmediatePropagation();
  27163. e.preventDefault();
  27164. if (e.keyCode >= 33 && e.keyCode <= 40) {
  27165. // if i press an arrow key just update selection
  27166. this.inCompositionMode = false;
  27167. this.clearContextTop();
  27168. this.renderCursorOrSelection();
  27169. }
  27170. else {
  27171. this.canvas && this.canvas.requestRenderAll();
  27172. }
  27173. },
  27174. /**
  27175. * Handles keyup event
  27176. * We handle KeyUp because ie11 and edge have difficulties copy/pasting
  27177. * if a copy/cut event fired, keyup is dismissed
  27178. * @param {Event} e Event object
  27179. */
  27180. onKeyUp: function(e) {
  27181. if (!this.isEditing || this._copyDone || this.inCompositionMode) {
  27182. this._copyDone = false;
  27183. return;
  27184. }
  27185. if ((e.keyCode in this.ctrlKeysMapUp) && (e.ctrlKey || e.metaKey)) {
  27186. this[this.ctrlKeysMapUp[e.keyCode]](e);
  27187. }
  27188. else {
  27189. return;
  27190. }
  27191. e.stopImmediatePropagation();
  27192. e.preventDefault();
  27193. this.canvas && this.canvas.requestRenderAll();
  27194. },
  27195. /**
  27196. * Handles onInput event
  27197. * @param {Event} e Event object
  27198. */
  27199. onInput: function(e) {
  27200. var fromPaste = this.fromPaste;
  27201. this.fromPaste = false;
  27202. e && e.stopPropagation();
  27203. if (!this.isEditing) {
  27204. return;
  27205. }
  27206. // decisions about style changes.
  27207. var nextText = this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,
  27208. charCount = this._text.length,
  27209. nextCharCount = nextText.length,
  27210. removedText, insertedText,
  27211. charDiff = nextCharCount - charCount,
  27212. selectionStart = this.selectionStart, selectionEnd = this.selectionEnd,
  27213. selection = selectionStart !== selectionEnd,
  27214. copiedStyle, removeFrom, removeTo;
  27215. if (this.hiddenTextarea.value === '') {
  27216. this.styles = { };
  27217. this.updateFromTextArea();
  27218. this.fire('changed');
  27219. if (this.canvas) {
  27220. this.canvas.fire('text:changed', { target: this });
  27221. this.canvas.requestRenderAll();
  27222. }
  27223. return;
  27224. }
  27225. var textareaSelection = this.fromStringToGraphemeSelection(
  27226. this.hiddenTextarea.selectionStart,
  27227. this.hiddenTextarea.selectionEnd,
  27228. this.hiddenTextarea.value
  27229. );
  27230. var backDelete = selectionStart > textareaSelection.selectionStart;
  27231. if (selection) {
  27232. removedText = this._text.slice(selectionStart, selectionEnd);
  27233. charDiff += selectionEnd - selectionStart;
  27234. }
  27235. else if (nextCharCount < charCount) {
  27236. if (backDelete) {
  27237. removedText = this._text.slice(selectionEnd + charDiff, selectionEnd);
  27238. }
  27239. else {
  27240. removedText = this._text.slice(selectionStart, selectionStart - charDiff);
  27241. }
  27242. }
  27243. insertedText = nextText.slice(textareaSelection.selectionEnd - charDiff, textareaSelection.selectionEnd);
  27244. if (removedText && removedText.length) {
  27245. if (insertedText.length) {
  27246. // let's copy some style before deleting.
  27247. // we want to copy the style before the cursor OR the style at the cursor if selection
  27248. // is bigger than 0.
  27249. copiedStyle = this.getSelectionStyles(selectionStart, selectionStart + 1, false);
  27250. // now duplicate the style one for each inserted text.
  27251. copiedStyle = insertedText.map(function() {
  27252. // this return an array of references, but that is fine since we are
  27253. // copying the style later.
  27254. return copiedStyle[0];
  27255. });
  27256. }
  27257. if (selection) {
  27258. removeFrom = selectionStart;
  27259. removeTo = selectionEnd;
  27260. }
  27261. else if (backDelete) {
  27262. // detect differences between forwardDelete and backDelete
  27263. removeFrom = selectionEnd - removedText.length;
  27264. removeTo = selectionEnd;
  27265. }
  27266. else {
  27267. removeFrom = selectionEnd;
  27268. removeTo = selectionEnd + removedText.length;
  27269. }
  27270. this.removeStyleFromTo(removeFrom, removeTo);
  27271. }
  27272. if (insertedText.length) {
  27273. if (fromPaste && insertedText.join('') === fabric.copiedText && !fabric.disableStyleCopyPaste) {
  27274. copiedStyle = fabric.copiedTextStyle;
  27275. }
  27276. this.insertNewStyleBlock(insertedText, selectionStart, copiedStyle);
  27277. }
  27278. this.updateFromTextArea();
  27279. this.fire('changed');
  27280. if (this.canvas) {
  27281. this.canvas.fire('text:changed', { target: this });
  27282. this.canvas.requestRenderAll();
  27283. }
  27284. },
  27285. /**
  27286. * Composition start
  27287. */
  27288. onCompositionStart: function() {
  27289. this.inCompositionMode = true;
  27290. },
  27291. /**
  27292. * Composition end
  27293. */
  27294. onCompositionEnd: function() {
  27295. this.inCompositionMode = false;
  27296. },
  27297. // /**
  27298. // * Composition update
  27299. // */
  27300. onCompositionUpdate: function(e) {
  27301. this.compositionStart = e.target.selectionStart;
  27302. this.compositionEnd = e.target.selectionEnd;
  27303. this.updateTextareaPosition();
  27304. },
  27305. /**
  27306. * Copies selected text
  27307. * @param {Event} e Event object
  27308. */
  27309. copy: function() {
  27310. if (this.selectionStart === this.selectionEnd) {
  27311. //do not cut-copy if no selection
  27312. return;
  27313. }
  27314. fabric.copiedText = this.getSelectedText();
  27315. if (!fabric.disableStyleCopyPaste) {
  27316. fabric.copiedTextStyle = this.getSelectionStyles(this.selectionStart, this.selectionEnd, true);
  27317. }
  27318. else {
  27319. fabric.copiedTextStyle = null;
  27320. }
  27321. this._copyDone = true;
  27322. },
  27323. /**
  27324. * Pastes text
  27325. * @param {Event} e Event object
  27326. */
  27327. paste: function() {
  27328. this.fromPaste = true;
  27329. },
  27330. /**
  27331. * @private
  27332. * @param {Event} e Event object
  27333. * @return {Object} Clipboard data object
  27334. */
  27335. _getClipboardData: function(e) {
  27336. return (e && e.clipboardData) || fabric.window.clipboardData;
  27337. },
  27338. /**
  27339. * Finds the width in pixels before the cursor on the same line
  27340. * @private
  27341. * @param {Number} lineIndex
  27342. * @param {Number} charIndex
  27343. * @return {Number} widthBeforeCursor width before cursor
  27344. */
  27345. _getWidthBeforeCursor: function(lineIndex, charIndex) {
  27346. var widthBeforeCursor = this._getLineLeftOffset(lineIndex), bound;
  27347. if (charIndex > 0) {
  27348. bound = this.__charBounds[lineIndex][charIndex - 1];
  27349. widthBeforeCursor += bound.left + bound.width;
  27350. }
  27351. return widthBeforeCursor;
  27352. },
  27353. /**
  27354. * Gets start offset of a selection
  27355. * @param {Event} e Event object
  27356. * @param {Boolean} isRight
  27357. * @return {Number}
  27358. */
  27359. getDownCursorOffset: function(e, isRight) {
  27360. var selectionProp = this._getSelectionForOffset(e, isRight),
  27361. cursorLocation = this.get2DCursorLocation(selectionProp),
  27362. lineIndex = cursorLocation.lineIndex;
  27363. // if on last line, down cursor goes to end of line
  27364. if (lineIndex === this._textLines.length - 1 || e.metaKey || e.keyCode === 34) {
  27365. // move to the end of a text
  27366. return this._text.length - selectionProp;
  27367. }
  27368. var charIndex = cursorLocation.charIndex,
  27369. widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex),
  27370. indexOnOtherLine = this._getIndexOnLine(lineIndex + 1, widthBeforeCursor),
  27371. textAfterCursor = this._textLines[lineIndex].slice(charIndex);
  27372. return textAfterCursor.length + indexOnOtherLine + 1 + this.missingNewlineOffset(lineIndex);
  27373. },
  27374. /**
  27375. * private
  27376. * Helps finding if the offset should be counted from Start or End
  27377. * @param {Event} e Event object
  27378. * @param {Boolean} isRight
  27379. * @return {Number}
  27380. */
  27381. _getSelectionForOffset: function(e, isRight) {
  27382. if (e.shiftKey && this.selectionStart !== this.selectionEnd && isRight) {
  27383. return this.selectionEnd;
  27384. }
  27385. else {
  27386. return this.selectionStart;
  27387. }
  27388. },
  27389. /**
  27390. * @param {Event} e Event object
  27391. * @param {Boolean} isRight
  27392. * @return {Number}
  27393. */
  27394. getUpCursorOffset: function(e, isRight) {
  27395. var selectionProp = this._getSelectionForOffset(e, isRight),
  27396. cursorLocation = this.get2DCursorLocation(selectionProp),
  27397. lineIndex = cursorLocation.lineIndex;
  27398. if (lineIndex === 0 || e.metaKey || e.keyCode === 33) {
  27399. // if on first line, up cursor goes to start of line
  27400. return -selectionProp;
  27401. }
  27402. var charIndex = cursorLocation.charIndex,
  27403. widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex),
  27404. indexOnOtherLine = this._getIndexOnLine(lineIndex - 1, widthBeforeCursor),
  27405. textBeforeCursor = this._textLines[lineIndex].slice(0, charIndex),
  27406. missingNewlineOffset = this.missingNewlineOffset(lineIndex - 1);
  27407. // return a negative offset
  27408. return -this._textLines[lineIndex - 1].length
  27409. + indexOnOtherLine - textBeforeCursor.length + (1 - missingNewlineOffset);
  27410. },
  27411. /**
  27412. * for a given width it founds the matching character.
  27413. * @private
  27414. */
  27415. _getIndexOnLine: function(lineIndex, width) {
  27416. var line = this._textLines[lineIndex],
  27417. lineLeftOffset = this._getLineLeftOffset(lineIndex),
  27418. widthOfCharsOnLine = lineLeftOffset,
  27419. indexOnLine = 0, charWidth, foundMatch;
  27420. for (var j = 0, jlen = line.length; j < jlen; j++) {
  27421. charWidth = this.__charBounds[lineIndex][j].width;
  27422. widthOfCharsOnLine += charWidth;
  27423. if (widthOfCharsOnLine > width) {
  27424. foundMatch = true;
  27425. var leftEdge = widthOfCharsOnLine - charWidth,
  27426. rightEdge = widthOfCharsOnLine,
  27427. offsetFromLeftEdge = Math.abs(leftEdge - width),
  27428. offsetFromRightEdge = Math.abs(rightEdge - width);
  27429. indexOnLine = offsetFromRightEdge < offsetFromLeftEdge ? j : (j - 1);
  27430. break;
  27431. }
  27432. }
  27433. // reached end
  27434. if (!foundMatch) {
  27435. indexOnLine = line.length - 1;
  27436. }
  27437. return indexOnLine;
  27438. },
  27439. /**
  27440. * Moves cursor down
  27441. * @param {Event} e Event object
  27442. */
  27443. moveCursorDown: function(e) {
  27444. if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {
  27445. return;
  27446. }
  27447. this._moveCursorUpOrDown('Down', e);
  27448. },
  27449. /**
  27450. * Moves cursor up
  27451. * @param {Event} e Event object
  27452. */
  27453. moveCursorUp: function(e) {
  27454. if (this.selectionStart === 0 && this.selectionEnd === 0) {
  27455. return;
  27456. }
  27457. this._moveCursorUpOrDown('Up', e);
  27458. },
  27459. /**
  27460. * Moves cursor up or down, fires the events
  27461. * @param {String} direction 'Up' or 'Down'
  27462. * @param {Event} e Event object
  27463. */
  27464. _moveCursorUpOrDown: function(direction, e) {
  27465. // getUpCursorOffset
  27466. // getDownCursorOffset
  27467. var action = 'get' + direction + 'CursorOffset',
  27468. offset = this[action](e, this._selectionDirection === 'right');
  27469. if (e.shiftKey) {
  27470. this.moveCursorWithShift(offset);
  27471. }
  27472. else {
  27473. this.moveCursorWithoutShift(offset);
  27474. }
  27475. if (offset !== 0) {
  27476. this.setSelectionInBoundaries();
  27477. this.abortCursorAnimation();
  27478. this._currentCursorOpacity = 1;
  27479. this.initDelayedCursor();
  27480. this._fireSelectionChanged();
  27481. this._updateTextarea();
  27482. }
  27483. },
  27484. /**
  27485. * Moves cursor with shift
  27486. * @param {Number} offset
  27487. */
  27488. moveCursorWithShift: function(offset) {
  27489. var newSelection = this._selectionDirection === 'left'
  27490. ? this.selectionStart + offset
  27491. : this.selectionEnd + offset;
  27492. this.setSelectionStartEndWithShift(this.selectionStart, this.selectionEnd, newSelection);
  27493. return offset !== 0;
  27494. },
  27495. /**
  27496. * Moves cursor up without shift
  27497. * @param {Number} offset
  27498. */
  27499. moveCursorWithoutShift: function(offset) {
  27500. if (offset < 0) {
  27501. this.selectionStart += offset;
  27502. this.selectionEnd = this.selectionStart;
  27503. }
  27504. else {
  27505. this.selectionEnd += offset;
  27506. this.selectionStart = this.selectionEnd;
  27507. }
  27508. return offset !== 0;
  27509. },
  27510. /**
  27511. * Moves cursor left
  27512. * @param {Event} e Event object
  27513. */
  27514. moveCursorLeft: function(e) {
  27515. if (this.selectionStart === 0 && this.selectionEnd === 0) {
  27516. return;
  27517. }
  27518. this._moveCursorLeftOrRight('Left', e);
  27519. },
  27520. /**
  27521. * @private
  27522. * @return {Boolean} true if a change happened
  27523. */
  27524. _move: function(e, prop, direction) {
  27525. var newValue;
  27526. if (e.altKey) {
  27527. newValue = this['findWordBoundary' + direction](this[prop]);
  27528. }
  27529. else if (e.metaKey || e.keyCode === 35 || e.keyCode === 36 ) {
  27530. newValue = this['findLineBoundary' + direction](this[prop]);
  27531. }
  27532. else {
  27533. this[prop] += direction === 'Left' ? -1 : 1;
  27534. return true;
  27535. }
  27536. if (typeof newValue !== undefined && this[prop] !== newValue) {
  27537. this[prop] = newValue;
  27538. return true;
  27539. }
  27540. },
  27541. /**
  27542. * @private
  27543. */
  27544. _moveLeft: function(e, prop) {
  27545. return this._move(e, prop, 'Left');
  27546. },
  27547. /**
  27548. * @private
  27549. */
  27550. _moveRight: function(e, prop) {
  27551. return this._move(e, prop, 'Right');
  27552. },
  27553. /**
  27554. * Moves cursor left without keeping selection
  27555. * @param {Event} e
  27556. */
  27557. moveCursorLeftWithoutShift: function(e) {
  27558. var change = true;
  27559. this._selectionDirection = 'left';
  27560. // only move cursor when there is no selection,
  27561. // otherwise we discard it, and leave cursor on same place
  27562. if (this.selectionEnd === this.selectionStart && this.selectionStart !== 0) {
  27563. change = this._moveLeft(e, 'selectionStart');
  27564. }
  27565. this.selectionEnd = this.selectionStart;
  27566. return change;
  27567. },
  27568. /**
  27569. * Moves cursor left while keeping selection
  27570. * @param {Event} e
  27571. */
  27572. moveCursorLeftWithShift: function(e) {
  27573. if (this._selectionDirection === 'right' && this.selectionStart !== this.selectionEnd) {
  27574. return this._moveLeft(e, 'selectionEnd');
  27575. }
  27576. else if (this.selectionStart !== 0){
  27577. this._selectionDirection = 'left';
  27578. return this._moveLeft(e, 'selectionStart');
  27579. }
  27580. },
  27581. /**
  27582. * Moves cursor right
  27583. * @param {Event} e Event object
  27584. */
  27585. moveCursorRight: function(e) {
  27586. if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {
  27587. return;
  27588. }
  27589. this._moveCursorLeftOrRight('Right', e);
  27590. },
  27591. /**
  27592. * Moves cursor right or Left, fires event
  27593. * @param {String} direction 'Left', 'Right'
  27594. * @param {Event} e Event object
  27595. */
  27596. _moveCursorLeftOrRight: function(direction, e) {
  27597. var actionName = 'moveCursor' + direction + 'With';
  27598. this._currentCursorOpacity = 1;
  27599. if (e.shiftKey) {
  27600. actionName += 'Shift';
  27601. }
  27602. else {
  27603. actionName += 'outShift';
  27604. }
  27605. if (this[actionName](e)) {
  27606. this.abortCursorAnimation();
  27607. this.initDelayedCursor();
  27608. this._fireSelectionChanged();
  27609. this._updateTextarea();
  27610. }
  27611. },
  27612. /**
  27613. * Moves cursor right while keeping selection
  27614. * @param {Event} e
  27615. */
  27616. moveCursorRightWithShift: function(e) {
  27617. if (this._selectionDirection === 'left' && this.selectionStart !== this.selectionEnd) {
  27618. return this._moveRight(e, 'selectionStart');
  27619. }
  27620. else if (this.selectionEnd !== this._text.length) {
  27621. this._selectionDirection = 'right';
  27622. return this._moveRight(e, 'selectionEnd');
  27623. }
  27624. },
  27625. /**
  27626. * Moves cursor right without keeping selection
  27627. * @param {Event} e Event object
  27628. */
  27629. moveCursorRightWithoutShift: function(e) {
  27630. var changed = true;
  27631. this._selectionDirection = 'right';
  27632. if (this.selectionStart === this.selectionEnd) {
  27633. changed = this._moveRight(e, 'selectionStart');
  27634. this.selectionEnd = this.selectionStart;
  27635. }
  27636. else {
  27637. this.selectionStart = this.selectionEnd;
  27638. }
  27639. return changed;
  27640. },
  27641. /**
  27642. * Removes characters from start/end
  27643. * start/end ar per grapheme position in _text array.
  27644. *
  27645. * @param {Number} start
  27646. * @param {Number} end default to start + 1
  27647. */
  27648. removeChars: function(start, end) {
  27649. if (typeof end === 'undefined') {
  27650. end = start + 1;
  27651. }
  27652. this.removeStyleFromTo(start, end);
  27653. this._text.splice(start, end - start);
  27654. this.text = this._text.join('');
  27655. this.set('dirty', true);
  27656. if (this._shouldClearDimensionCache()) {
  27657. this.initDimensions();
  27658. this.setCoords();
  27659. }
  27660. this._removeExtraneousStyles();
  27661. },
  27662. /**
  27663. * insert characters at start position, before start position.
  27664. * start equal 1 it means the text get inserted between actual grapheme 0 and 1
  27665. * if style array is provided, it must be as the same length of text in graphemes
  27666. * if end is provided and is bigger than start, old text is replaced.
  27667. * start/end ar per grapheme position in _text array.
  27668. *
  27669. * @param {String} text text to insert
  27670. * @param {Array} style array of style objects
  27671. * @param {Number} start
  27672. * @param {Number} end default to start + 1
  27673. */
  27674. insertChars: function(text, style, start, end) {
  27675. if (typeof end === 'undefined') {
  27676. end = start;
  27677. }
  27678. if (end > start) {
  27679. this.removeStyleFromTo(start, end);
  27680. }
  27681. var graphemes = fabric.util.string.graphemeSplit(text);
  27682. this.insertNewStyleBlock(graphemes, start, style);
  27683. this._text = [].concat(this._text.slice(0, start), graphemes, this._text.slice(end));
  27684. this.text = this._text.join('');
  27685. this.set('dirty', true);
  27686. if (this._shouldClearDimensionCache()) {
  27687. this.initDimensions();
  27688. this.setCoords();
  27689. }
  27690. this._removeExtraneousStyles();
  27691. },
  27692. });
  27693. /* _TO_SVG_START_ */
  27694. (function() {
  27695. var toFixed = fabric.util.toFixed,
  27696. multipleSpacesRegex = / +/g;
  27697. fabric.util.object.extend(fabric.Text.prototype, /** @lends fabric.Text.prototype */ {
  27698. /**
  27699. * Returns SVG representation of an instance
  27700. * @param {Function} [reviver] Method for further parsing of svg representation.
  27701. * @return {String} svg representation of an instance
  27702. */
  27703. _toSVG: function() {
  27704. var offsets = this._getSVGLeftTopOffsets(),
  27705. textAndBg = this._getSVGTextAndBg(offsets.textTop, offsets.textLeft);
  27706. return this._wrapSVGTextAndBg(textAndBg);
  27707. },
  27708. /**
  27709. * Returns svg representation of an instance
  27710. * @param {Function} [reviver] Method for further parsing of svg representation.
  27711. * @return {String} svg representation of an instance
  27712. */
  27713. toSVG: function(reviver) {
  27714. return this._createBaseSVGMarkup(
  27715. this._toSVG(),
  27716. { reviver: reviver, noStyle: true, withShadow: true }
  27717. );
  27718. },
  27719. /**
  27720. * @private
  27721. */
  27722. _getSVGLeftTopOffsets: function() {
  27723. return {
  27724. textLeft: -this.width / 2,
  27725. textTop: -this.height / 2,
  27726. lineTop: this.getHeightOfLine(0)
  27727. };
  27728. },
  27729. /**
  27730. * @private
  27731. */
  27732. _wrapSVGTextAndBg: function(textAndBg) {
  27733. var noShadow = true,
  27734. textDecoration = this.getSvgTextDecoration(this);
  27735. return [
  27736. textAndBg.textBgRects.join(''),
  27737. '\t\t<text xml:space="preserve" ',
  27738. (this.fontFamily ? 'font-family="' + this.fontFamily.replace(/"/g, '\'') + '" ' : ''),
  27739. (this.fontSize ? 'font-size="' + this.fontSize + '" ' : ''),
  27740. (this.fontStyle ? 'font-style="' + this.fontStyle + '" ' : ''),
  27741. (this.fontWeight ? 'font-weight="' + this.fontWeight + '" ' : ''),
  27742. (textDecoration ? 'text-decoration="' + textDecoration + '" ' : ''),
  27743. 'style="', this.getSvgStyles(noShadow), '"', this.addPaintOrder(), ' >',
  27744. textAndBg.textSpans.join(''),
  27745. '</text>\n'
  27746. ];
  27747. },
  27748. /**
  27749. * @private
  27750. * @param {Number} textTopOffset Text top offset
  27751. * @param {Number} textLeftOffset Text left offset
  27752. * @return {Object}
  27753. */
  27754. _getSVGTextAndBg: function(textTopOffset, textLeftOffset) {
  27755. var textSpans = [],
  27756. textBgRects = [],
  27757. height = textTopOffset, lineOffset;
  27758. // bounding-box background
  27759. this._setSVGBg(textBgRects);
  27760. // text and text-background
  27761. for (var i = 0, len = this._textLines.length; i < len; i++) {
  27762. lineOffset = this._getLineLeftOffset(i);
  27763. if (this.textBackgroundColor || this.styleHas('textBackgroundColor', i)) {
  27764. this._setSVGTextLineBg(textBgRects, i, textLeftOffset + lineOffset, height);
  27765. }
  27766. this._setSVGTextLineText(textSpans, i, textLeftOffset + lineOffset, height);
  27767. height += this.getHeightOfLine(i);
  27768. }
  27769. return {
  27770. textSpans: textSpans,
  27771. textBgRects: textBgRects
  27772. };
  27773. },
  27774. /**
  27775. * @private
  27776. */
  27777. _createTextCharSpan: function(_char, styleDecl, left, top) {
  27778. var shouldUseWhitespace = _char !== _char.trim() || _char.match(multipleSpacesRegex),
  27779. styleProps = this.getSvgSpanStyles(styleDecl, shouldUseWhitespace),
  27780. fillStyles = styleProps ? 'style="' + styleProps + '"' : '',
  27781. dy = styleDecl.deltaY, dySpan = '',
  27782. NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;
  27783. if (dy) {
  27784. dySpan = ' dy="' + toFixed(dy, NUM_FRACTION_DIGITS) + '" ';
  27785. }
  27786. return [
  27787. '<tspan x="', toFixed(left, NUM_FRACTION_DIGITS), '" y="',
  27788. toFixed(top, NUM_FRACTION_DIGITS), '" ', dySpan,
  27789. fillStyles, '>',
  27790. fabric.util.string.escapeXml(_char),
  27791. '</tspan>'
  27792. ].join('');
  27793. },
  27794. _setSVGTextLineText: function(textSpans, lineIndex, textLeftOffset, textTopOffset) {
  27795. // set proper line offset
  27796. var lineHeight = this.getHeightOfLine(lineIndex),
  27797. isJustify = this.textAlign.indexOf('justify') !== -1,
  27798. actualStyle,
  27799. nextStyle,
  27800. charsToRender = '',
  27801. charBox, style,
  27802. boxWidth = 0,
  27803. line = this._textLines[lineIndex],
  27804. timeToRender;
  27805. textTopOffset += lineHeight * (1 - this._fontSizeFraction) / this.lineHeight;
  27806. for (var i = 0, len = line.length - 1; i <= len; i++) {
  27807. timeToRender = i === len || this.charSpacing;
  27808. charsToRender += line[i];
  27809. charBox = this.__charBounds[lineIndex][i];
  27810. if (boxWidth === 0) {
  27811. textLeftOffset += charBox.kernedWidth - charBox.width;
  27812. boxWidth += charBox.width;
  27813. }
  27814. else {
  27815. boxWidth += charBox.kernedWidth;
  27816. }
  27817. if (isJustify && !timeToRender) {
  27818. if (this._reSpaceAndTab.test(line[i])) {
  27819. timeToRender = true;
  27820. }
  27821. }
  27822. if (!timeToRender) {
  27823. // if we have charSpacing, we render char by char
  27824. actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i);
  27825. nextStyle = this.getCompleteStyleDeclaration(lineIndex, i + 1);
  27826. timeToRender = fabric.util.hasStyleChanged(actualStyle, nextStyle, true);
  27827. }
  27828. if (timeToRender) {
  27829. style = this._getStyleDeclaration(lineIndex, i) || { };
  27830. textSpans.push(this._createTextCharSpan(charsToRender, style, textLeftOffset, textTopOffset));
  27831. charsToRender = '';
  27832. actualStyle = nextStyle;
  27833. textLeftOffset += boxWidth;
  27834. boxWidth = 0;
  27835. }
  27836. }
  27837. },
  27838. _pushTextBgRect: function(textBgRects, color, left, top, width, height) {
  27839. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;
  27840. textBgRects.push(
  27841. '\t\t<rect ',
  27842. this._getFillAttributes(color),
  27843. ' x="',
  27844. toFixed(left, NUM_FRACTION_DIGITS),
  27845. '" y="',
  27846. toFixed(top, NUM_FRACTION_DIGITS),
  27847. '" width="',
  27848. toFixed(width, NUM_FRACTION_DIGITS),
  27849. '" height="',
  27850. toFixed(height, NUM_FRACTION_DIGITS),
  27851. '"></rect>\n');
  27852. },
  27853. _setSVGTextLineBg: function(textBgRects, i, leftOffset, textTopOffset) {
  27854. var line = this._textLines[i],
  27855. heightOfLine = this.getHeightOfLine(i) / this.lineHeight,
  27856. boxWidth = 0,
  27857. boxStart = 0,
  27858. charBox, currentColor,
  27859. lastColor = this.getValueOfPropertyAt(i, 0, 'textBackgroundColor');
  27860. for (var j = 0, jlen = line.length; j < jlen; j++) {
  27861. charBox = this.__charBounds[i][j];
  27862. currentColor = this.getValueOfPropertyAt(i, j, 'textBackgroundColor');
  27863. if (currentColor !== lastColor) {
  27864. lastColor && this._pushTextBgRect(textBgRects, lastColor, leftOffset + boxStart,
  27865. textTopOffset, boxWidth, heightOfLine);
  27866. boxStart = charBox.left;
  27867. boxWidth = charBox.width;
  27868. lastColor = currentColor;
  27869. }
  27870. else {
  27871. boxWidth += charBox.kernedWidth;
  27872. }
  27873. }
  27874. currentColor && this._pushTextBgRect(textBgRects, currentColor, leftOffset + boxStart,
  27875. textTopOffset, boxWidth, heightOfLine);
  27876. },
  27877. /**
  27878. * Adobe Illustrator (at least CS5) is unable to render rgba()-based fill values
  27879. * we work around it by "moving" alpha channel into opacity attribute and setting fill's alpha to 1
  27880. *
  27881. * @private
  27882. * @param {*} value
  27883. * @return {String}
  27884. */
  27885. _getFillAttributes: function(value) {
  27886. var fillColor = (value && typeof value === 'string') ? new fabric.Color(value) : '';
  27887. if (!fillColor || !fillColor.getSource() || fillColor.getAlpha() === 1) {
  27888. return 'fill="' + value + '"';
  27889. }
  27890. return 'opacity="' + fillColor.getAlpha() + '" fill="' + fillColor.setAlpha(1).toRgb() + '"';
  27891. },
  27892. /**
  27893. * @private
  27894. */
  27895. _getSVGLineTopOffset: function(lineIndex) {
  27896. var lineTopOffset = 0, lastHeight = 0;
  27897. for (var j = 0; j < lineIndex; j++) {
  27898. lineTopOffset += this.getHeightOfLine(j);
  27899. }
  27900. lastHeight = this.getHeightOfLine(j);
  27901. return {
  27902. lineTop: lineTopOffset,
  27903. offset: (this._fontSizeMult - this._fontSizeFraction) * lastHeight / (this.lineHeight * this._fontSizeMult)
  27904. };
  27905. },
  27906. /**
  27907. * Returns styles-string for svg-export
  27908. * @param {Boolean} skipShadow a boolean to skip shadow filter output
  27909. * @return {String}
  27910. */
  27911. getSvgStyles: function(skipShadow) {
  27912. var svgStyle = fabric.Object.prototype.getSvgStyles.call(this, skipShadow);
  27913. return svgStyle + ' white-space: pre;';
  27914. },
  27915. });
  27916. })();
  27917. /* _TO_SVG_END_ */
  27918. (function(global) {
  27919. 'use strict';
  27920. var fabric = global.fabric || (global.fabric = {});
  27921. /**
  27922. * Textbox class, based on IText, allows the user to resize the text rectangle
  27923. * and wraps lines automatically. Textboxes have their Y scaling locked, the
  27924. * user can only change width. Height is adjusted automatically based on the
  27925. * wrapping of lines.
  27926. * @class fabric.Textbox
  27927. * @extends fabric.IText
  27928. * @mixes fabric.Observable
  27929. * @return {fabric.Textbox} thisArg
  27930. * @see {@link fabric.Textbox#initialize} for constructor definition
  27931. */
  27932. fabric.Textbox = fabric.util.createClass(fabric.IText, fabric.Observable, {
  27933. /**
  27934. * Type of an object
  27935. * @type String
  27936. * @default
  27937. */
  27938. type: 'textbox',
  27939. /**
  27940. * Minimum width of textbox, in pixels.
  27941. * @type Number
  27942. * @default
  27943. */
  27944. minWidth: 20,
  27945. /**
  27946. * Minimum calculated width of a textbox, in pixels.
  27947. * fixed to 2 so that an empty textbox cannot go to 0
  27948. * and is still selectable without text.
  27949. * @type Number
  27950. * @default
  27951. */
  27952. dynamicMinWidth: 2,
  27953. /**
  27954. * Cached array of text wrapping.
  27955. * @type Array
  27956. */
  27957. __cachedLines: null,
  27958. /**
  27959. * Override standard Object class values
  27960. */
  27961. lockScalingFlip: true,
  27962. /**
  27963. * Override standard Object class values
  27964. * Textbox needs this on false
  27965. */
  27966. noScaleCache: false,
  27967. /**
  27968. * Properties which when set cause object to change dimensions
  27969. * @type Object
  27970. * @private
  27971. */
  27972. _dimensionAffectingProps: fabric.Text.prototype._dimensionAffectingProps.concat('width'),
  27973. /**
  27974. * Use this regular expression to split strings in breakable lines
  27975. * @private
  27976. */
  27977. _wordJoiners: /[ \t\r]/,
  27978. /**
  27979. * Use this boolean property in order to split strings that have no white space concept.
  27980. * this is a cheap way to help with chinese/japanese
  27981. * @type Boolean
  27982. * @since 2.6.0
  27983. */
  27984. splitByGrapheme: false,
  27985. /**
  27986. * Unlike superclass's version of this function, Textbox does not update
  27987. * its width.
  27988. * @private
  27989. * @override
  27990. */
  27991. initDimensions: function() {
  27992. if (this.__skipDimension) {
  27993. return;
  27994. }
  27995. this.isEditing && this.initDelayedCursor();
  27996. this.clearContextTop();
  27997. this._clearCache();
  27998. // clear dynamicMinWidth as it will be different after we re-wrap line
  27999. this.dynamicMinWidth = 0;
  28000. // wrap lines
  28001. this._styleMap = this._generateStyleMap(this._splitText());
  28002. // if after wrapping, the width is smaller than dynamicMinWidth, change the width and re-wrap
  28003. if (this.dynamicMinWidth > this.width) {
  28004. this._set('width', this.dynamicMinWidth);
  28005. }
  28006. if (this.textAlign.indexOf('justify') !== -1) {
  28007. // once text is measured we need to make space fatter to make justified text.
  28008. this.enlargeSpaces();
  28009. }
  28010. // clear cache and re-calculate height
  28011. this.height = this.calcTextHeight();
  28012. this.saveState({ propertySet: '_dimensionAffectingProps' });
  28013. },
  28014. /**
  28015. * Generate an object that translates the style object so that it is
  28016. * broken up by visual lines (new lines and automatic wrapping).
  28017. * The original text styles object is broken up by actual lines (new lines only),
  28018. * which is only sufficient for Text / IText
  28019. * @private
  28020. */
  28021. _generateStyleMap: function(textInfo) {
  28022. var realLineCount = 0,
  28023. realLineCharCount = 0,
  28024. charCount = 0,
  28025. map = {};
  28026. for (var i = 0; i < textInfo.graphemeLines.length; i++) {
  28027. if (textInfo.graphemeText[charCount] === '\n' && i > 0) {
  28028. realLineCharCount = 0;
  28029. charCount++;
  28030. realLineCount++;
  28031. }
  28032. else if (!this.splitByGrapheme && this._reSpaceAndTab.test(textInfo.graphemeText[charCount]) && i > 0) {
  28033. // this case deals with space's that are removed from end of lines when wrapping
  28034. realLineCharCount++;
  28035. charCount++;
  28036. }
  28037. map[i] = { line: realLineCount, offset: realLineCharCount };
  28038. charCount += textInfo.graphemeLines[i].length;
  28039. realLineCharCount += textInfo.graphemeLines[i].length;
  28040. }
  28041. return map;
  28042. },
  28043. /**
  28044. * Returns true if object has a style property or has it on a specified line
  28045. * @param {Number} lineIndex
  28046. * @return {Boolean}
  28047. */
  28048. styleHas: function(property, lineIndex) {
  28049. if (this._styleMap && !this.isWrapping) {
  28050. var map = this._styleMap[lineIndex];
  28051. if (map) {
  28052. lineIndex = map.line;
  28053. }
  28054. }
  28055. return fabric.Text.prototype.styleHas.call(this, property, lineIndex);
  28056. },
  28057. /**
  28058. * Returns true if object has no styling or no styling in a line
  28059. * @param {Number} lineIndex , lineIndex is on wrapped lines.
  28060. * @return {Boolean}
  28061. */
  28062. isEmptyStyles: function(lineIndex) {
  28063. if (!this.styles) {
  28064. return true;
  28065. }
  28066. var offset = 0, nextLineIndex = lineIndex + 1, nextOffset, obj, shouldLimit = false,
  28067. map = this._styleMap[lineIndex], mapNextLine = this._styleMap[lineIndex + 1];
  28068. if (map) {
  28069. lineIndex = map.line;
  28070. offset = map.offset;
  28071. }
  28072. if (mapNextLine) {
  28073. nextLineIndex = mapNextLine.line;
  28074. shouldLimit = nextLineIndex === lineIndex;
  28075. nextOffset = mapNextLine.offset;
  28076. }
  28077. obj = typeof lineIndex === 'undefined' ? this.styles : { line: this.styles[lineIndex] };
  28078. for (var p1 in obj) {
  28079. for (var p2 in obj[p1]) {
  28080. if (p2 >= offset && (!shouldLimit || p2 < nextOffset)) {
  28081. // eslint-disable-next-line no-unused-vars
  28082. for (var p3 in obj[p1][p2]) {
  28083. return false;
  28084. }
  28085. }
  28086. }
  28087. }
  28088. return true;
  28089. },
  28090. /**
  28091. * @param {Number} lineIndex
  28092. * @param {Number} charIndex
  28093. * @private
  28094. */
  28095. _getStyleDeclaration: function(lineIndex, charIndex) {
  28096. if (this._styleMap && !this.isWrapping) {
  28097. var map = this._styleMap[lineIndex];
  28098. if (!map) {
  28099. return null;
  28100. }
  28101. lineIndex = map.line;
  28102. charIndex = map.offset + charIndex;
  28103. }
  28104. return this.callSuper('_getStyleDeclaration', lineIndex, charIndex);
  28105. },
  28106. /**
  28107. * @param {Number} lineIndex
  28108. * @param {Number} charIndex
  28109. * @param {Object} style
  28110. * @private
  28111. */
  28112. _setStyleDeclaration: function(lineIndex, charIndex, style) {
  28113. var map = this._styleMap[lineIndex];
  28114. lineIndex = map.line;
  28115. charIndex = map.offset + charIndex;
  28116. this.styles[lineIndex][charIndex] = style;
  28117. },
  28118. /**
  28119. * @param {Number} lineIndex
  28120. * @param {Number} charIndex
  28121. * @private
  28122. */
  28123. _deleteStyleDeclaration: function(lineIndex, charIndex) {
  28124. var map = this._styleMap[lineIndex];
  28125. lineIndex = map.line;
  28126. charIndex = map.offset + charIndex;
  28127. delete this.styles[lineIndex][charIndex];
  28128. },
  28129. /**
  28130. * probably broken need a fix
  28131. * Returns the real style line that correspond to the wrapped lineIndex line
  28132. * Used just to verify if the line does exist or not.
  28133. * @param {Number} lineIndex
  28134. * @returns {Boolean} if the line exists or not
  28135. * @private
  28136. */
  28137. _getLineStyle: function(lineIndex) {
  28138. var map = this._styleMap[lineIndex];
  28139. return !!this.styles[map.line];
  28140. },
  28141. /**
  28142. * Set the line style to an empty object so that is initialized
  28143. * @param {Number} lineIndex
  28144. * @param {Object} style
  28145. * @private
  28146. */
  28147. _setLineStyle: function(lineIndex) {
  28148. var map = this._styleMap[lineIndex];
  28149. this.styles[map.line] = {};
  28150. },
  28151. /**
  28152. * Wraps text using the 'width' property of Textbox. First this function
  28153. * splits text on newlines, so we preserve newlines entered by the user.
  28154. * Then it wraps each line using the width of the Textbox by calling
  28155. * _wrapLine().
  28156. * @param {Array} lines The string array of text that is split into lines
  28157. * @param {Number} desiredWidth width you want to wrap to
  28158. * @returns {Array} Array of lines
  28159. */
  28160. _wrapText: function(lines, desiredWidth) {
  28161. var wrapped = [], i;
  28162. this.isWrapping = true;
  28163. for (i = 0; i < lines.length; i++) {
  28164. wrapped = wrapped.concat(this._wrapLine(lines[i], i, desiredWidth));
  28165. }
  28166. this.isWrapping = false;
  28167. return wrapped;
  28168. },
  28169. /**
  28170. * Helper function to measure a string of text, given its lineIndex and charIndex offset
  28171. * it gets called when charBounds are not available yet.
  28172. * @param {CanvasRenderingContext2D} ctx
  28173. * @param {String} text
  28174. * @param {number} lineIndex
  28175. * @param {number} charOffset
  28176. * @returns {number}
  28177. * @private
  28178. */
  28179. _measureWord: function(word, lineIndex, charOffset) {
  28180. var width = 0, prevGrapheme, skipLeft = true;
  28181. charOffset = charOffset || 0;
  28182. for (var i = 0, len = word.length; i < len; i++) {
  28183. var box = this._getGraphemeBox(word[i], lineIndex, i + charOffset, prevGrapheme, skipLeft);
  28184. width += box.kernedWidth;
  28185. prevGrapheme = word[i];
  28186. }
  28187. return width;
  28188. },
  28189. /**
  28190. * Wraps a line of text using the width of the Textbox and a context.
  28191. * @param {Array} line The grapheme array that represent the line
  28192. * @param {Number} lineIndex
  28193. * @param {Number} desiredWidth width you want to wrap the line to
  28194. * @param {Number} reservedSpace space to remove from wrapping for custom functionalities
  28195. * @returns {Array} Array of line(s) into which the given text is wrapped
  28196. * to.
  28197. */
  28198. _wrapLine: function(_line, lineIndex, desiredWidth, reservedSpace) {
  28199. var lineWidth = 0,
  28200. splitByGrapheme = this.splitByGrapheme,
  28201. graphemeLines = [],
  28202. line = [],
  28203. // spaces in different languages?
  28204. words = splitByGrapheme ? fabric.util.string.graphemeSplit(_line) : _line.split(this._wordJoiners),
  28205. word = '',
  28206. offset = 0,
  28207. infix = splitByGrapheme ? '' : ' ',
  28208. wordWidth = 0,
  28209. infixWidth = 0,
  28210. largestWordWidth = 0,
  28211. lineJustStarted = true,
  28212. additionalSpace = this._getWidthOfCharSpacing(),
  28213. reservedSpace = reservedSpace || 0;
  28214. // fix a difference between split and graphemeSplit
  28215. if (words.length === 0) {
  28216. words.push([]);
  28217. }
  28218. desiredWidth -= reservedSpace;
  28219. for (var i = 0; i < words.length; i++) {
  28220. // if using splitByGrapheme words are already in graphemes.
  28221. word = splitByGrapheme ? words[i] : fabric.util.string.graphemeSplit(words[i]);
  28222. wordWidth = this._measureWord(word, lineIndex, offset);
  28223. offset += word.length;
  28224. lineWidth += infixWidth + wordWidth - additionalSpace;
  28225. if (lineWidth > desiredWidth && !lineJustStarted) {
  28226. graphemeLines.push(line);
  28227. line = [];
  28228. lineWidth = wordWidth;
  28229. lineJustStarted = true;
  28230. }
  28231. else {
  28232. lineWidth += additionalSpace;
  28233. }
  28234. if (!lineJustStarted && !splitByGrapheme) {
  28235. line.push(infix);
  28236. }
  28237. line = line.concat(word);
  28238. infixWidth = splitByGrapheme ? 0 : this._measureWord([infix], lineIndex, offset);
  28239. offset++;
  28240. lineJustStarted = false;
  28241. // keep track of largest word
  28242. if (wordWidth > largestWordWidth) {
  28243. largestWordWidth = wordWidth;
  28244. }
  28245. }
  28246. i && graphemeLines.push(line);
  28247. if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
  28248. this.dynamicMinWidth = largestWordWidth - additionalSpace + reservedSpace;
  28249. }
  28250. return graphemeLines;
  28251. },
  28252. /**
  28253. * Detect if the text line is ended with an hard break
  28254. * text and itext do not have wrapping, return false
  28255. * @param {Number} lineIndex text to split
  28256. * @return {Boolean}
  28257. */
  28258. isEndOfWrapping: function(lineIndex) {
  28259. if (!this._styleMap[lineIndex + 1]) {
  28260. // is last line, return true;
  28261. return true;
  28262. }
  28263. if (this._styleMap[lineIndex + 1].line !== this._styleMap[lineIndex].line) {
  28264. // this is last line before a line break, return true;
  28265. return true;
  28266. }
  28267. return false;
  28268. },
  28269. /**
  28270. * Detect if a line has a linebreak and so we need to account for it when moving
  28271. * and counting style.
  28272. * @return Number
  28273. */
  28274. missingNewlineOffset: function(lineIndex) {
  28275. if (this.splitByGrapheme) {
  28276. return this.isEndOfWrapping(lineIndex) ? 1 : 0;
  28277. }
  28278. return 1;
  28279. },
  28280. /**
  28281. * Gets lines of text to render in the Textbox. This function calculates
  28282. * text wrapping on the fly every time it is called.
  28283. * @param {String} text text to split
  28284. * @returns {Array} Array of lines in the Textbox.
  28285. * @override
  28286. */
  28287. _splitTextIntoLines: function(text) {
  28288. var newText = fabric.Text.prototype._splitTextIntoLines.call(this, text),
  28289. graphemeLines = this._wrapText(newText.lines, this.width),
  28290. lines = new Array(graphemeLines.length);
  28291. for (var i = 0; i < graphemeLines.length; i++) {
  28292. lines[i] = graphemeLines[i].join('');
  28293. }
  28294. newText.lines = lines;
  28295. newText.graphemeLines = graphemeLines;
  28296. return newText;
  28297. },
  28298. getMinWidth: function() {
  28299. return Math.max(this.minWidth, this.dynamicMinWidth);
  28300. },
  28301. _removeExtraneousStyles: function() {
  28302. var linesToKeep = {};
  28303. for (var prop in this._styleMap) {
  28304. if (this._textLines[prop]) {
  28305. linesToKeep[this._styleMap[prop].line] = 1;
  28306. }
  28307. }
  28308. for (var prop in this.styles) {
  28309. if (!linesToKeep[prop]) {
  28310. delete this.styles[prop];
  28311. }
  28312. }
  28313. },
  28314. /**
  28315. * Returns object representation of an instance
  28316. * @method toObject
  28317. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  28318. * @return {Object} object representation of an instance
  28319. */
  28320. toObject: function(propertiesToInclude) {
  28321. return this.callSuper('toObject', ['minWidth', 'splitByGrapheme'].concat(propertiesToInclude));
  28322. }
  28323. });
  28324. /**
  28325. * Returns fabric.Textbox instance from an object representation
  28326. * @static
  28327. * @memberOf fabric.Textbox
  28328. * @param {Object} object Object to create an instance from
  28329. * @param {Function} [callback] Callback to invoke when an fabric.Textbox instance is created
  28330. */
  28331. fabric.Textbox.fromObject = function(object, callback) {
  28332. object.styles = fabric.util.stylesFromArray(object.styles, object.text);
  28333. return fabric.Object._fromObject('Textbox', object, callback, 'text');
  28334. };
  28335. })(typeof exports !== 'undefined' ? exports : this);
  28336. (function() {
  28337. var controlsUtils = fabric.controlsUtils,
  28338. scaleSkewStyleHandler = controlsUtils.scaleSkewCursorStyleHandler,
  28339. scaleStyleHandler = controlsUtils.scaleCursorStyleHandler,
  28340. scalingEqually = controlsUtils.scalingEqually,
  28341. scalingYOrSkewingX = controlsUtils.scalingYOrSkewingX,
  28342. scalingXOrSkewingY = controlsUtils.scalingXOrSkewingY,
  28343. scaleOrSkewActionName = controlsUtils.scaleOrSkewActionName,
  28344. objectControls = fabric.Object.prototype.controls;
  28345. objectControls.ml = new fabric.Control({
  28346. x: -0.5,
  28347. y: 0,
  28348. cursorStyleHandler: scaleSkewStyleHandler,
  28349. actionHandler: scalingXOrSkewingY,
  28350. getActionName: scaleOrSkewActionName,
  28351. });
  28352. objectControls.mr = new fabric.Control({
  28353. x: 0.5,
  28354. y: 0,
  28355. cursorStyleHandler: scaleSkewStyleHandler,
  28356. actionHandler: scalingXOrSkewingY,
  28357. getActionName: scaleOrSkewActionName,
  28358. });
  28359. objectControls.mb = new fabric.Control({
  28360. x: 0,
  28361. y: 0.5,
  28362. cursorStyleHandler: scaleSkewStyleHandler,
  28363. actionHandler: scalingYOrSkewingX,
  28364. getActionName: scaleOrSkewActionName,
  28365. });
  28366. objectControls.mt = new fabric.Control({
  28367. x: 0,
  28368. y: -0.5,
  28369. cursorStyleHandler: scaleSkewStyleHandler,
  28370. actionHandler: scalingYOrSkewingX,
  28371. getActionName: scaleOrSkewActionName,
  28372. });
  28373. objectControls.tl = new fabric.Control({
  28374. x: -0.5,
  28375. y: -0.5,
  28376. cursorStyleHandler: scaleStyleHandler,
  28377. actionHandler: scalingEqually
  28378. });
  28379. objectControls.tr = new fabric.Control({
  28380. x: 0.5,
  28381. y: -0.5,
  28382. cursorStyleHandler: scaleStyleHandler,
  28383. actionHandler: scalingEqually
  28384. });
  28385. objectControls.bl = new fabric.Control({
  28386. x: -0.5,
  28387. y: 0.5,
  28388. cursorStyleHandler: scaleStyleHandler,
  28389. actionHandler: scalingEqually
  28390. });
  28391. objectControls.br = new fabric.Control({
  28392. x: 0.5,
  28393. y: 0.5,
  28394. cursorStyleHandler: scaleStyleHandler,
  28395. actionHandler: scalingEqually
  28396. });
  28397. objectControls.mtr = new fabric.Control({
  28398. x: 0,
  28399. y: -0.5,
  28400. actionHandler: controlsUtils.rotationWithSnapping,
  28401. cursorStyleHandler: controlsUtils.rotationStyleHandler,
  28402. offsetY: -40,
  28403. withConnection: true,
  28404. actionName: 'rotate',
  28405. });
  28406. if (fabric.Textbox) {
  28407. // this is breaking the prototype inheritance, no time / ideas to fix it.
  28408. // is important to document that if you want to have all objects to have a
  28409. // specific custom control, you have to add it to Object prototype and to Textbox
  28410. // prototype. The controls are shared as references. So changes to control `tr`
  28411. // can still apply to all objects if needed.
  28412. var textBoxControls = fabric.Textbox.prototype.controls = { };
  28413. textBoxControls.mtr = objectControls.mtr;
  28414. textBoxControls.tr = objectControls.tr;
  28415. textBoxControls.br = objectControls.br;
  28416. textBoxControls.tl = objectControls.tl;
  28417. textBoxControls.bl = objectControls.bl;
  28418. textBoxControls.mt = objectControls.mt;
  28419. textBoxControls.mb = objectControls.mb;
  28420. textBoxControls.mr = new fabric.Control({
  28421. x: 0.5,
  28422. y: 0,
  28423. actionHandler: controlsUtils.changeWidth,
  28424. cursorStyleHandler: scaleSkewStyleHandler,
  28425. actionName: 'resizing',
  28426. });
  28427. textBoxControls.ml = new fabric.Control({
  28428. x: -0.5,
  28429. y: 0,
  28430. actionHandler: controlsUtils.changeWidth,
  28431. cursorStyleHandler: scaleSkewStyleHandler,
  28432. actionName: 'resizing',
  28433. });
  28434. }
  28435. })();
  28436. (function () {
  28437. /** ERASER_START */
  28438. /**
  28439. * add `eraser` to enlivened props
  28440. */
  28441. fabric.Object.ENLIVEN_PROPS.push('eraser');
  28442. var __drawClipPath = fabric.Object.prototype._drawClipPath;
  28443. var _needsItsOwnCache = fabric.Object.prototype.needsItsOwnCache;
  28444. var _toObject = fabric.Object.prototype.toObject;
  28445. var _getSvgCommons = fabric.Object.prototype.getSvgCommons;
  28446. var __createBaseClipPathSVGMarkup = fabric.Object.prototype._createBaseClipPathSVGMarkup;
  28447. var __createBaseSVGMarkup = fabric.Object.prototype._createBaseSVGMarkup;
  28448. fabric.Object.prototype.cacheProperties.push('eraser');
  28449. fabric.Object.prototype.stateProperties.push('eraser');
  28450. /**
  28451. * @fires erasing:end
  28452. */
  28453. fabric.util.object.extend(fabric.Object.prototype, {
  28454. /**
  28455. * Indicates whether this object can be erased by {@link fabric.EraserBrush}
  28456. * The `deep` option introduces fine grained control over a group's `erasable` property.
  28457. * When set to `deep` the eraser will erase nested objects if they are erasable, leaving the group and the other objects untouched.
  28458. * When set to `true` the eraser will erase the entire group. Once the group changes the eraser is propagated to its children for proper functionality.
  28459. * When set to `false` the eraser will leave all objects including the group untouched.
  28460. * @tutorial {@link http://fabricjs.com/erasing#erasable_property}
  28461. * @type boolean | 'deep'
  28462. * @default true
  28463. */
  28464. erasable: true,
  28465. /**
  28466. * @tutorial {@link http://fabricjs.com/erasing#eraser}
  28467. * @type fabric.Eraser
  28468. */
  28469. eraser: undefined,
  28470. /**
  28471. * @override
  28472. * @returns Boolean
  28473. */
  28474. needsItsOwnCache: function () {
  28475. return _needsItsOwnCache.call(this) || !!this.eraser;
  28476. },
  28477. /**
  28478. * draw eraser above clip path
  28479. * @override
  28480. * @private
  28481. * @param {CanvasRenderingContext2D} ctx
  28482. * @param {fabric.Object} clipPath
  28483. */
  28484. _drawClipPath: function (ctx, clipPath) {
  28485. __drawClipPath.call(this, ctx, clipPath);
  28486. if (this.eraser) {
  28487. // update eraser size to match instance
  28488. var size = this._getNonTransformedDimensions();
  28489. this.eraser.isType('eraser') && this.eraser.set({
  28490. width: size.x,
  28491. height: size.y
  28492. });
  28493. __drawClipPath.call(this, ctx, this.eraser);
  28494. }
  28495. },
  28496. /**
  28497. * Returns an object representation of an instance
  28498. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  28499. * @return {Object} Object representation of an instance
  28500. */
  28501. toObject: function (propertiesToInclude) {
  28502. var object = _toObject.call(this, ['erasable'].concat(propertiesToInclude));
  28503. if (this.eraser && !this.eraser.excludeFromExport) {
  28504. object.eraser = this.eraser.toObject(propertiesToInclude);
  28505. }
  28506. return object;
  28507. },
  28508. /* _TO_SVG_START_ */
  28509. /**
  28510. * Returns id attribute for svg output
  28511. * @override
  28512. * @return {String}
  28513. */
  28514. getSvgCommons: function () {
  28515. return _getSvgCommons.call(this) + (this.eraser ? 'mask="url(#' + this.eraser.clipPathId + ')" ' : '');
  28516. },
  28517. /**
  28518. * create svg markup for eraser
  28519. * use <mask> to achieve erasing for svg, credit: https://travishorn.com/removing-parts-of-shapes-in-svg-b539a89e5649
  28520. * must be called before object markup creation as it relies on the `clipPathId` property of the mask
  28521. * @param {Function} [reviver]
  28522. * @returns
  28523. */
  28524. _createEraserSVGMarkup: function (reviver) {
  28525. if (this.eraser) {
  28526. this.eraser.clipPathId = 'MASK_' + fabric.Object.__uid++;
  28527. return [
  28528. '<mask id="', this.eraser.clipPathId, '" >',
  28529. this.eraser.toSVG(reviver),
  28530. '</mask>', '\n'
  28531. ].join('');
  28532. }
  28533. return '';
  28534. },
  28535. /**
  28536. * @private
  28537. */
  28538. _createBaseClipPathSVGMarkup: function (objectMarkup, options) {
  28539. return [
  28540. this._createEraserSVGMarkup(options && options.reviver),
  28541. __createBaseClipPathSVGMarkup.call(this, objectMarkup, options)
  28542. ].join('');
  28543. },
  28544. /**
  28545. * @private
  28546. */
  28547. _createBaseSVGMarkup: function (objectMarkup, options) {
  28548. return [
  28549. this._createEraserSVGMarkup(options && options.reviver),
  28550. __createBaseSVGMarkup.call(this, objectMarkup, options)
  28551. ].join('');
  28552. }
  28553. /* _TO_SVG_END_ */
  28554. });
  28555. var __restoreObjectsState = fabric.Group.prototype._restoreObjectsState;
  28556. fabric.util.object.extend(fabric.Group.prototype, {
  28557. /**
  28558. * @private
  28559. * @param {fabric.Path} path
  28560. */
  28561. _addEraserPathToObjects: function (path) {
  28562. this._objects.forEach(function (object) {
  28563. fabric.EraserBrush.prototype._addPathToObjectEraser.call(
  28564. fabric.EraserBrush.prototype,
  28565. object,
  28566. path
  28567. );
  28568. });
  28569. },
  28570. /**
  28571. * Applies the group's eraser to its objects
  28572. * @tutorial {@link http://fabricjs.com/erasing#erasable_property}
  28573. */
  28574. applyEraserToObjects: function () {
  28575. var _this = this, eraser = this.eraser;
  28576. if (eraser) {
  28577. delete this.eraser;
  28578. var transform = _this.calcTransformMatrix();
  28579. eraser.clone(function (eraser) {
  28580. var clipPath = _this.clipPath;
  28581. eraser.getObjects('path')
  28582. .forEach(function (path) {
  28583. // first we transform the path from the group's coordinate system to the canvas'
  28584. var originalTransform = fabric.util.multiplyTransformMatrices(
  28585. transform,
  28586. path.calcTransformMatrix()
  28587. );
  28588. fabric.util.applyTransformToObject(path, originalTransform);
  28589. if (clipPath) {
  28590. clipPath.clone(function (_clipPath) {
  28591. var eraserPath = fabric.EraserBrush.prototype.applyClipPathToPath.call(
  28592. fabric.EraserBrush.prototype,
  28593. path,
  28594. _clipPath,
  28595. transform
  28596. );
  28597. _this._addEraserPathToObjects(eraserPath);
  28598. }, ['absolutePositioned', 'inverted']);
  28599. }
  28600. else {
  28601. _this._addEraserPathToObjects(path);
  28602. }
  28603. });
  28604. });
  28605. }
  28606. },
  28607. /**
  28608. * Propagate the group's eraser to its objects, crucial for proper functionality of the eraser within the group and nested objects.
  28609. * @private
  28610. */
  28611. _restoreObjectsState: function () {
  28612. this.erasable === true && this.applyEraserToObjects();
  28613. return __restoreObjectsState.call(this);
  28614. }
  28615. });
  28616. /**
  28617. * An object's Eraser
  28618. * @private
  28619. * @class fabric.Eraser
  28620. * @extends fabric.Group
  28621. * @memberof fabric
  28622. */
  28623. fabric.Eraser = fabric.util.createClass(fabric.Group, {
  28624. /**
  28625. * @readonly
  28626. * @static
  28627. */
  28628. type: 'eraser',
  28629. /**
  28630. * @default
  28631. */
  28632. originX: 'center',
  28633. /**
  28634. * @default
  28635. */
  28636. originY: 'center',
  28637. drawObject: function (ctx) {
  28638. ctx.save();
  28639. ctx.fillStyle = 'black';
  28640. ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);
  28641. ctx.restore();
  28642. this.callSuper('drawObject', ctx);
  28643. },
  28644. /**
  28645. * eraser should retain size
  28646. * dimensions should not change when paths are added or removed
  28647. * handled by {@link fabric.Object#_drawClipPath}
  28648. * @override
  28649. * @private
  28650. */
  28651. _getBounds: function () {
  28652. // noop
  28653. },
  28654. /* _TO_SVG_START_ */
  28655. /**
  28656. * Returns svg representation of an instance
  28657. * use <mask> to achieve erasing for svg, credit: https://travishorn.com/removing-parts-of-shapes-in-svg-b539a89e5649
  28658. * for masking we need to add a white rect before all paths
  28659. *
  28660. * @param {Function} [reviver] Method for further parsing of svg representation.
  28661. * @return {String} svg representation of an instance
  28662. */
  28663. _toSVG: function (reviver) {
  28664. var svgString = ['<g ', 'COMMON_PARTS', ' >\n'];
  28665. var x = -this.width / 2, y = -this.height / 2;
  28666. var rectSvg = [
  28667. '<rect ', 'fill="white" ',
  28668. 'x="', x, '" y="', y,
  28669. '" width="', this.width, '" height="', this.height,
  28670. '" />\n'
  28671. ].join('');
  28672. svgString.push('\t\t', rectSvg);
  28673. for (var i = 0, len = this._objects.length; i < len; i++) {
  28674. svgString.push('\t\t', this._objects[i].toSVG(reviver));
  28675. }
  28676. svgString.push('</g>\n');
  28677. return svgString;
  28678. },
  28679. /* _TO_SVG_END_ */
  28680. });
  28681. /**
  28682. * Returns {@link fabric.Eraser} instance from an object representation
  28683. * @static
  28684. * @memberOf fabric.Eraser
  28685. * @param {Object} object Object to create an Eraser from
  28686. * @param {Function} [callback] Callback to invoke when an eraser instance is created
  28687. */
  28688. fabric.Eraser.fromObject = function (object, callback) {
  28689. var objects = object.objects;
  28690. fabric.util.enlivenObjects(objects, function (enlivenedObjects) {
  28691. var options = fabric.util.object.clone(object, true);
  28692. delete options.objects;
  28693. fabric.util.enlivenObjectEnlivables(object, options, function () {
  28694. callback && callback(new fabric.Eraser(enlivenedObjects, options, true));
  28695. });
  28696. });
  28697. };
  28698. var __renderOverlay = fabric.Canvas.prototype._renderOverlay;
  28699. /**
  28700. * @fires erasing:start
  28701. * @fires erasing:end
  28702. */
  28703. fabric.util.object.extend(fabric.Canvas.prototype, {
  28704. /**
  28705. * Used by {@link #renderAll}
  28706. * @returns boolean
  28707. */
  28708. isErasing: function () {
  28709. return (
  28710. this.isDrawingMode &&
  28711. this.freeDrawingBrush &&
  28712. this.freeDrawingBrush.type === 'eraser' &&
  28713. this.freeDrawingBrush._isErasing
  28714. );
  28715. },
  28716. /**
  28717. * While erasing the brush clips out the erasing path from canvas
  28718. * so we need to render it on top of canvas every render
  28719. * @param {CanvasRenderingContext2D} ctx
  28720. */
  28721. _renderOverlay: function (ctx) {
  28722. __renderOverlay.call(this, ctx);
  28723. if (this.isErasing() && !this.freeDrawingBrush.inverted) {
  28724. this.freeDrawingBrush._render();
  28725. }
  28726. }
  28727. });
  28728. /**
  28729. * EraserBrush class
  28730. * Supports selective erasing meaning that only erasable objects are affected by the eraser brush.
  28731. * Supports **inverted** erasing meaning that the brush can "undo" erasing.
  28732. *
  28733. * In order to support selective erasing, the brush clips the entire canvas
  28734. * and then draws all non-erasable objects over the erased path using a pattern brush so to speak (masking).
  28735. * If brush is **inverted** there is no need to clip canvas. The brush draws all erasable objects without their eraser.
  28736. * This achieves the desired effect of seeming to erase or unerase only erasable objects.
  28737. * After erasing is done the created path is added to all intersected objects' `eraser` property.
  28738. *
  28739. * In order to update the EraserBrush call `preparePattern`.
  28740. * It may come in handy when canvas changes during erasing (i.e animations) and you want the eraser to reflect the changes.
  28741. *
  28742. * @tutorial {@link http://fabricjs.com/erasing}
  28743. * @class fabric.EraserBrush
  28744. * @extends fabric.PencilBrush
  28745. * @memberof fabric
  28746. */
  28747. fabric.EraserBrush = fabric.util.createClass(
  28748. fabric.PencilBrush,
  28749. /** @lends fabric.EraserBrush.prototype */ {
  28750. type: 'eraser',
  28751. /**
  28752. * When set to `true` the brush will create a visual effect of undoing erasing
  28753. */
  28754. inverted: false,
  28755. /**
  28756. * @private
  28757. */
  28758. _isErasing: false,
  28759. /**
  28760. *
  28761. * @private
  28762. * @param {fabric.Object} object
  28763. * @returns boolean
  28764. */
  28765. _isErasable: function (object) {
  28766. return object.erasable !== false;
  28767. },
  28768. /**
  28769. * @private
  28770. * This is designed to support erasing a collection with both erasable and non-erasable objects.
  28771. * Iterates over collections to allow nested selective erasing.
  28772. * Prepares the pattern brush that will draw on the top context to achieve the desired visual effect.
  28773. * If brush is **NOT** inverted render all non-erasable objects.
  28774. * If brush is inverted render all erasable objects that have been erased with their clip path inverted.
  28775. * This will render the erased parts as if they were not erased.
  28776. *
  28777. * @param {fabric.Collection} collection
  28778. * @param {CanvasRenderingContext2D} ctx
  28779. * @param {{ visibility: fabric.Object[], eraser: fabric.Object[], collection: fabric.Object[] }} restorationContext
  28780. */
  28781. _prepareCollectionTraversal: function (collection, ctx, restorationContext) {
  28782. collection.forEachObject(function (obj) {
  28783. if (obj.forEachObject && obj.erasable === 'deep') {
  28784. // traverse
  28785. this._prepareCollectionTraversal(obj, ctx, restorationContext);
  28786. }
  28787. else if (!this.inverted && obj.erasable && obj.visible) {
  28788. // render only non-erasable objects
  28789. obj.visible = false;
  28790. collection.dirty = true;
  28791. restorationContext.visibility.push(obj);
  28792. restorationContext.collection.push(collection);
  28793. }
  28794. else if (this.inverted && obj.visible) {
  28795. // render only erasable objects that were erased
  28796. if (obj.erasable && obj.eraser) {
  28797. obj.eraser.inverted = true;
  28798. obj.dirty = true;
  28799. collection.dirty = true;
  28800. restorationContext.eraser.push(obj);
  28801. restorationContext.collection.push(collection);
  28802. }
  28803. else {
  28804. obj.visible = false;
  28805. collection.dirty = true;
  28806. restorationContext.visibility.push(obj);
  28807. restorationContext.collection.push(collection);
  28808. }
  28809. }
  28810. }, this);
  28811. },
  28812. /**
  28813. * Prepare the pattern for the erasing brush
  28814. * This pattern will be drawn on the top context, achieving a visual effect of erasing only erasable objects
  28815. * @todo decide how overlay color should behave when `inverted === true`, currently draws over it which is undesirable
  28816. * @private
  28817. */
  28818. preparePattern: function () {
  28819. if (!this._patternCanvas) {
  28820. this._patternCanvas = fabric.util.createCanvasElement();
  28821. }
  28822. var canvas = this._patternCanvas;
  28823. canvas.width = this.canvas.width;
  28824. canvas.height = this.canvas.height;
  28825. var patternCtx = canvas.getContext('2d');
  28826. if (this.canvas._isRetinaScaling()) {
  28827. var retinaScaling = this.canvas.getRetinaScaling();
  28828. this.canvas.__initRetinaScaling(retinaScaling, canvas, patternCtx);
  28829. }
  28830. var backgroundImage = this.canvas.backgroundImage,
  28831. bgErasable = backgroundImage && this._isErasable(backgroundImage),
  28832. overlayImage = this.canvas.overlayImage,
  28833. overlayErasable = overlayImage && this._isErasable(overlayImage);
  28834. if (!this.inverted && ((backgroundImage && !bgErasable) || !!this.canvas.backgroundColor)) {
  28835. if (bgErasable) { this.canvas.backgroundImage = undefined; }
  28836. this.canvas._renderBackground(patternCtx);
  28837. if (bgErasable) { this.canvas.backgroundImage = backgroundImage; }
  28838. }
  28839. else if (this.inverted && (backgroundImage && bgErasable)) {
  28840. var color = this.canvas.backgroundColor;
  28841. this.canvas.backgroundColor = undefined;
  28842. this.canvas._renderBackground(patternCtx);
  28843. this.canvas.backgroundColor = color;
  28844. }
  28845. patternCtx.save();
  28846. patternCtx.transform.apply(patternCtx, this.canvas.viewportTransform);
  28847. var restorationContext = { visibility: [], eraser: [], collection: [] };
  28848. this._prepareCollectionTraversal(this.canvas, patternCtx, restorationContext);
  28849. let opacity = this.opacity
  28850. restorationContext.visibility.forEach(function (obj) { obj.opacity = 1 - opacity; obj.visible = true; });
  28851. this.canvas._renderObjects(patternCtx, this.canvas._objects);
  28852. restorationContext.visibility.forEach(function (obj) { obj.opacity = 1; });
  28853. // restorationContext.visibility.forEach(function (obj) { obj.visible = true; });
  28854. restorationContext.eraser.forEach(function (obj) {
  28855. obj.eraser.inverted = false;
  28856. obj.dirty = true;
  28857. });
  28858. restorationContext.collection.forEach(function (obj) { obj.dirty = true; });
  28859. patternCtx.restore();
  28860. if (!this.inverted && ((overlayImage && !overlayErasable) || !!this.canvas.overlayColor)) {
  28861. if (overlayErasable) { this.canvas.overlayImage = undefined; }
  28862. __renderOverlay.call(this.canvas, patternCtx);
  28863. if (overlayErasable) { this.canvas.overlayImage = overlayImage; }
  28864. }
  28865. else if (this.inverted && (overlayImage && overlayErasable)) {
  28866. var color = this.canvas.overlayColor;
  28867. this.canvas.overlayColor = undefined;
  28868. __renderOverlay.call(this.canvas, patternCtx);
  28869. this.canvas.overlayColor = color;
  28870. }
  28871. },
  28872. /**
  28873. * Sets brush styles
  28874. * @private
  28875. * @param {CanvasRenderingContext2D} ctx
  28876. */
  28877. _setBrushStyles: function (ctx) {
  28878. this.callSuper('_setBrushStyles', ctx);
  28879. ctx.strokeStyle = 'black';
  28880. },
  28881. /**
  28882. * **Customiztion**
  28883. *
  28884. * if you need the eraser to update on each render (i.e animating during erasing) override this method by **adding** the following (performance may suffer):
  28885. * @example
  28886. * ```
  28887. * if(ctx === this.canvas.contextTop) {
  28888. * this.preparePattern();
  28889. * }
  28890. * ```
  28891. *
  28892. * @override fabric.BaseBrush#_saveAndTransform
  28893. * @param {CanvasRenderingContext2D} ctx
  28894. */
  28895. _saveAndTransform: function (ctx) {
  28896. this.callSuper('_saveAndTransform', ctx);
  28897. this._setBrushStyles(ctx);
  28898. ctx.globalCompositeOperation = ctx === this.canvas.getContext() ? 'destination-out' : 'source-over';
  28899. },
  28900. /**
  28901. * We indicate {@link fabric.PencilBrush} to repaint itself if necessary
  28902. * @returns
  28903. */
  28904. needsFullRender: function () {
  28905. return true;
  28906. },
  28907. /**
  28908. *
  28909. * @param {fabric.Point} pointer
  28910. * @param {fabric.IEvent} options
  28911. * @returns
  28912. */
  28913. onMouseDown: function (pointer, options) {
  28914. if (!this.canvas._isMainEvent(options.e)) {
  28915. return;
  28916. }
  28917. this._prepareForDrawing(pointer);
  28918. // capture coordinates immediately
  28919. // this allows to draw dots (when movement never occurs)
  28920. this._captureDrawingPath(pointer);
  28921. // prepare for erasing
  28922. this.preparePattern();
  28923. this._isErasing = true;
  28924. this.canvas.fire('erasing:start');
  28925. this._render();
  28926. },
  28927. /**
  28928. * Rendering Logic:
  28929. * 1. Use brush to clip canvas by rendering it on top of canvas (unnecessary if `inverted === true`)
  28930. * 2. Render brush with canvas pattern on top context
  28931. *
  28932. */
  28933. _render: function () {
  28934. var ctx;
  28935. if (!this.inverted) {
  28936. // clip canvas
  28937. ctx = this.canvas.getContext();
  28938. this.callSuper('_render', ctx);
  28939. }
  28940. // render brush and mask it with image of non erasables
  28941. ctx = this.canvas.contextTop;
  28942. this.canvas.clearContext(ctx);
  28943. this.callSuper('_render', ctx);
  28944. ctx.save();
  28945. var t = this.canvas.getRetinaScaling(), s = 1 / t;
  28946. ctx.scale(s, s);
  28947. ctx.globalCompositeOperation = 'source-in';
  28948. ctx.drawImage(this._patternCanvas, 0, 0);
  28949. ctx.restore();
  28950. },
  28951. /**
  28952. * Creates fabric.Path object
  28953. * @override
  28954. * @private
  28955. * @param {(string|number)[][]} pathData Path data
  28956. * @return {fabric.Path} Path to add on canvas
  28957. * @returns
  28958. */
  28959. createPath: function (pathData) {
  28960. var path = this.callSuper('createPath', pathData);
  28961. path.globalCompositeOperation = this.inverted ? 'source-over' : 'destination-out';
  28962. path.stroke = this.inverted ? 'white' : 'black';
  28963. path.opacity = this.opacity
  28964. return path;
  28965. },
  28966. /**
  28967. * Utility to apply a clip path to a path.
  28968. * Used to preserve clipping on eraser paths in nested objects.
  28969. * Called when a group has a clip path that should be applied to the path before applying erasing on the group's objects.
  28970. * @param {fabric.Path} path The eraser path in canvas coordinate plane
  28971. * @param {fabric.Object} clipPath The clipPath to apply to the path
  28972. * @param {number[]} clipPathContainerTransformMatrix The transform matrix of the object that the clip path belongs to
  28973. * @returns {fabric.Path} path with clip path
  28974. */
  28975. applyClipPathToPath: function (path, clipPath, clipPathContainerTransformMatrix) {
  28976. var pathInvTransform = fabric.util.invertTransform(path.calcTransformMatrix()),
  28977. clipPathTransform = clipPath.calcTransformMatrix(),
  28978. transform = clipPath.absolutePositioned ?
  28979. pathInvTransform :
  28980. fabric.util.multiplyTransformMatrices(
  28981. pathInvTransform,
  28982. clipPathContainerTransformMatrix
  28983. );
  28984. // when passing down a clip path it becomes relative to the parent
  28985. // so we transform it acoordingly and set `absolutePositioned` to false
  28986. clipPath.absolutePositioned = false;
  28987. fabric.util.applyTransformToObject(
  28988. clipPath,
  28989. fabric.util.multiplyTransformMatrices(
  28990. transform,
  28991. clipPathTransform
  28992. )
  28993. );
  28994. // We need to clip `path` with both `clipPath` and it's own clip path if existing (`path.clipPath`)
  28995. // so in turn `path` erases an object only where it overlaps with all it's clip paths, regardless of how many there are.
  28996. // this is done because both clip paths may have nested clip paths of their own (this method walks down a collection => this may reccur),
  28997. // so we can't assign one to the other's clip path property.
  28998. path.clipPath = path.clipPath ? fabric.util.mergeClipPaths(clipPath, path.clipPath) : clipPath;
  28999. return path;
  29000. },
  29001. /**
  29002. * Utility to apply a clip path to a path.
  29003. * Used to preserve clipping on eraser paths in nested objects.
  29004. * Called when a group has a clip path that should be applied to the path before applying erasing on the group's objects.
  29005. * @param {fabric.Path} path The eraser path
  29006. * @param {fabric.Object} object The clipPath to apply to path belongs to object
  29007. * @param {Function} callback Callback to be invoked with the cloned path after applying the clip path
  29008. */
  29009. clonePathWithClipPath: function (path, object, callback) {
  29010. var objTransform = object.calcTransformMatrix();
  29011. var clipPath = object.clipPath;
  29012. var _this = this;
  29013. path.clone(function (_path) {
  29014. clipPath.clone(function (_clipPath) {
  29015. callback(_this.applyClipPathToPath(_path, _clipPath, objTransform));
  29016. }, ['absolutePositioned', 'inverted']);
  29017. });
  29018. },
  29019. /**
  29020. * Adds path to object's eraser, walks down object's descendants if necessary
  29021. *
  29022. * @fires erasing:end on object
  29023. * @param {fabric.Object} obj
  29024. * @param {fabric.Path} path
  29025. */
  29026. _addPathToObjectEraser: function (obj, path) {
  29027. var _this = this;
  29028. // object is collection, i.e group
  29029. if (obj.forEachObject && obj.erasable === 'deep') {
  29030. var targets = obj._objects.filter(function (_obj) {
  29031. return _obj.erasable;
  29032. });
  29033. if (targets.length > 0 && obj.clipPath) {
  29034. this.clonePathWithClipPath(path, obj, function (_path) {
  29035. targets.forEach(function (_obj) {
  29036. _this._addPathToObjectEraser(_obj, _path);
  29037. });
  29038. });
  29039. }
  29040. else if (targets.length > 0) {
  29041. targets.forEach(function (_obj) {
  29042. _this._addPathToObjectEraser(_obj, path);
  29043. });
  29044. }
  29045. return;
  29046. }
  29047. // prepare eraser
  29048. var eraser = obj.eraser;
  29049. if (!eraser) {
  29050. eraser = new fabric.Eraser();
  29051. obj.eraser = eraser;
  29052. }
  29053. // clone and add path
  29054. path.clone(function (path) {
  29055. // http://fabricjs.com/using-transformations
  29056. var desiredTransform = fabric.util.multiplyTransformMatrices(
  29057. fabric.util.invertTransform(
  29058. obj.calcTransformMatrix()
  29059. ),
  29060. path.calcTransformMatrix()
  29061. );
  29062. fabric.util.applyTransformToObject(path, desiredTransform);
  29063. eraser.addWithUpdate(path);
  29064. obj.set('dirty', true);
  29065. obj.fire('erasing:end', {
  29066. path: path
  29067. });
  29068. if (obj.group && Array.isArray(_this.__subTargets)) {
  29069. _this.__subTargets.push(obj);
  29070. }
  29071. });
  29072. },
  29073. /**
  29074. * Add the eraser path to canvas drawables' clip paths
  29075. *
  29076. * @param {fabric.Canvas} source
  29077. * @param {fabric.Canvas} path
  29078. * @returns {Object} canvas drawables that were erased by the path
  29079. */
  29080. applyEraserToCanvas: function (path) {
  29081. var canvas = this.canvas;
  29082. var drawables = {};
  29083. [
  29084. 'backgroundImage',
  29085. 'overlayImage',
  29086. ].forEach(function (prop) {
  29087. var drawable = canvas[prop];
  29088. if (drawable && drawable.erasable) {
  29089. this._addPathToObjectEraser(drawable, path);
  29090. drawables[prop] = drawable;
  29091. }
  29092. }, this);
  29093. return drawables;
  29094. },
  29095. /**
  29096. * On mouseup after drawing the path on contextTop canvas
  29097. * we use the points captured to create an new fabric path object
  29098. * and add it to every intersected erasable object.
  29099. */
  29100. _finalizeAndAddPath: function () {
  29101. var ctx = this.canvas.contextTop, canvas = this.canvas;
  29102. ctx.closePath();
  29103. if (this.decimate) {
  29104. this._points = this.decimatePoints(this._points, this.decimate);
  29105. }
  29106. // clear
  29107. canvas.clearContext(canvas.contextTop);
  29108. this._isErasing = false;
  29109. var pathData = this._points && this._points.length > 1 ?
  29110. this.convertPointsToSVGPath(this._points) :
  29111. null;
  29112. if (!pathData || this._isEmptySVGPath(pathData)) {
  29113. canvas.fire('erasing:end');
  29114. // do not create 0 width/height paths, as they are
  29115. // rendered inconsistently across browsers
  29116. // Firefox 4, for example, renders a dot,
  29117. // whereas Chrome 10 renders nothing
  29118. canvas.requestRenderAll();
  29119. return;
  29120. }
  29121. var path = this.createPath(pathData);
  29122. // needed for `intersectsWithObject`
  29123. path.setCoords();
  29124. // commense event sequence
  29125. canvas.fire('before:path:created', { path: path });
  29126. // finalize erasing
  29127. var drawables = this.applyEraserToCanvas(path);
  29128. var _this = this;
  29129. this.__subTargets = [];
  29130. var targets = [];
  29131. canvas.forEachObject(function (obj) {
  29132. if (obj.erasable && obj.intersectsWithObject(path, true, true)) {
  29133. _this._addPathToObjectEraser(obj, path);
  29134. targets.push(obj);
  29135. }
  29136. });
  29137. // fire erasing:end
  29138. canvas.fire('erasing:end', {
  29139. path: path,
  29140. targets: targets,
  29141. subTargets: this.__subTargets,
  29142. drawables: drawables
  29143. });
  29144. delete this.__subTargets;
  29145. canvas.requestRenderAll();
  29146. this._resetShadow();
  29147. // fire event 'path' created
  29148. canvas.fire('path:created', { path: path });
  29149. }
  29150. }
  29151. );
  29152. /** ERASER_END */
  29153. })();