fabric.js 665 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452
  1. /* build: `node build.js modules=ALL exclude=json,gestures minifier=uglifyjs` */
  2. /*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */
  3. var fabric = fabric || { version: "1.5.0" };
  4. if (typeof exports !== 'undefined') {
  5. exports.fabric = fabric;
  6. }
  7. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  8. fabric.document = document;
  9. fabric.window = window;
  10. // ensure globality even if entire library were function wrapped (as in Meteor.js packaging system)
  11. window.fabric = fabric;
  12. }
  13. else {
  14. // assume we're running under node.js when document/window are not present
  15. fabric.document = require("jsdom")
  16. .jsdom("<!DOCTYPE html><html><head></head><body></body></html>");
  17. if (fabric.document.createWindow) {
  18. fabric.window = fabric.document.createWindow();
  19. } else {
  20. fabric.window = fabric.document.parentWindow;
  21. }
  22. }
  23. /**
  24. * True when in environment that supports touch events
  25. * @type boolean
  26. */
  27. fabric.isTouchSupported = "ontouchstart" in fabric.document.documentElement;
  28. /**
  29. * True when in environment that's probably Node.js
  30. * @type boolean
  31. */
  32. fabric.isLikelyNode = typeof Buffer !== 'undefined' &&
  33. typeof window === 'undefined';
  34. /* _FROM_SVG_START_ */
  35. /**
  36. * Attributes parsed from all SVG elements
  37. * @type array
  38. */
  39. fabric.SHARED_ATTRIBUTES = [
  40. "display",
  41. "transform",
  42. "fill", "fill-opacity", "fill-rule",
  43. "opacity",
  44. "stroke", "stroke-dasharray", "stroke-linecap",
  45. "stroke-linejoin", "stroke-miterlimit",
  46. "stroke-opacity", "stroke-width"
  47. ];
  48. /* _FROM_SVG_END_ */
  49. /**
  50. * Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
  51. */
  52. fabric.DPI = 96;
  53. fabric.reNum = '(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:e[-+]?\\d+)?)';
  54. (function() {
  55. /**
  56. * @private
  57. * @param {String} eventName
  58. * @param {Function} handler
  59. */
  60. function _removeEventListener(eventName, handler) {
  61. if (!this.__eventListeners[eventName]) {
  62. return;
  63. }
  64. if (handler) {
  65. fabric.util.removeFromArray(this.__eventListeners[eventName], handler);
  66. }
  67. else {
  68. this.__eventListeners[eventName].length = 0;
  69. }
  70. }
  71. /**
  72. * Observes specified event
  73. * @deprecated `observe` deprecated since 0.8.34 (use `on` instead)
  74. * @memberOf fabric.Observable
  75. * @alias on
  76. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  77. * @param {Function} handler Function that receives a notification when an event of the specified type occurs
  78. * @return {Self} thisArg
  79. * @chainable
  80. */
  81. function observe(eventName, handler) {
  82. if (!this.__eventListeners) {
  83. this.__eventListeners = { };
  84. }
  85. // one object with key/value pairs was passed
  86. if (arguments.length === 1) {
  87. for (var prop in eventName) {
  88. this.on(prop, eventName[prop]);
  89. }
  90. }
  91. else {
  92. if (!this.__eventListeners[eventName]) {
  93. this.__eventListeners[eventName] = [ ];
  94. }
  95. this.__eventListeners[eventName].push(handler);
  96. }
  97. return this;
  98. }
  99. /**
  100. * Stops event observing for a particular event handler. Calling this method
  101. * without arguments removes all handlers for all events
  102. * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
  103. * @memberOf fabric.Observable
  104. * @alias off
  105. * @param {String|Object} eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
  106. * @param {Function} handler Function to be deleted from EventListeners
  107. * @return {Self} thisArg
  108. * @chainable
  109. */
  110. function stopObserving(eventName, handler) {
  111. if (!this.__eventListeners) {
  112. return;
  113. }
  114. // remove all key/value pairs (event name -> event handler)
  115. if (arguments.length === 0) {
  116. this.__eventListeners = { };
  117. }
  118. // one object with key/value pairs was passed
  119. else if (arguments.length === 1 && typeof arguments[0] === 'object') {
  120. for (var prop in eventName) {
  121. _removeEventListener.call(this, prop, eventName[prop]);
  122. }
  123. }
  124. else {
  125. _removeEventListener.call(this, eventName, handler);
  126. }
  127. return this;
  128. }
  129. /**
  130. * Fires event with an optional options object
  131. * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
  132. * @memberOf fabric.Observable
  133. * @alias trigger
  134. * @param {String} eventName Event name to fire
  135. * @param {Object} [options] Options object
  136. * @return {Self} thisArg
  137. * @chainable
  138. */
  139. function fire(eventName, options) {
  140. if (!this.__eventListeners) {
  141. return;
  142. }
  143. var listenersForEvent = this.__eventListeners[eventName];
  144. if (!listenersForEvent) {
  145. return;
  146. }
  147. for (var i = 0, len = listenersForEvent.length; i < len; i++) {
  148. // avoiding try/catch for perf. reasons
  149. listenersForEvent[i].call(this, options || { });
  150. }
  151. return this;
  152. }
  153. /**
  154. * @namespace fabric.Observable
  155. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#events}
  156. * @see {@link http://fabricjs.com/events/|Events demo}
  157. */
  158. fabric.Observable = {
  159. observe: observe,
  160. stopObserving: stopObserving,
  161. fire: fire,
  162. on: observe,
  163. off: stopObserving,
  164. trigger: fire
  165. };
  166. })();
  167. /**
  168. * @namespace fabric.Collection
  169. */
  170. fabric.Collection = {
  171. /**
  172. * Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`)
  173. * Objects should be instances of (or inherit from) fabric.Object
  174. * @param {...fabric.Object} object Zero or more fabric instances
  175. * @return {Self} thisArg
  176. */
  177. add: function () {
  178. this._objects.push.apply(this._objects, arguments);
  179. for (var i = 0, length = arguments.length; i < length; i++) {
  180. this._onObjectAdded(arguments[i]);
  181. }
  182. this.renderOnAddRemove && this.renderAll();
  183. return this;
  184. },
  185. /**
  186. * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`)
  187. * An object should be an instance of (or inherit from) fabric.Object
  188. * @param {Object} object Object to insert
  189. * @param {Number} index Index to insert object at
  190. * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs
  191. * @return {Self} thisArg
  192. * @chainable
  193. */
  194. insertAt: function (object, index, nonSplicing) {
  195. var objects = this.getObjects();
  196. if (nonSplicing) {
  197. objects[index] = object;
  198. }
  199. else {
  200. objects.splice(index, 0, object);
  201. }
  202. this._onObjectAdded(object);
  203. this.renderOnAddRemove && this.renderAll();
  204. return this;
  205. },
  206. /**
  207. * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`)
  208. * @param {...fabric.Object} object Zero or more fabric instances
  209. * @return {Self} thisArg
  210. * @chainable
  211. */
  212. remove: function() {
  213. var objects = this.getObjects(),
  214. index;
  215. for (var i = 0, length = arguments.length; i < length; i++) {
  216. index = objects.indexOf(arguments[i]);
  217. // only call onObjectRemoved if an object was actually removed
  218. if (index !== -1) {
  219. objects.splice(index, 1);
  220. this._onObjectRemoved(arguments[i]);
  221. }
  222. }
  223. this.renderOnAddRemove && this.renderAll();
  224. return this;
  225. },
  226. /**
  227. * Executes given function for each object in this group
  228. * @param {Function} callback
  229. * Callback invoked with current object as first argument,
  230. * index - as second and an array of all objects - as third.
  231. * Iteration happens in reverse order (for performance reasons).
  232. * Callback is invoked in a context of Global Object (e.g. `window`)
  233. * when no `context` argument is given
  234. *
  235. * @param {Object} context Context (aka thisObject)
  236. * @return {Self} thisArg
  237. */
  238. forEachObject: function(callback, context) {
  239. var objects = this.getObjects(),
  240. i = objects.length;
  241. while (i--) {
  242. callback.call(context, objects[i], i, objects);
  243. }
  244. return this;
  245. },
  246. /**
  247. * Returns an array of children objects of this instance
  248. * Type parameter introduced in 1.3.10
  249. * @param {String} [type] When specified, only objects of this type are returned
  250. * @return {Array}
  251. */
  252. getObjects: function(type) {
  253. if (typeof type === 'undefined') {
  254. return this._objects;
  255. }
  256. return this._objects.filter(function(o) {
  257. return o.type === type;
  258. });
  259. },
  260. /**
  261. * Returns object at specified index
  262. * @param {Number} index
  263. * @return {Self} thisArg
  264. */
  265. item: function (index) {
  266. return this.getObjects()[index];
  267. },
  268. /**
  269. * Returns true if collection contains no objects
  270. * @return {Boolean} true if collection is empty
  271. */
  272. isEmpty: function () {
  273. return this.getObjects().length === 0;
  274. },
  275. /**
  276. * Returns a size of a collection (i.e: length of an array containing its objects)
  277. * @return {Number} Collection size
  278. */
  279. size: function() {
  280. return this.getObjects().length;
  281. },
  282. /**
  283. * Returns true if collection contains an object
  284. * @param {Object} object Object to check against
  285. * @return {Boolean} `true` if collection contains an object
  286. */
  287. contains: function(object) {
  288. return this.getObjects().indexOf(object) > -1;
  289. },
  290. /**
  291. * Returns number representation of a collection complexity
  292. * @return {Number} complexity
  293. */
  294. complexity: function () {
  295. return this.getObjects().reduce(function (memo, current) {
  296. memo += current.complexity ? current.complexity() : 0;
  297. return memo;
  298. }, 0);
  299. }
  300. };
  301. (function(global) {
  302. var sqrt = Math.sqrt,
  303. atan2 = Math.atan2,
  304. PiBy180 = Math.PI / 180;
  305. /**
  306. * @namespace fabric.util
  307. */
  308. fabric.util = {
  309. /**
  310. * Removes value from an array.
  311. * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf`
  312. * @static
  313. * @memberOf fabric.util
  314. * @param {Array} array
  315. * @param {Any} value
  316. * @return {Array} original array
  317. */
  318. removeFromArray: function(array, value) {
  319. var idx = array.indexOf(value);
  320. if (idx !== -1) {
  321. array.splice(idx, 1);
  322. }
  323. return array;
  324. },
  325. /**
  326. * Returns random number between 2 specified ones.
  327. * @static
  328. * @memberOf fabric.util
  329. * @param {Number} min lower limit
  330. * @param {Number} max upper limit
  331. * @return {Number} random value (between min and max)
  332. */
  333. getRandomInt: function(min, max) {
  334. return Math.floor(Math.random() * (max - min + 1)) + min;
  335. },
  336. /**
  337. * Transforms degrees to radians.
  338. * @static
  339. * @memberOf fabric.util
  340. * @param {Number} degrees value in degrees
  341. * @return {Number} value in radians
  342. */
  343. degreesToRadians: function(degrees) {
  344. return degrees * PiBy180;
  345. },
  346. /**
  347. * Transforms radians to degrees.
  348. * @static
  349. * @memberOf fabric.util
  350. * @param {Number} radians value in radians
  351. * @return {Number} value in degrees
  352. */
  353. radiansToDegrees: function(radians) {
  354. return radians / PiBy180;
  355. },
  356. /**
  357. * Rotates `point` around `origin` with `radians`
  358. * @static
  359. * @memberOf fabric.util
  360. * @param {fabric.Point} point The point to rotate
  361. * @param {fabric.Point} origin The origin of the rotation
  362. * @param {Number} radians The radians of the angle for the rotation
  363. * @return {fabric.Point} The new rotated point
  364. */
  365. rotatePoint: function(point, origin, radians) {
  366. var sin = Math.sin(radians),
  367. cos = Math.cos(radians);
  368. point.subtractEquals(origin);
  369. var rx = point.x * cos - point.y * sin,
  370. ry = point.x * sin + point.y * cos;
  371. return new fabric.Point(rx, ry).addEquals(origin);
  372. },
  373. /**
  374. * Apply transform t to point p
  375. * @static
  376. * @memberOf fabric.util
  377. * @param {fabric.Point} p The point to transform
  378. * @param {Array} t The transform
  379. * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied
  380. * @return {fabric.Point} The transformed point
  381. */
  382. transformPoint: function(p, t, ignoreOffset) {
  383. if (ignoreOffset) {
  384. return new fabric.Point(
  385. t[0] * p.x + t[2] * p.y,
  386. t[1] * p.x + t[3] * p.y
  387. );
  388. }
  389. return new fabric.Point(
  390. t[0] * p.x + t[2] * p.y + t[4],
  391. t[1] * p.x + t[3] * p.y + t[5]
  392. );
  393. },
  394. /**
  395. * Invert transformation t
  396. * @static
  397. * @memberOf fabric.util
  398. * @param {Array} t The transform
  399. * @return {Array} The inverted transform
  400. */
  401. invertTransform: function(t) {
  402. var r = t.slice(),
  403. a = 1 / (t[0] * t[3] - t[1] * t[2]);
  404. r = [a * t[3], -a * t[1], -a * t[2], a * t[0], 0, 0];
  405. var o = fabric.util.transformPoint({ x: t[4], y: t[5] }, r);
  406. r[4] = -o.x;
  407. r[5] = -o.y;
  408. return r;
  409. },
  410. /**
  411. * A wrapper around Number#toFixed, which contrary to native method returns number, not string.
  412. * @static
  413. * @memberOf fabric.util
  414. * @param {Number|String} number number to operate on
  415. * @param {Number} fractionDigits number of fraction digits to "leave"
  416. * @return {Number}
  417. */
  418. toFixed: function(number, fractionDigits) {
  419. return parseFloat(Number(number).toFixed(fractionDigits));
  420. },
  421. /**
  422. * Converts from attribute value to pixel value if applicable.
  423. * Returns converted pixels or original value not converted.
  424. * @param {Number|String} value number to operate on
  425. * @return {Number|String}
  426. */
  427. parseUnit: function(value, fontSize) {
  428. var unit = /\D{0,2}$/.exec(value),
  429. number = parseFloat(value);
  430. if (!fontSize) {
  431. fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
  432. }
  433. switch (unit[0]) {
  434. case 'mm':
  435. return number * fabric.DPI / 25.4;
  436. case 'cm':
  437. return number * fabric.DPI / 2.54;
  438. case 'in':
  439. return number * fabric.DPI;
  440. case 'pt':
  441. return number * fabric.DPI / 72; // or * 4 / 3
  442. case 'pc':
  443. return number * fabric.DPI / 72 * 12; // or * 16
  444. case 'em':
  445. return number * fontSize;
  446. default:
  447. return number;
  448. }
  449. },
  450. /**
  451. * Function which always returns `false`.
  452. * @static
  453. * @memberOf fabric.util
  454. * @return {Boolean}
  455. */
  456. falseFunction: function() {
  457. return false;
  458. },
  459. /**
  460. * Returns klass "Class" object of given namespace
  461. * @memberOf fabric.util
  462. * @param {String} type Type of object (eg. 'circle')
  463. * @param {String} namespace Namespace to get klass "Class" object from
  464. * @return {Object} klass "Class"
  465. */
  466. getKlass: function(type, namespace) {
  467. // capitalize first letter only
  468. type = fabric.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
  469. return fabric.util.resolveNamespace(namespace)[type];
  470. },
  471. /**
  472. * Returns object of given namespace
  473. * @memberOf fabric.util
  474. * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric'
  475. * @return {Object} Object for given namespace (default fabric)
  476. */
  477. resolveNamespace: function(namespace) {
  478. if (!namespace) {
  479. return fabric;
  480. }
  481. var parts = namespace.split('.'),
  482. len = parts.length,
  483. obj = global || fabric.window;
  484. for (var i = 0; i < len; ++i) {
  485. obj = obj[parts[i]];
  486. }
  487. return obj;
  488. },
  489. /**
  490. * Loads image element from given url and passes it to a callback
  491. * @memberOf fabric.util
  492. * @param {String} url URL representing an image
  493. * @param {Function} callback Callback; invoked with loaded image
  494. * @param {Any} [context] Context to invoke callback in
  495. * @param {Object} [crossOrigin] crossOrigin value to set image element to
  496. */
  497. loadImage: function(url, callback, context, crossOrigin) {
  498. if (!url) {
  499. callback && callback.call(context, url);
  500. return;
  501. }
  502. var img = fabric.util.createImage();
  503. /** @ignore */
  504. img.onload = function () {
  505. callback && callback.call(context, img);
  506. img = img.onload = img.onerror = null;
  507. };
  508. /** @ignore */
  509. img.onerror = function() {
  510. fabric.log('Error loading ' + img.src);
  511. callback && callback.call(context, null, true);
  512. img = img.onload = img.onerror = null;
  513. };
  514. // data-urls appear to be buggy with crossOrigin
  515. // https://github.com/kangax/fabric.js/commit/d0abb90f1cd5c5ef9d2a94d3fb21a22330da3e0a#commitcomment-4513767
  516. // see https://code.google.com/p/chromium/issues/detail?id=315152
  517. // https://bugzilla.mozilla.org/show_bug.cgi?id=935069
  518. if (url.indexOf('data') !== 0 && typeof crossOrigin !== 'undefined') {
  519. img.crossOrigin = crossOrigin;
  520. }
  521. img.src = url;
  522. },
  523. /**
  524. * Creates corresponding fabric instances from their object representations
  525. * @static
  526. * @memberOf fabric.util
  527. * @param {Array} objects Objects to enliven
  528. * @param {Function} callback Callback to invoke when all objects are created
  529. * @param {String} namespace Namespace to get klass "Class" object from
  530. * @param {Function} reviver Method for further parsing of object elements,
  531. * called after each fabric object created.
  532. */
  533. enlivenObjects: function(objects, callback, namespace, reviver) {
  534. objects = objects || [ ];
  535. function onLoaded() {
  536. if (++numLoadedObjects === numTotalObjects) {
  537. callback && callback(enlivenedObjects);
  538. }
  539. }
  540. var enlivenedObjects = [ ],
  541. numLoadedObjects = 0,
  542. numTotalObjects = objects.length;
  543. if (!numTotalObjects) {
  544. callback && callback(enlivenedObjects);
  545. return;
  546. }
  547. objects.forEach(function (o, index) {
  548. // if sparse array
  549. if (!o || !o.type) {
  550. onLoaded();
  551. return;
  552. }
  553. var klass = fabric.util.getKlass(o.type, namespace);
  554. if (klass.async) {
  555. klass.fromObject(o, function (obj, error) {
  556. if (!error) {
  557. enlivenedObjects[index] = obj;
  558. reviver && reviver(o, enlivenedObjects[index]);
  559. }
  560. onLoaded();
  561. });
  562. }
  563. else {
  564. enlivenedObjects[index] = klass.fromObject(o);
  565. reviver && reviver(o, enlivenedObjects[index]);
  566. onLoaded();
  567. }
  568. });
  569. },
  570. /**
  571. * Groups SVG elements (usually those retrieved from SVG document)
  572. * @static
  573. * @memberOf fabric.util
  574. * @param {Array} elements SVG elements to group
  575. * @param {Object} [options] Options object
  576. * @return {fabric.Object|fabric.PathGroup}
  577. */
  578. groupSVGElements: function(elements, options, path) {
  579. var object;
  580. object = new fabric.PathGroup(elements, options);
  581. if (typeof path !== 'undefined') {
  582. object.setSourcePath(path);
  583. }
  584. return object;
  585. },
  586. /**
  587. * Populates an object with properties of another object
  588. * @static
  589. * @memberOf fabric.util
  590. * @param {Object} source Source object
  591. * @param {Object} destination Destination object
  592. * @return {Array} properties Propertie names to include
  593. */
  594. populateWithProperties: function(source, destination, properties) {
  595. if (properties && Object.prototype.toString.call(properties) === '[object Array]') {
  596. for (var i = 0, len = properties.length; i < len; i++) {
  597. if (properties[i] in source) {
  598. destination[properties[i]] = source[properties[i]];
  599. }
  600. }
  601. }
  602. },
  603. /**
  604. * Draws a dashed line between two points
  605. *
  606. * This method is used to draw dashed line around selection area.
  607. * See <a href="http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas">dotted stroke in canvas</a>
  608. *
  609. * @param {CanvasRenderingContext2D} ctx context
  610. * @param {Number} x start x coordinate
  611. * @param {Number} y start y coordinate
  612. * @param {Number} x2 end x coordinate
  613. * @param {Number} y2 end y coordinate
  614. * @param {Array} da dash array pattern
  615. */
  616. drawDashedLine: function(ctx, x, y, x2, y2, da) {
  617. var dx = x2 - x,
  618. dy = y2 - y,
  619. len = sqrt(dx * dx + dy * dy),
  620. rot = atan2(dy, dx),
  621. dc = da.length,
  622. di = 0,
  623. draw = true;
  624. ctx.save();
  625. ctx.translate(x, y);
  626. ctx.moveTo(0, 0);
  627. ctx.rotate(rot);
  628. x = 0;
  629. while (len > x) {
  630. x += da[di++ % dc];
  631. if (x > len) {
  632. x = len;
  633. }
  634. ctx[draw ? 'lineTo' : 'moveTo'](x, 0);
  635. draw = !draw;
  636. }
  637. ctx.restore();
  638. },
  639. /**
  640. * Creates canvas element and initializes it via excanvas if necessary
  641. * @static
  642. * @memberOf fabric.util
  643. * @param {CanvasElement} [canvasEl] optional canvas element to initialize;
  644. * when not given, element is created implicitly
  645. * @return {CanvasElement} initialized canvas element
  646. */
  647. createCanvasElement: function(canvasEl) {
  648. canvasEl || (canvasEl = fabric.document.createElement('canvas'));
  649. //jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  650. if (!canvasEl.getContext && typeof G_vmlCanvasManager !== 'undefined') {
  651. G_vmlCanvasManager.initElement(canvasEl);
  652. }
  653. //jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  654. return canvasEl;
  655. },
  656. /**
  657. * Creates image element (works on client and node)
  658. * @static
  659. * @memberOf fabric.util
  660. * @return {HTMLImageElement} HTML image element
  661. */
  662. createImage: function() {
  663. return fabric.isLikelyNode
  664. ? new (require('canvas').Image)()
  665. : fabric.document.createElement('img');
  666. },
  667. /**
  668. * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array
  669. * @static
  670. * @memberOf fabric.util
  671. * @param {Object} klass "Class" to create accessors for
  672. */
  673. createAccessors: function(klass) {
  674. var proto = klass.prototype;
  675. for (var i = proto.stateProperties.length; i--; ) {
  676. var propName = proto.stateProperties[i],
  677. capitalizedPropName = propName.charAt(0).toUpperCase() + propName.slice(1),
  678. setterName = 'set' + capitalizedPropName,
  679. getterName = 'get' + capitalizedPropName;
  680. // using `new Function` for better introspection
  681. if (!proto[getterName]) {
  682. proto[getterName] = (function(property) {
  683. return new Function('return this.get("' + property + '")');
  684. })(propName);
  685. }
  686. if (!proto[setterName]) {
  687. proto[setterName] = (function(property) {
  688. return new Function('value', 'return this.set("' + property + '", value)');
  689. })(propName);
  690. }
  691. }
  692. },
  693. /**
  694. * @static
  695. * @memberOf fabric.util
  696. * @param {fabric.Object} receiver Object implementing `clipTo` method
  697. * @param {CanvasRenderingContext2D} ctx Context to clip
  698. */
  699. clipContext: function(receiver, ctx) {
  700. ctx.save();
  701. ctx.beginPath();
  702. receiver.clipTo(ctx);
  703. ctx.clip();
  704. },
  705. /**
  706. * Multiply matrix A by matrix B to nest transformations
  707. * @static
  708. * @memberOf fabric.util
  709. * @param {Array} a First transformMatrix
  710. * @param {Array} b Second transformMatrix
  711. * @return {Array} The product of the two transform matrices
  712. */
  713. multiplyTransformMatrices: function(a, b) {
  714. // Matrix multiply a * b
  715. return [
  716. a[0] * b[0] + a[2] * b[1],
  717. a[1] * b[0] + a[3] * b[1],
  718. a[0] * b[2] + a[2] * b[3],
  719. a[1] * b[2] + a[3] * b[3],
  720. a[0] * b[4] + a[2] * b[5] + a[4],
  721. a[1] * b[4] + a[3] * b[5] + a[5]
  722. ];
  723. },
  724. /**
  725. * Returns string representation of function body
  726. * @param {Function} fn Function to get body of
  727. * @return {String} Function body
  728. */
  729. getFunctionBody: function(fn) {
  730. return (String(fn).match(/function[^{]*\{([\s\S]*)\}/) || {})[1];
  731. },
  732. /**
  733. * Returns true if context has transparent pixel
  734. * at specified location (taking tolerance into account)
  735. * @param {CanvasRenderingContext2D} ctx context
  736. * @param {Number} x x coordinate
  737. * @param {Number} y y coordinate
  738. * @param {Number} tolerance Tolerance
  739. */
  740. isTransparent: function(ctx, x, y, tolerance) {
  741. // If tolerance is > 0 adjust start coords to take into account.
  742. // If moves off Canvas fix to 0
  743. if (tolerance > 0) {
  744. if (x > tolerance) {
  745. x -= tolerance;
  746. }
  747. else {
  748. x = 0;
  749. }
  750. if (y > tolerance) {
  751. y -= tolerance;
  752. }
  753. else {
  754. y = 0;
  755. }
  756. }
  757. var _isTransparent = true,
  758. imageData = ctx.getImageData(x, y, (tolerance * 2) || 1, (tolerance * 2) || 1);
  759. // Split image data - for tolerance > 1, pixelDataSize = 4;
  760. for (var i = 3, l = imageData.data.length; i < l; i += 4) {
  761. var temp = imageData.data[i];
  762. _isTransparent = temp <= 0;
  763. if (_isTransparent === false) {
  764. break; // Stop if colour found
  765. }
  766. }
  767. imageData = null;
  768. return _isTransparent;
  769. }
  770. };
  771. })(typeof exports !== 'undefined' ? exports : this);
  772. (function() {
  773. var arcToSegmentsCache = { },
  774. segmentToBezierCache = { },
  775. boundsOfCurveCache = { },
  776. _join = Array.prototype.join;
  777. /* Adapted from http://dxr.mozilla.org/mozilla-central/source/content/svg/content/src/nsSVGPathDataParser.cpp
  778. * by Andrea Bogazzi code is under MPL. if you don't have a copy of the license you can take it here
  779. * http://mozilla.org/MPL/2.0/
  780. */
  781. function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {
  782. var argsString = _join.call(arguments);
  783. if (arcToSegmentsCache[argsString]) {
  784. return arcToSegmentsCache[argsString];
  785. }
  786. var PI = Math.PI, th = rotateX * PI / 180,
  787. sinTh = Math.sin(th),
  788. cosTh = Math.cos(th),
  789. fromX = 0, fromY = 0;
  790. rx = Math.abs(rx);
  791. ry = Math.abs(ry);
  792. var px = -cosTh * toX * 0.5 - sinTh * toY * 0.5,
  793. py = -cosTh * toY * 0.5 + sinTh * toX * 0.5,
  794. rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px2 = px * px,
  795. pl = rx2 * ry2 - rx2 * py2 - ry2 * px2,
  796. root = 0;
  797. if (pl < 0) {
  798. var s = Math.sqrt(1 - pl/(rx2 * ry2));
  799. rx *= s;
  800. ry *= s;
  801. }
  802. else {
  803. root = (large === sweep ? -1.0 : 1.0) *
  804. Math.sqrt( pl /(rx2 * py2 + ry2 * px2));
  805. }
  806. var cx = root * rx * py / ry,
  807. cy = -root * ry * px / rx,
  808. cx1 = cosTh * cx - sinTh * cy + toX * 0.5,
  809. cy1 = sinTh * cx + cosTh * cy + toY * 0.5,
  810. mTheta = calcVectorAngle(1, 0, (px - cx) / rx, (py - cy) / ry),
  811. dtheta = calcVectorAngle((px - cx) / rx, (py - cy) / ry, (-px - cx) / rx, (-py - cy) / ry);
  812. if (sweep === 0 && dtheta > 0) {
  813. dtheta -= 2 * PI;
  814. }
  815. else if (sweep === 1 && dtheta < 0) {
  816. dtheta += 2 * PI;
  817. }
  818. // Convert into cubic bezier segments <= 90deg
  819. var segments = Math.ceil(Math.abs(dtheta / PI * 2)),
  820. result = [], mDelta = dtheta / segments,
  821. mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2),
  822. th3 = mTheta + mDelta;
  823. for (var i = 0; i < segments; i++) {
  824. result[i] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);
  825. fromX = result[i][4];
  826. fromY = result[i][5];
  827. mTheta = th3;
  828. th3 += mDelta;
  829. }
  830. arcToSegmentsCache[argsString] = result;
  831. return result;
  832. }
  833. function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {
  834. var argsString2 = _join.call(arguments);
  835. if (segmentToBezierCache[argsString2]) {
  836. return segmentToBezierCache[argsString2];
  837. }
  838. var costh2 = Math.cos(th2),
  839. sinth2 = Math.sin(th2),
  840. costh3 = Math.cos(th3),
  841. sinth3 = Math.sin(th3),
  842. toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1,
  843. toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1,
  844. cp1X = fromX + mT * ( - cosTh * rx * sinth2 - sinTh * ry * costh2),
  845. cp1Y = fromY + mT * ( - sinTh * rx * sinth2 + cosTh * ry * costh2),
  846. cp2X = toX + mT * ( cosTh * rx * sinth3 + sinTh * ry * costh3),
  847. cp2Y = toY + mT * ( sinTh * rx * sinth3 - cosTh * ry * costh3);
  848. segmentToBezierCache[argsString2] = [
  849. cp1X, cp1Y,
  850. cp2X, cp2Y,
  851. toX, toY
  852. ];
  853. return segmentToBezierCache[argsString2];
  854. }
  855. /*
  856. * Private
  857. */
  858. function calcVectorAngle(ux, uy, vx, vy) {
  859. var ta = Math.atan2(uy, ux),
  860. tb = Math.atan2(vy, vx);
  861. if (tb >= ta) {
  862. return tb - ta;
  863. }
  864. else {
  865. return 2 * Math.PI - (ta - tb);
  866. }
  867. }
  868. /**
  869. * Draws arc
  870. * @param {CanvasRenderingContext2D} ctx
  871. * @param {Number} fx
  872. * @param {Number} fy
  873. * @param {Array} coords
  874. */
  875. fabric.util.drawArc = function(ctx, fx, fy, coords) {
  876. var rx = coords[0],
  877. ry = coords[1],
  878. rot = coords[2],
  879. large = coords[3],
  880. sweep = coords[4],
  881. tx = coords[5],
  882. ty = coords[6],
  883. segs = [[ ], [ ], [ ], [ ]],
  884. segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
  885. for (var i = 0, len = segsNorm.length; i < len; i++) {
  886. segs[i][0] = segsNorm[i][0] + fx;
  887. segs[i][1] = segsNorm[i][1] + fy;
  888. segs[i][2] = segsNorm[i][2] + fx;
  889. segs[i][3] = segsNorm[i][3] + fy;
  890. segs[i][4] = segsNorm[i][4] + fx;
  891. segs[i][5] = segsNorm[i][5] + fy;
  892. ctx.bezierCurveTo.apply(ctx, segs[i]);
  893. }
  894. };
  895. /**
  896. * Calculate bounding box of a elliptic-arc
  897. * @param {Number} fx start point of arc
  898. * @param {Number} fy
  899. * @param {Number} rx horizontal radius
  900. * @param {Number} ry vertical radius
  901. * @param {Number} rot angle of horizontal axe
  902. * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points
  903. * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction
  904. * @param {Number} tx end point of arc
  905. * @param {Number} ty
  906. */
  907. fabric.util.getBoundsOfArc = function(fx, fy, rx, ry, rot, large, sweep, tx, ty) {
  908. var fromX = 0, fromY = 0, bound = [ ], bounds = [ ],
  909. segs = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot),
  910. boundCopy = [[ ], [ ]];
  911. for (var i = 0, len = segs.length; i < len; i++) {
  912. bound = getBoundsOfCurve(fromX, fromY, segs[i][0], segs[i][1], segs[i][2], segs[i][3], segs[i][4], segs[i][5]);
  913. boundCopy[0].x = bound[0].x + fx;
  914. boundCopy[0].y = bound[0].y + fy;
  915. boundCopy[1].x = bound[1].x + fx;
  916. boundCopy[1].y = bound[1].y + fy;
  917. bounds.push(boundCopy[0]);
  918. bounds.push(boundCopy[1]);
  919. fromX = segs[i][4];
  920. fromY = segs[i][5];
  921. }
  922. return bounds;
  923. };
  924. /**
  925. * Calculate bounding box of a beziercurve
  926. * @param {Number} x0 starting point
  927. * @param {Number} y0
  928. * @param {Number} x1 first control point
  929. * @param {Number} y1
  930. * @param {Number} x2 secondo control point
  931. * @param {Number} y2
  932. * @param {Number} x3 end of beizer
  933. * @param {Number} y3
  934. */
  935. // taken from http://jsbin.com/ivomiq/56/edit no credits available for that.
  936. function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {
  937. var argsString = _join.call(arguments);
  938. if (boundsOfCurveCache[argsString]) {
  939. return boundsOfCurveCache[argsString];
  940. }
  941. var sqrt = Math.sqrt,
  942. min = Math.min, max = Math.max,
  943. abs = Math.abs, tvalues = [ ],
  944. bounds = [[ ], [ ]],
  945. a, b, c, t, t1, t2, b2ac, sqrtb2ac;
  946. b = 6 * x0 - 12 * x1 + 6 * x2;
  947. a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
  948. c = 3 * x1 - 3 * x0;
  949. for (var i = 0; i < 2; ++i) {
  950. if (i > 0) {
  951. b = 6 * y0 - 12 * y1 + 6 * y2;
  952. a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
  953. c = 3 * y1 - 3 * y0;
  954. }
  955. if (abs(a) < 1e-12) {
  956. if (abs(b) < 1e-12) {
  957. continue;
  958. }
  959. t = -c / b;
  960. if (0 < t && t < 1) {
  961. tvalues.push(t);
  962. }
  963. continue;
  964. }
  965. b2ac = b * b - 4 * c * a;
  966. if (b2ac < 0) {
  967. continue;
  968. }
  969. sqrtb2ac = sqrt(b2ac);
  970. t1 = (-b + sqrtb2ac) / (2 * a);
  971. if (0 < t1 && t1 < 1) {
  972. tvalues.push(t1);
  973. }
  974. t2 = (-b - sqrtb2ac) / (2 * a);
  975. if (0 < t2 && t2 < 1) {
  976. tvalues.push(t2);
  977. }
  978. }
  979. var x, y, j = tvalues.length, jlen = j, mt;
  980. while (j--) {
  981. t = tvalues[j];
  982. mt = 1 - t;
  983. x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
  984. bounds[0][j] = x;
  985. y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
  986. bounds[1][j] = y;
  987. }
  988. bounds[0][jlen] = x0;
  989. bounds[1][jlen] = y0;
  990. bounds[0][jlen + 1] = x3;
  991. bounds[1][jlen + 1] = y3;
  992. var result = [
  993. {
  994. x: min.apply(null, bounds[0]),
  995. y: min.apply(null, bounds[1])
  996. },
  997. {
  998. x: max.apply(null, bounds[0]),
  999. y: max.apply(null, bounds[1])
  1000. }
  1001. ];
  1002. boundsOfCurveCache[argsString] = result;
  1003. return result;
  1004. }
  1005. fabric.util.getBoundsOfCurve = getBoundsOfCurve;
  1006. })();
  1007. (function() {
  1008. var slice = Array.prototype.slice;
  1009. /* _ES5_COMPAT_START_ */
  1010. if (!Array.prototype.indexOf) {
  1011. /**
  1012. * Finds index of an element in an array
  1013. * @param {Any} searchElement
  1014. * @param {Number} [fromIndex]
  1015. * @return {Number}
  1016. */
  1017. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  1018. if (this === void 0 || this === null) {
  1019. throw new TypeError();
  1020. }
  1021. var t = Object(this), len = t.length >>> 0;
  1022. if (len === 0) {
  1023. return -1;
  1024. }
  1025. var n = 0;
  1026. if (arguments.length > 0) {
  1027. n = Number(arguments[1]);
  1028. if (n !== n) { // shortcut for verifying if it's NaN
  1029. n = 0;
  1030. }
  1031. else if (n !== 0 && n !== Number.POSITIVE_INFINITY && n !== Number.NEGATIVE_INFINITY) {
  1032. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  1033. }
  1034. }
  1035. if (n >= len) {
  1036. return -1;
  1037. }
  1038. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  1039. for (; k < len; k++) {
  1040. if (k in t && t[k] === searchElement) {
  1041. return k;
  1042. }
  1043. }
  1044. return -1;
  1045. };
  1046. }
  1047. if (!Array.prototype.forEach) {
  1048. /**
  1049. * Iterates an array, invoking callback for each element
  1050. * @param {Function} fn Callback to invoke for each element
  1051. * @param {Object} [context] Context to invoke callback in
  1052. * @return {Array}
  1053. */
  1054. Array.prototype.forEach = function(fn, context) {
  1055. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1056. if (i in this) {
  1057. fn.call(context, this[i], i, this);
  1058. }
  1059. }
  1060. };
  1061. }
  1062. if (!Array.prototype.map) {
  1063. /**
  1064. * Returns a result of iterating over an array, invoking callback for each element
  1065. * @param {Function} fn Callback to invoke for each element
  1066. * @param {Object} [context] Context to invoke callback in
  1067. * @return {Array}
  1068. */
  1069. Array.prototype.map = function(fn, context) {
  1070. var result = [ ];
  1071. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1072. if (i in this) {
  1073. result[i] = fn.call(context, this[i], i, this);
  1074. }
  1075. }
  1076. return result;
  1077. };
  1078. }
  1079. if (!Array.prototype.every) {
  1080. /**
  1081. * Returns true if a callback returns truthy value for all elements in an array
  1082. * @param {Function} fn Callback to invoke for each element
  1083. * @param {Object} [context] Context to invoke callback in
  1084. * @return {Boolean}
  1085. */
  1086. Array.prototype.every = function(fn, context) {
  1087. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1088. if (i in this && !fn.call(context, this[i], i, this)) {
  1089. return false;
  1090. }
  1091. }
  1092. return true;
  1093. };
  1094. }
  1095. if (!Array.prototype.some) {
  1096. /**
  1097. * Returns true if a callback returns truthy value for at least one element in an array
  1098. * @param {Function} fn Callback to invoke for each element
  1099. * @param {Object} [context] Context to invoke callback in
  1100. * @return {Boolean}
  1101. */
  1102. Array.prototype.some = function(fn, context) {
  1103. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1104. if (i in this && fn.call(context, this[i], i, this)) {
  1105. return true;
  1106. }
  1107. }
  1108. return false;
  1109. };
  1110. }
  1111. if (!Array.prototype.filter) {
  1112. /**
  1113. * Returns the result of iterating over elements in an array
  1114. * @param {Function} fn Callback to invoke for each element
  1115. * @param {Object} [context] Context to invoke callback in
  1116. * @return {Array}
  1117. */
  1118. Array.prototype.filter = function(fn, context) {
  1119. var result = [ ], val;
  1120. for (var i = 0, len = this.length >>> 0; i < len; i++) {
  1121. if (i in this) {
  1122. val = this[i]; // in case fn mutates this
  1123. if (fn.call(context, val, i, this)) {
  1124. result.push(val);
  1125. }
  1126. }
  1127. }
  1128. return result;
  1129. };
  1130. }
  1131. if (!Array.prototype.reduce) {
  1132. /**
  1133. * Returns "folded" (reduced) result of iterating over elements in an array
  1134. * @param {Function} fn Callback to invoke for each element
  1135. * @param {Object} [initial] Object to use as the first argument to the first call of the callback
  1136. * @return {Any}
  1137. */
  1138. Array.prototype.reduce = function(fn /*, initial*/) {
  1139. var len = this.length >>> 0,
  1140. i = 0,
  1141. rv;
  1142. if (arguments.length > 1) {
  1143. rv = arguments[1];
  1144. }
  1145. else {
  1146. do {
  1147. if (i in this) {
  1148. rv = this[i++];
  1149. break;
  1150. }
  1151. // if array contains no values, no initial value to return
  1152. if (++i >= len) {
  1153. throw new TypeError();
  1154. }
  1155. }
  1156. while (true);
  1157. }
  1158. for (; i < len; i++) {
  1159. if (i in this) {
  1160. rv = fn.call(null, rv, this[i], i, this);
  1161. }
  1162. }
  1163. return rv;
  1164. };
  1165. }
  1166. /* _ES5_COMPAT_END_ */
  1167. /**
  1168. * Invokes method on all items in a given array
  1169. * @memberOf fabric.util.array
  1170. * @param {Array} array Array to iterate over
  1171. * @param {String} method Name of a method to invoke
  1172. * @return {Array}
  1173. */
  1174. function invoke(array, method) {
  1175. var args = slice.call(arguments, 2), result = [ ];
  1176. for (var i = 0, len = array.length; i < len; i++) {
  1177. result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]);
  1178. }
  1179. return result;
  1180. }
  1181. /**
  1182. * Finds maximum value in array (not necessarily "first" one)
  1183. * @memberOf fabric.util.array
  1184. * @param {Array} array Array to iterate over
  1185. * @param {String} byProperty
  1186. * @return {Any}
  1187. */
  1188. function max(array, byProperty) {
  1189. return find(array, byProperty, function(value1, value2) {
  1190. return value1 >= value2;
  1191. });
  1192. }
  1193. /**
  1194. * Finds minimum value in array (not necessarily "first" one)
  1195. * @memberOf fabric.util.array
  1196. * @param {Array} array Array to iterate over
  1197. * @param {String} byProperty
  1198. * @return {Any}
  1199. */
  1200. function min(array, byProperty) {
  1201. return find(array, byProperty, function(value1, value2) {
  1202. return value1 < value2;
  1203. });
  1204. }
  1205. /**
  1206. * @private
  1207. */
  1208. function find(array, byProperty, condition) {
  1209. if (!array || array.length === 0) {
  1210. return;
  1211. }
  1212. var i = array.length - 1,
  1213. result = byProperty ? array[i][byProperty] : array[i];
  1214. if (byProperty) {
  1215. while (i--) {
  1216. if (condition(array[i][byProperty], result)) {
  1217. result = array[i][byProperty];
  1218. }
  1219. }
  1220. }
  1221. else {
  1222. while (i--) {
  1223. if (condition(array[i], result)) {
  1224. result = array[i];
  1225. }
  1226. }
  1227. }
  1228. return result;
  1229. }
  1230. /**
  1231. * @namespace fabric.util.array
  1232. */
  1233. fabric.util.array = {
  1234. invoke: invoke,
  1235. min: min,
  1236. max: max
  1237. };
  1238. })();
  1239. (function() {
  1240. /**
  1241. * Copies all enumerable properties of one object to another
  1242. * @memberOf fabric.util.object
  1243. * @param {Object} destination Where to copy to
  1244. * @param {Object} source Where to copy from
  1245. * @return {Object}
  1246. */
  1247. function extend(destination, source) {
  1248. // JScript DontEnum bug is not taken care of
  1249. for (var property in source) {
  1250. destination[property] = source[property];
  1251. }
  1252. return destination;
  1253. }
  1254. /**
  1255. * Creates an empty object and copies all enumerable properties of another object to it
  1256. * @memberOf fabric.util.object
  1257. * @param {Object} object Object to clone
  1258. * @return {Object}
  1259. */
  1260. function clone(object) {
  1261. return extend({ }, object);
  1262. }
  1263. /** @namespace fabric.util.object */
  1264. fabric.util.object = {
  1265. extend: extend,
  1266. clone: clone
  1267. };
  1268. })();
  1269. (function() {
  1270. /* _ES5_COMPAT_START_ */
  1271. if (!String.prototype.trim) {
  1272. /**
  1273. * Trims a string (removing whitespace from the beginning and the end)
  1274. * @function external:String#trim
  1275. * @see <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim">String#trim on MDN</a>
  1276. */
  1277. String.prototype.trim = function () {
  1278. // this trim is not fully ES3 or ES5 compliant, but it should cover most cases for now
  1279. return this.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
  1280. };
  1281. }
  1282. /* _ES5_COMPAT_END_ */
  1283. /**
  1284. * Camelizes a string
  1285. * @memberOf fabric.util.string
  1286. * @param {String} string String to camelize
  1287. * @return {String} Camelized version of a string
  1288. */
  1289. function camelize(string) {
  1290. return string.replace(/-+(.)?/g, function(match, character) {
  1291. return character ? character.toUpperCase() : '';
  1292. });
  1293. }
  1294. /**
  1295. * Capitalizes a string
  1296. * @memberOf fabric.util.string
  1297. * @param {String} string String to capitalize
  1298. * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized
  1299. * and other letters stay untouched, if false first letter is capitalized
  1300. * and other letters are converted to lowercase.
  1301. * @return {String} Capitalized version of a string
  1302. */
  1303. function capitalize(string, firstLetterOnly) {
  1304. return string.charAt(0).toUpperCase() +
  1305. (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());
  1306. }
  1307. /**
  1308. * Escapes XML in a string
  1309. * @memberOf fabric.util.string
  1310. * @param {String} string String to escape
  1311. * @return {String} Escaped version of a string
  1312. */
  1313. function escapeXml(string) {
  1314. return string.replace(/&/g, '&amp;')
  1315. .replace(/"/g, '&quot;')
  1316. .replace(/'/g, '&apos;')
  1317. .replace(/</g, '&lt;')
  1318. .replace(/>/g, '&gt;');
  1319. }
  1320. /**
  1321. * String utilities
  1322. * @namespace fabric.util.string
  1323. */
  1324. fabric.util.string = {
  1325. camelize: camelize,
  1326. capitalize: capitalize,
  1327. escapeXml: escapeXml
  1328. };
  1329. }());
  1330. /* _ES5_COMPAT_START_ */
  1331. (function() {
  1332. var slice = Array.prototype.slice,
  1333. apply = Function.prototype.apply,
  1334. Dummy = function() { };
  1335. if (!Function.prototype.bind) {
  1336. /**
  1337. * Cross-browser approximation of ES5 Function.prototype.bind (not fully spec conforming)
  1338. * @see <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind">Function#bind on MDN</a>
  1339. * @param {Object} thisArg Object to bind function to
  1340. * @param {Any[]} [...] Values to pass to a bound function
  1341. * @return {Function}
  1342. */
  1343. Function.prototype.bind = function(thisArg) {
  1344. var _this = this, args = slice.call(arguments, 1), bound;
  1345. if (args.length) {
  1346. bound = function() {
  1347. return apply.call(_this, this instanceof Dummy ? this : thisArg, args.concat(slice.call(arguments)));
  1348. };
  1349. }
  1350. else {
  1351. /** @ignore */
  1352. bound = function() {
  1353. return apply.call(_this, this instanceof Dummy ? this : thisArg, arguments);
  1354. };
  1355. }
  1356. Dummy.prototype = this.prototype;
  1357. bound.prototype = new Dummy();
  1358. return bound;
  1359. };
  1360. }
  1361. })();
  1362. /* _ES5_COMPAT_END_ */
  1363. (function() {
  1364. var slice = Array.prototype.slice, emptyFunction = function() { },
  1365. IS_DONTENUM_BUGGY = (function() {
  1366. for (var p in { toString: 1 }) {
  1367. if (p === 'toString') {
  1368. return false;
  1369. }
  1370. }
  1371. return true;
  1372. })(),
  1373. /** @ignore */
  1374. addMethods = function(klass, source, parent) {
  1375. for (var property in source) {
  1376. if (property in klass.prototype &&
  1377. typeof klass.prototype[property] === 'function' &&
  1378. (source[property] + '').indexOf('callSuper') > -1) {
  1379. klass.prototype[property] = (function(property) {
  1380. return function() {
  1381. var superclass = this.constructor.superclass;
  1382. this.constructor.superclass = parent;
  1383. var returnValue = source[property].apply(this, arguments);
  1384. this.constructor.superclass = superclass;
  1385. if (property !== 'initialize') {
  1386. return returnValue;
  1387. }
  1388. };
  1389. })(property);
  1390. }
  1391. else {
  1392. klass.prototype[property] = source[property];
  1393. }
  1394. if (IS_DONTENUM_BUGGY) {
  1395. if (source.toString !== Object.prototype.toString) {
  1396. klass.prototype.toString = source.toString;
  1397. }
  1398. if (source.valueOf !== Object.prototype.valueOf) {
  1399. klass.prototype.valueOf = source.valueOf;
  1400. }
  1401. }
  1402. }
  1403. };
  1404. function Subclass() { }
  1405. function callSuper(methodName) {
  1406. var fn = this.constructor.superclass.prototype[methodName];
  1407. return (arguments.length > 1)
  1408. ? fn.apply(this, slice.call(arguments, 1))
  1409. : fn.call(this);
  1410. }
  1411. /**
  1412. * Helper for creation of "classes".
  1413. * @memberOf fabric.util
  1414. * @param {Function} [parent] optional "Class" to inherit from
  1415. * @param {Object} [properties] Properties shared by all instances of this class
  1416. * (be careful modifying objects defined here as this would affect all instances)
  1417. */
  1418. function createClass() {
  1419. var parent = null,
  1420. properties = slice.call(arguments, 0);
  1421. if (typeof properties[0] === 'function') {
  1422. parent = properties.shift();
  1423. }
  1424. function klass() {
  1425. this.initialize.apply(this, arguments);
  1426. }
  1427. klass.superclass = parent;
  1428. klass.subclasses = [ ];
  1429. if (parent) {
  1430. Subclass.prototype = parent.prototype;
  1431. klass.prototype = new Subclass();
  1432. parent.subclasses.push(klass);
  1433. }
  1434. for (var i = 0, length = properties.length; i < length; i++) {
  1435. addMethods(klass, properties[i], parent);
  1436. }
  1437. if (!klass.prototype.initialize) {
  1438. klass.prototype.initialize = emptyFunction;
  1439. }
  1440. klass.prototype.constructor = klass;
  1441. klass.prototype.callSuper = callSuper;
  1442. return klass;
  1443. }
  1444. fabric.util.createClass = createClass;
  1445. })();
  1446. (function () {
  1447. var unknown = 'unknown';
  1448. /* EVENT HANDLING */
  1449. function areHostMethods(object) {
  1450. var methodNames = Array.prototype.slice.call(arguments, 1),
  1451. t, i, len = methodNames.length;
  1452. for (i = 0; i < len; i++) {
  1453. t = typeof object[methodNames[i]];
  1454. if (!(/^(?:function|object|unknown)$/).test(t)) {
  1455. return false;
  1456. }
  1457. }
  1458. return true;
  1459. }
  1460. /** @ignore */
  1461. var getElement,
  1462. setElement,
  1463. getUniqueId = (function () {
  1464. var uid = 0;
  1465. return function (element) {
  1466. return element.__uniqueID || (element.__uniqueID = 'uniqueID__' + uid++);
  1467. };
  1468. })();
  1469. (function () {
  1470. var elements = { };
  1471. /** @ignore */
  1472. getElement = function (uid) {
  1473. return elements[uid];
  1474. };
  1475. /** @ignore */
  1476. setElement = function (uid, element) {
  1477. elements[uid] = element;
  1478. };
  1479. })();
  1480. function createListener(uid, handler) {
  1481. return {
  1482. handler: handler,
  1483. wrappedHandler: createWrappedHandler(uid, handler)
  1484. };
  1485. }
  1486. function createWrappedHandler(uid, handler) {
  1487. return function (e) {
  1488. handler.call(getElement(uid), e || fabric.window.event);
  1489. };
  1490. }
  1491. function createDispatcher(uid, eventName) {
  1492. return function (e) {
  1493. if (handlers[uid] && handlers[uid][eventName]) {
  1494. var handlersForEvent = handlers[uid][eventName];
  1495. for (var i = 0, len = handlersForEvent.length; i < len; i++) {
  1496. handlersForEvent[i].call(this, e || fabric.window.event);
  1497. }
  1498. }
  1499. };
  1500. }
  1501. var shouldUseAddListenerRemoveListener = (
  1502. areHostMethods(fabric.document.documentElement, 'addEventListener', 'removeEventListener') &&
  1503. areHostMethods(fabric.window, 'addEventListener', 'removeEventListener')),
  1504. shouldUseAttachEventDetachEvent = (
  1505. areHostMethods(fabric.document.documentElement, 'attachEvent', 'detachEvent') &&
  1506. areHostMethods(fabric.window, 'attachEvent', 'detachEvent')),
  1507. // IE branch
  1508. listeners = { },
  1509. // DOM L0 branch
  1510. handlers = { },
  1511. addListener, removeListener;
  1512. if (shouldUseAddListenerRemoveListener) {
  1513. /** @ignore */
  1514. addListener = function (element, eventName, handler) {
  1515. element.addEventListener(eventName, handler, false);
  1516. };
  1517. /** @ignore */
  1518. removeListener = function (element, eventName, handler) {
  1519. element.removeEventListener(eventName, handler, false);
  1520. };
  1521. }
  1522. else if (shouldUseAttachEventDetachEvent) {
  1523. /** @ignore */
  1524. addListener = function (element, eventName, handler) {
  1525. var uid = getUniqueId(element);
  1526. setElement(uid, element);
  1527. if (!listeners[uid]) {
  1528. listeners[uid] = { };
  1529. }
  1530. if (!listeners[uid][eventName]) {
  1531. listeners[uid][eventName] = [ ];
  1532. }
  1533. var listener = createListener(uid, handler);
  1534. listeners[uid][eventName].push(listener);
  1535. element.attachEvent('on' + eventName, listener.wrappedHandler);
  1536. };
  1537. /** @ignore */
  1538. removeListener = function (element, eventName, handler) {
  1539. var uid = getUniqueId(element), listener;
  1540. if (listeners[uid] && listeners[uid][eventName]) {
  1541. for (var i = 0, len = listeners[uid][eventName].length; i < len; i++) {
  1542. listener = listeners[uid][eventName][i];
  1543. if (listener && listener.handler === handler) {
  1544. element.detachEvent('on' + eventName, listener.wrappedHandler);
  1545. listeners[uid][eventName][i] = null;
  1546. }
  1547. }
  1548. }
  1549. };
  1550. }
  1551. else {
  1552. /** @ignore */
  1553. addListener = function (element, eventName, handler) {
  1554. var uid = getUniqueId(element);
  1555. if (!handlers[uid]) {
  1556. handlers[uid] = { };
  1557. }
  1558. if (!handlers[uid][eventName]) {
  1559. handlers[uid][eventName] = [ ];
  1560. var existingHandler = element['on' + eventName];
  1561. if (existingHandler) {
  1562. handlers[uid][eventName].push(existingHandler);
  1563. }
  1564. element['on' + eventName] = createDispatcher(uid, eventName);
  1565. }
  1566. handlers[uid][eventName].push(handler);
  1567. };
  1568. /** @ignore */
  1569. removeListener = function (element, eventName, handler) {
  1570. var uid = getUniqueId(element);
  1571. if (handlers[uid] && handlers[uid][eventName]) {
  1572. var handlersForEvent = handlers[uid][eventName];
  1573. for (var i = 0, len = handlersForEvent.length; i < len; i++) {
  1574. if (handlersForEvent[i] === handler) {
  1575. handlersForEvent.splice(i, 1);
  1576. }
  1577. }
  1578. }
  1579. };
  1580. }
  1581. /**
  1582. * Adds an event listener to an element
  1583. * @function
  1584. * @memberOf fabric.util
  1585. * @param {HTMLElement} element
  1586. * @param {String} eventName
  1587. * @param {Function} handler
  1588. */
  1589. fabric.util.addListener = addListener;
  1590. /**
  1591. * Removes an event listener from an element
  1592. * @function
  1593. * @memberOf fabric.util
  1594. * @param {HTMLElement} element
  1595. * @param {String} eventName
  1596. * @param {Function} handler
  1597. */
  1598. fabric.util.removeListener = removeListener;
  1599. /**
  1600. * Cross-browser wrapper for getting event's coordinates
  1601. * @memberOf fabric.util
  1602. * @param {Event} event Event object
  1603. * @param {HTMLCanvasElement} upperCanvasEl &lt;canvas> element on which object selection is drawn
  1604. */
  1605. function getPointer(event, upperCanvasEl) {
  1606. event || (event = fabric.window.event);
  1607. var element = event.target ||
  1608. (typeof event.srcElement !== unknown ? event.srcElement : null),
  1609. scroll = fabric.util.getScrollLeftTop(element, upperCanvasEl);
  1610. return {
  1611. x: pointerX(event) + scroll.left,
  1612. y: pointerY(event) + scroll.top
  1613. };
  1614. }
  1615. var pointerX = function(event) {
  1616. // looks like in IE (<9) clientX at certain point (apparently when mouseup fires on VML element)
  1617. // is represented as COM object, with all the consequences, like "unknown" type and error on [[Get]]
  1618. // need to investigate later
  1619. return (typeof event.clientX !== unknown ? event.clientX : 0);
  1620. },
  1621. pointerY = function(event) {
  1622. return (typeof event.clientY !== unknown ? event.clientY : 0);
  1623. };
  1624. function _getPointer(event, pageProp, clientProp) {
  1625. var touchProp = event.type === 'touchend' ? 'changedTouches' : 'touches';
  1626. return (event[touchProp] && event[touchProp][0]
  1627. ? (event[touchProp][0][pageProp] - (event[touchProp][0][pageProp] - event[touchProp][0][clientProp]))
  1628. || event[clientProp]
  1629. : event[clientProp]);
  1630. }
  1631. if (fabric.isTouchSupported) {
  1632. pointerX = function(event) {
  1633. return _getPointer(event, 'pageX', 'clientX');
  1634. };
  1635. pointerY = function(event) {
  1636. return _getPointer(event, 'pageY', 'clientY');
  1637. };
  1638. }
  1639. fabric.util.getPointer = getPointer;
  1640. fabric.util.object.extend(fabric.util, fabric.Observable);
  1641. })();
  1642. (function () {
  1643. /**
  1644. * Cross-browser wrapper for setting element's style
  1645. * @memberOf fabric.util
  1646. * @param {HTMLElement} element
  1647. * @param {Object} styles
  1648. * @return {HTMLElement} Element that was passed as a first argument
  1649. */
  1650. function setStyle(element, styles) {
  1651. var elementStyle = element.style;
  1652. if (!elementStyle) {
  1653. return element;
  1654. }
  1655. if (typeof styles === 'string') {
  1656. element.style.cssText += ';' + styles;
  1657. return styles.indexOf('opacity') > -1
  1658. ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1])
  1659. : element;
  1660. }
  1661. for (var property in styles) {
  1662. if (property === 'opacity') {
  1663. setOpacity(element, styles[property]);
  1664. }
  1665. else {
  1666. var normalizedProperty = (property === 'float' || property === 'cssFloat')
  1667. ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat')
  1668. : property;
  1669. elementStyle[normalizedProperty] = styles[property];
  1670. }
  1671. }
  1672. return element;
  1673. }
  1674. var parseEl = fabric.document.createElement('div'),
  1675. supportsOpacity = typeof parseEl.style.opacity === 'string',
  1676. supportsFilters = typeof parseEl.style.filter === 'string',
  1677. reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
  1678. /** @ignore */
  1679. setOpacity = function (element) { return element; };
  1680. if (supportsOpacity) {
  1681. /** @ignore */
  1682. setOpacity = function(element, value) {
  1683. element.style.opacity = value;
  1684. return element;
  1685. };
  1686. }
  1687. else if (supportsFilters) {
  1688. /** @ignore */
  1689. setOpacity = function(element, value) {
  1690. var es = element.style;
  1691. if (element.currentStyle && !element.currentStyle.hasLayout) {
  1692. es.zoom = 1;
  1693. }
  1694. if (reOpacity.test(es.filter)) {
  1695. value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
  1696. es.filter = es.filter.replace(reOpacity, value);
  1697. }
  1698. else {
  1699. es.filter += ' alpha(opacity=' + (value * 100) + ')';
  1700. }
  1701. return element;
  1702. };
  1703. }
  1704. fabric.util.setStyle = setStyle;
  1705. })();
  1706. (function() {
  1707. var _slice = Array.prototype.slice;
  1708. /**
  1709. * Takes id and returns an element with that id (if one exists in a document)
  1710. * @memberOf fabric.util
  1711. * @param {String|HTMLElement} id
  1712. * @return {HTMLElement|null}
  1713. */
  1714. function getById(id) {
  1715. return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  1716. }
  1717. var sliceCanConvertNodelists,
  1718. /**
  1719. * Converts an array-like object (e.g. arguments or NodeList) to an array
  1720. * @memberOf fabric.util
  1721. * @param {Object} arrayLike
  1722. * @return {Array}
  1723. */
  1724. toArray = function(arrayLike) {
  1725. return _slice.call(arrayLike, 0);
  1726. };
  1727. try {
  1728. sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  1729. }
  1730. catch (err) { }
  1731. if (!sliceCanConvertNodelists) {
  1732. toArray = function(arrayLike) {
  1733. var arr = new Array(arrayLike.length), i = arrayLike.length;
  1734. while (i--) {
  1735. arr[i] = arrayLike[i];
  1736. }
  1737. return arr;
  1738. };
  1739. }
  1740. /**
  1741. * Creates specified element with specified attributes
  1742. * @memberOf fabric.util
  1743. * @param {String} tagName Type of an element to create
  1744. * @param {Object} [attributes] Attributes to set on an element
  1745. * @return {HTMLElement} Newly created element
  1746. */
  1747. function makeElement(tagName, attributes) {
  1748. var el = fabric.document.createElement(tagName);
  1749. for (var prop in attributes) {
  1750. if (prop === 'class') {
  1751. el.className = attributes[prop];
  1752. }
  1753. else if (prop === 'for') {
  1754. el.htmlFor = attributes[prop];
  1755. }
  1756. else {
  1757. el.setAttribute(prop, attributes[prop]);
  1758. }
  1759. }
  1760. return el;
  1761. }
  1762. /**
  1763. * Adds class to an element
  1764. * @memberOf fabric.util
  1765. * @param {HTMLElement} element Element to add class to
  1766. * @param {String} className Class to add to an element
  1767. */
  1768. function addClass(element, className) {
  1769. if (element && (' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
  1770. element.className += (element.className ? ' ' : '') + className;
  1771. }
  1772. }
  1773. /**
  1774. * Wraps element with another element
  1775. * @memberOf fabric.util
  1776. * @param {HTMLElement} element Element to wrap
  1777. * @param {HTMLElement|String} wrapper Element to wrap with
  1778. * @param {Object} [attributes] Attributes to set on a wrapper
  1779. * @return {HTMLElement} wrapper
  1780. */
  1781. function wrapElement(element, wrapper, attributes) {
  1782. if (typeof wrapper === 'string') {
  1783. wrapper = makeElement(wrapper, attributes);
  1784. }
  1785. if (element.parentNode) {
  1786. element.parentNode.replaceChild(wrapper, element);
  1787. }
  1788. wrapper.appendChild(element);
  1789. return wrapper;
  1790. }
  1791. /**
  1792. * Returns element scroll offsets
  1793. * @memberOf fabric.util
  1794. * @param {HTMLElement} element Element to operate on
  1795. * @param {HTMLElement} upperCanvasEl Upper canvas element
  1796. * @return {Object} Object with left/top values
  1797. */
  1798. function getScrollLeftTop(element, upperCanvasEl) {
  1799. var firstFixedAncestor,
  1800. origElement,
  1801. left = 0,
  1802. top = 0,
  1803. docElement = fabric.document.documentElement,
  1804. body = fabric.document.body || {
  1805. scrollLeft: 0, scrollTop: 0
  1806. };
  1807. origElement = element;
  1808. while (element && element.parentNode && !firstFixedAncestor) {
  1809. element = element.parentNode;
  1810. if (element.nodeType === 1 &&
  1811. fabric.util.getElementStyle(element, 'position') === 'fixed') {
  1812. firstFixedAncestor = element;
  1813. }
  1814. if (element.nodeType === 1 &&
  1815. origElement !== upperCanvasEl &&
  1816. fabric.util.getElementStyle(element, 'position') === 'absolute') {
  1817. left = 0;
  1818. top = 0;
  1819. }
  1820. else if (element === fabric.document) {
  1821. left = body.scrollLeft || docElement.scrollLeft || 0;
  1822. top = body.scrollTop || docElement.scrollTop || 0;
  1823. }
  1824. else {
  1825. left += element.scrollLeft || 0;
  1826. top += element.scrollTop || 0;
  1827. }
  1828. }
  1829. return { left: left, top: top };
  1830. }
  1831. /**
  1832. * Returns offset for a given element
  1833. * @function
  1834. * @memberOf fabric.util
  1835. * @param {HTMLElement} element Element to get offset for
  1836. * @return {Object} Object with "left" and "top" properties
  1837. */
  1838. function getElementOffset(element) {
  1839. var docElem,
  1840. doc = element && element.ownerDocument,
  1841. box = { left: 0, top: 0 },
  1842. offset = { left: 0, top: 0 },
  1843. scrollLeftTop,
  1844. offsetAttributes = {
  1845. borderLeftWidth: 'left',
  1846. borderTopWidth: 'top',
  1847. paddingLeft: 'left',
  1848. paddingTop: 'top'
  1849. };
  1850. if (!doc) {
  1851. return { left: 0, top: 0 };
  1852. }
  1853. for (var attr in offsetAttributes) {
  1854. offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
  1855. }
  1856. docElem = doc.documentElement;
  1857. if ( typeof element.getBoundingClientRect !== 'undefined' ) {
  1858. box = element.getBoundingClientRect();
  1859. }
  1860. scrollLeftTop = fabric.util.getScrollLeftTop(element, null);
  1861. return {
  1862. left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
  1863. top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top
  1864. };
  1865. }
  1866. /**
  1867. * Returns style attribute value of a given element
  1868. * @memberOf fabric.util
  1869. * @param {HTMLElement} element Element to get style attribute for
  1870. * @param {String} attr Style attribute to get for element
  1871. * @return {String} Style attribute value of the given element.
  1872. */
  1873. var getElementStyle;
  1874. if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
  1875. getElementStyle = function(element, attr) {
  1876. var style = fabric.document.defaultView.getComputedStyle(element, null);
  1877. return style ? style[attr] : undefined;
  1878. };
  1879. }
  1880. else {
  1881. getElementStyle = function(element, attr) {
  1882. var value = element.style[attr];
  1883. if (!value && element.currentStyle) {
  1884. value = element.currentStyle[attr];
  1885. }
  1886. return value;
  1887. };
  1888. }
  1889. (function () {
  1890. var style = fabric.document.documentElement.style,
  1891. selectProp = 'userSelect' in style
  1892. ? 'userSelect'
  1893. : 'MozUserSelect' in style
  1894. ? 'MozUserSelect'
  1895. : 'WebkitUserSelect' in style
  1896. ? 'WebkitUserSelect'
  1897. : 'KhtmlUserSelect' in style
  1898. ? 'KhtmlUserSelect'
  1899. : '';
  1900. /**
  1901. * Makes element unselectable
  1902. * @memberOf fabric.util
  1903. * @param {HTMLElement} element Element to make unselectable
  1904. * @return {HTMLElement} Element that was passed in
  1905. */
  1906. function makeElementUnselectable(element) {
  1907. if (typeof element.onselectstart !== 'undefined') {
  1908. element.onselectstart = fabric.util.falseFunction;
  1909. }
  1910. if (selectProp) {
  1911. element.style[selectProp] = 'none';
  1912. }
  1913. else if (typeof element.unselectable === 'string') {
  1914. element.unselectable = 'on';
  1915. }
  1916. return element;
  1917. }
  1918. /**
  1919. * Makes element selectable
  1920. * @memberOf fabric.util
  1921. * @param {HTMLElement} element Element to make selectable
  1922. * @return {HTMLElement} Element that was passed in
  1923. */
  1924. function makeElementSelectable(element) {
  1925. if (typeof element.onselectstart !== 'undefined') {
  1926. element.onselectstart = null;
  1927. }
  1928. if (selectProp) {
  1929. element.style[selectProp] = '';
  1930. }
  1931. else if (typeof element.unselectable === 'string') {
  1932. element.unselectable = '';
  1933. }
  1934. return element;
  1935. }
  1936. fabric.util.makeElementUnselectable = makeElementUnselectable;
  1937. fabric.util.makeElementSelectable = makeElementSelectable;
  1938. })();
  1939. (function() {
  1940. /**
  1941. * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
  1942. * @memberOf fabric.util
  1943. * @param {String} url URL of a script to load
  1944. * @param {Function} callback Callback to execute when script is finished loading
  1945. */
  1946. function getScript(url, callback) {
  1947. var headEl = fabric.document.getElementsByTagName('head')[0],
  1948. scriptEl = fabric.document.createElement('script'),
  1949. loading = true;
  1950. /** @ignore */
  1951. scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
  1952. if (loading) {
  1953. if (typeof this.readyState === 'string' &&
  1954. this.readyState !== 'loaded' &&
  1955. this.readyState !== 'complete') {
  1956. return;
  1957. }
  1958. loading = false;
  1959. callback(e || fabric.window.event);
  1960. scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
  1961. }
  1962. };
  1963. scriptEl.src = url;
  1964. headEl.appendChild(scriptEl);
  1965. // causes issue in Opera
  1966. // headEl.removeChild(scriptEl);
  1967. }
  1968. fabric.util.getScript = getScript;
  1969. })();
  1970. fabric.util.getById = getById;
  1971. fabric.util.toArray = toArray;
  1972. fabric.util.makeElement = makeElement;
  1973. fabric.util.addClass = addClass;
  1974. fabric.util.wrapElement = wrapElement;
  1975. fabric.util.getScrollLeftTop = getScrollLeftTop;
  1976. fabric.util.getElementOffset = getElementOffset;
  1977. fabric.util.getElementStyle = getElementStyle;
  1978. })();
  1979. (function() {
  1980. function addParamToUrl(url, param) {
  1981. return url + (/\?/.test(url) ? '&' : '?') + param;
  1982. }
  1983. var makeXHR = (function() {
  1984. var factories = [
  1985. function() { return new ActiveXObject('Microsoft.XMLHTTP'); },
  1986. function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
  1987. function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
  1988. function() { return new XMLHttpRequest(); }
  1989. ];
  1990. for (var i = factories.length; i--; ) {
  1991. try {
  1992. var req = factories[i]();
  1993. if (req) {
  1994. return factories[i];
  1995. }
  1996. }
  1997. catch (err) { }
  1998. }
  1999. })();
  2000. function emptyFn() { }
  2001. /**
  2002. * Cross-browser abstraction for sending XMLHttpRequest
  2003. * @memberOf fabric.util
  2004. * @param {String} url URL to send XMLHttpRequest to
  2005. * @param {Object} [options] Options object
  2006. * @param {String} [options.method="GET"]
  2007. * @param {Function} options.onComplete Callback to invoke when request is completed
  2008. * @return {XMLHttpRequest} request
  2009. */
  2010. function request(url, options) {
  2011. options || (options = { });
  2012. var method = options.method ? options.method.toUpperCase() : 'GET',
  2013. onComplete = options.onComplete || function() { },
  2014. xhr = makeXHR(),
  2015. body;
  2016. /** @ignore */
  2017. xhr.onreadystatechange = function() {
  2018. if (xhr.readyState === 4) {
  2019. onComplete(xhr);
  2020. xhr.onreadystatechange = emptyFn;
  2021. }
  2022. };
  2023. if (method === 'GET') {
  2024. body = null;
  2025. if (typeof options.parameters === 'string') {
  2026. url = addParamToUrl(url, options.parameters);
  2027. }
  2028. }
  2029. xhr.open(method, url, true);
  2030. if (method === 'POST' || method === 'PUT') {
  2031. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  2032. }
  2033. xhr.send(body);
  2034. return xhr;
  2035. }
  2036. fabric.util.request = request;
  2037. })();
  2038. /**
  2039. * Wrapper around `console.log` (when available)
  2040. * @param {Any} [values] Values to log
  2041. */
  2042. fabric.log = function() { };
  2043. /**
  2044. * Wrapper around `console.warn` (when available)
  2045. * @param {Any} [values] Values to log as a warning
  2046. */
  2047. fabric.warn = function() { };
  2048. if (typeof console !== 'undefined') {
  2049. ['log', 'warn'].forEach(function(methodName) {
  2050. if (typeof console[methodName] !== 'undefined' &&
  2051. typeof console[methodName].apply === 'function') {
  2052. fabric[methodName] = function() {
  2053. return console[methodName].apply(console, arguments);
  2054. };
  2055. }
  2056. });
  2057. }
  2058. (function() {
  2059. /**
  2060. * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
  2061. * @memberOf fabric.util
  2062. * @param {Object} [options] Animation options
  2063. * @param {Function} [options.onChange] Callback; invoked on every value change
  2064. * @param {Function} [options.onComplete] Callback; invoked when value change is completed
  2065. * @param {Number} [options.startValue=0] Starting value
  2066. * @param {Number} [options.endValue=100] Ending value
  2067. * @param {Number} [options.byValue=100] Value to modify the property by
  2068. * @param {Function} [options.easing] Easing function
  2069. * @param {Number} [options.duration=500] Duration of change (in ms)
  2070. */
  2071. function animate(options) {
  2072. requestAnimFrame(function(timestamp) {
  2073. options || (options = { });
  2074. var start = timestamp || +new Date(),
  2075. duration = options.duration || 500,
  2076. finish = start + duration, time,
  2077. onChange = options.onChange || function() { },
  2078. abort = options.abort || function() { return false; },
  2079. easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;},
  2080. startValue = 'startValue' in options ? options.startValue : 0,
  2081. endValue = 'endValue' in options ? options.endValue : 100,
  2082. byValue = options.byValue || endValue - startValue;
  2083. options.onStart && options.onStart();
  2084. (function tick(ticktime) {
  2085. time = ticktime || +new Date();
  2086. var currentTime = time > finish ? duration : (time - start);
  2087. if (abort()) {
  2088. options.onComplete && options.onComplete();
  2089. return;
  2090. }
  2091. onChange(easing(currentTime, startValue, byValue, duration));
  2092. if (time > finish) {
  2093. options.onComplete && options.onComplete();
  2094. return;
  2095. }
  2096. requestAnimFrame(tick);
  2097. })(start);
  2098. });
  2099. }
  2100. var _requestAnimFrame = fabric.window.requestAnimationFrame ||
  2101. fabric.window.webkitRequestAnimationFrame ||
  2102. fabric.window.mozRequestAnimationFrame ||
  2103. fabric.window.oRequestAnimationFrame ||
  2104. fabric.window.msRequestAnimationFrame ||
  2105. function(callback) {
  2106. fabric.window.setTimeout(callback, 1000 / 60);
  2107. };
  2108. /**
  2109. * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  2110. * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method
  2111. * @memberOf fabric.util
  2112. * @param {Function} callback Callback to invoke
  2113. * @param {DOMElement} element optional Element to associate with animation
  2114. */
  2115. function requestAnimFrame() {
  2116. return _requestAnimFrame.apply(fabric.window, arguments);
  2117. }
  2118. fabric.util.animate = animate;
  2119. fabric.util.requestAnimFrame = requestAnimFrame;
  2120. })();
  2121. (function() {
  2122. function normalize(a, c, p, s) {
  2123. if (a < Math.abs(c)) {
  2124. a = c;
  2125. s = p / 4;
  2126. }
  2127. else {
  2128. s = p / (2 * Math.PI) * Math.asin(c / a);
  2129. }
  2130. return { a: a, c: c, p: p, s: s };
  2131. }
  2132. function elastic(opts, t, d) {
  2133. return opts.a *
  2134. Math.pow(2, 10 * (t -= 1)) *
  2135. Math.sin( (t * d - opts.s) * (2 * Math.PI) / opts.p );
  2136. }
  2137. /**
  2138. * Cubic easing out
  2139. * @memberOf fabric.util.ease
  2140. */
  2141. function easeOutCubic(t, b, c, d) {
  2142. return c * ((t = t / d - 1) * t * t + 1) + b;
  2143. }
  2144. /**
  2145. * Cubic easing in and out
  2146. * @memberOf fabric.util.ease
  2147. */
  2148. function easeInOutCubic(t, b, c, d) {
  2149. t /= d/2;
  2150. if (t < 1) {
  2151. return c / 2 * t * t * t + b;
  2152. }
  2153. return c / 2 * ((t -= 2) * t * t + 2) + b;
  2154. }
  2155. /**
  2156. * Quartic easing in
  2157. * @memberOf fabric.util.ease
  2158. */
  2159. function easeInQuart(t, b, c, d) {
  2160. return c * (t /= d) * t * t * t + b;
  2161. }
  2162. /**
  2163. * Quartic easing out
  2164. * @memberOf fabric.util.ease
  2165. */
  2166. function easeOutQuart(t, b, c, d) {
  2167. return -c * ((t = t / d - 1) * t * t * t - 1) + b;
  2168. }
  2169. /**
  2170. * Quartic easing in and out
  2171. * @memberOf fabric.util.ease
  2172. */
  2173. function easeInOutQuart(t, b, c, d) {
  2174. t /= d / 2;
  2175. if (t < 1) {
  2176. return c / 2 * t * t * t * t + b;
  2177. }
  2178. return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
  2179. }
  2180. /**
  2181. * Quintic easing in
  2182. * @memberOf fabric.util.ease
  2183. */
  2184. function easeInQuint(t, b, c, d) {
  2185. return c * (t /= d) * t * t * t * t + b;
  2186. }
  2187. /**
  2188. * Quintic easing out
  2189. * @memberOf fabric.util.ease
  2190. */
  2191. function easeOutQuint(t, b, c, d) {
  2192. return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  2193. }
  2194. /**
  2195. * Quintic easing in and out
  2196. * @memberOf fabric.util.ease
  2197. */
  2198. function easeInOutQuint(t, b, c, d) {
  2199. t /= d / 2;
  2200. if (t < 1) {
  2201. return c / 2 * t * t * t * t * t + b;
  2202. }
  2203. return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
  2204. }
  2205. /**
  2206. * Sinusoidal easing in
  2207. * @memberOf fabric.util.ease
  2208. */
  2209. function easeInSine(t, b, c, d) {
  2210. return -c * Math.cos(t / d * (Math.PI / 2)) + c + b;
  2211. }
  2212. /**
  2213. * Sinusoidal easing out
  2214. * @memberOf fabric.util.ease
  2215. */
  2216. function easeOutSine(t, b, c, d) {
  2217. return c * Math.sin(t / d * (Math.PI / 2)) + b;
  2218. }
  2219. /**
  2220. * Sinusoidal easing in and out
  2221. * @memberOf fabric.util.ease
  2222. */
  2223. function easeInOutSine(t, b, c, d) {
  2224. return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b;
  2225. }
  2226. /**
  2227. * Exponential easing in
  2228. * @memberOf fabric.util.ease
  2229. */
  2230. function easeInExpo(t, b, c, d) {
  2231. return (t === 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
  2232. }
  2233. /**
  2234. * Exponential easing out
  2235. * @memberOf fabric.util.ease
  2236. */
  2237. function easeOutExpo(t, b, c, d) {
  2238. return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
  2239. }
  2240. /**
  2241. * Exponential easing in and out
  2242. * @memberOf fabric.util.ease
  2243. */
  2244. function easeInOutExpo(t, b, c, d) {
  2245. if (t === 0) {
  2246. return b;
  2247. }
  2248. if (t === d) {
  2249. return b + c;
  2250. }
  2251. t /= d / 2;
  2252. if (t < 1) {
  2253. return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
  2254. }
  2255. return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
  2256. }
  2257. /**
  2258. * Circular easing in
  2259. * @memberOf fabric.util.ease
  2260. */
  2261. function easeInCirc(t, b, c, d) {
  2262. return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
  2263. }
  2264. /**
  2265. * Circular easing out
  2266. * @memberOf fabric.util.ease
  2267. */
  2268. function easeOutCirc(t, b, c, d) {
  2269. return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
  2270. }
  2271. /**
  2272. * Circular easing in and out
  2273. * @memberOf fabric.util.ease
  2274. */
  2275. function easeInOutCirc(t, b, c, d) {
  2276. t /= d / 2;
  2277. if (t < 1) {
  2278. return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
  2279. }
  2280. return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
  2281. }
  2282. /**
  2283. * Elastic easing in
  2284. * @memberOf fabric.util.ease
  2285. */
  2286. function easeInElastic(t, b, c, d) {
  2287. var s = 1.70158, p = 0, a = c;
  2288. if (t === 0) {
  2289. return b;
  2290. }
  2291. t /= d;
  2292. if (t === 1) {
  2293. return b + c;
  2294. }
  2295. if (!p) {
  2296. p = d * 0.3;
  2297. }
  2298. var opts = normalize(a, c, p, s);
  2299. return -elastic(opts, t, d) + b;
  2300. }
  2301. /**
  2302. * Elastic easing out
  2303. * @memberOf fabric.util.ease
  2304. */
  2305. function easeOutElastic(t, b, c, d) {
  2306. var s = 1.70158, p = 0, a = c;
  2307. if (t === 0) {
  2308. return b;
  2309. }
  2310. t /= d;
  2311. if (t === 1) {
  2312. return b + c;
  2313. }
  2314. if (!p) {
  2315. p = d * 0.3;
  2316. }
  2317. var opts = normalize(a, c, p, s);
  2318. return opts.a * Math.pow(2, -10 * t) * Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) + opts.c + b;
  2319. }
  2320. /**
  2321. * Elastic easing in and out
  2322. * @memberOf fabric.util.ease
  2323. */
  2324. function easeInOutElastic(t, b, c, d) {
  2325. var s = 1.70158, p = 0, a = c;
  2326. if (t === 0) {
  2327. return b;
  2328. }
  2329. t /= d / 2;
  2330. if (t === 2) {
  2331. return b + c;
  2332. }
  2333. if (!p) {
  2334. p = d * (0.3 * 1.5);
  2335. }
  2336. var opts = normalize(a, c, p, s);
  2337. if (t < 1) {
  2338. return -0.5 * elastic(opts, t, d) + b;
  2339. }
  2340. return opts.a * Math.pow(2, -10 * (t -= 1)) *
  2341. Math.sin((t * d - opts.s) * (2 * Math.PI) / opts.p ) * 0.5 + opts.c + b;
  2342. }
  2343. /**
  2344. * Backwards easing in
  2345. * @memberOf fabric.util.ease
  2346. */
  2347. function easeInBack(t, b, c, d, s) {
  2348. if (s === undefined) {
  2349. s = 1.70158;
  2350. }
  2351. return c * (t /= d) * t * ((s + 1) * t - s) + b;
  2352. }
  2353. /**
  2354. * Backwards easing out
  2355. * @memberOf fabric.util.ease
  2356. */
  2357. function easeOutBack(t, b, c, d, s) {
  2358. if (s === undefined) {
  2359. s = 1.70158;
  2360. }
  2361. return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
  2362. }
  2363. /**
  2364. * Backwards easing in and out
  2365. * @memberOf fabric.util.ease
  2366. */
  2367. function easeInOutBack(t, b, c, d, s) {
  2368. if (s === undefined) {
  2369. s = 1.70158;
  2370. }
  2371. t /= d / 2;
  2372. if (t < 1) {
  2373. return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
  2374. }
  2375. return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
  2376. }
  2377. /**
  2378. * Bouncing easing in
  2379. * @memberOf fabric.util.ease
  2380. */
  2381. function easeInBounce(t, b, c, d) {
  2382. return c - easeOutBounce (d - t, 0, c, d) + b;
  2383. }
  2384. /**
  2385. * Bouncing easing out
  2386. * @memberOf fabric.util.ease
  2387. */
  2388. function easeOutBounce(t, b, c, d) {
  2389. if ((t /= d) < (1 / 2.75)) {
  2390. return c * (7.5625 * t * t) + b;
  2391. }
  2392. else if (t < (2/2.75)) {
  2393. return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
  2394. }
  2395. else if (t < (2.5/2.75)) {
  2396. return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
  2397. }
  2398. else {
  2399. return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
  2400. }
  2401. }
  2402. /**
  2403. * Bouncing easing in and out
  2404. * @memberOf fabric.util.ease
  2405. */
  2406. function easeInOutBounce(t, b, c, d) {
  2407. if (t < d / 2) {
  2408. return easeInBounce (t * 2, 0, c, d) * 0.5 + b;
  2409. }
  2410. return easeOutBounce(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
  2411. }
  2412. /**
  2413. * Easing functions
  2414. * See <a href="http://gizma.com/easing/">Easing Equations by Robert Penner</a>
  2415. * @namespace fabric.util.ease
  2416. */
  2417. fabric.util.ease = {
  2418. /**
  2419. * Quadratic easing in
  2420. * @memberOf fabric.util.ease
  2421. */
  2422. easeInQuad: function(t, b, c, d) {
  2423. return c * (t /= d) * t + b;
  2424. },
  2425. /**
  2426. * Quadratic easing out
  2427. * @memberOf fabric.util.ease
  2428. */
  2429. easeOutQuad: function(t, b, c, d) {
  2430. return -c * (t /= d) * (t - 2) + b;
  2431. },
  2432. /**
  2433. * Quadratic easing in and out
  2434. * @memberOf fabric.util.ease
  2435. */
  2436. easeInOutQuad: function(t, b, c, d) {
  2437. t /= (d / 2);
  2438. if (t < 1) {
  2439. return c / 2 * t * t + b;
  2440. }
  2441. return -c / 2 * ((--t) * (t - 2) - 1) + b;
  2442. },
  2443. /**
  2444. * Cubic easing in
  2445. * @memberOf fabric.util.ease
  2446. */
  2447. easeInCubic: function(t, b, c, d) {
  2448. return c * (t /= d) * t * t + b;
  2449. },
  2450. easeOutCubic: easeOutCubic,
  2451. easeInOutCubic: easeInOutCubic,
  2452. easeInQuart: easeInQuart,
  2453. easeOutQuart: easeOutQuart,
  2454. easeInOutQuart: easeInOutQuart,
  2455. easeInQuint: easeInQuint,
  2456. easeOutQuint: easeOutQuint,
  2457. easeInOutQuint: easeInOutQuint,
  2458. easeInSine: easeInSine,
  2459. easeOutSine: easeOutSine,
  2460. easeInOutSine: easeInOutSine,
  2461. easeInExpo: easeInExpo,
  2462. easeOutExpo: easeOutExpo,
  2463. easeInOutExpo: easeInOutExpo,
  2464. easeInCirc: easeInCirc,
  2465. easeOutCirc: easeOutCirc,
  2466. easeInOutCirc: easeInOutCirc,
  2467. easeInElastic: easeInElastic,
  2468. easeOutElastic: easeOutElastic,
  2469. easeInOutElastic: easeInOutElastic,
  2470. easeInBack: easeInBack,
  2471. easeOutBack: easeOutBack,
  2472. easeInOutBack: easeInOutBack,
  2473. easeInBounce: easeInBounce,
  2474. easeOutBounce: easeOutBounce,
  2475. easeInOutBounce: easeInOutBounce
  2476. };
  2477. }());
  2478. (function(global) {
  2479. 'use strict';
  2480. /**
  2481. * @name fabric
  2482. * @namespace
  2483. */
  2484. var fabric = global.fabric || (global.fabric = { }),
  2485. extend = fabric.util.object.extend,
  2486. capitalize = fabric.util.string.capitalize,
  2487. clone = fabric.util.object.clone,
  2488. toFixed = fabric.util.toFixed,
  2489. parseUnit = fabric.util.parseUnit,
  2490. multiplyTransformMatrices = fabric.util.multiplyTransformMatrices,
  2491. attributesMap = {
  2492. cx: 'left',
  2493. x: 'left',
  2494. r: 'radius',
  2495. cy: 'top',
  2496. y: 'top',
  2497. display: 'visible',
  2498. visibility: 'visible',
  2499. transform: 'transformMatrix',
  2500. 'fill-opacity': 'fillOpacity',
  2501. 'fill-rule': 'fillRule',
  2502. 'font-family': 'fontFamily',
  2503. 'font-size': 'fontSize',
  2504. 'font-style': 'fontStyle',
  2505. 'font-weight': 'fontWeight',
  2506. 'stroke-dasharray': 'strokeDashArray',
  2507. 'stroke-linecap': 'strokeLineCap',
  2508. 'stroke-linejoin': 'strokeLineJoin',
  2509. 'stroke-miterlimit': 'strokeMiterLimit',
  2510. 'stroke-opacity': 'strokeOpacity',
  2511. 'stroke-width': 'strokeWidth',
  2512. 'text-decoration': 'textDecoration',
  2513. 'text-anchor': 'originX'
  2514. },
  2515. colorAttributes = {
  2516. stroke: 'strokeOpacity',
  2517. fill: 'fillOpacity'
  2518. };
  2519. fabric.cssRules = { };
  2520. fabric.gradientDefs = { };
  2521. function normalizeAttr(attr) {
  2522. // transform attribute names
  2523. if (attr in attributesMap) {
  2524. return attributesMap[attr];
  2525. }
  2526. return attr;
  2527. }
  2528. function normalizeValue(attr, value, parentAttributes, fontSize) {
  2529. var isArray = Object.prototype.toString.call(value) === '[object Array]',
  2530. parsed;
  2531. if ((attr === 'fill' || attr === 'stroke') && value === 'none') {
  2532. value = '';
  2533. }
  2534. else if (attr === 'strokeDashArray') {
  2535. value = value.replace(/,/g, ' ').split(/\s+/).map(function(n) {
  2536. return parseFloat(n);
  2537. });
  2538. }
  2539. else if (attr === 'transformMatrix') {
  2540. if (parentAttributes && parentAttributes.transformMatrix) {
  2541. value = multiplyTransformMatrices(
  2542. parentAttributes.transformMatrix, fabric.parseTransformAttribute(value));
  2543. }
  2544. else {
  2545. value = fabric.parseTransformAttribute(value);
  2546. }
  2547. }
  2548. else if (attr === 'visible') {
  2549. value = (value === 'none' || value === 'hidden') ? false : true;
  2550. // display=none on parent element always takes precedence over child element
  2551. if (parentAttributes && parentAttributes.visible === false) {
  2552. value = false;
  2553. }
  2554. }
  2555. else if (attr === 'originX' /* text-anchor */) {
  2556. value = value === 'start' ? 'left' : value === 'end' ? 'right' : 'center';
  2557. }
  2558. else {
  2559. parsed = isArray ? value.map(parseUnit) : parseUnit(value, fontSize);
  2560. }
  2561. return (!isArray && isNaN(parsed) ? value : parsed);
  2562. }
  2563. /**
  2564. * @private
  2565. * @param {Object} attributes Array of attributes to parse
  2566. */
  2567. function _setStrokeFillOpacity(attributes) {
  2568. for (var attr in colorAttributes) {
  2569. if (!attributes[attr] || typeof attributes[colorAttributes[attr]] === 'undefined') {
  2570. continue;
  2571. }
  2572. if (attributes[attr].indexOf('url(') === 0) {
  2573. continue;
  2574. }
  2575. var color = new fabric.Color(attributes[attr]);
  2576. attributes[attr] = color.setAlpha(toFixed(color.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
  2577. }
  2578. return attributes;
  2579. }
  2580. /**
  2581. * Parses "transform" attribute, returning an array of values
  2582. * @static
  2583. * @function
  2584. * @memberOf fabric
  2585. * @param {String} attributeValue String containing attribute value
  2586. * @return {Array} Array of 6 elements representing transformation matrix
  2587. */
  2588. fabric.parseTransformAttribute = (function() {
  2589. function rotateMatrix(matrix, args) {
  2590. var angle = args[0];
  2591. matrix[0] = Math.cos(angle);
  2592. matrix[1] = Math.sin(angle);
  2593. matrix[2] = -Math.sin(angle);
  2594. matrix[3] = Math.cos(angle);
  2595. }
  2596. function scaleMatrix(matrix, args) {
  2597. var multiplierX = args[0],
  2598. multiplierY = (args.length === 2) ? args[1] : args[0];
  2599. matrix[0] = multiplierX;
  2600. matrix[3] = multiplierY;
  2601. }
  2602. function skewXMatrix(matrix, args) {
  2603. matrix[2] = Math.tan(fabric.util.degreesToRadians(args[0]));
  2604. }
  2605. function skewYMatrix(matrix, args) {
  2606. matrix[1] = Math.tan(fabric.util.degreesToRadians(args[0]));
  2607. }
  2608. function translateMatrix(matrix, args) {
  2609. matrix[4] = args[0];
  2610. if (args.length === 2) {
  2611. matrix[5] = args[1];
  2612. }
  2613. }
  2614. // identity matrix
  2615. var iMatrix = [
  2616. 1, // a
  2617. 0, // b
  2618. 0, // c
  2619. 1, // d
  2620. 0, // e
  2621. 0 // f
  2622. ],
  2623. // == begin transform regexp
  2624. number = fabric.reNum,
  2625. commaWsp = '(?:\\s+,?\\s*|,\\s*)',
  2626. skewX = '(?:(skewX)\\s*\\(\\s*(' + number + ')\\s*\\))',
  2627. skewY = '(?:(skewY)\\s*\\(\\s*(' + number + ')\\s*\\))',
  2628. rotate = '(?:(rotate)\\s*\\(\\s*(' + number + ')(?:' +
  2629. commaWsp + '(' + number + ')' +
  2630. commaWsp + '(' + number + '))?\\s*\\))',
  2631. scale = '(?:(scale)\\s*\\(\\s*(' + number + ')(?:' +
  2632. commaWsp + '(' + number + '))?\\s*\\))',
  2633. translate = '(?:(translate)\\s*\\(\\s*(' + number + ')(?:' +
  2634. commaWsp + '(' + number + '))?\\s*\\))',
  2635. matrix = '(?:(matrix)\\s*\\(\\s*' +
  2636. '(' + number + ')' + commaWsp +
  2637. '(' + number + ')' + commaWsp +
  2638. '(' + number + ')' + commaWsp +
  2639. '(' + number + ')' + commaWsp +
  2640. '(' + number + ')' + commaWsp +
  2641. '(' + number + ')' +
  2642. '\\s*\\))',
  2643. transform = '(?:' +
  2644. matrix + '|' +
  2645. translate + '|' +
  2646. scale + '|' +
  2647. rotate + '|' +
  2648. skewX + '|' +
  2649. skewY +
  2650. ')',
  2651. transforms = '(?:' + transform + '(?:' + commaWsp + transform + ')*' + ')',
  2652. transformList = '^\\s*(?:' + transforms + '?)\\s*$',
  2653. // http://www.w3.org/TR/SVG/coords.html#TransformAttribute
  2654. reTransformList = new RegExp(transformList),
  2655. // == end transform regexp
  2656. reTransform = new RegExp(transform, 'g');
  2657. return function(attributeValue) {
  2658. // start with identity matrix
  2659. var matrix = iMatrix.concat(),
  2660. matrices = [ ];
  2661. // return if no argument was given or
  2662. // an argument does not match transform attribute regexp
  2663. if (!attributeValue || (attributeValue && !reTransformList.test(attributeValue))) {
  2664. return matrix;
  2665. }
  2666. attributeValue.replace(reTransform, function(match) {
  2667. var m = new RegExp(transform).exec(match).filter(function (match) {
  2668. return (match !== '' && match != null);
  2669. }),
  2670. operation = m[1],
  2671. args = m.slice(2).map(parseFloat);
  2672. switch (operation) {
  2673. case 'translate':
  2674. translateMatrix(matrix, args);
  2675. break;
  2676. case 'rotate':
  2677. args[0] = fabric.util.degreesToRadians(args[0]);
  2678. rotateMatrix(matrix, args);
  2679. break;
  2680. case 'scale':
  2681. scaleMatrix(matrix, args);
  2682. break;
  2683. case 'skewX':
  2684. skewXMatrix(matrix, args);
  2685. break;
  2686. case 'skewY':
  2687. skewYMatrix(matrix, args);
  2688. break;
  2689. case 'matrix':
  2690. matrix = args;
  2691. break;
  2692. }
  2693. // snapshot current matrix into matrices array
  2694. matrices.push(matrix.concat());
  2695. // reset
  2696. matrix = iMatrix.concat();
  2697. });
  2698. var combinedMatrix = matrices[0];
  2699. while (matrices.length > 1) {
  2700. matrices.shift();
  2701. combinedMatrix = fabric.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
  2702. }
  2703. return combinedMatrix;
  2704. };
  2705. })();
  2706. /**
  2707. * @private
  2708. */
  2709. function parseStyleString(style, oStyle) {
  2710. var attr, value;
  2711. style.replace(/;$/, '').split(';').forEach(function (chunk) {
  2712. var pair = chunk.split(':');
  2713. attr = normalizeAttr(pair[0].trim().toLowerCase());
  2714. value = normalizeValue(attr, pair[1].trim());
  2715. oStyle[attr] = value;
  2716. });
  2717. }
  2718. /**
  2719. * @private
  2720. */
  2721. function parseStyleObject(style, oStyle) {
  2722. var attr, value;
  2723. for (var prop in style) {
  2724. if (typeof style[prop] === 'undefined') {
  2725. continue;
  2726. }
  2727. attr = normalizeAttr(prop.toLowerCase());
  2728. value = normalizeValue(attr, style[prop]);
  2729. oStyle[attr] = value;
  2730. }
  2731. }
  2732. /**
  2733. * @private
  2734. */
  2735. function getGlobalStylesForElement(element, svgUid) {
  2736. var styles = { };
  2737. for (var rule in fabric.cssRules[svgUid]) {
  2738. if (elementMatchesRule(element, rule.split(' '))) {
  2739. for (var property in fabric.cssRules[svgUid][rule]) {
  2740. styles[property] = fabric.cssRules[svgUid][rule][property];
  2741. }
  2742. }
  2743. }
  2744. return styles;
  2745. }
  2746. /**
  2747. * @private
  2748. */
  2749. function elementMatchesRule(element, selectors) {
  2750. var firstMatching, parentMatching = true;
  2751. //start from rightmost selector.
  2752. firstMatching = selectorMatches(element, selectors.pop());
  2753. if (firstMatching && selectors.length) {
  2754. parentMatching = doesSomeParentMatch(element, selectors);
  2755. }
  2756. return firstMatching && parentMatching && (selectors.length === 0);
  2757. }
  2758. function doesSomeParentMatch(element, selectors) {
  2759. var selector, parentMatching = true;
  2760. while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {
  2761. if (parentMatching) {
  2762. selector = selectors.pop();
  2763. }
  2764. element = element.parentNode;
  2765. parentMatching = selectorMatches(element, selector);
  2766. }
  2767. return selectors.length === 0;
  2768. }
  2769. /**
  2770. * @private
  2771. */
  2772. function selectorMatches(element, selector) {
  2773. var nodeName = element.nodeName,
  2774. classNames = element.getAttribute('class'),
  2775. id = element.getAttribute('id'), matcher;
  2776. // i check if a selector matches slicing away part from it.
  2777. // if i get empty string i should match
  2778. matcher = new RegExp('^' + nodeName, 'i');
  2779. selector = selector.replace(matcher, '');
  2780. if (id && selector.length) {
  2781. matcher = new RegExp('#' + id + '(?![a-zA-Z\\-]+)', 'i');
  2782. selector = selector.replace(matcher, '');
  2783. }
  2784. if (classNames && selector.length) {
  2785. classNames = classNames.split(' ');
  2786. for (var i = classNames.length; i--;) {
  2787. matcher = new RegExp('\\.' + classNames[i] + '(?![a-zA-Z\\-]+)', 'i');
  2788. selector = selector.replace(matcher, '');
  2789. }
  2790. }
  2791. return selector.length === 0;
  2792. }
  2793. /**
  2794. * @private
  2795. */
  2796. function parseUseDirectives(doc) {
  2797. var nodelist = doc.getElementsByTagName('use');
  2798. while (nodelist.length) {
  2799. var el = nodelist[0],
  2800. xlink = el.getAttribute('xlink:href').substr(1),
  2801. x = el.getAttribute('x') || 0,
  2802. y = el.getAttribute('y') || 0,
  2803. el2 = doc.getElementById(xlink).cloneNode(true),
  2804. currentTrans = (el2.getAttribute('transform') || '') + ' translate(' + x + ', ' + y + ')',
  2805. parentNode;
  2806. for (var j = 0, attrs = el.attributes, l = attrs.length; j < l; j++) {
  2807. var attr = attrs.item(j);
  2808. if (attr.nodeName === 'x' || attr.nodeName === 'y' || attr.nodeName === 'xlink:href') {
  2809. continue;
  2810. }
  2811. if (attr.nodeName === 'transform') {
  2812. currentTrans = attr.nodeValue + ' ' + currentTrans;
  2813. }
  2814. else {
  2815. el2.setAttribute(attr.nodeName, attr.nodeValue);
  2816. }
  2817. }
  2818. el2.setAttribute('transform', currentTrans);
  2819. el2.setAttribute('instantiated_by_use', '1');
  2820. el2.removeAttribute('id');
  2821. parentNode = el.parentNode;
  2822. parentNode.replaceChild(el2, el);
  2823. }
  2824. }
  2825. // http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
  2826. // matches, e.g.: +14.56e-12, etc.
  2827. var reViewBoxAttrValue = new RegExp(
  2828. '^' +
  2829. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  2830. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  2831. '\\s*(' + fabric.reNum + '+)\\s*,?' +
  2832. '\\s*(' + fabric.reNum + '+)\\s*' +
  2833. '$'
  2834. );
  2835. /**
  2836. * Add a <g> element that envelop all child elements and makes the viewbox transformMatrix descend on all elements
  2837. */
  2838. function addVBTransform(element, widthAttr, heightAttr) {
  2839. var viewBoxAttr = element.getAttribute('viewBox'),
  2840. scaleX = 1,
  2841. scaleY = 1,
  2842. minX = 0,
  2843. minY = 0,
  2844. viewBoxWidth, viewBoxHeight, matrix, el;
  2845. if (viewBoxAttr && (viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))) {
  2846. minX = -parseFloat(viewBoxAttr[1]),
  2847. minY = -parseFloat(viewBoxAttr[2]),
  2848. viewBoxWidth = parseFloat(viewBoxAttr[3]),
  2849. viewBoxHeight = parseFloat(viewBoxAttr[4]);
  2850. }
  2851. else {
  2852. return;
  2853. }
  2854. if (widthAttr && widthAttr !== viewBoxWidth) {
  2855. scaleX = widthAttr / viewBoxWidth;
  2856. }
  2857. if (heightAttr && heightAttr !== viewBoxHeight) {
  2858. scaleY = heightAttr / viewBoxHeight;
  2859. }
  2860. // default is to preserve aspect ratio
  2861. // preserveAspectRatio attribute to be implemented
  2862. scaleY = scaleX = (scaleX > scaleY ? scaleY : scaleX);
  2863. if (!(scaleX !== 1 || scaleY !== 1 || minX !== 0 || minY !== 0)) {
  2864. return;
  2865. }
  2866. matrix = ' matrix(' + scaleX +
  2867. ' 0' +
  2868. ' 0 ' +
  2869. scaleY + ' ' +
  2870. (minX * scaleX) + ' ' +
  2871. (minY * scaleY) + ') ';
  2872. if (element.tagName === 'svg') {
  2873. el = element.ownerDocument.createElement('g');
  2874. while (element.firstChild != null) {
  2875. el.appendChild(element.firstChild);
  2876. }
  2877. element.appendChild(el);
  2878. }
  2879. else {
  2880. el = element;
  2881. matrix = el.getAttribute('transform') + matrix;
  2882. }
  2883. el.setAttribute('transform', matrix);
  2884. }
  2885. /**
  2886. * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback
  2887. * @static
  2888. * @function
  2889. * @memberOf fabric
  2890. * @param {SVGDocument} doc SVG document to parse
  2891. * @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document).
  2892. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  2893. */
  2894. fabric.parseSVGDocument = (function() {
  2895. var reAllowedSVGTagNames = /^(path|circle|polygon|polyline|ellipse|rect|line|image|text)$/,
  2896. reViewBoxTagNames = /^(symbol|image|marker|pattern|view)$/;
  2897. function hasAncestorWithNodeName(element, nodeName) {
  2898. while (element && (element = element.parentNode)) {
  2899. if (nodeName.test(element.nodeName) && !element.getAttribute('instantiated_by_use')) {
  2900. return true;
  2901. }
  2902. }
  2903. return false;
  2904. }
  2905. return function(doc, callback, reviver) {
  2906. if (!doc) {
  2907. return;
  2908. }
  2909. parseUseDirectives(doc);
  2910. var startTime = new Date(),
  2911. svgUid = fabric.Object.__uid++,
  2912. widthAttr, heightAttr, toBeParsed = false;
  2913. if (doc.getAttribute('width') && doc.getAttribute('width') !== '100%') {
  2914. widthAttr = parseUnit(doc.getAttribute('width'));
  2915. }
  2916. if (doc.getAttribute('height') && doc.getAttribute('height') !== '100%') {
  2917. heightAttr = parseUnit(doc.getAttribute('height'));
  2918. }
  2919. if (!widthAttr || !heightAttr) {
  2920. var viewBoxAttr = doc.getAttribute('viewBox');
  2921. if (viewBoxAttr && (viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue))) {
  2922. widthAttr = parseFloat(viewBoxAttr[3]),
  2923. heightAttr = parseFloat(viewBoxAttr[4]);
  2924. }
  2925. else {
  2926. toBeParsed = true;
  2927. }
  2928. }
  2929. addVBTransform(doc, widthAttr, heightAttr);
  2930. var descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
  2931. if (descendants.length === 0 && fabric.isLikelyNode) {
  2932. // we're likely in node, where "o3-xml" library fails to gEBTN("*")
  2933. // https://github.com/ajaxorg/node-o3-xml/issues/21
  2934. descendants = doc.selectNodes('//*[name(.)!="svg"]');
  2935. var arr = [ ];
  2936. for (var i = 0, len = descendants.length; i < len; i++) {
  2937. arr[i] = descendants[i];
  2938. }
  2939. descendants = arr;
  2940. }
  2941. var elements = descendants.filter(function(el) {
  2942. reViewBoxTagNames.test(el.tagName) && addVBTransform(el, 0, 0);
  2943. return reAllowedSVGTagNames.test(el.tagName) &&
  2944. !hasAncestorWithNodeName(el, /^(?:pattern|defs|symbol)$/); // http://www.w3.org/TR/SVG/struct.html#DefsElement
  2945. });
  2946. if (!elements || (elements && !elements.length)) {
  2947. callback && callback([], {});
  2948. return;
  2949. }
  2950. var options = {
  2951. width: widthAttr,
  2952. height: heightAttr,
  2953. svgUid: svgUid,
  2954. toBeParsed: toBeParsed
  2955. };
  2956. fabric.gradientDefs[svgUid] = fabric.getGradientDefs(doc);
  2957. fabric.cssRules[svgUid] = fabric.getCSSRules(doc);
  2958. // Precedence of rules: style > class > attribute
  2959. fabric.parseElements(elements, function(instances) {
  2960. fabric.documentParsingTime = new Date() - startTime;
  2961. if (callback) {
  2962. callback(instances, options);
  2963. }
  2964. }, clone(options), reviver);
  2965. };
  2966. })();
  2967. /**
  2968. * Used for caching SVG documents (loaded via `fabric.Canvas#loadSVGFromURL`)
  2969. * @namespace
  2970. */
  2971. var svgCache = {
  2972. /**
  2973. * @param {String} name
  2974. * @param {Function} callback
  2975. */
  2976. has: function (name, callback) {
  2977. callback(false);
  2978. },
  2979. get: function () {
  2980. /* NOOP */
  2981. },
  2982. set: function () {
  2983. /* NOOP */
  2984. }
  2985. };
  2986. /**
  2987. * @private
  2988. */
  2989. function _enlivenCachedObject(cachedObject) {
  2990. var objects = cachedObject.objects,
  2991. options = cachedObject.options;
  2992. objects = objects.map(function (o) {
  2993. return fabric[capitalize(o.type)].fromObject(o);
  2994. });
  2995. return ({ objects: objects, options: options });
  2996. }
  2997. /**
  2998. * @private
  2999. */
  3000. function _createSVGPattern(markup, canvas, property) {
  3001. if (canvas[property] && canvas[property].toSVG) {
  3002. markup.push(
  3003. '<pattern x="0" y="0" id="', property, 'Pattern" ',
  3004. 'width="', canvas[property].source.width,
  3005. '" height="', canvas[property].source.height,
  3006. '" patternUnits="userSpaceOnUse">',
  3007. '<image x="0" y="0" ',
  3008. 'width="', canvas[property].source.width,
  3009. '" height="', canvas[property].source.height,
  3010. '" xlink:href="', canvas[property].source.src,
  3011. '"></image></pattern>'
  3012. );
  3013. }
  3014. }
  3015. var reFontDeclaration = new RegExp(
  3016. '(normal|italic)?\\s*(normal|small-caps)?\\s*' +
  3017. '(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(' +
  3018. fabric.reNum +
  3019. '(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|' + fabric.reNum + '))?\\s+(.*)');
  3020. extend(fabric, {
  3021. /**
  3022. * Parses a short font declaration, building adding its properties to a style object
  3023. * @static
  3024. * @function
  3025. * @memberOf fabric
  3026. * @param {String} value font declaration
  3027. * @param {Object} oStyle definition
  3028. */
  3029. parseFontDeclaration: function(value, oStyle) {
  3030. var match = value.match(reFontDeclaration);
  3031. if (!match) {
  3032. return;
  3033. }
  3034. var fontStyle = match[1],
  3035. // font variant is not used
  3036. // fontVariant = match[2],
  3037. fontWeight = match[3],
  3038. fontSize = match[4],
  3039. lineHeight = match[5],
  3040. fontFamily = match[6];
  3041. if (fontStyle) {
  3042. oStyle.fontStyle = fontStyle;
  3043. }
  3044. if (fontWeight) {
  3045. oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
  3046. }
  3047. if (fontSize) {
  3048. oStyle.fontSize = parseUnit(fontSize);
  3049. }
  3050. if (fontFamily) {
  3051. oStyle.fontFamily = fontFamily;
  3052. }
  3053. if (lineHeight) {
  3054. oStyle.lineHeight = lineHeight === 'normal' ? 1 : lineHeight;
  3055. }
  3056. },
  3057. /**
  3058. * Parses an SVG document, returning all of the gradient declarations found in it
  3059. * @static
  3060. * @function
  3061. * @memberOf fabric
  3062. * @param {SVGDocument} doc SVG document to parse
  3063. * @return {Object} Gradient definitions; key corresponds to element id, value -- to gradient definition element
  3064. */
  3065. getGradientDefs: function(doc) {
  3066. var linearGradientEls = doc.getElementsByTagName('linearGradient'),
  3067. radialGradientEls = doc.getElementsByTagName('radialGradient'),
  3068. el, i, j = 0, id, xlink, elList = [ ],
  3069. gradientDefs = { }, idsToXlinkMap = { };
  3070. elList.length = linearGradientEls.length + radialGradientEls.length;
  3071. i = linearGradientEls.length;
  3072. while (i--) {
  3073. elList[j++] = linearGradientEls[i];
  3074. }
  3075. i = radialGradientEls.length;
  3076. while (i--) {
  3077. elList[j++] = radialGradientEls[i];
  3078. }
  3079. while (j--) {
  3080. el = elList[j];
  3081. xlink = el.getAttribute('xlink:href');
  3082. id = el.getAttribute('id');
  3083. if (xlink) {
  3084. idsToXlinkMap[id] = xlink.substr(1);
  3085. }
  3086. gradientDefs[id] = el;
  3087. }
  3088. for (id in idsToXlinkMap) {
  3089. var el2 = gradientDefs[idsToXlinkMap[id]].cloneNode(true);
  3090. el = gradientDefs[id];
  3091. while (el2.firstChild) {
  3092. el.appendChild(el2.firstChild);
  3093. }
  3094. }
  3095. return gradientDefs;
  3096. },
  3097. /**
  3098. * Returns an object of attributes' name/value, given element and an array of attribute names;
  3099. * Parses parent "g" nodes recursively upwards.
  3100. * @static
  3101. * @memberOf fabric
  3102. * @param {DOMElement} element Element to parse
  3103. * @param {Array} attributes Array of attributes to parse
  3104. * @return {Object} object containing parsed attributes' names/values
  3105. */
  3106. parseAttributes: function(element, attributes, svgUid) {
  3107. if (!element) {
  3108. return;
  3109. }
  3110. var value,
  3111. parentAttributes = { },
  3112. fontSize;
  3113. if (typeof svgUid === 'undefined') {
  3114. svgUid = element.getAttribute('svgUid');
  3115. }
  3116. // if there's a parent container (`g` or `a` or `symbol` node), parse its attributes recursively upwards
  3117. if (element.parentNode && /^symbol|[g|a]$/i.test(element.parentNode.nodeName)) {
  3118. parentAttributes = fabric.parseAttributes(element.parentNode, attributes, svgUid);
  3119. }
  3120. fontSize = (parentAttributes && parentAttributes.fontSize ) ||
  3121. element.getAttribute('font-size') || fabric.Text.DEFAULT_SVG_FONT_SIZE;
  3122. var ownAttributes = attributes.reduce(function(memo, attr) {
  3123. value = element.getAttribute(attr);
  3124. if (value) {
  3125. attr = normalizeAttr(attr);
  3126. value = normalizeValue(attr, value, parentAttributes, fontSize);
  3127. memo[attr] = value;
  3128. }
  3129. return memo;
  3130. }, { });
  3131. // add values parsed from style, which take precedence over attributes
  3132. // (see: http://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes)
  3133. ownAttributes = extend(ownAttributes,
  3134. extend(getGlobalStylesForElement(element, svgUid), fabric.parseStyleAttribute(element)));
  3135. if (ownAttributes.font) {
  3136. fabric.parseFontDeclaration(ownAttributes.font, ownAttributes);
  3137. }
  3138. return _setStrokeFillOpacity(extend(parentAttributes, ownAttributes));
  3139. },
  3140. /**
  3141. * Transforms an array of svg elements to corresponding fabric.* instances
  3142. * @static
  3143. * @memberOf fabric
  3144. * @param {Array} elements Array of elements to parse
  3145. * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements)
  3146. * @param {Object} [options] Options object
  3147. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3148. */
  3149. parseElements: function(elements, callback, options, reviver) {
  3150. new fabric.ElementsParser(elements, callback, options, reviver).parse();
  3151. },
  3152. /**
  3153. * Parses "style" attribute, retuning an object with values
  3154. * @static
  3155. * @memberOf fabric
  3156. * @param {SVGElement} element Element to parse
  3157. * @return {Object} Objects with values parsed from style attribute of an element
  3158. */
  3159. parseStyleAttribute: function(element) {
  3160. var oStyle = { },
  3161. style = element.getAttribute('style');
  3162. if (!style) {
  3163. return oStyle;
  3164. }
  3165. if (typeof style === 'string') {
  3166. parseStyleString(style, oStyle);
  3167. }
  3168. else {
  3169. parseStyleObject(style, oStyle);
  3170. }
  3171. return oStyle;
  3172. },
  3173. /**
  3174. * Parses "points" attribute, returning an array of values
  3175. * @static
  3176. * @memberOf fabric
  3177. * @param {String} points points attribute string
  3178. * @return {Array} array of points
  3179. */
  3180. parsePointsAttribute: function(points) {
  3181. // points attribute is required and must not be empty
  3182. if (!points) {
  3183. return null;
  3184. }
  3185. // replace commas with whitespace and remove bookending whitespace
  3186. points = points.replace(/,/g, ' ').trim();
  3187. points = points.split(/\s+/);
  3188. var parsedPoints = [ ], i, len;
  3189. i = 0;
  3190. len = points.length;
  3191. for (; i < len; i+=2) {
  3192. parsedPoints.push({
  3193. x: parseFloat(points[i]),
  3194. y: parseFloat(points[i + 1])
  3195. });
  3196. }
  3197. // odd number of points is an error
  3198. // if (parsedPoints.length % 2 !== 0) {
  3199. // return null;
  3200. // }
  3201. return parsedPoints;
  3202. },
  3203. /**
  3204. * Returns CSS rules for a given SVG document
  3205. * @static
  3206. * @function
  3207. * @memberOf fabric
  3208. * @param {SVGDocument} doc SVG document to parse
  3209. * @return {Object} CSS rules of this document
  3210. */
  3211. getCSSRules: function(doc) {
  3212. var styles = doc.getElementsByTagName('style'),
  3213. allRules = { }, rules;
  3214. // very crude parsing of style contents
  3215. for (var i = 0, len = styles.length; i < len; i++) {
  3216. var styleContents = styles[i].textContent;
  3217. // remove comments
  3218. styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, '');
  3219. if (styleContents.trim() === '') {
  3220. continue;
  3221. }
  3222. rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
  3223. rules = rules.map(function(rule) { return rule.trim(); });
  3224. rules.forEach(function(rule) {
  3225. var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/),
  3226. ruleObj = { }, declaration = match[2].trim(),
  3227. propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/);
  3228. for (var i = 0, len = propertyValuePairs.length; i < len; i++) {
  3229. var pair = propertyValuePairs[i].split(/\s*:\s*/),
  3230. property = normalizeAttr(pair[0]),
  3231. value = normalizeValue(property, pair[1], pair[0]);
  3232. ruleObj[property] = value;
  3233. }
  3234. rule = match[1];
  3235. rule.split(',').forEach(function(_rule) {
  3236. _rule = _rule.replace(/^svg/i, '').trim();
  3237. if (_rule === '') {
  3238. return;
  3239. }
  3240. allRules[_rule] = fabric.util.object.clone(ruleObj);
  3241. });
  3242. });
  3243. }
  3244. return allRules;
  3245. },
  3246. /**
  3247. * Takes url corresponding to an SVG document, and parses it into a set of fabric objects. Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
  3248. * @memberof fabric
  3249. * @param {String} url
  3250. * @param {Function} callback
  3251. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3252. */
  3253. loadSVGFromURL: function(url, callback, reviver) {
  3254. url = url.replace(/^\n\s*/, '').trim();
  3255. svgCache.has(url, function (hasUrl) {
  3256. if (hasUrl) {
  3257. svgCache.get(url, function (value) {
  3258. var enlivedRecord = _enlivenCachedObject(value);
  3259. callback(enlivedRecord.objects, enlivedRecord.options);
  3260. });
  3261. }
  3262. else {
  3263. new fabric.util.request(url, {
  3264. method: 'get',
  3265. onComplete: onComplete
  3266. });
  3267. }
  3268. });
  3269. function onComplete(r) {
  3270. var xml = r.responseXML;
  3271. if (xml && !xml.documentElement && fabric.window.ActiveXObject && r.responseText) {
  3272. xml = new ActiveXObject('Microsoft.XMLDOM');
  3273. xml.async = 'false';
  3274. //IE chokes on DOCTYPE
  3275. xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
  3276. }
  3277. if (!xml || !xml.documentElement) {
  3278. return;
  3279. }
  3280. fabric.parseSVGDocument(xml.documentElement, function (results, options) {
  3281. svgCache.set(url, {
  3282. objects: fabric.util.array.invoke(results, 'toObject'),
  3283. options: options
  3284. });
  3285. callback(results, options);
  3286. }, reviver);
  3287. }
  3288. },
  3289. /**
  3290. * Takes string corresponding to an SVG document, and parses it into a set of fabric objects
  3291. * @memberof fabric
  3292. * @param {String} string
  3293. * @param {Function} callback
  3294. * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
  3295. */
  3296. loadSVGFromString: function(string, callback, reviver) {
  3297. string = string.trim();
  3298. var doc;
  3299. if (typeof DOMParser !== 'undefined') {
  3300. var parser = new DOMParser();
  3301. if (parser && parser.parseFromString) {
  3302. doc = parser.parseFromString(string, 'text/xml');
  3303. }
  3304. }
  3305. else if (fabric.window.ActiveXObject) {
  3306. doc = new ActiveXObject('Microsoft.XMLDOM');
  3307. doc.async = 'false';
  3308. // IE chokes on DOCTYPE
  3309. doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i, ''));
  3310. }
  3311. fabric.parseSVGDocument(doc.documentElement, function (results, options) {
  3312. callback(results, options);
  3313. }, reviver);
  3314. },
  3315. /**
  3316. * Creates markup containing SVG font faces
  3317. * @param {Array} objects Array of fabric objects
  3318. * @return {String}
  3319. */
  3320. createSVGFontFacesMarkup: function(objects) {
  3321. var markup = '';
  3322. for (var i = 0, len = objects.length; i < len; i++) {
  3323. if (objects[i].type !== 'text' || !objects[i].path) {
  3324. continue;
  3325. }
  3326. markup += [
  3327. //jscs:disable validateIndentation
  3328. '@font-face {',
  3329. 'font-family: ', objects[i].fontFamily, '; ',
  3330. 'src: url(\'', objects[i].path, '\')',
  3331. '}'
  3332. //jscs:enable validateIndentation
  3333. ].join('');
  3334. }
  3335. if (markup) {
  3336. markup = [
  3337. //jscs:disable validateIndentation
  3338. '<style type="text/css">',
  3339. '<![CDATA[',
  3340. markup,
  3341. ']]>',
  3342. '</style>'
  3343. //jscs:enable validateIndentation
  3344. ].join('');
  3345. }
  3346. return markup;
  3347. },
  3348. /**
  3349. * Creates markup containing SVG referenced elements like patterns, gradients etc.
  3350. * @param {fabric.Canvas} canvas instance of fabric.Canvas
  3351. * @return {String}
  3352. */
  3353. createSVGRefElementsMarkup: function(canvas) {
  3354. var markup = [ ];
  3355. _createSVGPattern(markup, canvas, 'backgroundColor');
  3356. _createSVGPattern(markup, canvas, 'overlayColor');
  3357. return markup.join('');
  3358. }
  3359. });
  3360. })(typeof exports !== 'undefined' ? exports : this);
  3361. fabric.ElementsParser = function(elements, callback, options, reviver) {
  3362. this.elements = elements;
  3363. this.callback = callback;
  3364. this.options = options;
  3365. this.reviver = reviver;
  3366. this.svgUid = (options && options.svgUid) || 0;
  3367. };
  3368. fabric.ElementsParser.prototype.parse = function() {
  3369. this.instances = new Array(this.elements.length);
  3370. this.numElements = this.elements.length;
  3371. this.createObjects();
  3372. };
  3373. fabric.ElementsParser.prototype.createObjects = function() {
  3374. for (var i = 0, len = this.elements.length; i < len; i++) {
  3375. this.elements[i].setAttribute('svgUid', this.svgUid);
  3376. (function(_this, i) {
  3377. setTimeout(function() {
  3378. _this.createObject(_this.elements[i], i);
  3379. }, 0);
  3380. })(this, i);
  3381. }
  3382. };
  3383. fabric.ElementsParser.prototype.createObject = function(el, index) {
  3384. var klass = fabric[fabric.util.string.capitalize(el.tagName)];
  3385. if (klass && klass.fromElement) {
  3386. try {
  3387. this._createObject(klass, el, index);
  3388. }
  3389. catch (err) {
  3390. fabric.log(err);
  3391. }
  3392. }
  3393. else {
  3394. this.checkIfDone();
  3395. }
  3396. };
  3397. fabric.ElementsParser.prototype._createObject = function(klass, el, index) {
  3398. if (klass.async) {
  3399. klass.fromElement(el, this.createCallback(index, el), this.options);
  3400. }
  3401. else {
  3402. var obj = klass.fromElement(el, this.options);
  3403. this.resolveGradient(obj, 'fill');
  3404. this.resolveGradient(obj, 'stroke');
  3405. this.reviver && this.reviver(el, obj);
  3406. this.instances[index] = obj;
  3407. this.checkIfDone();
  3408. }
  3409. };
  3410. fabric.ElementsParser.prototype.createCallback = function(index, el) {
  3411. var _this = this;
  3412. return function(obj) {
  3413. _this.resolveGradient(obj, 'fill');
  3414. _this.resolveGradient(obj, 'stroke');
  3415. _this.reviver && _this.reviver(el, obj);
  3416. _this.instances[index] = obj;
  3417. _this.checkIfDone();
  3418. };
  3419. };
  3420. fabric.ElementsParser.prototype.resolveGradient = function(obj, property) {
  3421. var instanceFillValue = obj.get(property);
  3422. if (!(/^url\(/).test(instanceFillValue)) {
  3423. return;
  3424. }
  3425. var gradientId = instanceFillValue.slice(5, instanceFillValue.length - 1);
  3426. if (fabric.gradientDefs[this.svgUid][gradientId]) {
  3427. obj.set(property,
  3428. fabric.Gradient.fromElement(fabric.gradientDefs[this.svgUid][gradientId], obj));
  3429. }
  3430. };
  3431. fabric.ElementsParser.prototype.checkIfDone = function() {
  3432. if (--this.numElements === 0) {
  3433. this.instances = this.instances.filter(function(el) {
  3434. return el != null;
  3435. });
  3436. this.callback(this.instances);
  3437. }
  3438. };
  3439. (function(global) {
  3440. 'use strict';
  3441. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  3442. var fabric = global.fabric || (global.fabric = { });
  3443. if (fabric.Point) {
  3444. fabric.warn('fabric.Point is already defined');
  3445. return;
  3446. }
  3447. fabric.Point = Point;
  3448. /**
  3449. * Point class
  3450. * @class fabric.Point
  3451. * @memberOf fabric
  3452. * @constructor
  3453. * @param {Number} x
  3454. * @param {Number} y
  3455. * @return {fabric.Point} thisArg
  3456. */
  3457. function Point(x, y) {
  3458. this.x = x;
  3459. this.y = y;
  3460. }
  3461. Point.prototype = /** @lends fabric.Point.prototype */ {
  3462. constructor: Point,
  3463. /**
  3464. * Adds another point to this one and returns another one
  3465. * @param {fabric.Point} that
  3466. * @return {fabric.Point} new Point instance with added values
  3467. */
  3468. add: function (that) {
  3469. return new Point(this.x + that.x, this.y + that.y);
  3470. },
  3471. /**
  3472. * Adds another point to this one
  3473. * @param {fabric.Point} that
  3474. * @return {fabric.Point} thisArg
  3475. */
  3476. addEquals: function (that) {
  3477. this.x += that.x;
  3478. this.y += that.y;
  3479. return this;
  3480. },
  3481. /**
  3482. * Adds value to this point and returns a new one
  3483. * @param {Number} scalar
  3484. * @return {fabric.Point} new Point with added value
  3485. */
  3486. scalarAdd: function (scalar) {
  3487. return new Point(this.x + scalar, this.y + scalar);
  3488. },
  3489. /**
  3490. * Adds value to this point
  3491. * @param {Number} scalar
  3492. * @return {fabric.Point} thisArg
  3493. */
  3494. scalarAddEquals: function (scalar) {
  3495. this.x += scalar;
  3496. this.y += scalar;
  3497. return this;
  3498. },
  3499. /**
  3500. * Subtracts another point from this point and returns a new one
  3501. * @param {fabric.Point} that
  3502. * @return {fabric.Point} new Point object with subtracted values
  3503. */
  3504. subtract: function (that) {
  3505. return new Point(this.x - that.x, this.y - that.y);
  3506. },
  3507. /**
  3508. * Subtracts another point from this point
  3509. * @param {fabric.Point} that
  3510. * @return {fabric.Point} thisArg
  3511. */
  3512. subtractEquals: function (that) {
  3513. this.x -= that.x;
  3514. this.y -= that.y;
  3515. return this;
  3516. },
  3517. /**
  3518. * Subtracts value from this point and returns a new one
  3519. * @param {Number} scalar
  3520. * @return {fabric.Point}
  3521. */
  3522. scalarSubtract: function (scalar) {
  3523. return new Point(this.x - scalar, this.y - scalar);
  3524. },
  3525. /**
  3526. * Subtracts value from this point
  3527. * @param {Number} scalar
  3528. * @return {fabric.Point} thisArg
  3529. */
  3530. scalarSubtractEquals: function (scalar) {
  3531. this.x -= scalar;
  3532. this.y -= scalar;
  3533. return this;
  3534. },
  3535. /**
  3536. * Miltiplies this point by a value and returns a new one
  3537. * @param {Number} scalar
  3538. * @return {fabric.Point}
  3539. */
  3540. multiply: function (scalar) {
  3541. return new Point(this.x * scalar, this.y * scalar);
  3542. },
  3543. /**
  3544. * Miltiplies this point by a value
  3545. * @param {Number} scalar
  3546. * @return {fabric.Point} thisArg
  3547. */
  3548. multiplyEquals: function (scalar) {
  3549. this.x *= scalar;
  3550. this.y *= scalar;
  3551. return this;
  3552. },
  3553. /**
  3554. * Divides this point by a value and returns a new one
  3555. * @param {Number} scalar
  3556. * @return {fabric.Point}
  3557. */
  3558. divide: function (scalar) {
  3559. return new Point(this.x / scalar, this.y / scalar);
  3560. },
  3561. /**
  3562. * Divides this point by a value
  3563. * @param {Number} scalar
  3564. * @return {fabric.Point} thisArg
  3565. */
  3566. divideEquals: function (scalar) {
  3567. this.x /= scalar;
  3568. this.y /= scalar;
  3569. return this;
  3570. },
  3571. /**
  3572. * Returns true if this point is equal to another one
  3573. * @param {fabric.Point} that
  3574. * @return {Boolean}
  3575. */
  3576. eq: function (that) {
  3577. return (this.x === that.x && this.y === that.y);
  3578. },
  3579. /**
  3580. * Returns true if this point is less than another one
  3581. * @param {fabric.Point} that
  3582. * @return {Boolean}
  3583. */
  3584. lt: function (that) {
  3585. return (this.x < that.x && this.y < that.y);
  3586. },
  3587. /**
  3588. * Returns true if this point is less than or equal to another one
  3589. * @param {fabric.Point} that
  3590. * @return {Boolean}
  3591. */
  3592. lte: function (that) {
  3593. return (this.x <= that.x && this.y <= that.y);
  3594. },
  3595. /**
  3596. * Returns true if this point is greater another one
  3597. * @param {fabric.Point} that
  3598. * @return {Boolean}
  3599. */
  3600. gt: function (that) {
  3601. return (this.x > that.x && this.y > that.y);
  3602. },
  3603. /**
  3604. * Returns true if this point is greater than or equal to another one
  3605. * @param {fabric.Point} that
  3606. * @return {Boolean}
  3607. */
  3608. gte: function (that) {
  3609. return (this.x >= that.x && this.y >= that.y);
  3610. },
  3611. /**
  3612. * Returns new point which is the result of linear interpolation with this one and another one
  3613. * @param {fabric.Point} that
  3614. * @param {Number} t
  3615. * @return {fabric.Point}
  3616. */
  3617. lerp: function (that, t) {
  3618. return new Point(this.x + (that.x - this.x) * t, this.y + (that.y - this.y) * t);
  3619. },
  3620. /**
  3621. * Returns distance from this point and another one
  3622. * @param {fabric.Point} that
  3623. * @return {Number}
  3624. */
  3625. distanceFrom: function (that) {
  3626. var dx = this.x - that.x,
  3627. dy = this.y - that.y;
  3628. return Math.sqrt(dx * dx + dy * dy);
  3629. },
  3630. /**
  3631. * Returns the point between this point and another one
  3632. * @param {fabric.Point} that
  3633. * @return {fabric.Point}
  3634. */
  3635. midPointFrom: function (that) {
  3636. return new Point(this.x + (that.x - this.x)/2, this.y + (that.y - this.y)/2);
  3637. },
  3638. /**
  3639. * Returns a new point which is the min of this and another one
  3640. * @param {fabric.Point} that
  3641. * @return {fabric.Point}
  3642. */
  3643. min: function (that) {
  3644. return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
  3645. },
  3646. /**
  3647. * Returns a new point which is the max of this and another one
  3648. * @param {fabric.Point} that
  3649. * @return {fabric.Point}
  3650. */
  3651. max: function (that) {
  3652. return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
  3653. },
  3654. /**
  3655. * Returns string representation of this point
  3656. * @return {String}
  3657. */
  3658. toString: function () {
  3659. return this.x + ',' + this.y;
  3660. },
  3661. /**
  3662. * Sets x/y of this point
  3663. * @param {Number} x
  3664. * @param {Number} y
  3665. */
  3666. setXY: function (x, y) {
  3667. this.x = x;
  3668. this.y = y;
  3669. },
  3670. /**
  3671. * Sets x/y of this point from another point
  3672. * @param {fabric.Point} that
  3673. */
  3674. setFromPoint: function (that) {
  3675. this.x = that.x;
  3676. this.y = that.y;
  3677. },
  3678. /**
  3679. * Swaps x/y of this point and another point
  3680. * @param {fabric.Point} that
  3681. */
  3682. swap: function (that) {
  3683. var x = this.x,
  3684. y = this.y;
  3685. this.x = that.x;
  3686. this.y = that.y;
  3687. that.x = x;
  3688. that.y = y;
  3689. }
  3690. };
  3691. })(typeof exports !== 'undefined' ? exports : this);
  3692. (function(global) {
  3693. 'use strict';
  3694. /* Adaptation of work of Kevin Lindsey (kevin@kevlindev.com) */
  3695. var fabric = global.fabric || (global.fabric = { });
  3696. if (fabric.Intersection) {
  3697. fabric.warn('fabric.Intersection is already defined');
  3698. return;
  3699. }
  3700. /**
  3701. * Intersection class
  3702. * @class fabric.Intersection
  3703. * @memberOf fabric
  3704. * @constructor
  3705. */
  3706. function Intersection(status) {
  3707. this.status = status;
  3708. this.points = [];
  3709. }
  3710. fabric.Intersection = Intersection;
  3711. fabric.Intersection.prototype = /** @lends fabric.Intersection.prototype */ {
  3712. /**
  3713. * Appends a point to intersection
  3714. * @param {fabric.Point} point
  3715. */
  3716. appendPoint: function (point) {
  3717. this.points.push(point);
  3718. },
  3719. /**
  3720. * Appends points to intersection
  3721. * @param {Array} points
  3722. */
  3723. appendPoints: function (points) {
  3724. this.points = this.points.concat(points);
  3725. }
  3726. };
  3727. /**
  3728. * Checks if one line intersects another
  3729. * @static
  3730. * @param {fabric.Point} a1
  3731. * @param {fabric.Point} a2
  3732. * @param {fabric.Point} b1
  3733. * @param {fabric.Point} b2
  3734. * @return {fabric.Intersection}
  3735. */
  3736. fabric.Intersection.intersectLineLine = function (a1, a2, b1, b2) {
  3737. var result,
  3738. uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x),
  3739. ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x),
  3740. uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
  3741. if (uB !== 0) {
  3742. var ua = uaT / uB,
  3743. ub = ubT / uB;
  3744. if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
  3745. result = new Intersection('Intersection');
  3746. result.points.push(new fabric.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
  3747. }
  3748. else {
  3749. result = new Intersection();
  3750. }
  3751. }
  3752. else {
  3753. if (uaT === 0 || ubT === 0) {
  3754. result = new Intersection('Coincident');
  3755. }
  3756. else {
  3757. result = new Intersection('Parallel');
  3758. }
  3759. }
  3760. return result;
  3761. };
  3762. /**
  3763. * Checks if line intersects polygon
  3764. * @static
  3765. * @param {fabric.Point} a1
  3766. * @param {fabric.Point} a2
  3767. * @param {Array} points
  3768. * @return {fabric.Intersection}
  3769. */
  3770. fabric.Intersection.intersectLinePolygon = function(a1, a2, points) {
  3771. var result = new Intersection(),
  3772. length = points.length;
  3773. for (var i = 0; i < length; i++) {
  3774. var b1 = points[i],
  3775. b2 = points[(i + 1) % length],
  3776. inter = Intersection.intersectLineLine(a1, a2, b1, b2);
  3777. result.appendPoints(inter.points);
  3778. }
  3779. if (result.points.length > 0) {
  3780. result.status = 'Intersection';
  3781. }
  3782. return result;
  3783. };
  3784. /**
  3785. * Checks if polygon intersects another polygon
  3786. * @static
  3787. * @param {Array} points1
  3788. * @param {Array} points2
  3789. * @return {fabric.Intersection}
  3790. */
  3791. fabric.Intersection.intersectPolygonPolygon = function (points1, points2) {
  3792. var result = new Intersection(),
  3793. length = points1.length;
  3794. for (var i = 0; i < length; i++) {
  3795. var a1 = points1[i],
  3796. a2 = points1[(i + 1) % length],
  3797. inter = Intersection.intersectLinePolygon(a1, a2, points2);
  3798. result.appendPoints(inter.points);
  3799. }
  3800. if (result.points.length > 0) {
  3801. result.status = 'Intersection';
  3802. }
  3803. return result;
  3804. };
  3805. /**
  3806. * Checks if polygon intersects rectangle
  3807. * @static
  3808. * @param {Array} points
  3809. * @param {Number} r1
  3810. * @param {Number} r2
  3811. * @return {fabric.Intersection}
  3812. */
  3813. fabric.Intersection.intersectPolygonRectangle = function (points, r1, r2) {
  3814. var min = r1.min(r2),
  3815. max = r1.max(r2),
  3816. topRight = new fabric.Point(max.x, min.y),
  3817. bottomLeft = new fabric.Point(min.x, max.y),
  3818. inter1 = Intersection.intersectLinePolygon(min, topRight, points),
  3819. inter2 = Intersection.intersectLinePolygon(topRight, max, points),
  3820. inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points),
  3821. inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points),
  3822. result = new Intersection();
  3823. result.appendPoints(inter1.points);
  3824. result.appendPoints(inter2.points);
  3825. result.appendPoints(inter3.points);
  3826. result.appendPoints(inter4.points);
  3827. if (result.points.length > 0) {
  3828. result.status = 'Intersection';
  3829. }
  3830. return result;
  3831. };
  3832. })(typeof exports !== 'undefined' ? exports : this);
  3833. (function(global) {
  3834. 'use strict';
  3835. var fabric = global.fabric || (global.fabric = { });
  3836. if (fabric.Color) {
  3837. fabric.warn('fabric.Color is already defined.');
  3838. return;
  3839. }
  3840. /**
  3841. * Color class
  3842. * The purpose of {@link fabric.Color} is to abstract and encapsulate common color operations;
  3843. * {@link fabric.Color} is a constructor and creates instances of {@link fabric.Color} objects.
  3844. *
  3845. * @class fabric.Color
  3846. * @param {String} color optional in hex or rgb(a) format
  3847. * @return {fabric.Color} thisArg
  3848. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#colors}
  3849. */
  3850. function Color(color) {
  3851. if (!color) {
  3852. this.setSource([0, 0, 0, 1]);
  3853. }
  3854. else {
  3855. this._tryParsingColor(color);
  3856. }
  3857. }
  3858. fabric.Color = Color;
  3859. fabric.Color.prototype = /** @lends fabric.Color.prototype */ {
  3860. /**
  3861. * @private
  3862. * @param {String|Array} color Color value to parse
  3863. */
  3864. _tryParsingColor: function(color) {
  3865. var source;
  3866. if (color in Color.colorNameMap) {
  3867. color = Color.colorNameMap[color];
  3868. }
  3869. if (color === 'transparent') {
  3870. this.setSource([255, 255, 255, 0]);
  3871. return;
  3872. }
  3873. source = Color.sourceFromHex(color);
  3874. if (!source) {
  3875. source = Color.sourceFromRgb(color);
  3876. }
  3877. if (!source) {
  3878. source = Color.sourceFromHsl(color);
  3879. }
  3880. if (source) {
  3881. this.setSource(source);
  3882. }
  3883. },
  3884. /**
  3885. * 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>
  3886. * @private
  3887. * @param {Number} r Red color value
  3888. * @param {Number} g Green color value
  3889. * @param {Number} b Blue color value
  3890. * @return {Array} Hsl color
  3891. */
  3892. _rgbToHsl: function(r, g, b) {
  3893. r /= 255, g /= 255, b /= 255;
  3894. var h, s, l,
  3895. max = fabric.util.array.max([r, g, b]),
  3896. min = fabric.util.array.min([r, g, b]);
  3897. l = (max + min) / 2;
  3898. if (max === min) {
  3899. h = s = 0; // achromatic
  3900. }
  3901. else {
  3902. var d = max - min;
  3903. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  3904. switch (max) {
  3905. case r:
  3906. h = (g - b) / d + (g < b ? 6 : 0);
  3907. break;
  3908. case g:
  3909. h = (b - r) / d + 2;
  3910. break;
  3911. case b:
  3912. h = (r - g) / d + 4;
  3913. break;
  3914. }
  3915. h /= 6;
  3916. }
  3917. return [
  3918. Math.round(h * 360),
  3919. Math.round(s * 100),
  3920. Math.round(l * 100)
  3921. ];
  3922. },
  3923. /**
  3924. * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  3925. * @return {Array}
  3926. */
  3927. getSource: function() {
  3928. return this._source;
  3929. },
  3930. /**
  3931. * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
  3932. * @param {Array} source
  3933. */
  3934. setSource: function(source) {
  3935. this._source = source;
  3936. },
  3937. /**
  3938. * Returns color represenation in RGB format
  3939. * @return {String} ex: rgb(0-255,0-255,0-255)
  3940. */
  3941. toRgb: function() {
  3942. var source = this.getSource();
  3943. return 'rgb(' + source[0] + ',' + source[1] + ',' + source[2] + ')';
  3944. },
  3945. /**
  3946. * Returns color represenation in RGBA format
  3947. * @return {String} ex: rgba(0-255,0-255,0-255,0-1)
  3948. */
  3949. toRgba: function() {
  3950. var source = this.getSource();
  3951. return 'rgba(' + source[0] + ',' + source[1] + ',' + source[2] + ',' + source[3] + ')';
  3952. },
  3953. /**
  3954. * Returns color represenation in HSL format
  3955. * @return {String} ex: hsl(0-360,0%-100%,0%-100%)
  3956. */
  3957. toHsl: function() {
  3958. var source = this.getSource(),
  3959. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  3960. return 'hsl(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%)';
  3961. },
  3962. /**
  3963. * Returns color represenation in HSLA format
  3964. * @return {String} ex: hsla(0-360,0%-100%,0%-100%,0-1)
  3965. */
  3966. toHsla: function() {
  3967. var source = this.getSource(),
  3968. hsl = this._rgbToHsl(source[0], source[1], source[2]);
  3969. return 'hsla(' + hsl[0] + ',' + hsl[1] + '%,' + hsl[2] + '%,' + source[3] + ')';
  3970. },
  3971. /**
  3972. * Returns color represenation in HEX format
  3973. * @return {String} ex: FF5555
  3974. */
  3975. toHex: function() {
  3976. var source = this.getSource(), r, g, b;
  3977. r = source[0].toString(16);
  3978. r = (r.length === 1) ? ('0' + r) : r;
  3979. g = source[1].toString(16);
  3980. g = (g.length === 1) ? ('0' + g) : g;
  3981. b = source[2].toString(16);
  3982. b = (b.length === 1) ? ('0' + b) : b;
  3983. return r.toUpperCase() + g.toUpperCase() + b.toUpperCase();
  3984. },
  3985. /**
  3986. * Gets value of alpha channel for this color
  3987. * @return {Number} 0-1
  3988. */
  3989. getAlpha: function() {
  3990. return this.getSource()[3];
  3991. },
  3992. /**
  3993. * Sets value of alpha channel for this color
  3994. * @param {Number} alpha Alpha value 0-1
  3995. * @return {fabric.Color} thisArg
  3996. */
  3997. setAlpha: function(alpha) {
  3998. var source = this.getSource();
  3999. source[3] = alpha;
  4000. this.setSource(source);
  4001. return this;
  4002. },
  4003. /**
  4004. * Transforms color to its grayscale representation
  4005. * @return {fabric.Color} thisArg
  4006. */
  4007. toGrayscale: function() {
  4008. var source = this.getSource(),
  4009. average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10),
  4010. currentAlpha = source[3];
  4011. this.setSource([average, average, average, currentAlpha]);
  4012. return this;
  4013. },
  4014. /**
  4015. * Transforms color to its black and white representation
  4016. * @param {Number} threshold
  4017. * @return {fabric.Color} thisArg
  4018. */
  4019. toBlackWhite: function(threshold) {
  4020. var source = this.getSource(),
  4021. average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0),
  4022. currentAlpha = source[3];
  4023. threshold = threshold || 127;
  4024. average = (Number(average) < Number(threshold)) ? 0 : 255;
  4025. this.setSource([average, average, average, currentAlpha]);
  4026. return this;
  4027. },
  4028. /**
  4029. * Overlays color with another color
  4030. * @param {String|fabric.Color} otherColor
  4031. * @return {fabric.Color} thisArg
  4032. */
  4033. overlayWith: function(otherColor) {
  4034. if (!(otherColor instanceof Color)) {
  4035. otherColor = new Color(otherColor);
  4036. }
  4037. var result = [],
  4038. alpha = this.getAlpha(),
  4039. otherAlpha = 0.5,
  4040. source = this.getSource(),
  4041. otherSource = otherColor.getSource();
  4042. for (var i = 0; i < 3; i++) {
  4043. result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha)));
  4044. }
  4045. result[3] = alpha;
  4046. this.setSource(result);
  4047. return this;
  4048. }
  4049. };
  4050. /**
  4051. * 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))
  4052. * @static
  4053. * @field
  4054. * @memberOf fabric.Color
  4055. */
  4056. 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*)?\)$/;
  4057. /**
  4058. * 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 ))
  4059. * @static
  4060. * @field
  4061. * @memberOf fabric.Color
  4062. */
  4063. fabric.Color.reHSLa = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/;
  4064. /**
  4065. * Regex matching color in HEX format (ex: #FF5555, 010155, aff)
  4066. * @static
  4067. * @field
  4068. * @memberOf fabric.Color
  4069. */
  4070. fabric.Color.reHex = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i;
  4071. /**
  4072. * Map of the 17 basic color names with HEX code
  4073. * @static
  4074. * @field
  4075. * @memberOf fabric.Color
  4076. * @see: http://www.w3.org/TR/CSS2/syndata.html#color-units
  4077. */
  4078. fabric.Color.colorNameMap = {
  4079. aqua: '#00FFFF',
  4080. black: '#000000',
  4081. blue: '#0000FF',
  4082. fuchsia: '#FF00FF',
  4083. gray: '#808080',
  4084. green: '#008000',
  4085. lime: '#00FF00',
  4086. maroon: '#800000',
  4087. navy: '#000080',
  4088. olive: '#808000',
  4089. orange: '#FFA500',
  4090. purple: '#800080',
  4091. red: '#FF0000',
  4092. silver: '#C0C0C0',
  4093. teal: '#008080',
  4094. white: '#FFFFFF',
  4095. yellow: '#FFFF00'
  4096. };
  4097. /**
  4098. * @private
  4099. * @param {Number} p
  4100. * @param {Number} q
  4101. * @param {Number} t
  4102. * @return {Number}
  4103. */
  4104. function hue2rgb(p, q, t) {
  4105. if (t < 0) {
  4106. t += 1;
  4107. }
  4108. if (t > 1) {
  4109. t -= 1;
  4110. }
  4111. if (t < 1/6) {
  4112. return p + (q - p) * 6 * t;
  4113. }
  4114. if (t < 1/2) {
  4115. return q;
  4116. }
  4117. if (t < 2/3) {
  4118. return p + (q - p) * (2/3 - t) * 6;
  4119. }
  4120. return p;
  4121. }
  4122. /**
  4123. * Returns new color object, when given a color in RGB format
  4124. * @memberOf fabric.Color
  4125. * @param {String} color Color value ex: rgb(0-255,0-255,0-255)
  4126. * @return {fabric.Color}
  4127. */
  4128. fabric.Color.fromRgb = function(color) {
  4129. return Color.fromSource(Color.sourceFromRgb(color));
  4130. };
  4131. /**
  4132. * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format
  4133. * @memberOf fabric.Color
  4134. * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%)
  4135. * @return {Array} source
  4136. */
  4137. fabric.Color.sourceFromRgb = function(color) {
  4138. var match = color.match(Color.reRGBa);
  4139. if (match) {
  4140. var r = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1),
  4141. g = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1),
  4142. b = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
  4143. return [
  4144. parseInt(r, 10),
  4145. parseInt(g, 10),
  4146. parseInt(b, 10),
  4147. match[4] ? parseFloat(match[4]) : 1
  4148. ];
  4149. }
  4150. };
  4151. /**
  4152. * Returns new color object, when given a color in RGBA format
  4153. * @static
  4154. * @function
  4155. * @memberOf fabric.Color
  4156. * @param {String} color
  4157. * @return {fabric.Color}
  4158. */
  4159. fabric.Color.fromRgba = Color.fromRgb;
  4160. /**
  4161. * Returns new color object, when given a color in HSL format
  4162. * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%)
  4163. * @memberOf fabric.Color
  4164. * @return {fabric.Color}
  4165. */
  4166. fabric.Color.fromHsl = function(color) {
  4167. return Color.fromSource(Color.sourceFromHsl(color));
  4168. };
  4169. /**
  4170. * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format.
  4171. * 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>
  4172. * @memberOf fabric.Color
  4173. * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1)
  4174. * @return {Array} source
  4175. * @see http://http://www.w3.org/TR/css3-color/#hsl-color
  4176. */
  4177. fabric.Color.sourceFromHsl = function(color) {
  4178. var match = color.match(Color.reHSLa);
  4179. if (!match) {
  4180. return;
  4181. }
  4182. var h = (((parseFloat(match[1]) % 360) + 360) % 360) / 360,
  4183. s = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1),
  4184. l = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1),
  4185. r, g, b;
  4186. if (s === 0) {
  4187. r = g = b = l;
  4188. }
  4189. else {
  4190. var q = l <= 0.5 ? l * (s + 1) : l + s - l * s,
  4191. p = l * 2 - q;
  4192. r = hue2rgb(p, q, h + 1/3);
  4193. g = hue2rgb(p, q, h);
  4194. b = hue2rgb(p, q, h - 1/3);
  4195. }
  4196. return [
  4197. Math.round(r * 255),
  4198. Math.round(g * 255),
  4199. Math.round(b * 255),
  4200. match[4] ? parseFloat(match[4]) : 1
  4201. ];
  4202. };
  4203. /**
  4204. * Returns new color object, when given a color in HSLA format
  4205. * @static
  4206. * @function
  4207. * @memberOf fabric.Color
  4208. * @param {String} color
  4209. * @return {fabric.Color}
  4210. */
  4211. fabric.Color.fromHsla = Color.fromHsl;
  4212. /**
  4213. * Returns new color object, when given a color in HEX format
  4214. * @static
  4215. * @memberOf fabric.Color
  4216. * @param {String} color Color value ex: FF5555
  4217. * @return {fabric.Color}
  4218. */
  4219. fabric.Color.fromHex = function(color) {
  4220. return Color.fromSource(Color.sourceFromHex(color));
  4221. };
  4222. /**
  4223. * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format
  4224. * @static
  4225. * @memberOf fabric.Color
  4226. * @param {String} color ex: FF5555
  4227. * @return {Array} source
  4228. */
  4229. fabric.Color.sourceFromHex = function(color) {
  4230. if (color.match(Color.reHex)) {
  4231. var value = color.slice(color.indexOf('#') + 1),
  4232. isShortNotation = (value.length === 3),
  4233. r = isShortNotation ? (value.charAt(0) + value.charAt(0)) : value.substring(0, 2),
  4234. g = isShortNotation ? (value.charAt(1) + value.charAt(1)) : value.substring(2, 4),
  4235. b = isShortNotation ? (value.charAt(2) + value.charAt(2)) : value.substring(4, 6);
  4236. return [
  4237. parseInt(r, 16),
  4238. parseInt(g, 16),
  4239. parseInt(b, 16),
  4240. 1
  4241. ];
  4242. }
  4243. };
  4244. /**
  4245. * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5])
  4246. * @static
  4247. * @memberOf fabric.Color
  4248. * @param {Array} source
  4249. * @return {fabric.Color}
  4250. */
  4251. fabric.Color.fromSource = function(source) {
  4252. var oColor = new Color();
  4253. oColor.setSource(source);
  4254. return oColor;
  4255. };
  4256. })(typeof exports !== 'undefined' ? exports : this);
  4257. (function() {
  4258. /* _FROM_SVG_START_ */
  4259. function getColorStop(el) {
  4260. var style = el.getAttribute('style'),
  4261. offset = el.getAttribute('offset'),
  4262. color, colorAlpha, opacity;
  4263. // convert percents to absolute values
  4264. offset = parseFloat(offset) / (/%$/.test(offset) ? 100 : 1);
  4265. offset = offset < 0 ? 0 : offset > 1 ? 1 : offset;
  4266. if (style) {
  4267. var keyValuePairs = style.split(/\s*;\s*/);
  4268. if (keyValuePairs[keyValuePairs.length - 1] === '') {
  4269. keyValuePairs.pop();
  4270. }
  4271. for (var i = keyValuePairs.length; i--; ) {
  4272. var split = keyValuePairs[i].split(/\s*:\s*/),
  4273. key = split[0].trim(),
  4274. value = split[1].trim();
  4275. if (key === 'stop-color') {
  4276. color = value;
  4277. }
  4278. else if (key === 'stop-opacity') {
  4279. opacity = value;
  4280. }
  4281. }
  4282. }
  4283. if (!color) {
  4284. color = el.getAttribute('stop-color') || 'rgb(0,0,0)';
  4285. }
  4286. if (!opacity) {
  4287. opacity = el.getAttribute('stop-opacity');
  4288. }
  4289. color = new fabric.Color(color);
  4290. colorAlpha = color.getAlpha();
  4291. opacity = isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity);
  4292. opacity *= colorAlpha;
  4293. return {
  4294. offset: offset,
  4295. color: color.toRgb(),
  4296. opacity: opacity
  4297. };
  4298. }
  4299. function getLinearCoords(el) {
  4300. return {
  4301. x1: el.getAttribute('x1') || 0,
  4302. y1: el.getAttribute('y1') || 0,
  4303. x2: el.getAttribute('x2') || '100%',
  4304. y2: el.getAttribute('y2') || 0
  4305. };
  4306. }
  4307. function getRadialCoords(el) {
  4308. return {
  4309. x1: el.getAttribute('fx') || el.getAttribute('cx') || '50%',
  4310. y1: el.getAttribute('fy') || el.getAttribute('cy') || '50%',
  4311. r1: 0,
  4312. x2: el.getAttribute('cx') || '50%',
  4313. y2: el.getAttribute('cy') || '50%',
  4314. r2: el.getAttribute('r') || '50%'
  4315. };
  4316. }
  4317. /* _FROM_SVG_END_ */
  4318. /**
  4319. * Gradient class
  4320. * @class fabric.Gradient
  4321. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#gradients}
  4322. * @see {@link fabric.Gradient#initialize} for constructor definition
  4323. */
  4324. fabric.Gradient = fabric.util.createClass(/** @lends fabric.Gradient.prototype */ {
  4325. /**
  4326. * Horizontal offset for aligning gradients coming from SVG when outside pathgroups
  4327. * @type Number
  4328. * @default 0
  4329. */
  4330. offsetX: 0,
  4331. /**
  4332. * Vertical offset for aligning gradients coming from SVG when outside pathgroups
  4333. * @type Number
  4334. * @default 0
  4335. */
  4336. offsetY: 0,
  4337. /**
  4338. * Constructor
  4339. * @param {Object} [options] Options object with type, coords, gradientUnits and colorStops
  4340. * @return {fabric.Gradient} thisArg
  4341. */
  4342. initialize: function(options) {
  4343. options || (options = { });
  4344. var coords = { };
  4345. this.id = fabric.Object.__uid++;
  4346. this.type = options.type || 'linear';
  4347. coords = {
  4348. x1: options.coords.x1 || 0,
  4349. y1: options.coords.y1 || 0,
  4350. x2: options.coords.x2 || 0,
  4351. y2: options.coords.y2 || 0
  4352. };
  4353. if (this.type === 'radial') {
  4354. coords.r1 = options.coords.r1 || 0;
  4355. coords.r2 = options.coords.r2 || 0;
  4356. }
  4357. this.coords = coords;
  4358. this.colorStops = options.colorStops.slice();
  4359. if (options.gradientTransform) {
  4360. this.gradientTransform = options.gradientTransform;
  4361. }
  4362. this.offsetX = options.offsetX || this.offsetX;
  4363. this.offsetY = options.offsetY || this.offsetY;
  4364. },
  4365. /**
  4366. * Adds another colorStop
  4367. * @param {Object} colorStop Object with offset and color
  4368. * @return {fabric.Gradient} thisArg
  4369. */
  4370. addColorStop: function(colorStop) {
  4371. for (var position in colorStop) {
  4372. var color = new fabric.Color(colorStop[position]);
  4373. this.colorStops.push({
  4374. offset: position,
  4375. color: color.toRgb(),
  4376. opacity: color.getAlpha()
  4377. });
  4378. }
  4379. return this;
  4380. },
  4381. /**
  4382. * Returns object representation of a gradient
  4383. * @return {Object}
  4384. */
  4385. toObject: function() {
  4386. return {
  4387. type: this.type,
  4388. coords: this.coords,
  4389. colorStops: this.colorStops,
  4390. offsetX: this.offsetX,
  4391. offsetY: this.offsetY
  4392. };
  4393. },
  4394. /* _TO_SVG_START_ */
  4395. /**
  4396. * Returns SVG representation of an gradient
  4397. * @param {Object} object Object to create a gradient for
  4398. * @param {Boolean} normalize Whether coords should be normalized
  4399. * @return {String} SVG representation of an gradient (linear/radial)
  4400. */
  4401. toSVG: function(object) {
  4402. var coords = fabric.util.object.clone(this.coords),
  4403. markup, commonAttributes;
  4404. // colorStops must be sorted ascending
  4405. this.colorStops.sort(function(a, b) {
  4406. return a.offset - b.offset;
  4407. });
  4408. if (!(object.group && object.group.type === 'path-group')) {
  4409. for (var prop in coords) {
  4410. if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
  4411. coords[prop] += this.offsetX - object.width / 2;
  4412. }
  4413. else if (prop === 'y1' || prop === 'y2') {
  4414. coords[prop] += this.offsetY - object.height / 2;
  4415. }
  4416. }
  4417. }
  4418. commonAttributes = 'id="SVGID_' + this.id +
  4419. '" gradientUnits="userSpaceOnUse"';
  4420. if (this.gradientTransform) {
  4421. commonAttributes += ' gradientTransform="matrix(' + this.gradientTransform.join(' ') + ')" ';
  4422. }
  4423. if (this.type === 'linear') {
  4424. markup = [
  4425. //jscs:disable validateIndentation
  4426. '<linearGradient ',
  4427. commonAttributes,
  4428. ' x1="', coords.x1,
  4429. '" y1="', coords.y1,
  4430. '" x2="', coords.x2,
  4431. '" y2="', coords.y2,
  4432. '">\n'
  4433. //jscs:enable validateIndentation
  4434. ];
  4435. }
  4436. else if (this.type === 'radial') {
  4437. markup = [
  4438. //jscs:disable validateIndentation
  4439. '<radialGradient ',
  4440. commonAttributes,
  4441. ' cx="', coords.x2,
  4442. '" cy="', coords.y2,
  4443. '" r="', coords.r2,
  4444. '" fx="', coords.x1,
  4445. '" fy="', coords.y1,
  4446. '">\n'
  4447. //jscs:enable validateIndentation
  4448. ];
  4449. }
  4450. for (var i = 0; i < this.colorStops.length; i++) {
  4451. markup.push(
  4452. //jscs:disable validateIndentation
  4453. '<stop ',
  4454. 'offset="', (this.colorStops[i].offset * 100) + '%',
  4455. '" style="stop-color:', this.colorStops[i].color,
  4456. (this.colorStops[i].opacity != null ? ';stop-opacity: ' + this.colorStops[i].opacity : ';'),
  4457. '"/>\n'
  4458. //jscs:enable validateIndentation
  4459. );
  4460. }
  4461. markup.push((this.type === 'linear' ? '</linearGradient>\n' : '</radialGradient>\n'));
  4462. return markup.join('');
  4463. },
  4464. /* _TO_SVG_END_ */
  4465. /**
  4466. * Returns an instance of CanvasGradient
  4467. * @param {CanvasRenderingContext2D} ctx Context to render on
  4468. * @return {CanvasGradient}
  4469. */
  4470. toLive: function(ctx, object) {
  4471. var gradient, prop, coords = fabric.util.object.clone(this.coords);
  4472. if (!this.type) {
  4473. return;
  4474. }
  4475. if (object.group && object.group.type === 'path-group') {
  4476. for (prop in coords) {
  4477. if (prop === 'x1' || prop === 'x2') {
  4478. coords[prop] += -this.offsetX + object.width / 2;
  4479. }
  4480. else if (prop === 'y1' || prop === 'y2') {
  4481. coords[prop] += -this.offsetY + object.height / 2;
  4482. }
  4483. }
  4484. }
  4485. if (object.type === 'text' || object.type === 'i-text') {
  4486. for (prop in coords) {
  4487. if (prop === 'x1' || prop === 'x2') {
  4488. coords[prop] -= object.width / 2;
  4489. }
  4490. else if (prop === 'y1' || prop === 'y2') {
  4491. coords[prop] -= object.height / 2;
  4492. }
  4493. }
  4494. }
  4495. if (this.type === 'linear') {
  4496. gradient = ctx.createLinearGradient(
  4497. coords.x1, coords.y1, coords.x2, coords.y2);
  4498. }
  4499. else if (this.type === 'radial') {
  4500. gradient = ctx.createRadialGradient(
  4501. coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);
  4502. }
  4503. for (var i = 0, len = this.colorStops.length; i < len; i++) {
  4504. var color = this.colorStops[i].color,
  4505. opacity = this.colorStops[i].opacity,
  4506. offset = this.colorStops[i].offset;
  4507. if (typeof opacity !== 'undefined') {
  4508. color = new fabric.Color(color).setAlpha(opacity).toRgba();
  4509. }
  4510. gradient.addColorStop(parseFloat(offset), color);
  4511. }
  4512. return gradient;
  4513. }
  4514. });
  4515. fabric.util.object.extend(fabric.Gradient, {
  4516. /* _FROM_SVG_START_ */
  4517. /**
  4518. * Returns {@link fabric.Gradient} instance from an SVG element
  4519. * @static
  4520. * @memberof fabric.Gradient
  4521. * @param {SVGGradientElement} el SVG gradient element
  4522. * @param {fabric.Object} instance
  4523. * @return {fabric.Gradient} Gradient instance
  4524. * @see http://www.w3.org/TR/SVG/pservers.html#LinearGradientElement
  4525. * @see http://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
  4526. */
  4527. fromElement: function(el, instance) {
  4528. /**
  4529. * @example:
  4530. *
  4531. * <linearGradient id="linearGrad1">
  4532. * <stop offset="0%" stop-color="white"/>
  4533. * <stop offset="100%" stop-color="black"/>
  4534. * </linearGradient>
  4535. *
  4536. * OR
  4537. *
  4538. * <linearGradient id="linearGrad2">
  4539. * <stop offset="0" style="stop-color:rgb(255,255,255)"/>
  4540. * <stop offset="1" style="stop-color:rgb(0,0,0)"/>
  4541. * </linearGradient>
  4542. *
  4543. * OR
  4544. *
  4545. * <radialGradient id="radialGrad1">
  4546. * <stop offset="0%" stop-color="white" stop-opacity="1" />
  4547. * <stop offset="50%" stop-color="black" stop-opacity="0.5" />
  4548. * <stop offset="100%" stop-color="white" stop-opacity="1" />
  4549. * </radialGradient>
  4550. *
  4551. * OR
  4552. *
  4553. * <radialGradient id="radialGrad2">
  4554. * <stop offset="0" stop-color="rgb(255,255,255)" />
  4555. * <stop offset="0.5" stop-color="rgb(0,0,0)" />
  4556. * <stop offset="1" stop-color="rgb(255,255,255)" />
  4557. * </radialGradient>
  4558. *
  4559. */
  4560. var colorStopEls = el.getElementsByTagName('stop'),
  4561. type = (el.nodeName === 'linearGradient' ? 'linear' : 'radial'),
  4562. gradientUnits = el.getAttribute('gradientUnits') || 'objectBoundingBox',
  4563. gradientTransform = el.getAttribute('gradientTransform'),
  4564. colorStops = [],
  4565. coords = { }, ellipseMatrix;
  4566. if (type === 'linear') {
  4567. coords = getLinearCoords(el);
  4568. }
  4569. else if (type === 'radial') {
  4570. coords = getRadialCoords(el);
  4571. }
  4572. for (var i = colorStopEls.length; i--; ) {
  4573. colorStops.push(getColorStop(colorStopEls[i]));
  4574. }
  4575. ellipseMatrix = _convertPercentUnitsToValues(instance, coords, gradientUnits);
  4576. var gradient = new fabric.Gradient({
  4577. type: type,
  4578. coords: coords,
  4579. colorStops: colorStops,
  4580. offsetX: -instance.left,
  4581. offsetY: -instance.top
  4582. });
  4583. if (gradientTransform || ellipseMatrix !== '') {
  4584. gradient.gradientTransform = fabric.parseTransformAttribute((gradientTransform || '') + ellipseMatrix);
  4585. }
  4586. return gradient;
  4587. },
  4588. /* _FROM_SVG_END_ */
  4589. /**
  4590. * Returns {@link fabric.Gradient} instance from its object representation
  4591. * @static
  4592. * @memberof fabric.Gradient
  4593. * @param {Object} obj
  4594. * @param {Object} [options] Options object
  4595. */
  4596. forObject: function(obj, options) {
  4597. options || (options = { });
  4598. _convertPercentUnitsToValues(obj, options.coords, 'userSpaceOnUse');
  4599. return new fabric.Gradient(options);
  4600. }
  4601. });
  4602. /**
  4603. * @private
  4604. */
  4605. function _convertPercentUnitsToValues(object, options, gradientUnits) {
  4606. var propValue, addFactor = 0, multFactor = 1, ellipseMatrix = '';
  4607. for (var prop in options) {
  4608. propValue = parseFloat(options[prop], 10);
  4609. if (typeof options[prop] === 'string' && /^\d+%$/.test(options[prop])) {
  4610. multFactor = 0.01;
  4611. }
  4612. else {
  4613. multFactor = 1;
  4614. }
  4615. if (prop === 'x1' || prop === 'x2' || prop === 'r2') {
  4616. multFactor *= gradientUnits === 'objectBoundingBox' ? object.width : 1;
  4617. addFactor = gradientUnits === 'objectBoundingBox' ? object.left || 0 : 0;
  4618. }
  4619. else if (prop === 'y1' || prop === 'y2') {
  4620. multFactor *= gradientUnits === 'objectBoundingBox' ? object.height : 1;
  4621. addFactor = gradientUnits === 'objectBoundingBox' ? object.top || 0 : 0;
  4622. }
  4623. options[prop] = propValue * multFactor + addFactor;
  4624. }
  4625. if (object.type === 'ellipse' &&
  4626. options.r2 !== null &&
  4627. gradientUnits === 'objectBoundingBox' &&
  4628. object.rx !== object.ry) {
  4629. var scaleFactor = object.ry/object.rx;
  4630. ellipseMatrix = ' scale(1, ' + scaleFactor + ')';
  4631. if (options.y1) {
  4632. options.y1 /= scaleFactor;
  4633. }
  4634. if (options.y2) {
  4635. options.y2 /= scaleFactor;
  4636. }
  4637. }
  4638. return ellipseMatrix;
  4639. }
  4640. })();
  4641. /**
  4642. * Pattern class
  4643. * @class fabric.Pattern
  4644. * @see {@link http://fabricjs.com/patterns/|Pattern demo}
  4645. * @see {@link http://fabricjs.com/dynamic-patterns/|DynamicPattern demo}
  4646. * @see {@link fabric.Pattern#initialize} for constructor definition
  4647. */
  4648. fabric.Pattern = fabric.util.createClass(/** @lends fabric.Pattern.prototype */ {
  4649. /**
  4650. * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  4651. * @type String
  4652. * @default
  4653. */
  4654. repeat: 'repeat',
  4655. /**
  4656. * Pattern horizontal offset from object's left/top corner
  4657. * @type Number
  4658. * @default
  4659. */
  4660. offsetX: 0,
  4661. /**
  4662. * Pattern vertical offset from object's left/top corner
  4663. * @type Number
  4664. * @default
  4665. */
  4666. offsetY: 0,
  4667. /**
  4668. * Constructor
  4669. * @param {Object} [options] Options object
  4670. * @return {fabric.Pattern} thisArg
  4671. */
  4672. initialize: function(options) {
  4673. options || (options = { });
  4674. this.id = fabric.Object.__uid++;
  4675. if (options.source) {
  4676. if (typeof options.source === 'string') {
  4677. // function string
  4678. if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
  4679. this.source = new Function(fabric.util.getFunctionBody(options.source));
  4680. }
  4681. else {
  4682. // img src string
  4683. var _this = this;
  4684. this.source = fabric.util.createImage();
  4685. fabric.util.loadImage(options.source, function(img) {
  4686. _this.source = img;
  4687. });
  4688. }
  4689. }
  4690. else {
  4691. // img element
  4692. this.source = options.source;
  4693. }
  4694. }
  4695. if (options.repeat) {
  4696. this.repeat = options.repeat;
  4697. }
  4698. if (options.offsetX) {
  4699. this.offsetX = options.offsetX;
  4700. }
  4701. if (options.offsetY) {
  4702. this.offsetY = options.offsetY;
  4703. }
  4704. },
  4705. /**
  4706. * Returns object representation of a pattern
  4707. * @return {Object} Object representation of a pattern instance
  4708. */
  4709. toObject: function() {
  4710. var source;
  4711. // callback
  4712. if (typeof this.source === 'function') {
  4713. source = String(this.source);
  4714. }
  4715. // <img> element
  4716. else if (typeof this.source.src === 'string') {
  4717. source = this.source.src;
  4718. }
  4719. return {
  4720. source: source,
  4721. repeat: this.repeat,
  4722. offsetX: this.offsetX,
  4723. offsetY: this.offsetY
  4724. };
  4725. },
  4726. /* _TO_SVG_START_ */
  4727. /**
  4728. * Returns SVG representation of a pattern
  4729. * @param {fabric.Object} object
  4730. * @return {String} SVG representation of a pattern
  4731. */
  4732. toSVG: function(object) {
  4733. var patternSource = typeof this.source === 'function' ? this.source() : this.source,
  4734. patternWidth = patternSource.width / object.getWidth(),
  4735. patternHeight = patternSource.height / object.getHeight(),
  4736. patternOffsetX = this.offsetX / object.getWidth(),
  4737. patternOffsetY = this.offsetY / object.getHeight(),
  4738. patternImgSrc = '';
  4739. if (this.repeat === 'repeat-x' || this.repeat === 'no-repeat') {
  4740. patternHeight = 1;
  4741. }
  4742. if (this.repeat === 'repeat-y' || this.repeat === 'no-repeat') {
  4743. patternWidth = 1;
  4744. }
  4745. if (patternSource.src) {
  4746. patternImgSrc = patternSource.src;
  4747. }
  4748. else if (patternSource.toDataURL) {
  4749. patternImgSrc = patternSource.toDataURL();
  4750. }
  4751. return '<pattern id="SVGID_' + this.id +
  4752. '" x="' + patternOffsetX +
  4753. '" y="' + patternOffsetY +
  4754. '" width="' + patternWidth +
  4755. '" height="' + patternHeight + '">\n' +
  4756. '<image x="0" y="0"' +
  4757. ' width="' + patternSource.width +
  4758. '" height="' + patternSource.height +
  4759. '" xlink:href="' + patternImgSrc +
  4760. '"></image>\n' +
  4761. '</pattern>\n';
  4762. },
  4763. /* _TO_SVG_END_ */
  4764. /**
  4765. * Returns an instance of CanvasPattern
  4766. * @param {CanvasRenderingContext2D} ctx Context to create pattern
  4767. * @return {CanvasPattern}
  4768. */
  4769. toLive: function(ctx) {
  4770. var source = typeof this.source === 'function'
  4771. ? this.source()
  4772. : this.source;
  4773. // if the image failed to load, return, and allow rest to continue loading
  4774. if (!source) {
  4775. return '';
  4776. }
  4777. // if an image
  4778. if (typeof source.src !== 'undefined') {
  4779. if (!source.complete) {
  4780. return '';
  4781. }
  4782. if (source.naturalWidth === 0 || source.naturalHeight === 0) {
  4783. return '';
  4784. }
  4785. }
  4786. return ctx.createPattern(source, this.repeat);
  4787. }
  4788. });
  4789. (function(global) {
  4790. 'use strict';
  4791. var fabric = global.fabric || (global.fabric = { }),
  4792. toFixed = fabric.util.toFixed;
  4793. if (fabric.Shadow) {
  4794. fabric.warn('fabric.Shadow is already defined.');
  4795. return;
  4796. }
  4797. /**
  4798. * Shadow class
  4799. * @class fabric.Shadow
  4800. * @see {@link http://fabricjs.com/shadows/|Shadow demo}
  4801. * @see {@link fabric.Shadow#initialize} for constructor definition
  4802. */
  4803. fabric.Shadow = fabric.util.createClass(/** @lends fabric.Shadow.prototype */ {
  4804. /**
  4805. * Shadow color
  4806. * @type String
  4807. * @default
  4808. */
  4809. color: 'rgb(0,0,0)',
  4810. /**
  4811. * Shadow blur
  4812. * @type Number
  4813. */
  4814. blur: 0,
  4815. /**
  4816. * Shadow horizontal offset
  4817. * @type Number
  4818. * @default
  4819. */
  4820. offsetX: 0,
  4821. /**
  4822. * Shadow vertical offset
  4823. * @type Number
  4824. * @default
  4825. */
  4826. offsetY: 0,
  4827. /**
  4828. * Whether the shadow should affect stroke operations
  4829. * @type Boolean
  4830. * @default
  4831. */
  4832. affectStroke: false,
  4833. /**
  4834. * Indicates whether toObject should include default values
  4835. * @type Boolean
  4836. * @default
  4837. */
  4838. includeDefaultValues: true,
  4839. /**
  4840. * Constructor
  4841. * @param {Object|String} [options] Options object with any of color, blur, offsetX, offsetX properties or string (e.g. "rgba(0,0,0,0.2) 2px 2px 10px, "2px 2px 10px rgba(0,0,0,0.2)")
  4842. * @return {fabric.Shadow} thisArg
  4843. */
  4844. initialize: function(options) {
  4845. if (typeof options === 'string') {
  4846. options = this._parseShadow(options);
  4847. }
  4848. for (var prop in options) {
  4849. this[prop] = options[prop];
  4850. }
  4851. this.id = fabric.Object.__uid++;
  4852. },
  4853. /**
  4854. * @private
  4855. * @param {String} shadow Shadow value to parse
  4856. * @return {Object} Shadow object with color, offsetX, offsetY and blur
  4857. */
  4858. _parseShadow: function(shadow) {
  4859. var shadowStr = shadow.trim(),
  4860. offsetsAndBlur = fabric.Shadow.reOffsetsAndBlur.exec(shadowStr) || [ ],
  4861. color = shadowStr.replace(fabric.Shadow.reOffsetsAndBlur, '') || 'rgb(0,0,0)';
  4862. return {
  4863. color: color.trim(),
  4864. offsetX: parseInt(offsetsAndBlur[1], 10) || 0,
  4865. offsetY: parseInt(offsetsAndBlur[2], 10) || 0,
  4866. blur: parseInt(offsetsAndBlur[3], 10) || 0
  4867. };
  4868. },
  4869. /**
  4870. * Returns a string representation of an instance
  4871. * @see http://www.w3.org/TR/css-text-decor-3/#text-shadow
  4872. * @return {String} Returns CSS3 text-shadow declaration
  4873. */
  4874. toString: function() {
  4875. return [this.offsetX, this.offsetY, this.blur, this.color].join('px ');
  4876. },
  4877. /* _TO_SVG_START_ */
  4878. /**
  4879. * Returns SVG representation of a shadow
  4880. * @param {fabric.Object} object
  4881. * @return {String} SVG representation of a shadow
  4882. */
  4883. toSVG: function(object) {
  4884. var mode = 'SourceAlpha', fBoxX = 40, fBoxY = 40;
  4885. if (object && (object.fill === this.color || object.stroke === this.color)) {
  4886. mode = 'SourceGraphic';
  4887. }
  4888. if (object.width && object.height) {
  4889. //http://www.w3.org/TR/SVG/filters.html#FilterEffectsRegion
  4890. // we add some extra space to filter box to contain the blur ( 20 )
  4891. fBoxX = toFixed(Math.abs(this.offsetX / object.getWidth()), 2) * 100 + 20;
  4892. fBoxY = toFixed(Math.abs(this.offsetY / object.getHeight()), 2) * 100 + 20;
  4893. }
  4894. return (
  4895. '<filter id="SVGID_' + this.id + '" y="-' + fBoxY + '%" height="' + (100 + 2 * fBoxY) + '%" ' +
  4896. 'x="-' + fBoxX + '%" width="' + (100 + 2 * fBoxX) + '%" ' + '>\n' +
  4897. '\t<feGaussianBlur in="' + mode + '" stdDeviation="' +
  4898. toFixed(this.blur ? this.blur / 2 : 0, 3) +
  4899. '" result="blurOut"></feGaussianBlur>\n' +
  4900. '\t<feColorMatrix result="matrixOut" in="blurOut" type="matrix" ' +
  4901. 'values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0.30 0" ></feColorMatrix >\n' +
  4902. '\t<feOffset dx="' + this.offsetX + '" dy="' + this.offsetY + '"></feOffset>\n' +
  4903. '\t<feMerge>\n' +
  4904. '\t\t<feMergeNode></feMergeNode>\n' +
  4905. '\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n' +
  4906. '\t</feMerge>\n' +
  4907. '</filter>\n');
  4908. },
  4909. /* _TO_SVG_END_ */
  4910. /**
  4911. * Returns object representation of a shadow
  4912. * @return {Object} Object representation of a shadow instance
  4913. */
  4914. toObject: function() {
  4915. if (this.includeDefaultValues) {
  4916. return {
  4917. color: this.color,
  4918. blur: this.blur,
  4919. offsetX: this.offsetX,
  4920. offsetY: this.offsetY
  4921. };
  4922. }
  4923. var obj = { }, proto = fabric.Shadow.prototype;
  4924. if (this.color !== proto.color) {
  4925. obj.color = this.color;
  4926. }
  4927. if (this.blur !== proto.blur) {
  4928. obj.blur = this.blur;
  4929. }
  4930. if (this.offsetX !== proto.offsetX) {
  4931. obj.offsetX = this.offsetX;
  4932. }
  4933. if (this.offsetY !== proto.offsetY) {
  4934. obj.offsetY = this.offsetY;
  4935. }
  4936. return obj;
  4937. }
  4938. });
  4939. /**
  4940. * Regex matching shadow offsetX, offsetY and blur (ex: "2px 2px 10px rgba(0,0,0,0.2)", "rgb(0,255,0) 2px 2px")
  4941. * @static
  4942. * @field
  4943. * @memberOf fabric.Shadow
  4944. */
  4945. fabric.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:px)?(?:\s?|$))?(-?\d+(?:px)?(?:\s?|$))?(\d+(?:px)?)?(?:\s?|$)(?:$|\s)/;
  4946. })(typeof exports !== 'undefined' ? exports : this);
  4947. (function () {
  4948. 'use strict';
  4949. if (fabric.StaticCanvas) {
  4950. fabric.warn('fabric.StaticCanvas is already defined.');
  4951. return;
  4952. }
  4953. // aliases for faster resolution
  4954. var extend = fabric.util.object.extend,
  4955. getElementOffset = fabric.util.getElementOffset,
  4956. removeFromArray = fabric.util.removeFromArray,
  4957. CANVAS_INIT_ERROR = new Error('Could not initialize `canvas` element');
  4958. /**
  4959. * Static canvas class
  4960. * @class fabric.StaticCanvas
  4961. * @mixes fabric.Collection
  4962. * @mixes fabric.Observable
  4963. * @see {@link http://fabricjs.com/static_canvas/|StaticCanvas demo}
  4964. * @see {@link fabric.StaticCanvas#initialize} for constructor definition
  4965. * @fires before:render
  4966. * @fires after:render
  4967. * @fires canvas:cleared
  4968. * @fires object:added
  4969. * @fires object:removed
  4970. */
  4971. fabric.StaticCanvas = fabric.util.createClass(/** @lends fabric.StaticCanvas.prototype */ {
  4972. /**
  4973. * Constructor
  4974. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  4975. * @param {Object} [options] Options object
  4976. * @return {Object} thisArg
  4977. */
  4978. initialize: function(el, options) {
  4979. options || (options = { });
  4980. this._initStatic(el, options);
  4981. fabric.StaticCanvas.activeInstance = this;
  4982. },
  4983. /**
  4984. * Background color of canvas instance.
  4985. * Should be set via {@link fabric.StaticCanvas#setBackgroundColor}.
  4986. * @type {(String|fabric.Pattern)}
  4987. * @default
  4988. */
  4989. backgroundColor: '',
  4990. /**
  4991. * Background image of canvas instance.
  4992. * Should be set via {@link fabric.StaticCanvas#setBackgroundImage}.
  4993. * <b>Backwards incompatibility note:</b> The "backgroundImageOpacity"
  4994. * and "backgroundImageStretch" properties are deprecated since 1.3.9.
  4995. * Use {@link fabric.Image#opacity}, {@link fabric.Image#width} and {@link fabric.Image#height}.
  4996. * @type fabric.Image
  4997. * @default
  4998. */
  4999. backgroundImage: null,
  5000. /**
  5001. * Overlay color of canvas instance.
  5002. * Should be set via {@link fabric.StaticCanvas#setOverlayColor}
  5003. * @since 1.3.9
  5004. * @type {(String|fabric.Pattern)}
  5005. * @default
  5006. */
  5007. overlayColor: '',
  5008. /**
  5009. * Overlay image of canvas instance.
  5010. * Should be set via {@link fabric.StaticCanvas#setOverlayImage}.
  5011. * <b>Backwards incompatibility note:</b> The "overlayImageLeft"
  5012. * and "overlayImageTop" properties are deprecated since 1.3.9.
  5013. * Use {@link fabric.Image#left} and {@link fabric.Image#top}.
  5014. * @type fabric.Image
  5015. * @default
  5016. */
  5017. overlayImage: null,
  5018. /**
  5019. * Indicates whether toObject/toDatalessObject should include default values
  5020. * @type Boolean
  5021. * @default
  5022. */
  5023. includeDefaultValues: true,
  5024. /**
  5025. * Indicates whether objects' state should be saved
  5026. * @type Boolean
  5027. * @default
  5028. */
  5029. stateful: true,
  5030. /**
  5031. * Indicates whether {@link fabric.Collection.add}, {@link fabric.Collection.insertAt} and {@link fabric.Collection.remove} should also re-render canvas.
  5032. * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once
  5033. * (followed by a manual rendering after addition/deletion)
  5034. * @type Boolean
  5035. * @default
  5036. */
  5037. renderOnAddRemove: true,
  5038. /**
  5039. * Function that determines clipping of entire canvas area
  5040. * Being passed context as first argument. See clipping canvas area in {@link https://github.com/kangax/fabric.js/wiki/FAQ}
  5041. * @type Function
  5042. * @default
  5043. */
  5044. clipTo: null,
  5045. /**
  5046. * Indicates whether object controls (borders/controls) are rendered above overlay image
  5047. * @type Boolean
  5048. * @default
  5049. */
  5050. controlsAboveOverlay: false,
  5051. /**
  5052. * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas
  5053. * @type Boolean
  5054. * @default
  5055. */
  5056. allowTouchScrolling: false,
  5057. /**
  5058. * Indicates whether this canvas will use image smoothing, this is on by default in browsers
  5059. * @type Boolean
  5060. * @default
  5061. */
  5062. imageSmoothingEnabled: true,
  5063. /**
  5064. * Indicates whether objects should remain in current stack position when selected. When false objects are brought to top and rendered as part of the selection group
  5065. * @type Boolean
  5066. * @default
  5067. */
  5068. preserveObjectStacking: false,
  5069. /**
  5070. * The transformation (in the format of Canvas transform) which focuses the viewport
  5071. * @type Array
  5072. * @default
  5073. */
  5074. viewportTransform: [1, 0, 0, 1, 0, 0],
  5075. /**
  5076. * Callback; invoked right before object is about to be scaled/rotated
  5077. */
  5078. onBeforeScaleRotate: function () {
  5079. /* NOOP */
  5080. },
  5081. /**
  5082. * @private
  5083. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  5084. * @param {Object} [options] Options object
  5085. */
  5086. _initStatic: function(el, options) {
  5087. this._objects = [];
  5088. this._createLowerCanvas(el);
  5089. this._initOptions(options);
  5090. this._setImageSmoothing();
  5091. if (options.overlayImage) {
  5092. this.setOverlayImage(options.overlayImage, this.renderAll.bind(this));
  5093. }
  5094. if (options.backgroundImage) {
  5095. this.setBackgroundImage(options.backgroundImage, this.renderAll.bind(this));
  5096. }
  5097. if (options.backgroundColor) {
  5098. this.setBackgroundColor(options.backgroundColor, this.renderAll.bind(this));
  5099. }
  5100. if (options.overlayColor) {
  5101. this.setOverlayColor(options.overlayColor, this.renderAll.bind(this));
  5102. }
  5103. this.calcOffset();
  5104. },
  5105. /**
  5106. * Calculates canvas element offset relative to the document
  5107. * This method is also attached as "resize" event handler of window
  5108. * @return {fabric.Canvas} instance
  5109. * @chainable
  5110. */
  5111. calcOffset: function () {
  5112. this._offset = getElementOffset(this.lowerCanvasEl);
  5113. return this;
  5114. },
  5115. /**
  5116. * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas
  5117. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to
  5118. * @param {Function} callback callback to invoke when image is loaded and set as an overlay
  5119. * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}.
  5120. * @return {fabric.Canvas} thisArg
  5121. * @chainable
  5122. * @see {@link http://jsfiddle.net/fabricjs/MnzHT/|jsFiddle demo}
  5123. * @example <caption>Normal overlayImage with left/top = 0</caption>
  5124. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5125. * // Needed to position overlayImage at 0/0
  5126. * originX: 'left',
  5127. * originY: 'top'
  5128. * });
  5129. * @example <caption>overlayImage with different properties</caption>
  5130. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5131. * opacity: 0.5,
  5132. * angle: 45,
  5133. * left: 400,
  5134. * top: 400,
  5135. * originX: 'left',
  5136. * originY: 'top'
  5137. * });
  5138. * @example <caption>Stretched overlayImage #1 - width/height correspond to canvas width/height</caption>
  5139. * fabric.Image.fromURL('http://fabricjs.com/assets/jail_cell_bars.png', function(img) {
  5140. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  5141. * canvas.setOverlayImage(img, canvas.renderAll.bind(canvas));
  5142. * });
  5143. * @example <caption>Stretched overlayImage #2 - width/height correspond to canvas width/height</caption>
  5144. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5145. * width: canvas.width,
  5146. * height: canvas.height,
  5147. * // Needed to position overlayImage at 0/0
  5148. * originX: 'left',
  5149. * originY: 'top'
  5150. * });
  5151. * @example <caption>overlayImage loaded from cross-origin</caption>
  5152. * canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
  5153. * opacity: 0.5,
  5154. * angle: 45,
  5155. * left: 400,
  5156. * top: 400,
  5157. * originX: 'left',
  5158. * originY: 'top',
  5159. * crossOrigin: 'anonymous'
  5160. * });
  5161. */
  5162. setOverlayImage: function (image, callback, options) {
  5163. return this.__setBgOverlayImage('overlayImage', image, callback, options);
  5164. },
  5165. /**
  5166. * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas
  5167. * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to
  5168. * @param {Function} callback Callback to invoke when image is loaded and set as background
  5169. * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}.
  5170. * @return {fabric.Canvas} thisArg
  5171. * @chainable
  5172. * @see {@link http://jsfiddle.net/fabricjs/YH9yD/|jsFiddle demo}
  5173. * @example <caption>Normal backgroundImage with left/top = 0</caption>
  5174. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5175. * // Needed to position backgroundImage at 0/0
  5176. * originX: 'left',
  5177. * originY: 'top'
  5178. * });
  5179. * @example <caption>backgroundImage with different properties</caption>
  5180. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5181. * opacity: 0.5,
  5182. * angle: 45,
  5183. * left: 400,
  5184. * top: 400,
  5185. * originX: 'left',
  5186. * originY: 'top'
  5187. * });
  5188. * @example <caption>Stretched backgroundImage #1 - width/height correspond to canvas width/height</caption>
  5189. * fabric.Image.fromURL('http://fabricjs.com/assets/honey_im_subtle.png', function(img) {
  5190. * img.set({width: canvas.width, height: canvas.height, originX: 'left', originY: 'top'});
  5191. * canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
  5192. * });
  5193. * @example <caption>Stretched backgroundImage #2 - width/height correspond to canvas width/height</caption>
  5194. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5195. * width: canvas.width,
  5196. * height: canvas.height,
  5197. * // Needed to position backgroundImage at 0/0
  5198. * originX: 'left',
  5199. * originY: 'top'
  5200. * });
  5201. * @example <caption>backgroundImage loaded from cross-origin</caption>
  5202. * canvas.setBackgroundImage('http://fabricjs.com/assets/honey_im_subtle.png', canvas.renderAll.bind(canvas), {
  5203. * opacity: 0.5,
  5204. * angle: 45,
  5205. * left: 400,
  5206. * top: 400,
  5207. * originX: 'left',
  5208. * originY: 'top',
  5209. * crossOrigin: 'anonymous'
  5210. * });
  5211. */
  5212. setBackgroundImage: function (image, callback, options) {
  5213. return this.__setBgOverlayImage('backgroundImage', image, callback, options);
  5214. },
  5215. /**
  5216. * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas
  5217. * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set background color to
  5218. * @param {Function} callback Callback to invoke when background color is set
  5219. * @return {fabric.Canvas} thisArg
  5220. * @chainable
  5221. * @see {@link http://jsfiddle.net/fabricjs/pB55h/|jsFiddle demo}
  5222. * @example <caption>Normal overlayColor - color value</caption>
  5223. * canvas.setOverlayColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  5224. * @example <caption>fabric.Pattern used as overlayColor</caption>
  5225. * canvas.setOverlayColor({
  5226. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  5227. * }, canvas.renderAll.bind(canvas));
  5228. * @example <caption>fabric.Pattern used as overlayColor with repeat and offset</caption>
  5229. * canvas.setOverlayColor({
  5230. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  5231. * repeat: 'repeat',
  5232. * offsetX: 200,
  5233. * offsetY: 100
  5234. * }, canvas.renderAll.bind(canvas));
  5235. */
  5236. setOverlayColor: function(overlayColor, callback) {
  5237. return this.__setBgOverlayColor('overlayColor', overlayColor, callback);
  5238. },
  5239. /**
  5240. * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas
  5241. * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to
  5242. * @param {Function} callback Callback to invoke when background color is set
  5243. * @return {fabric.Canvas} thisArg
  5244. * @chainable
  5245. * @see {@link http://jsfiddle.net/fabricjs/hXzvk/|jsFiddle demo}
  5246. * @example <caption>Normal backgroundColor - color value</caption>
  5247. * canvas.setBackgroundColor('rgba(255, 73, 64, 0.6)', canvas.renderAll.bind(canvas));
  5248. * @example <caption>fabric.Pattern used as backgroundColor</caption>
  5249. * canvas.setBackgroundColor({
  5250. * source: 'http://fabricjs.com/assets/escheresque_ste.png'
  5251. * }, canvas.renderAll.bind(canvas));
  5252. * @example <caption>fabric.Pattern used as backgroundColor with repeat and offset</caption>
  5253. * canvas.setBackgroundColor({
  5254. * source: 'http://fabricjs.com/assets/escheresque_ste.png',
  5255. * repeat: 'repeat',
  5256. * offsetX: 200,
  5257. * offsetY: 100
  5258. * }, canvas.renderAll.bind(canvas));
  5259. */
  5260. setBackgroundColor: function(backgroundColor, callback) {
  5261. return this.__setBgOverlayColor('backgroundColor', backgroundColor, callback);
  5262. },
  5263. /**
  5264. * @private
  5265. * @see {@link http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled|WhatWG Canvas Standard}
  5266. */
  5267. _setImageSmoothing: function() {
  5268. var ctx = this.getContext();
  5269. ctx.imageSmoothingEnabled = this.imageSmoothingEnabled;
  5270. ctx.webkitImageSmoothingEnabled = this.imageSmoothingEnabled;
  5271. ctx.mozImageSmoothingEnabled = this.imageSmoothingEnabled;
  5272. ctx.msImageSmoothingEnabled = this.imageSmoothingEnabled;
  5273. ctx.oImageSmoothingEnabled = this.imageSmoothingEnabled;
  5274. },
  5275. /**
  5276. * @private
  5277. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundImage|backgroundImage}
  5278. * or {@link fabric.StaticCanvas#overlayImage|overlayImage})
  5279. * @param {(fabric.Image|String|null)} image fabric.Image instance, URL of an image or null to set background or overlay to
  5280. * @param {Function} callback Callback to invoke when image is loaded and set as background or overlay
  5281. * @param {Object} [options] Optional options to set for the {@link fabric.Image|image}.
  5282. */
  5283. __setBgOverlayImage: function(property, image, callback, options) {
  5284. if (typeof image === 'string') {
  5285. fabric.util.loadImage(image, function(img) {
  5286. this[property] = new fabric.Image(img, options);
  5287. callback && callback();
  5288. }, this, options && options.crossOrigin);
  5289. }
  5290. else {
  5291. options && image.setOptions(options);
  5292. this[property] = image;
  5293. callback && callback();
  5294. }
  5295. return this;
  5296. },
  5297. /**
  5298. * @private
  5299. * @param {String} property Property to set ({@link fabric.StaticCanvas#backgroundColor|backgroundColor}
  5300. * or {@link fabric.StaticCanvas#overlayColor|overlayColor})
  5301. * @param {(Object|String|null)} color Object with pattern information, color value or null
  5302. * @param {Function} [callback] Callback is invoked when color is set
  5303. */
  5304. __setBgOverlayColor: function(property, color, callback) {
  5305. if (color && color.source) {
  5306. var _this = this;
  5307. fabric.util.loadImage(color.source, function(img) {
  5308. _this[property] = new fabric.Pattern({
  5309. source: img,
  5310. repeat: color.repeat,
  5311. offsetX: color.offsetX,
  5312. offsetY: color.offsetY
  5313. });
  5314. callback && callback();
  5315. });
  5316. }
  5317. else {
  5318. this[property] = color;
  5319. callback && callback();
  5320. }
  5321. return this;
  5322. },
  5323. /**
  5324. * @private
  5325. */
  5326. _createCanvasElement: function() {
  5327. var element = fabric.document.createElement('canvas');
  5328. if (!element.style) {
  5329. element.style = { };
  5330. }
  5331. if (!element) {
  5332. throw CANVAS_INIT_ERROR;
  5333. }
  5334. this._initCanvasElement(element);
  5335. return element;
  5336. },
  5337. /**
  5338. * @private
  5339. * @param {HTMLElement} element
  5340. */
  5341. _initCanvasElement: function(element) {
  5342. fabric.util.createCanvasElement(element);
  5343. if (typeof element.getContext === 'undefined') {
  5344. throw CANVAS_INIT_ERROR;
  5345. }
  5346. },
  5347. /**
  5348. * @private
  5349. * @param {Object} [options] Options object
  5350. */
  5351. _initOptions: function (options) {
  5352. for (var prop in options) {
  5353. this[prop] = options[prop];
  5354. }
  5355. this.width = this.width || parseInt(this.lowerCanvasEl.width, 10) || 0;
  5356. this.height = this.height || parseInt(this.lowerCanvasEl.height, 10) || 0;
  5357. if (!this.lowerCanvasEl.style) {
  5358. return;
  5359. }
  5360. this.lowerCanvasEl.width = this.width;
  5361. this.lowerCanvasEl.height = this.height;
  5362. this.lowerCanvasEl.style.width = this.width + 'px';
  5363. this.lowerCanvasEl.style.height = this.height + 'px';
  5364. this.viewportTransform = this.viewportTransform.slice();
  5365. },
  5366. /**
  5367. * Creates a bottom canvas
  5368. * @private
  5369. * @param {HTMLElement} [canvasEl]
  5370. */
  5371. _createLowerCanvas: function (canvasEl) {
  5372. this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();
  5373. this._initCanvasElement(this.lowerCanvasEl);
  5374. fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');
  5375. if (this.interactive) {
  5376. this._applyCanvasStyle(this.lowerCanvasEl);
  5377. }
  5378. this.contextContainer = this.lowerCanvasEl.getContext('2d');
  5379. },
  5380. /**
  5381. * Returns canvas width (in px)
  5382. * @return {Number}
  5383. */
  5384. getWidth: function () {
  5385. return this.width;
  5386. },
  5387. /**
  5388. * Returns canvas height (in px)
  5389. * @return {Number}
  5390. */
  5391. getHeight: function () {
  5392. return this.height;
  5393. },
  5394. /**
  5395. * Sets width of this canvas instance
  5396. * @param {Number|String} value Value to set width to
  5397. * @param {Object} [options] Options object
  5398. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  5399. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  5400. * @return {fabric.Canvas} instance
  5401. * @chainable true
  5402. */
  5403. setWidth: function (value, options) {
  5404. return this.setDimensions({ width: value }, options);
  5405. },
  5406. /**
  5407. * Sets height of this canvas instance
  5408. * @param {Number|String} value Value to set height to
  5409. * @param {Object} [options] Options object
  5410. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  5411. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  5412. * @return {fabric.Canvas} instance
  5413. * @chainable true
  5414. */
  5415. setHeight: function (value, options) {
  5416. return this.setDimensions({ height: value }, options);
  5417. },
  5418. /**
  5419. * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em)
  5420. * @param {Object} dimensions Object with width/height properties
  5421. * @param {Number|String} [dimensions.width] Width of canvas element
  5422. * @param {Number|String} [dimensions.height] Height of canvas element
  5423. * @param {Object} [options] Options object
  5424. * @param {Boolean} [options.backstoreOnly=false] Set the given dimensions only as canvas backstore dimensions
  5425. * @param {Boolean} [options.cssOnly=false] Set the given dimensions only as css dimensions
  5426. * @return {fabric.Canvas} thisArg
  5427. * @chainable
  5428. */
  5429. setDimensions: function (dimensions, options) {
  5430. var cssValue;
  5431. options = options || {};
  5432. for (var prop in dimensions) {
  5433. cssValue = dimensions[prop];
  5434. if (!options.cssOnly) {
  5435. this._setBackstoreDimension(prop, dimensions[prop]);
  5436. cssValue += 'px';
  5437. }
  5438. if (!options.backstoreOnly) {
  5439. this._setCssDimension(prop, cssValue);
  5440. }
  5441. }
  5442. if (!options.cssOnly) {
  5443. this.renderAll();
  5444. }
  5445. this.calcOffset();
  5446. return this;
  5447. },
  5448. /**
  5449. * Helper for setting width/height
  5450. * @private
  5451. * @param {String} prop property (width|height)
  5452. * @param {Number} value value to set property to
  5453. * @return {fabric.Canvas} instance
  5454. * @chainable true
  5455. */
  5456. _setBackstoreDimension: function (prop, value) {
  5457. this.lowerCanvasEl[prop] = value;
  5458. if (this.upperCanvasEl) {
  5459. this.upperCanvasEl[prop] = value;
  5460. }
  5461. if (this.cacheCanvasEl) {
  5462. this.cacheCanvasEl[prop] = value;
  5463. }
  5464. this[prop] = value;
  5465. return this;
  5466. },
  5467. /**
  5468. * Helper for setting css width/height
  5469. * @private
  5470. * @param {String} prop property (width|height)
  5471. * @param {String} value value to set property to
  5472. * @return {fabric.Canvas} instance
  5473. * @chainable true
  5474. */
  5475. _setCssDimension: function (prop, value) {
  5476. this.lowerCanvasEl.style[prop] = value;
  5477. if (this.upperCanvasEl) {
  5478. this.upperCanvasEl.style[prop] = value;
  5479. }
  5480. if (this.wrapperEl) {
  5481. this.wrapperEl.style[prop] = value;
  5482. }
  5483. return this;
  5484. },
  5485. /**
  5486. * Returns canvas zoom level
  5487. * @return {Number}
  5488. */
  5489. getZoom: function () {
  5490. return Math.sqrt(this.viewportTransform[0] * this.viewportTransform[3]);
  5491. },
  5492. /**
  5493. * Sets viewport transform of this canvas instance
  5494. * @param {Array} vpt the transform in the form of context.transform
  5495. * @return {fabric.Canvas} instance
  5496. * @chainable true
  5497. */
  5498. setViewportTransform: function (vpt) {
  5499. var activeGroup = this.getActiveGroup();
  5500. this.viewportTransform = vpt;
  5501. this.renderAll();
  5502. for (var i = 0, len = this._objects.length; i < len; i++) {
  5503. this._objects[i].setCoords();
  5504. }
  5505. if (activeGroup) {
  5506. activeGroup.setCoords();
  5507. }
  5508. return this;
  5509. },
  5510. /**
  5511. * Sets zoom level of this canvas instance, zoom centered around point
  5512. * @param {fabric.Point} point to zoom with respect to
  5513. * @param {Number} value to set zoom to, less than 1 zooms out
  5514. * @return {fabric.Canvas} instance
  5515. * @chainable true
  5516. */
  5517. zoomToPoint: function (point, value) {
  5518. // TODO: just change the scale, preserve other transformations
  5519. var before = point;
  5520. point = fabric.util.transformPoint(point, fabric.util.invertTransform(this.viewportTransform));
  5521. this.viewportTransform[0] = value;
  5522. this.viewportTransform[3] = value;
  5523. var after = fabric.util.transformPoint(point, this.viewportTransform);
  5524. this.viewportTransform[4] += before.x - after.x;
  5525. this.viewportTransform[5] += before.y - after.y;
  5526. this.renderAll();
  5527. for (var i = 0, len = this._objects.length; i < len; i++) {
  5528. this._objects[i].setCoords();
  5529. }
  5530. return this;
  5531. },
  5532. /**
  5533. * Sets zoom level of this canvas instance
  5534. * @param {Number} value to set zoom to, less than 1 zooms out
  5535. * @return {fabric.Canvas} instance
  5536. * @chainable true
  5537. */
  5538. setZoom: function (value) {
  5539. this.zoomToPoint(new fabric.Point(0, 0), value);
  5540. return this;
  5541. },
  5542. /**
  5543. * Pan viewport so as to place point at top left corner of canvas
  5544. * @param {fabric.Point} point to move to
  5545. * @return {fabric.Canvas} instance
  5546. * @chainable true
  5547. */
  5548. absolutePan: function (point) {
  5549. this.viewportTransform[4] = -point.x;
  5550. this.viewportTransform[5] = -point.y;
  5551. this.renderAll();
  5552. for (var i = 0, len = this._objects.length; i < len; i++) {
  5553. this._objects[i].setCoords();
  5554. }
  5555. return this;
  5556. },
  5557. /**
  5558. * Pans viewpoint relatively
  5559. * @param {fabric.Point} point (position vector) to move by
  5560. * @return {fabric.Canvas} instance
  5561. * @chainable true
  5562. */
  5563. relativePan: function (point) {
  5564. return this.absolutePan(new fabric.Point(
  5565. -point.x - this.viewportTransform[4],
  5566. -point.y - this.viewportTransform[5]
  5567. ));
  5568. },
  5569. /**
  5570. * Returns &lt;canvas> element corresponding to this instance
  5571. * @return {HTMLCanvasElement}
  5572. */
  5573. getElement: function () {
  5574. return this.lowerCanvasEl;
  5575. },
  5576. /**
  5577. * Returns currently selected object, if any
  5578. * @return {fabric.Object}
  5579. */
  5580. getActiveObject: function() {
  5581. return null;
  5582. },
  5583. /**
  5584. * Returns currently selected group of object, if any
  5585. * @return {fabric.Group}
  5586. */
  5587. getActiveGroup: function() {
  5588. return null;
  5589. },
  5590. /**
  5591. * Given a context, renders an object on that context
  5592. * @param {CanvasRenderingContext2D} ctx Context to render object on
  5593. * @param {fabric.Object} object Object to render
  5594. * @private
  5595. */
  5596. _draw: function (ctx, object) {
  5597. if (!object) {
  5598. return;
  5599. }
  5600. ctx.save();
  5601. var v = this.viewportTransform;
  5602. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  5603. if (this._shouldRenderObject(object)) {
  5604. object.render(ctx);
  5605. }
  5606. ctx.restore();
  5607. if (!this.controlsAboveOverlay) {
  5608. object._renderControls(ctx);
  5609. }
  5610. },
  5611. _shouldRenderObject: function(object) {
  5612. if (!object) {
  5613. return false;
  5614. }
  5615. return (object !== this.getActiveGroup() || !this.preserveObjectStacking);
  5616. },
  5617. /**
  5618. * @private
  5619. * @param {fabric.Object} obj Object that was added
  5620. */
  5621. _onObjectAdded: function(obj) {
  5622. this.stateful && obj.setupState();
  5623. obj.canvas = this;
  5624. obj.setCoords();
  5625. this.fire('object:added', { target: obj });
  5626. obj.fire('added');
  5627. },
  5628. /**
  5629. * @private
  5630. * @param {fabric.Object} obj Object that was removed
  5631. */
  5632. _onObjectRemoved: function(obj) {
  5633. // removing active object should fire "selection:cleared" events
  5634. if (this.getActiveObject() === obj) {
  5635. this.fire('before:selection:cleared', { target: obj });
  5636. this._discardActiveObject();
  5637. this.fire('selection:cleared');
  5638. }
  5639. this.fire('object:removed', { target: obj });
  5640. obj.fire('removed');
  5641. },
  5642. /**
  5643. * Clears specified context of canvas element
  5644. * @param {CanvasRenderingContext2D} ctx Context to clear
  5645. * @return {fabric.Canvas} thisArg
  5646. * @chainable
  5647. */
  5648. clearContext: function(ctx) {
  5649. ctx.clearRect(0, 0, this.width, this.height);
  5650. return this;
  5651. },
  5652. /**
  5653. * Returns context of canvas where objects are drawn
  5654. * @return {CanvasRenderingContext2D}
  5655. */
  5656. getContext: function () {
  5657. return this.contextContainer;
  5658. },
  5659. /**
  5660. * Clears all contexts (background, main, top) of an instance
  5661. * @return {fabric.Canvas} thisArg
  5662. * @chainable
  5663. */
  5664. clear: function () {
  5665. this._objects.length = 0;
  5666. if (this.discardActiveGroup) {
  5667. this.discardActiveGroup();
  5668. }
  5669. if (this.discardActiveObject) {
  5670. this.discardActiveObject();
  5671. }
  5672. this.clearContext(this.contextContainer);
  5673. if (this.contextTop) {
  5674. this.clearContext(this.contextTop);
  5675. }
  5676. this.fire('canvas:cleared');
  5677. this.renderAll();
  5678. return this;
  5679. },
  5680. /**
  5681. * Renders both the top canvas and the secondary container canvas.
  5682. * @param {Boolean} [allOnTop] Whether we want to force all images to be rendered on the top canvas
  5683. * @return {fabric.Canvas} instance
  5684. * @chainable
  5685. */
  5686. renderAll: function (allOnTop) {
  5687. var canvasToDrawOn = this[(allOnTop === true && this.interactive) ? 'contextTop' : 'contextContainer'],
  5688. activeGroup = this.getActiveGroup();
  5689. if (this.contextTop && this.selection && !this._groupSelector) {
  5690. this.clearContext(this.contextTop);
  5691. }
  5692. if (!allOnTop) {
  5693. this.clearContext(canvasToDrawOn);
  5694. }
  5695. this.fire('before:render');
  5696. if (this.clipTo) {
  5697. fabric.util.clipContext(this, canvasToDrawOn);
  5698. }
  5699. this._renderBackground(canvasToDrawOn);
  5700. this._renderObjects(canvasToDrawOn, activeGroup);
  5701. this._renderActiveGroup(canvasToDrawOn, activeGroup);
  5702. if (this.clipTo) {
  5703. canvasToDrawOn.restore();
  5704. }
  5705. this._renderOverlay(canvasToDrawOn);
  5706. if (this.controlsAboveOverlay && this.interactive) {
  5707. this.drawControls(canvasToDrawOn);
  5708. }
  5709. this.fire('after:render');
  5710. return this;
  5711. },
  5712. /**
  5713. * @private
  5714. * @param {CanvasRenderingContext2D} ctx Context to render on
  5715. * @param {fabric.Group} activeGroup
  5716. */
  5717. _renderObjects: function(ctx, activeGroup) {
  5718. var i, length;
  5719. // fast path
  5720. if (!activeGroup || this.preserveObjectStacking) {
  5721. for (i = 0, length = this._objects.length; i < length; ++i) {
  5722. this._draw(ctx, this._objects[i]);
  5723. }
  5724. }
  5725. else {
  5726. for (i = 0, length = this._objects.length; i < length; ++i) {
  5727. if (this._objects[i] && !activeGroup.contains(this._objects[i])) {
  5728. this._draw(ctx, this._objects[i]);
  5729. }
  5730. }
  5731. }
  5732. },
  5733. /**
  5734. * @private
  5735. * @param {CanvasRenderingContext2D} ctx Context to render on
  5736. * @param {fabric.Group} activeGroup
  5737. */
  5738. _renderActiveGroup: function(ctx, activeGroup) {
  5739. // delegate rendering to group selection (if one exists)
  5740. if (activeGroup) {
  5741. //Store objects in group preserving order, then replace
  5742. var sortedObjects = [];
  5743. this.forEachObject(function (object) {
  5744. if (activeGroup.contains(object)) {
  5745. sortedObjects.push(object);
  5746. }
  5747. });
  5748. activeGroup._set('objects', sortedObjects);
  5749. this._draw(ctx, activeGroup);
  5750. }
  5751. },
  5752. /**
  5753. * @private
  5754. * @param {CanvasRenderingContext2D} ctx Context to render on
  5755. */
  5756. _renderBackground: function(ctx) {
  5757. if (this.backgroundColor) {
  5758. ctx.fillStyle = this.backgroundColor.toLive
  5759. ? this.backgroundColor.toLive(ctx)
  5760. : this.backgroundColor;
  5761. ctx.fillRect(
  5762. this.backgroundColor.offsetX || 0,
  5763. this.backgroundColor.offsetY || 0,
  5764. this.width,
  5765. this.height);
  5766. }
  5767. if (this.backgroundImage) {
  5768. this._draw(ctx, this.backgroundImage);
  5769. }
  5770. },
  5771. /**
  5772. * @private
  5773. * @param {CanvasRenderingContext2D} ctx Context to render on
  5774. */
  5775. _renderOverlay: function(ctx) {
  5776. if (this.overlayColor) {
  5777. ctx.fillStyle = this.overlayColor.toLive
  5778. ? this.overlayColor.toLive(ctx)
  5779. : this.overlayColor;
  5780. ctx.fillRect(
  5781. this.overlayColor.offsetX || 0,
  5782. this.overlayColor.offsetY || 0,
  5783. this.width,
  5784. this.height);
  5785. }
  5786. if (this.overlayImage) {
  5787. this._draw(ctx, this.overlayImage);
  5788. }
  5789. },
  5790. /**
  5791. * Method to render only the top canvas.
  5792. * Also used to render the group selection box.
  5793. * @return {fabric.Canvas} thisArg
  5794. * @chainable
  5795. */
  5796. renderTop: function () {
  5797. var ctx = this.contextTop || this.contextContainer;
  5798. this.clearContext(ctx);
  5799. // we render the top context - last object
  5800. if (this.selection && this._groupSelector) {
  5801. this._drawSelection();
  5802. }
  5803. // delegate rendering to group selection if one exists
  5804. // used for drawing selection borders/controls
  5805. var activeGroup = this.getActiveGroup();
  5806. if (activeGroup) {
  5807. activeGroup.render(ctx);
  5808. }
  5809. this._renderOverlay(ctx);
  5810. this.fire('after:render');
  5811. return this;
  5812. },
  5813. /**
  5814. * Returns coordinates of a center of canvas.
  5815. * Returned value is an object with top and left properties
  5816. * @return {Object} object with "top" and "left" number values
  5817. */
  5818. getCenter: function () {
  5819. return {
  5820. top: this.getHeight() / 2,
  5821. left: this.getWidth() / 2
  5822. };
  5823. },
  5824. /**
  5825. * Centers object horizontally.
  5826. * You might need to call `setCoords` on an object after centering, to update controls area.
  5827. * @param {fabric.Object} object Object to center horizontally
  5828. * @return {fabric.Canvas} thisArg
  5829. */
  5830. centerObjectH: function (object) {
  5831. this._centerObject(object, new fabric.Point(this.getCenter().left, object.getCenterPoint().y));
  5832. this.renderAll();
  5833. return this;
  5834. },
  5835. /**
  5836. * Centers object vertically.
  5837. * You might need to call `setCoords` on an object after centering, to update controls area.
  5838. * @param {fabric.Object} object Object to center vertically
  5839. * @return {fabric.Canvas} thisArg
  5840. * @chainable
  5841. */
  5842. centerObjectV: function (object) {
  5843. this._centerObject(object, new fabric.Point(object.getCenterPoint().x, this.getCenter().top));
  5844. this.renderAll();
  5845. return this;
  5846. },
  5847. /**
  5848. * Centers object vertically and horizontally.
  5849. * You might need to call `setCoords` on an object after centering, to update controls area.
  5850. * @param {fabric.Object} object Object to center vertically and horizontally
  5851. * @return {fabric.Canvas} thisArg
  5852. * @chainable
  5853. */
  5854. centerObject: function(object) {
  5855. var center = this.getCenter();
  5856. this._centerObject(object, new fabric.Point(center.left, center.top));
  5857. this.renderAll();
  5858. return this;
  5859. },
  5860. /**
  5861. * @private
  5862. * @param {fabric.Object} object Object to center
  5863. * @param {fabric.Point} center Center point
  5864. * @return {fabric.Canvas} thisArg
  5865. * @chainable
  5866. */
  5867. _centerObject: function(object, center) {
  5868. object.setPositionByOrigin(center, 'center', 'center');
  5869. return this;
  5870. },
  5871. /**
  5872. * Returs dataless JSON representation of canvas
  5873. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  5874. * @return {String} json string
  5875. */
  5876. toDatalessJSON: function (propertiesToInclude) {
  5877. return this.toDatalessObject(propertiesToInclude);
  5878. },
  5879. /**
  5880. * Returns object representation of canvas
  5881. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  5882. * @return {Object} object representation of an instance
  5883. */
  5884. toObject: function (propertiesToInclude) {
  5885. return this._toObjectMethod('toObject', propertiesToInclude);
  5886. },
  5887. /**
  5888. * Returns dataless object representation of canvas
  5889. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  5890. * @return {Object} object representation of an instance
  5891. */
  5892. toDatalessObject: function (propertiesToInclude) {
  5893. return this._toObjectMethod('toDatalessObject', propertiesToInclude);
  5894. },
  5895. /**
  5896. * @private
  5897. */
  5898. _toObjectMethod: function (methodName, propertiesToInclude) {
  5899. var data = {
  5900. objects: this._toObjects(methodName, propertiesToInclude)
  5901. };
  5902. extend(data, this.__serializeBgOverlay());
  5903. fabric.util.populateWithProperties(this, data, propertiesToInclude);
  5904. return data;
  5905. },
  5906. /**
  5907. * @private
  5908. */
  5909. _toObjects: function(methodName, propertiesToInclude) {
  5910. return this.getObjects().map(function(instance) {
  5911. return this._toObject(instance, methodName, propertiesToInclude);
  5912. }, this);
  5913. },
  5914. /**
  5915. * @private
  5916. */
  5917. _toObject: function(instance, methodName, propertiesToInclude) {
  5918. var originalValue;
  5919. if (!this.includeDefaultValues) {
  5920. originalValue = instance.includeDefaultValues;
  5921. instance.includeDefaultValues = false;
  5922. }
  5923. //If the object is part of the current selection group, it should
  5924. //be transformed appropriately
  5925. //i.e. it should be serialised as it would appear if the selection group
  5926. //were to be destroyed.
  5927. var originalProperties = this._realizeGroupTransformOnObject(instance),
  5928. object = instance[methodName](propertiesToInclude);
  5929. if (!this.includeDefaultValues) {
  5930. instance.includeDefaultValues = originalValue;
  5931. }
  5932. //Undo the damage we did by changing all of its properties
  5933. this._unwindGroupTransformOnObject(instance, originalProperties);
  5934. return object;
  5935. },
  5936. /**
  5937. * Realises an object's group transformation on it
  5938. * @private
  5939. * @param {fabric.Object} [instance] the object to transform (gets mutated)
  5940. * @returns the original values of instance which were changed
  5941. */
  5942. _realizeGroupTransformOnObject: function(instance) {
  5943. var layoutProps = ['angle', 'flipX', 'flipY', 'height', 'left', 'scaleX', 'scaleY', 'top', 'width'];
  5944. if (instance.group && instance.group === this.getActiveGroup()) {
  5945. //Copy all the positionally relevant properties across now
  5946. var originalValues = {};
  5947. layoutProps.forEach(function(prop) {
  5948. originalValues[prop] = instance[prop];
  5949. });
  5950. this.getActiveGroup().realizeTransform(instance);
  5951. return originalValues;
  5952. }
  5953. else {
  5954. return null;
  5955. }
  5956. },
  5957. /*
  5958. * Restores the changed properties of instance
  5959. * @private
  5960. * @param {fabric.Object} [instance] the object to un-transform (gets mutated)
  5961. * @param {Object} [originalValues] the original values of instance, as returned by _realizeGroupTransformOnObject
  5962. */
  5963. _unwindGroupTransformOnObject: function(instance, originalValues) {
  5964. if (originalValues) {
  5965. instance.set(originalValues);
  5966. }
  5967. },
  5968. /**
  5969. * @private
  5970. */
  5971. __serializeBgOverlay: function() {
  5972. var data = {
  5973. background: (this.backgroundColor && this.backgroundColor.toObject)
  5974. ? this.backgroundColor.toObject()
  5975. : this.backgroundColor
  5976. };
  5977. if (this.overlayColor) {
  5978. data.overlay = this.overlayColor.toObject
  5979. ? this.overlayColor.toObject()
  5980. : this.overlayColor;
  5981. }
  5982. if (this.backgroundImage) {
  5983. data.backgroundImage = this.backgroundImage.toObject();
  5984. }
  5985. if (this.overlayImage) {
  5986. data.overlayImage = this.overlayImage.toObject();
  5987. }
  5988. return data;
  5989. },
  5990. /* _TO_SVG_START_ */
  5991. /**
  5992. * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true,
  5993. * a zoomed canvas will then produce zoomed SVG output.
  5994. * @type Boolean
  5995. * @default
  5996. */
  5997. svgViewportTransformation: true,
  5998. /**
  5999. * Returns SVG representation of canvas
  6000. * @function
  6001. * @param {Object} [options] Options object for SVG output
  6002. * @param {Boolean} [options.suppressPreamble=false] If true xml tag is not included
  6003. * @param {Object} [options.viewBox] SVG viewbox object
  6004. * @param {Number} [options.viewBox.x] x-cooridnate of viewbox
  6005. * @param {Number} [options.viewBox.y] y-coordinate of viewbox
  6006. * @param {Number} [options.viewBox.width] Width of viewbox
  6007. * @param {Number} [options.viewBox.height] Height of viewbox
  6008. * @param {String} [options.encoding=UTF-8] Encoding of SVG output
  6009. * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation.
  6010. * @return {String} SVG string
  6011. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#serialization}
  6012. * @see {@link http://jsfiddle.net/fabricjs/jQ3ZZ/|jsFiddle demo}
  6013. * @example <caption>Normal SVG output</caption>
  6014. * var svg = canvas.toSVG();
  6015. * @example <caption>SVG output without preamble (without &lt;?xml ../>)</caption>
  6016. * var svg = canvas.toSVG({suppressPreamble: true});
  6017. * @example <caption>SVG output with viewBox attribute</caption>
  6018. * var svg = canvas.toSVG({
  6019. * viewBox: {
  6020. * x: 100,
  6021. * y: 100,
  6022. * width: 200,
  6023. * height: 300
  6024. * }
  6025. * });
  6026. * @example <caption>SVG output with different encoding (default: UTF-8)</caption>
  6027. * var svg = canvas.toSVG({encoding: 'ISO-8859-1'});
  6028. * @example <caption>Modify SVG output with reviver function</caption>
  6029. * var svg = canvas.toSVG(null, function(svg) {
  6030. * return svg.replace('stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; ', '');
  6031. * });
  6032. */
  6033. toSVG: function(options, reviver) {
  6034. options || (options = { });
  6035. var markup = [];
  6036. this._setSVGPreamble(markup, options);
  6037. this._setSVGHeader(markup, options);
  6038. this._setSVGBgOverlayColor(markup, 'backgroundColor');
  6039. this._setSVGBgOverlayImage(markup, 'backgroundImage');
  6040. this._setSVGObjects(markup, reviver);
  6041. this._setSVGBgOverlayColor(markup, 'overlayColor');
  6042. this._setSVGBgOverlayImage(markup, 'overlayImage');
  6043. markup.push('</svg>');
  6044. return markup.join('');
  6045. },
  6046. /**
  6047. * @private
  6048. */
  6049. _setSVGPreamble: function(markup, options) {
  6050. if (!options.suppressPreamble) {
  6051. markup.push(
  6052. '<?xml version="1.0" encoding="', (options.encoding || 'UTF-8'), '" standalone="no" ?>',
  6053. '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',
  6054. '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'
  6055. );
  6056. }
  6057. },
  6058. /**
  6059. * @private
  6060. */
  6061. _setSVGHeader: function(markup, options) {
  6062. var width, height, vpt;
  6063. if (options.viewBox) {
  6064. width = options.viewBox.width;
  6065. height = options.viewBox.height;
  6066. }
  6067. else {
  6068. width = this.width;
  6069. height = this.height;
  6070. if (!this.svgViewportTransformation) {
  6071. vpt = this.viewportTransform;
  6072. width /= vpt[0];
  6073. height /= vpt[3];
  6074. }
  6075. }
  6076. markup.push(
  6077. '<svg ',
  6078. 'xmlns="http://www.w3.org/2000/svg" ',
  6079. 'xmlns:xlink="http://www.w3.org/1999/xlink" ',
  6080. 'version="1.1" ',
  6081. 'width="', width, '" ',
  6082. 'height="', height, '" ',
  6083. (this.backgroundColor && !this.backgroundColor.toLive
  6084. ? 'style="background-color: ' + this.backgroundColor + '" '
  6085. : null),
  6086. (options.viewBox
  6087. ? 'viewBox="' +
  6088. options.viewBox.x + ' ' +
  6089. options.viewBox.y + ' ' +
  6090. options.viewBox.width + ' ' +
  6091. options.viewBox.height + '" '
  6092. : null),
  6093. 'xml:space="preserve">',
  6094. '<desc>Created with Fabric.js ', fabric.version, '</desc>',
  6095. '<defs>',
  6096. fabric.createSVGFontFacesMarkup(this.getObjects()),
  6097. fabric.createSVGRefElementsMarkup(this),
  6098. '</defs>'
  6099. );
  6100. },
  6101. /**
  6102. * @private
  6103. */
  6104. _setSVGObjects: function(markup, reviver) {
  6105. for (var i = 0, objects = this.getObjects(), len = objects.length; i < len; i++) {
  6106. var instance = objects[i],
  6107. //If the object is in a selection group, simulate what would happen to that
  6108. //object when the group is deselected
  6109. originalProperties = this._realizeGroupTransformOnObject(instance);
  6110. markup.push(instance.toSVG(reviver));
  6111. this._unwindGroupTransformOnObject(instance, originalProperties);
  6112. }
  6113. },
  6114. /**
  6115. * @private
  6116. */
  6117. _setSVGBgOverlayImage: function(markup, property) {
  6118. if (this[property] && this[property].toSVG) {
  6119. markup.push(this[property].toSVG());
  6120. }
  6121. },
  6122. /**
  6123. * @private
  6124. */
  6125. _setSVGBgOverlayColor: function(markup, property) {
  6126. if (this[property] && this[property].source) {
  6127. markup.push(
  6128. '<rect x="', this[property].offsetX, '" y="', this[property].offsetY, '" ',
  6129. 'width="',
  6130. (this[property].repeat === 'repeat-y' || this[property].repeat === 'no-repeat'
  6131. ? this[property].source.width
  6132. : this.width),
  6133. '" height="',
  6134. (this[property].repeat === 'repeat-x' || this[property].repeat === 'no-repeat'
  6135. ? this[property].source.height
  6136. : this.height),
  6137. '" fill="url(#' + property + 'Pattern)"',
  6138. '></rect>'
  6139. );
  6140. }
  6141. else if (this[property] && property === 'overlayColor') {
  6142. markup.push(
  6143. '<rect x="0" y="0" ',
  6144. 'width="', this.width,
  6145. '" height="', this.height,
  6146. '" fill="', this[property], '"',
  6147. '></rect>'
  6148. );
  6149. }
  6150. },
  6151. /* _TO_SVG_END_ */
  6152. /**
  6153. * Moves an object to the bottom of the stack of drawn objects
  6154. * @param {fabric.Object} object Object to send to back
  6155. * @return {fabric.Canvas} thisArg
  6156. * @chainable
  6157. */
  6158. sendToBack: function (object) {
  6159. removeFromArray(this._objects, object);
  6160. this._objects.unshift(object);
  6161. return this.renderAll && this.renderAll();
  6162. },
  6163. /**
  6164. * Moves an object to the top of the stack of drawn objects
  6165. * @param {fabric.Object} object Object to send
  6166. * @return {fabric.Canvas} thisArg
  6167. * @chainable
  6168. */
  6169. bringToFront: function (object) {
  6170. removeFromArray(this._objects, object);
  6171. this._objects.push(object);
  6172. return this.renderAll && this.renderAll();
  6173. },
  6174. /**
  6175. * Moves an object down in stack of drawn objects
  6176. * @param {fabric.Object} object Object to send
  6177. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  6178. * @return {fabric.Canvas} thisArg
  6179. * @chainable
  6180. */
  6181. sendBackwards: function (object, intersecting) {
  6182. var idx = this._objects.indexOf(object);
  6183. // if object is not on the bottom of stack
  6184. if (idx !== 0) {
  6185. var newIdx = this._findNewLowerIndex(object, idx, intersecting);
  6186. removeFromArray(this._objects, object);
  6187. this._objects.splice(newIdx, 0, object);
  6188. this.renderAll && this.renderAll();
  6189. }
  6190. return this;
  6191. },
  6192. /**
  6193. * @private
  6194. */
  6195. _findNewLowerIndex: function(object, idx, intersecting) {
  6196. var newIdx;
  6197. if (intersecting) {
  6198. newIdx = idx;
  6199. // traverse down the stack looking for the nearest intersecting object
  6200. for (var i = idx - 1; i >= 0; --i) {
  6201. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  6202. object.isContainedWithinObject(this._objects[i]) ||
  6203. this._objects[i].isContainedWithinObject(object);
  6204. if (isIntersecting) {
  6205. newIdx = i;
  6206. break;
  6207. }
  6208. }
  6209. }
  6210. else {
  6211. newIdx = idx - 1;
  6212. }
  6213. return newIdx;
  6214. },
  6215. /**
  6216. * Moves an object up in stack of drawn objects
  6217. * @param {fabric.Object} object Object to send
  6218. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  6219. * @return {fabric.Canvas} thisArg
  6220. * @chainable
  6221. */
  6222. bringForward: function (object, intersecting) {
  6223. var idx = this._objects.indexOf(object);
  6224. // if object is not on top of stack (last item in an array)
  6225. if (idx !== this._objects.length - 1) {
  6226. var newIdx = this._findNewUpperIndex(object, idx, intersecting);
  6227. removeFromArray(this._objects, object);
  6228. this._objects.splice(newIdx, 0, object);
  6229. this.renderAll && this.renderAll();
  6230. }
  6231. return this;
  6232. },
  6233. /**
  6234. * @private
  6235. */
  6236. _findNewUpperIndex: function(object, idx, intersecting) {
  6237. var newIdx;
  6238. if (intersecting) {
  6239. newIdx = idx;
  6240. // traverse up the stack looking for the nearest intersecting object
  6241. for (var i = idx + 1; i < this._objects.length; ++i) {
  6242. var isIntersecting = object.intersectsWithObject(this._objects[i]) ||
  6243. object.isContainedWithinObject(this._objects[i]) ||
  6244. this._objects[i].isContainedWithinObject(object);
  6245. if (isIntersecting) {
  6246. newIdx = i;
  6247. break;
  6248. }
  6249. }
  6250. }
  6251. else {
  6252. newIdx = idx + 1;
  6253. }
  6254. return newIdx;
  6255. },
  6256. /**
  6257. * Moves an object to specified level in stack of drawn objects
  6258. * @param {fabric.Object} object Object to send
  6259. * @param {Number} index Position to move to
  6260. * @return {fabric.Canvas} thisArg
  6261. * @chainable
  6262. */
  6263. moveTo: function (object, index) {
  6264. removeFromArray(this._objects, object);
  6265. this._objects.splice(index, 0, object);
  6266. return this.renderAll && this.renderAll();
  6267. },
  6268. /**
  6269. * Clears a canvas element and removes all event listeners
  6270. * @return {fabric.Canvas} thisArg
  6271. * @chainable
  6272. */
  6273. dispose: function () {
  6274. this.clear();
  6275. this.interactive && this.removeListeners();
  6276. return this;
  6277. },
  6278. /**
  6279. * Returns a string representation of an instance
  6280. * @return {String} string representation of an instance
  6281. */
  6282. toString: function () {
  6283. return '#<fabric.Canvas (' + this.complexity() + '): ' +
  6284. '{ objects: ' + this.getObjects().length + ' }>';
  6285. }
  6286. });
  6287. extend(fabric.StaticCanvas.prototype, fabric.Observable);
  6288. extend(fabric.StaticCanvas.prototype, fabric.Collection);
  6289. extend(fabric.StaticCanvas.prototype, fabric.DataURLExporter);
  6290. extend(fabric.StaticCanvas, /** @lends fabric.StaticCanvas */ {
  6291. /**
  6292. * @static
  6293. * @type String
  6294. * @default
  6295. */
  6296. EMPTY_JSON: '{"objects": [], "background": "white"}',
  6297. /**
  6298. * Provides a way to check support of some of the canvas methods
  6299. * (either those of HTMLCanvasElement itself, or rendering context)
  6300. *
  6301. * @param {String} methodName Method to check support for;
  6302. * Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash"
  6303. * @return {Boolean | null} `true` if method is supported (or at least exists),
  6304. * `null` if canvas element or context can not be initialized
  6305. */
  6306. supports: function (methodName) {
  6307. var el = fabric.util.createCanvasElement();
  6308. if (!el || !el.getContext) {
  6309. return null;
  6310. }
  6311. var ctx = el.getContext('2d');
  6312. if (!ctx) {
  6313. return null;
  6314. }
  6315. switch (methodName) {
  6316. case 'getImageData':
  6317. return typeof ctx.getImageData !== 'undefined';
  6318. case 'setLineDash':
  6319. return typeof ctx.setLineDash !== 'undefined';
  6320. case 'toDataURL':
  6321. return typeof el.toDataURL !== 'undefined';
  6322. case 'toDataURLWithQuality':
  6323. try {
  6324. el.toDataURL('image/jpeg', 0);
  6325. return true;
  6326. }
  6327. catch (e) { }
  6328. return false;
  6329. default:
  6330. return null;
  6331. }
  6332. }
  6333. });
  6334. /**
  6335. * Returns JSON representation of canvas
  6336. * @function
  6337. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  6338. * @return {String} JSON string
  6339. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#serialization}
  6340. * @see {@link http://jsfiddle.net/fabricjs/pec86/|jsFiddle demo}
  6341. * @example <caption>JSON without additional properties</caption>
  6342. * var json = canvas.toJSON();
  6343. * @example <caption>JSON with additional properties included</caption>
  6344. * var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY', 'lockUniScaling']);
  6345. * @example <caption>JSON without default values</caption>
  6346. * canvas.includeDefaultValues = false;
  6347. * var json = canvas.toJSON();
  6348. */
  6349. fabric.StaticCanvas.prototype.toJSON = fabric.StaticCanvas.prototype.toObject;
  6350. })();
  6351. /**
  6352. * BaseBrush class
  6353. * @class fabric.BaseBrush
  6354. * @see {@link http://fabricjs.com/freedrawing/|Freedrawing demo}
  6355. */
  6356. fabric.BaseBrush = fabric.util.createClass(/** @lends fabric.BaseBrush.prototype */ {
  6357. /**
  6358. * Color of a brush
  6359. * @type String
  6360. * @default
  6361. */
  6362. color: 'rgb(0, 0, 0)',
  6363. /**
  6364. * Width of a brush
  6365. * @type Number
  6366. * @default
  6367. */
  6368. width: 1,
  6369. /**
  6370. * Shadow object representing shadow of this shape.
  6371. * <b>Backwards incompatibility note:</b> This property replaces "shadowColor" (String), "shadowOffsetX" (Number),
  6372. * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12
  6373. * @type fabric.Shadow
  6374. * @default
  6375. */
  6376. shadow: null,
  6377. /**
  6378. * Line endings style of a brush (one of "butt", "round", "square")
  6379. * @type String
  6380. * @default
  6381. */
  6382. strokeLineCap: 'round',
  6383. /**
  6384. * Corner style of a brush (one of "bevil", "round", "miter")
  6385. * @type String
  6386. * @default
  6387. */
  6388. strokeLineJoin: 'round',
  6389. /**
  6390. * Stroke Dash Array.
  6391. * @type Array
  6392. * @default
  6393. */
  6394. strokeDashArray: null,
  6395. /**
  6396. * Sets shadow of an object
  6397. * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)")
  6398. * @return {fabric.Object} thisArg
  6399. * @chainable
  6400. */
  6401. setShadow: function(options) {
  6402. this.shadow = new fabric.Shadow(options);
  6403. return this;
  6404. },
  6405. /**
  6406. * Sets brush styles
  6407. * @private
  6408. */
  6409. _setBrushStyles: function() {
  6410. var ctx = this.canvas.contextTop;
  6411. ctx.strokeStyle = this.color;
  6412. ctx.lineWidth = this.width;
  6413. ctx.lineCap = this.strokeLineCap;
  6414. ctx.lineJoin = this.strokeLineJoin;
  6415. if (this.strokeDashArray && fabric.StaticCanvas.supports('setLineDash')) {
  6416. ctx.setLineDash(this.strokeDashArray);
  6417. }
  6418. },
  6419. /**
  6420. * Sets brush shadow styles
  6421. * @private
  6422. */
  6423. _setShadow: function() {
  6424. if (!this.shadow) {
  6425. return;
  6426. }
  6427. var ctx = this.canvas.contextTop;
  6428. ctx.shadowColor = this.shadow.color;
  6429. ctx.shadowBlur = this.shadow.blur;
  6430. ctx.shadowOffsetX = this.shadow.offsetX;
  6431. ctx.shadowOffsetY = this.shadow.offsetY;
  6432. },
  6433. /**
  6434. * Removes brush shadow styles
  6435. * @private
  6436. */
  6437. _resetShadow: function() {
  6438. var ctx = this.canvas.contextTop;
  6439. ctx.shadowColor = '';
  6440. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  6441. }
  6442. });
  6443. (function() {
  6444. /**
  6445. * PencilBrush class
  6446. * @class fabric.PencilBrush
  6447. * @extends fabric.BaseBrush
  6448. */
  6449. fabric.PencilBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.PencilBrush.prototype */ {
  6450. /**
  6451. * Constructor
  6452. * @param {fabric.Canvas} canvas
  6453. * @return {fabric.PencilBrush} Instance of a pencil brush
  6454. */
  6455. initialize: function(canvas) {
  6456. this.canvas = canvas;
  6457. this._points = [ ];
  6458. },
  6459. /**
  6460. * Inovoked on mouse down
  6461. * @param {Object} pointer
  6462. */
  6463. onMouseDown: function(pointer) {
  6464. this._prepareForDrawing(pointer);
  6465. // capture coordinates immediately
  6466. // this allows to draw dots (when movement never occurs)
  6467. this._captureDrawingPath(pointer);
  6468. this._render();
  6469. },
  6470. /**
  6471. * Inovoked on mouse move
  6472. * @param {Object} pointer
  6473. */
  6474. onMouseMove: function(pointer) {
  6475. this._captureDrawingPath(pointer);
  6476. // redraw curve
  6477. // clear top canvas
  6478. this.canvas.clearContext(this.canvas.contextTop);
  6479. this._render();
  6480. },
  6481. /**
  6482. * Invoked on mouse up
  6483. */
  6484. onMouseUp: function() {
  6485. this._finalizeAndAddPath();
  6486. },
  6487. /**
  6488. * @private
  6489. * @param {Object} pointer Actual mouse position related to the canvas.
  6490. */
  6491. _prepareForDrawing: function(pointer) {
  6492. var p = new fabric.Point(pointer.x, pointer.y);
  6493. this._reset();
  6494. this._addPoint(p);
  6495. this.canvas.contextTop.moveTo(p.x, p.y);
  6496. },
  6497. /**
  6498. * @private
  6499. * @param {fabric.Point} point Point to be added to points array
  6500. */
  6501. _addPoint: function(point) {
  6502. this._points.push(point);
  6503. },
  6504. /**
  6505. * Clear points array and set contextTop canvas style.
  6506. * @private
  6507. */
  6508. _reset: function() {
  6509. this._points.length = 0;
  6510. this._setBrushStyles();
  6511. this._setShadow();
  6512. },
  6513. /**
  6514. * @private
  6515. * @param {Object} pointer Actual mouse position related to the canvas.
  6516. */
  6517. _captureDrawingPath: function(pointer) {
  6518. var pointerPoint = new fabric.Point(pointer.x, pointer.y);
  6519. this._addPoint(pointerPoint);
  6520. },
  6521. /**
  6522. * Draw a smooth path on the topCanvas using quadraticCurveTo
  6523. * @private
  6524. */
  6525. _render: function() {
  6526. var ctx = this.canvas.contextTop,
  6527. v = this.canvas.viewportTransform,
  6528. p1 = this._points[0],
  6529. p2 = this._points[1];
  6530. ctx.save();
  6531. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  6532. ctx.beginPath();
  6533. //if we only have 2 points in the path and they are the same
  6534. //it means that the user only clicked the canvas without moving the mouse
  6535. //then we should be drawing a dot. A path isn't drawn between two identical dots
  6536. //that's why we set them apart a bit
  6537. if (this._points.length === 2 && p1.x === p2.x && p1.y === p2.y) {
  6538. p1.x -= 0.5;
  6539. p2.x += 0.5;
  6540. }
  6541. ctx.moveTo(p1.x, p1.y);
  6542. for (var i = 1, len = this._points.length; i < len; i++) {
  6543. // we pick the point between pi + 1 & pi + 2 as the
  6544. // end point and p1 as our control point.
  6545. var midPoint = p1.midPointFrom(p2);
  6546. ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
  6547. p1 = this._points[i];
  6548. p2 = this._points[i + 1];
  6549. }
  6550. // Draw last line as a straight line while
  6551. // we wait for the next point to be able to calculate
  6552. // the bezier control point
  6553. ctx.lineTo(p1.x, p1.y);
  6554. ctx.stroke();
  6555. ctx.restore();
  6556. },
  6557. /**
  6558. * Converts points to SVG path
  6559. * @param {Array} points Array of points
  6560. * @param {Number} minX
  6561. * @param {Number} minY
  6562. * @return {String} SVG path
  6563. */
  6564. convertPointsToSVGPath: function(points) {
  6565. var path = [],
  6566. p1 = new fabric.Point(points[0].x, points[0].y),
  6567. p2 = new fabric.Point(points[1].x, points[1].y);
  6568. path.push('M ', points[0].x, ' ', points[0].y, ' ');
  6569. for (var i = 1, len = points.length; i < len; i++) {
  6570. var midPoint = p1.midPointFrom(p2);
  6571. // p1 is our bezier control point
  6572. // midpoint is our endpoint
  6573. // start point is p(i-1) value.
  6574. path.push('Q ', p1.x, ' ', p1.y, ' ', midPoint.x, ' ', midPoint.y, ' ');
  6575. p1 = new fabric.Point(points[i].x, points[i].y);
  6576. if ((i + 1) < points.length) {
  6577. p2 = new fabric.Point(points[i + 1].x, points[i + 1].y);
  6578. }
  6579. }
  6580. path.push('L ', p1.x, ' ', p1.y, ' ');
  6581. return path;
  6582. },
  6583. /**
  6584. * Creates fabric.Path object to add on canvas
  6585. * @param {String} pathData Path data
  6586. * @return {fabric.Path} Path to add on canvas
  6587. */
  6588. createPath: function(pathData) {
  6589. var path = new fabric.Path(pathData, {
  6590. fill: null,
  6591. stroke: this.color,
  6592. strokeWidth: this.width,
  6593. strokeLineCap: this.strokeLineCap,
  6594. strokeLineJoin: this.strokeLineJoin,
  6595. strokeDashArray: this.strokeDashArray,
  6596. originX: 'center',
  6597. originY: 'center'
  6598. });
  6599. if (this.shadow) {
  6600. this.shadow.affectStroke = true;
  6601. path.setShadow(this.shadow);
  6602. }
  6603. return path;
  6604. },
  6605. /**
  6606. * On mouseup after drawing the path on contextTop canvas
  6607. * we use the points captured to create an new fabric path object
  6608. * and add it to the fabric canvas.
  6609. */
  6610. _finalizeAndAddPath: function() {
  6611. var ctx = this.canvas.contextTop;
  6612. ctx.closePath();
  6613. var pathData = this.convertPointsToSVGPath(this._points).join('');
  6614. if (pathData === 'M 0 0 Q 0 0 0 0 L 0 0') {
  6615. // do not create 0 width/height paths, as they are
  6616. // rendered inconsistently across browsers
  6617. // Firefox 4, for example, renders a dot,
  6618. // whereas Chrome 10 renders nothing
  6619. this.canvas.renderAll();
  6620. return;
  6621. }
  6622. var path = this.createPath(pathData);
  6623. this.canvas.add(path);
  6624. path.setCoords();
  6625. this.canvas.clearContext(this.canvas.contextTop);
  6626. this._resetShadow();
  6627. this.canvas.renderAll();
  6628. // fire event 'path' created
  6629. this.canvas.fire('path:created', { path: path });
  6630. }
  6631. });
  6632. })();
  6633. /**
  6634. * CircleBrush class
  6635. * @class fabric.CircleBrush
  6636. */
  6637. fabric.CircleBrush = fabric.util.createClass(fabric.BaseBrush, /** @lends fabric.CircleBrush.prototype */ {
  6638. /**
  6639. * Width of a brush
  6640. * @type Number
  6641. * @default
  6642. */
  6643. width: 10,
  6644. /**
  6645. * Constructor
  6646. * @param {fabric.Canvas} canvas
  6647. * @return {fabric.CircleBrush} Instance of a circle brush
  6648. */
  6649. initialize: function(canvas) {
  6650. this.canvas = canvas;
  6651. this.points = [ ];
  6652. },
  6653. /**
  6654. * Invoked inside on mouse down and mouse move
  6655. * @param {Object} pointer
  6656. */
  6657. drawDot: function(pointer) {
  6658. var point = this.addPoint(pointer),
  6659. ctx = this.canvas.contextTop,
  6660. v = this.canvas.viewportTransform;
  6661. ctx.save();
  6662. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  6663. ctx.fillStyle = point.fill;
  6664. ctx.beginPath();
  6665. ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);
  6666. ctx.closePath();
  6667. ctx.fill();
  6668. ctx.restore();
  6669. },
  6670. /**
  6671. * Invoked on mouse down
  6672. */
  6673. onMouseDown: function(pointer) {
  6674. this.points.length = 0;
  6675. this.canvas.clearContext(this.canvas.contextTop);
  6676. this._setShadow();
  6677. this.drawDot(pointer);
  6678. },
  6679. /**
  6680. * Invoked on mouse move
  6681. * @param {Object} pointer
  6682. */
  6683. onMouseMove: function(pointer) {
  6684. this.drawDot(pointer);
  6685. },
  6686. /**
  6687. * Invoked on mouse up
  6688. */
  6689. onMouseUp: function() {
  6690. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
  6691. this.canvas.renderOnAddRemove = false;
  6692. var circles = [ ];
  6693. for (var i = 0, len = this.points.length; i < len; i++) {
  6694. var point = this.points[i],
  6695. circle = new fabric.Circle({
  6696. radius: point.radius,
  6697. left: point.x,
  6698. top: point.y,
  6699. originX: 'center',
  6700. originY: 'center',
  6701. fill: point.fill
  6702. });
  6703. this.shadow && circle.setShadow(this.shadow);
  6704. circles.push(circle);
  6705. }
  6706. var group = new fabric.Group(circles, { originX: 'center', originY: 'center' });
  6707. group.canvas = this.canvas;
  6708. this.canvas.add(group);
  6709. this.canvas.fire('path:created', { path: group });
  6710. this.canvas.clearContext(this.canvas.contextTop);
  6711. this._resetShadow();
  6712. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  6713. this.canvas.renderAll();
  6714. },
  6715. /**
  6716. * @param {Object} pointer
  6717. * @return {fabric.Point} Just added pointer point
  6718. */
  6719. addPoint: function(pointer) {
  6720. var pointerPoint = new fabric.Point(pointer.x, pointer.y),
  6721. circleRadius = fabric.util.getRandomInt(
  6722. Math.max(0, this.width - 20), this.width + 20) / 2,
  6723. circleColor = new fabric.Color(this.color)
  6724. .setAlpha(fabric.util.getRandomInt(0, 100) / 100)
  6725. .toRgba();
  6726. pointerPoint.radius = circleRadius;
  6727. pointerPoint.fill = circleColor;
  6728. this.points.push(pointerPoint);
  6729. return pointerPoint;
  6730. }
  6731. });
  6732. /**
  6733. * SprayBrush class
  6734. * @class fabric.SprayBrush
  6735. */
  6736. fabric.SprayBrush = fabric.util.createClass( fabric.BaseBrush, /** @lends fabric.SprayBrush.prototype */ {
  6737. /**
  6738. * Width of a spray
  6739. * @type Number
  6740. * @default
  6741. */
  6742. width: 10,
  6743. /**
  6744. * Density of a spray (number of dots per chunk)
  6745. * @type Number
  6746. * @default
  6747. */
  6748. density: 20,
  6749. /**
  6750. * Width of spray dots
  6751. * @type Number
  6752. * @default
  6753. */
  6754. dotWidth: 1,
  6755. /**
  6756. * Width variance of spray dots
  6757. * @type Number
  6758. * @default
  6759. */
  6760. dotWidthVariance: 1,
  6761. /**
  6762. * Whether opacity of a dot should be random
  6763. * @type Boolean
  6764. * @default
  6765. */
  6766. randomOpacity: false,
  6767. /**
  6768. * Whether overlapping dots (rectangles) should be removed (for performance reasons)
  6769. * @type Boolean
  6770. * @default
  6771. */
  6772. optimizeOverlapping: true,
  6773. /**
  6774. * Constructor
  6775. * @param {fabric.Canvas} canvas
  6776. * @return {fabric.SprayBrush} Instance of a spray brush
  6777. */
  6778. initialize: function(canvas) {
  6779. this.canvas = canvas;
  6780. this.sprayChunks = [ ];
  6781. },
  6782. /**
  6783. * Invoked on mouse down
  6784. * @param {Object} pointer
  6785. */
  6786. onMouseDown: function(pointer) {
  6787. this.sprayChunks.length = 0;
  6788. this.canvas.clearContext(this.canvas.contextTop);
  6789. this._setShadow();
  6790. this.addSprayChunk(pointer);
  6791. this.render();
  6792. },
  6793. /**
  6794. * Invoked on mouse move
  6795. * @param {Object} pointer
  6796. */
  6797. onMouseMove: function(pointer) {
  6798. this.addSprayChunk(pointer);
  6799. this.render();
  6800. },
  6801. /**
  6802. * Invoked on mouse up
  6803. */
  6804. onMouseUp: function() {
  6805. var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
  6806. this.canvas.renderOnAddRemove = false;
  6807. var rects = [ ];
  6808. for (var i = 0, ilen = this.sprayChunks.length; i < ilen; i++) {
  6809. var sprayChunk = this.sprayChunks[i];
  6810. for (var j = 0, jlen = sprayChunk.length; j < jlen; j++) {
  6811. var rect = new fabric.Rect({
  6812. width: sprayChunk[j].width,
  6813. height: sprayChunk[j].width,
  6814. left: sprayChunk[j].x + 1,
  6815. top: sprayChunk[j].y + 1,
  6816. originX: 'center',
  6817. originY: 'center',
  6818. fill: this.color
  6819. });
  6820. this.shadow && rect.setShadow(this.shadow);
  6821. rects.push(rect);
  6822. }
  6823. }
  6824. if (this.optimizeOverlapping) {
  6825. rects = this._getOptimizedRects(rects);
  6826. }
  6827. var group = new fabric.Group(rects, { originX: 'center', originY: 'center' });
  6828. group.canvas = this.canvas;
  6829. this.canvas.add(group);
  6830. this.canvas.fire('path:created', { path: group });
  6831. this.canvas.clearContext(this.canvas.contextTop);
  6832. this._resetShadow();
  6833. this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
  6834. this.canvas.renderAll();
  6835. },
  6836. /**
  6837. * @private
  6838. * @param {Array} rects
  6839. */
  6840. _getOptimizedRects: function(rects) {
  6841. // avoid creating duplicate rects at the same coordinates
  6842. var uniqueRects = { }, key;
  6843. for (var i = 0, len = rects.length; i < len; i++) {
  6844. key = rects[i].left + '' + rects[i].top;
  6845. if (!uniqueRects[key]) {
  6846. uniqueRects[key] = rects[i];
  6847. }
  6848. }
  6849. var uniqueRectsArray = [ ];
  6850. for (key in uniqueRects) {
  6851. uniqueRectsArray.push(uniqueRects[key]);
  6852. }
  6853. return uniqueRectsArray;
  6854. },
  6855. /**
  6856. * Renders brush
  6857. */
  6858. render: function() {
  6859. var ctx = this.canvas.contextTop;
  6860. ctx.fillStyle = this.color;
  6861. var v = this.canvas.viewportTransform;
  6862. ctx.save();
  6863. ctx.transform(v[0], v[1], v[2], v[3], v[4], v[5]);
  6864. for (var i = 0, len = this.sprayChunkPoints.length; i < len; i++) {
  6865. var point = this.sprayChunkPoints[i];
  6866. if (typeof point.opacity !== 'undefined') {
  6867. ctx.globalAlpha = point.opacity;
  6868. }
  6869. ctx.fillRect(point.x, point.y, point.width, point.width);
  6870. }
  6871. ctx.restore();
  6872. },
  6873. /**
  6874. * @param {Object} pointer
  6875. */
  6876. addSprayChunk: function(pointer) {
  6877. this.sprayChunkPoints = [ ];
  6878. var x, y, width, radius = this.width / 2;
  6879. for (var i = 0; i < this.density; i++) {
  6880. x = fabric.util.getRandomInt(pointer.x - radius, pointer.x + radius);
  6881. y = fabric.util.getRandomInt(pointer.y - radius, pointer.y + radius);
  6882. if (this.dotWidthVariance) {
  6883. width = fabric.util.getRandomInt(
  6884. // bottom clamp width to 1
  6885. Math.max(1, this.dotWidth - this.dotWidthVariance),
  6886. this.dotWidth + this.dotWidthVariance);
  6887. }
  6888. else {
  6889. width = this.dotWidth;
  6890. }
  6891. var point = new fabric.Point(x, y);
  6892. point.width = width;
  6893. if (this.randomOpacity) {
  6894. point.opacity = fabric.util.getRandomInt(0, 100) / 100;
  6895. }
  6896. this.sprayChunkPoints.push(point);
  6897. }
  6898. this.sprayChunks.push(this.sprayChunkPoints);
  6899. }
  6900. });
  6901. /**
  6902. * PatternBrush class
  6903. * @class fabric.PatternBrush
  6904. * @extends fabric.BaseBrush
  6905. */
  6906. fabric.PatternBrush = fabric.util.createClass(fabric.PencilBrush, /** @lends fabric.PatternBrush.prototype */ {
  6907. getPatternSrc: function() {
  6908. var dotWidth = 20,
  6909. dotDistance = 5,
  6910. patternCanvas = fabric.document.createElement('canvas'),
  6911. patternCtx = patternCanvas.getContext('2d');
  6912. patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;
  6913. patternCtx.fillStyle = this.color;
  6914. patternCtx.beginPath();
  6915. patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);
  6916. patternCtx.closePath();
  6917. patternCtx.fill();
  6918. return patternCanvas;
  6919. },
  6920. getPatternSrcFunction: function() {
  6921. return String(this.getPatternSrc).replace('this.color', '"' + this.color + '"');
  6922. },
  6923. /**
  6924. * Creates "pattern" instance property
  6925. */
  6926. getPattern: function() {
  6927. return this.canvas.contextTop.createPattern(this.source || this.getPatternSrc(), 'repeat');
  6928. },
  6929. /**
  6930. * Sets brush styles
  6931. */
  6932. _setBrushStyles: function() {
  6933. this.callSuper('_setBrushStyles');
  6934. this.canvas.contextTop.strokeStyle = this.getPattern();
  6935. },
  6936. /**
  6937. * Creates path
  6938. */
  6939. createPath: function(pathData) {
  6940. var path = this.callSuper('createPath', pathData);
  6941. path.stroke = new fabric.Pattern({
  6942. source: this.source || this.getPatternSrcFunction()
  6943. });
  6944. return path;
  6945. }
  6946. });
  6947. (function() {
  6948. var getPointer = fabric.util.getPointer,
  6949. degreesToRadians = fabric.util.degreesToRadians,
  6950. radiansToDegrees = fabric.util.radiansToDegrees,
  6951. atan2 = Math.atan2,
  6952. abs = Math.abs,
  6953. STROKE_OFFSET = 0.5;
  6954. /**
  6955. * Canvas class
  6956. * @class fabric.Canvas
  6957. * @extends fabric.StaticCanvas
  6958. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#canvas}
  6959. * @see {@link fabric.Canvas#initialize} for constructor definition
  6960. *
  6961. * @fires object:modified
  6962. * @fires object:rotating
  6963. * @fires object:scaling
  6964. * @fires object:moving
  6965. * @fires object:selected
  6966. *
  6967. * @fires before:selection:cleared
  6968. * @fires selection:cleared
  6969. * @fires selection:created
  6970. *
  6971. * @fires path:created
  6972. * @fires mouse:down
  6973. * @fires mouse:move
  6974. * @fires mouse:up
  6975. * @fires mouse:over
  6976. * @fires mouse:out
  6977. *
  6978. */
  6979. fabric.Canvas = fabric.util.createClass(fabric.StaticCanvas, /** @lends fabric.Canvas.prototype */ {
  6980. /**
  6981. * Constructor
  6982. * @param {HTMLElement | String} el &lt;canvas> element to initialize instance on
  6983. * @param {Object} [options] Options object
  6984. * @return {Object} thisArg
  6985. */
  6986. initialize: function(el, options) {
  6987. options || (options = { });
  6988. this._initStatic(el, options);
  6989. this._initInteractive();
  6990. this._createCacheCanvas();
  6991. fabric.Canvas.activeInstance = this;
  6992. },
  6993. /**
  6994. * When true, objects can be transformed by one side (unproportionally)
  6995. * @type Boolean
  6996. * @default
  6997. */
  6998. uniScaleTransform: false,
  6999. /**
  7000. * When true, objects use center point as the origin of scale transformation.
  7001. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  7002. * @since 1.3.4
  7003. * @type Boolean
  7004. * @default
  7005. */
  7006. centeredScaling: false,
  7007. /**
  7008. * When true, objects use center point as the origin of rotate transformation.
  7009. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  7010. * @since 1.3.4
  7011. * @type Boolean
  7012. * @default
  7013. */
  7014. centeredRotation: false,
  7015. /**
  7016. * Indicates that canvas is interactive. This property should not be changed.
  7017. * @type Boolean
  7018. * @default
  7019. */
  7020. interactive: true,
  7021. /**
  7022. * Indicates whether group selection should be enabled
  7023. * @type Boolean
  7024. * @default
  7025. */
  7026. selection: true,
  7027. /**
  7028. * Color of selection
  7029. * @type String
  7030. * @default
  7031. */
  7032. selectionColor: 'rgba(100, 100, 255, 0.3)', // blue
  7033. /**
  7034. * Default dash array pattern
  7035. * If not empty the selection border is dashed
  7036. * @type Array
  7037. */
  7038. selectionDashArray: [ ],
  7039. /**
  7040. * Color of the border of selection (usually slightly darker than color of selection itself)
  7041. * @type String
  7042. * @default
  7043. */
  7044. selectionBorderColor: 'rgba(255, 255, 255, 0.3)',
  7045. /**
  7046. * Width of a line used in object/group selection
  7047. * @type Number
  7048. * @default
  7049. */
  7050. selectionLineWidth: 1,
  7051. /**
  7052. * Default cursor value used when hovering over an object on canvas
  7053. * @type String
  7054. * @default
  7055. */
  7056. hoverCursor: 'move',
  7057. /**
  7058. * Default cursor value used when moving an object on canvas
  7059. * @type String
  7060. * @default
  7061. */
  7062. moveCursor: 'move',
  7063. /**
  7064. * Default cursor value used for the entire canvas
  7065. * @type String
  7066. * @default
  7067. */
  7068. defaultCursor: 'default',
  7069. /**
  7070. * Cursor value used during free drawing
  7071. * @type String
  7072. * @default
  7073. */
  7074. freeDrawingCursor: 'crosshair',
  7075. /**
  7076. * Cursor value used for rotation point
  7077. * @type String
  7078. * @default
  7079. */
  7080. rotationCursor: 'crosshair',
  7081. /**
  7082. * Default element class that's given to wrapper (div) element of canvas
  7083. * @type String
  7084. * @default
  7085. */
  7086. containerClass: 'canvas-container',
  7087. /**
  7088. * When true, object detection happens on per-pixel basis rather than on per-bounding-box
  7089. * @type Boolean
  7090. * @default
  7091. */
  7092. perPixelTargetFind: false,
  7093. /**
  7094. * Number of pixels around target pixel to tolerate (consider active) during object detection
  7095. * @type Number
  7096. * @default
  7097. */
  7098. targetFindTolerance: 0,
  7099. /**
  7100. * When true, target detection is skipped when hovering over canvas. This can be used to improve performance.
  7101. * @type Boolean
  7102. * @default
  7103. */
  7104. skipTargetFind: false,
  7105. /**
  7106. * @private
  7107. */
  7108. _initInteractive: function() {
  7109. this._currentTransform = null;
  7110. this._groupSelector = null;
  7111. this._initWrapperElement();
  7112. this._createUpperCanvas();
  7113. this._initEventListeners();
  7114. this.freeDrawingBrush = fabric.PencilBrush && new fabric.PencilBrush(this);
  7115. this.calcOffset();
  7116. },
  7117. /**
  7118. * Resets the current transform to its original values and chooses the type of resizing based on the event
  7119. * @private
  7120. * @param {Event} e Event object fired on mousemove
  7121. */
  7122. _resetCurrentTransform: function(e) {
  7123. var t = this._currentTransform;
  7124. t.target.set({
  7125. scaleX: t.original.scaleX,
  7126. scaleY: t.original.scaleY,
  7127. left: t.original.left,
  7128. top: t.original.top
  7129. });
  7130. if (this._shouldCenterTransform(e, t.target)) {
  7131. if (t.action === 'rotate') {
  7132. this._setOriginToCenter(t.target);
  7133. }
  7134. else {
  7135. if (t.originX !== 'center') {
  7136. if (t.originX === 'right') {
  7137. t.mouseXSign = -1;
  7138. }
  7139. else {
  7140. t.mouseXSign = 1;
  7141. }
  7142. }
  7143. if (t.originY !== 'center') {
  7144. if (t.originY === 'bottom') {
  7145. t.mouseYSign = -1;
  7146. }
  7147. else {
  7148. t.mouseYSign = 1;
  7149. }
  7150. }
  7151. t.originX = 'center';
  7152. t.originY = 'center';
  7153. }
  7154. }
  7155. else {
  7156. t.originX = t.original.originX;
  7157. t.originY = t.original.originY;
  7158. }
  7159. },
  7160. /**
  7161. * Checks if point is contained within an area of given object
  7162. * @param {Event} e Event object
  7163. * @param {fabric.Object} target Object to test against
  7164. * @return {Boolean} true if point is contained within an area of given object
  7165. */
  7166. containsPoint: function (e, target) {
  7167. var pointer = this.getPointer(e, true),
  7168. xy = this._normalizePointer(target, pointer);
  7169. // http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html
  7170. // http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html
  7171. return (target.containsPoint(xy) || target._findTargetCorner(pointer));
  7172. },
  7173. /**
  7174. * @private
  7175. */
  7176. _normalizePointer: function (object, pointer) {
  7177. var activeGroup = this.getActiveGroup(),
  7178. x = pointer.x,
  7179. y = pointer.y,
  7180. isObjectInGroup = (
  7181. activeGroup &&
  7182. object.type !== 'group' &&
  7183. activeGroup.contains(object)),
  7184. lt;
  7185. if (isObjectInGroup) {
  7186. lt = new fabric.Point(activeGroup.left, activeGroup.top);
  7187. lt = fabric.util.transformPoint(lt, this.viewportTransform, true);
  7188. x -= lt.x;
  7189. y -= lt.y;
  7190. }
  7191. return { x: x, y: y };
  7192. },
  7193. /**
  7194. * Returns true if object is transparent at a certain location
  7195. * @param {fabric.Object} target Object to check
  7196. * @param {Number} x Left coordinate
  7197. * @param {Number} y Top coordinate
  7198. * @return {Boolean}
  7199. */
  7200. isTargetTransparent: function (target, x, y) {
  7201. var hasBorders = target.hasBorders,
  7202. transparentCorners = target.transparentCorners;
  7203. target.hasBorders = target.transparentCorners = false;
  7204. this._draw(this.contextCache, target);
  7205. target.hasBorders = hasBorders;
  7206. target.transparentCorners = transparentCorners;
  7207. var isTransparent = fabric.util.isTransparent(
  7208. this.contextCache, x, y, this.targetFindTolerance);
  7209. this.clearContext(this.contextCache);
  7210. return isTransparent;
  7211. },
  7212. /**
  7213. * @private
  7214. * @param {Event} e Event object
  7215. * @param {fabric.Object} target
  7216. */
  7217. _shouldClearSelection: function (e, target) {
  7218. var activeGroup = this.getActiveGroup(),
  7219. activeObject = this.getActiveObject();
  7220. return (
  7221. !target
  7222. ||
  7223. (target &&
  7224. activeGroup &&
  7225. !activeGroup.contains(target) &&
  7226. activeGroup !== target &&
  7227. !e.shiftKey)
  7228. ||
  7229. (target && !target.evented)
  7230. ||
  7231. (target &&
  7232. !target.selectable &&
  7233. activeObject &&
  7234. activeObject !== target)
  7235. );
  7236. },
  7237. /**
  7238. * @private
  7239. * @param {Event} e Event object
  7240. * @param {fabric.Object} target
  7241. */
  7242. _shouldCenterTransform: function (e, target) {
  7243. if (!target) {
  7244. return;
  7245. }
  7246. var t = this._currentTransform,
  7247. centerTransform;
  7248. if (t.action === 'scale' || t.action === 'scaleX' || t.action === 'scaleY') {
  7249. centerTransform = this.centeredScaling || target.centeredScaling;
  7250. }
  7251. else if (t.action === 'rotate') {
  7252. centerTransform = this.centeredRotation || target.centeredRotation;
  7253. }
  7254. return centerTransform ? !e.altKey : e.altKey;
  7255. },
  7256. /**
  7257. * @private
  7258. */
  7259. _getOriginFromCorner: function(target, corner) {
  7260. var origin = {
  7261. x: target.originX,
  7262. y: target.originY
  7263. };
  7264. if (corner === 'ml' || corner === 'tl' || corner === 'bl') {
  7265. origin.x = 'right';
  7266. }
  7267. else if (corner === 'mr' || corner === 'tr' || corner === 'br') {
  7268. origin.x = 'left';
  7269. }
  7270. if (corner === 'tl' || corner === 'mt' || corner === 'tr') {
  7271. origin.y = 'bottom';
  7272. }
  7273. else if (corner === 'bl' || corner === 'mb' || corner === 'br') {
  7274. origin.y = 'top';
  7275. }
  7276. return origin;
  7277. },
  7278. /**
  7279. * @private
  7280. */
  7281. _getActionFromCorner: function(target, corner) {
  7282. var action = 'drag';
  7283. if (corner) {
  7284. action = (corner === 'ml' || corner === 'mr')
  7285. ? 'scaleX'
  7286. : (corner === 'mt' || corner === 'mb')
  7287. ? 'scaleY'
  7288. : corner === 'mtr'
  7289. ? 'rotate'
  7290. : 'scale';
  7291. }
  7292. return action;
  7293. },
  7294. /**
  7295. * @private
  7296. * @param {Event} e Event object
  7297. * @param {fabric.Object} target
  7298. */
  7299. _setupCurrentTransform: function (e, target) {
  7300. if (!target) {
  7301. return;
  7302. }
  7303. var pointer = this.getPointer(e),
  7304. corner = target._findTargetCorner(this.getPointer(e, true)),
  7305. action = this._getActionFromCorner(target, corner),
  7306. origin = this._getOriginFromCorner(target, corner);
  7307. this._currentTransform = {
  7308. target: target,
  7309. action: action,
  7310. scaleX: target.scaleX,
  7311. scaleY: target.scaleY,
  7312. offsetX: pointer.x - target.left,
  7313. offsetY: pointer.y - target.top,
  7314. originX: origin.x,
  7315. originY: origin.y,
  7316. ex: pointer.x,
  7317. ey: pointer.y,
  7318. left: target.left,
  7319. top: target.top,
  7320. theta: degreesToRadians(target.angle),
  7321. width: target.width * target.scaleX,
  7322. mouseXSign: 1,
  7323. mouseYSign: 1
  7324. };
  7325. this._currentTransform.original = {
  7326. left: target.left,
  7327. top: target.top,
  7328. scaleX: target.scaleX,
  7329. scaleY: target.scaleY,
  7330. originX: origin.x,
  7331. originY: origin.y
  7332. };
  7333. this._resetCurrentTransform(e);
  7334. },
  7335. /**
  7336. * Translates object by "setting" its left/top
  7337. * @private
  7338. * @param {Number} x pointer's x coordinate
  7339. * @param {Number} y pointer's y coordinate
  7340. */
  7341. _translateObject: function (x, y) {
  7342. var target = this._currentTransform.target;
  7343. if (!target.get('lockMovementX')) {
  7344. target.set('left', x - this._currentTransform.offsetX);
  7345. }
  7346. if (!target.get('lockMovementY')) {
  7347. target.set('top', y - this._currentTransform.offsetY);
  7348. }
  7349. },
  7350. /**
  7351. * Scales object by invoking its scaleX/scaleY methods
  7352. * @private
  7353. * @param {Number} x pointer's x coordinate
  7354. * @param {Number} y pointer's y coordinate
  7355. * @param {String} by Either 'x' or 'y' - specifies dimension constraint by which to scale an object.
  7356. * When not provided, an object is scaled by both dimensions equally
  7357. */
  7358. _scaleObject: function (x, y, by) {
  7359. var t = this._currentTransform,
  7360. target = t.target,
  7361. lockScalingX = target.get('lockScalingX'),
  7362. lockScalingY = target.get('lockScalingY'),
  7363. lockScalingFlip = target.get('lockScalingFlip');
  7364. if (lockScalingX && lockScalingY) {
  7365. return;
  7366. }
  7367. // Get the constraint point
  7368. var constraintPosition = target.translateToOriginPoint(target.getCenterPoint(), t.originX, t.originY),
  7369. localMouse = target.toLocalPoint(new fabric.Point(x, y), t.originX, t.originY);
  7370. this._setLocalMouse(localMouse, t);
  7371. // Actually scale the object
  7372. this._setObjectScale(localMouse, t, lockScalingX, lockScalingY, by, lockScalingFlip);
  7373. // Make sure the constraints apply
  7374. target.setPositionByOrigin(constraintPosition, t.originX, t.originY);
  7375. },
  7376. /**
  7377. * @private
  7378. */
  7379. _setObjectScale: function(localMouse, transform, lockScalingX, lockScalingY, by, lockScalingFlip) {
  7380. var target = transform.target, forbidScalingX = false, forbidScalingY = false,
  7381. strokeWidth = target.stroke ? target.strokeWidth : 0;
  7382. transform.newScaleX = localMouse.x / (target.width + strokeWidth / 2);
  7383. transform.newScaleY = localMouse.y / (target.height + strokeWidth / 2);
  7384. if (lockScalingFlip && transform.newScaleX <= 0 && transform.newScaleX < target.scaleX) {
  7385. forbidScalingX = true;
  7386. }
  7387. if (lockScalingFlip && transform.newScaleY <= 0 && transform.newScaleY < target.scaleY) {
  7388. forbidScalingY = true;
  7389. }
  7390. if (by === 'equally' && !lockScalingX && !lockScalingY) {
  7391. forbidScalingX || forbidScalingY || this._scaleObjectEqually(localMouse, target, transform);
  7392. }
  7393. else if (!by) {
  7394. forbidScalingX || lockScalingX || target.set('scaleX', transform.newScaleX);
  7395. forbidScalingY || lockScalingY || target.set('scaleY', transform.newScaleY);
  7396. }
  7397. else if (by === 'x' && !target.get('lockUniScaling')) {
  7398. forbidScalingX || lockScalingX || target.set('scaleX', transform.newScaleX);
  7399. }
  7400. else if (by === 'y' && !target.get('lockUniScaling')) {
  7401. forbidScalingY || lockScalingY || target.set('scaleY', transform.newScaleY);
  7402. }
  7403. forbidScalingX || forbidScalingY || this._flipObject(transform, by);
  7404. },
  7405. /**
  7406. * @private
  7407. */
  7408. _scaleObjectEqually: function(localMouse, target, transform) {
  7409. var dist = localMouse.y + localMouse.x,
  7410. strokeWidth = target.stroke ? target.strokeWidth : 0,
  7411. lastDist = (target.height + (strokeWidth / 2)) * transform.original.scaleY +
  7412. (target.width + (strokeWidth / 2)) * transform.original.scaleX;
  7413. // We use transform.scaleX/Y instead of target.scaleX/Y
  7414. // because the object may have a min scale and we'll loose the proportions
  7415. transform.newScaleX = transform.original.scaleX * dist / lastDist;
  7416. transform.newScaleY = transform.original.scaleY * dist / lastDist;
  7417. target.set('scaleX', transform.newScaleX);
  7418. target.set('scaleY', transform.newScaleY);
  7419. },
  7420. /**
  7421. * @private
  7422. */
  7423. _flipObject: function(transform, by) {
  7424. if (transform.newScaleX < 0 && by !== 'y') {
  7425. if (transform.originX === 'left') {
  7426. transform.originX = 'right';
  7427. }
  7428. else if (transform.originX === 'right') {
  7429. transform.originX = 'left';
  7430. }
  7431. }
  7432. if (transform.newScaleY < 0 && by !== 'x') {
  7433. if (transform.originY === 'top') {
  7434. transform.originY = 'bottom';
  7435. }
  7436. else if (transform.originY === 'bottom') {
  7437. transform.originY = 'top';
  7438. }
  7439. }
  7440. },
  7441. /**
  7442. * @private
  7443. */
  7444. _setLocalMouse: function(localMouse, t) {
  7445. var target = t.target;
  7446. if (t.originX === 'right') {
  7447. localMouse.x *= -1;
  7448. }
  7449. else if (t.originX === 'center') {
  7450. localMouse.x *= t.mouseXSign * 2;
  7451. if (localMouse.x < 0) {
  7452. t.mouseXSign = -t.mouseXSign;
  7453. }
  7454. }
  7455. if (t.originY === 'bottom') {
  7456. localMouse.y *= -1;
  7457. }
  7458. else if (t.originY === 'center') {
  7459. localMouse.y *= t.mouseYSign * 2;
  7460. if (localMouse.y < 0) {
  7461. t.mouseYSign = -t.mouseYSign;
  7462. }
  7463. }
  7464. // adjust the mouse coordinates when dealing with padding
  7465. if (abs(localMouse.x) > target.padding) {
  7466. if (localMouse.x < 0) {
  7467. localMouse.x += target.padding;
  7468. }
  7469. else {
  7470. localMouse.x -= target.padding;
  7471. }
  7472. }
  7473. else { // mouse is within the padding, set to 0
  7474. localMouse.x = 0;
  7475. }
  7476. if (abs(localMouse.y) > target.padding) {
  7477. if (localMouse.y < 0) {
  7478. localMouse.y += target.padding;
  7479. }
  7480. else {
  7481. localMouse.y -= target.padding;
  7482. }
  7483. }
  7484. else {
  7485. localMouse.y = 0;
  7486. }
  7487. },
  7488. /**
  7489. * Rotates object by invoking its rotate method
  7490. * @private
  7491. * @param {Number} x pointer's x coordinate
  7492. * @param {Number} y pointer's y coordinate
  7493. */
  7494. _rotateObject: function (x, y) {
  7495. var t = this._currentTransform;
  7496. if (t.target.get('lockRotation')) {
  7497. return;
  7498. }
  7499. var lastAngle = atan2(t.ey - t.top, t.ex - t.left),
  7500. curAngle = atan2(y - t.top, x - t.left),
  7501. angle = radiansToDegrees(curAngle - lastAngle + t.theta);
  7502. // normalize angle to positive value
  7503. if (angle < 0) {
  7504. angle = 360 + angle;
  7505. }
  7506. t.target.angle = angle % 360;
  7507. },
  7508. /**
  7509. * Set the cursor type of the canvas element
  7510. * @param {String} value Cursor type of the canvas element.
  7511. * @see http://www.w3.org/TR/css3-ui/#cursor
  7512. */
  7513. setCursor: function (value) {
  7514. this.upperCanvasEl.style.cursor = value;
  7515. },
  7516. /**
  7517. * @private
  7518. */
  7519. _resetObjectTransform: function (target) {
  7520. target.scaleX = 1;
  7521. target.scaleY = 1;
  7522. target.setAngle(0);
  7523. },
  7524. /**
  7525. * @private
  7526. */
  7527. _drawSelection: function () {
  7528. var ctx = this.contextTop,
  7529. groupSelector = this._groupSelector,
  7530. left = groupSelector.left,
  7531. top = groupSelector.top,
  7532. aleft = abs(left),
  7533. atop = abs(top);
  7534. ctx.fillStyle = this.selectionColor;
  7535. ctx.fillRect(
  7536. groupSelector.ex - ((left > 0) ? 0 : -left),
  7537. groupSelector.ey - ((top > 0) ? 0 : -top),
  7538. aleft,
  7539. atop
  7540. );
  7541. ctx.lineWidth = this.selectionLineWidth;
  7542. ctx.strokeStyle = this.selectionBorderColor;
  7543. // selection border
  7544. if (this.selectionDashArray.length > 1) {
  7545. var px = groupSelector.ex + STROKE_OFFSET - ((left > 0) ? 0: aleft),
  7546. py = groupSelector.ey + STROKE_OFFSET - ((top > 0) ? 0: atop);
  7547. ctx.beginPath();
  7548. fabric.util.drawDashedLine(ctx, px, py, px + aleft, py, this.selectionDashArray);
  7549. fabric.util.drawDashedLine(ctx, px, py + atop - 1, px + aleft, py + atop - 1, this.selectionDashArray);
  7550. fabric.util.drawDashedLine(ctx, px, py, px, py + atop, this.selectionDashArray);
  7551. fabric.util.drawDashedLine(ctx, px + aleft - 1, py, px + aleft - 1, py + atop, this.selectionDashArray);
  7552. ctx.closePath();
  7553. ctx.stroke();
  7554. }
  7555. else {
  7556. ctx.strokeRect(
  7557. groupSelector.ex + STROKE_OFFSET - ((left > 0) ? 0 : aleft),
  7558. groupSelector.ey + STROKE_OFFSET - ((top > 0) ? 0 : atop),
  7559. aleft,
  7560. atop
  7561. );
  7562. }
  7563. },
  7564. /**
  7565. * @private
  7566. */
  7567. _isLastRenderedObject: function(e) {
  7568. return (
  7569. this.controlsAboveOverlay &&
  7570. this.lastRenderedObjectWithControlsAboveOverlay &&
  7571. this.lastRenderedObjectWithControlsAboveOverlay.visible &&
  7572. this.containsPoint(e, this.lastRenderedObjectWithControlsAboveOverlay) &&
  7573. this.lastRenderedObjectWithControlsAboveOverlay._findTargetCorner(this.getPointer(e, true)));
  7574. },
  7575. /**
  7576. * Method that determines what object we are clicking on
  7577. * @param {Event} e mouse event
  7578. * @param {Boolean} skipGroup when true, group is skipped and only objects are traversed through
  7579. */
  7580. findTarget: function (e, skipGroup) {
  7581. if (this.skipTargetFind) {
  7582. return;
  7583. }
  7584. if (this._isLastRenderedObject(e)) {
  7585. return this.lastRenderedObjectWithControlsAboveOverlay;
  7586. }
  7587. // first check current group (if one exists)
  7588. var activeGroup = this.getActiveGroup();
  7589. if (activeGroup && !skipGroup && this.containsPoint(e, activeGroup)) {
  7590. return activeGroup;
  7591. }
  7592. var target = this._searchPossibleTargets(e);
  7593. this._fireOverOutEvents(target);
  7594. return target;
  7595. },
  7596. /**
  7597. * @private
  7598. */
  7599. _fireOverOutEvents: function(target) {
  7600. if (target) {
  7601. if (this._hoveredTarget !== target) {
  7602. this.fire('mouse:over', { target: target });
  7603. target.fire('mouseover');
  7604. if (this._hoveredTarget) {
  7605. this.fire('mouse:out', { target: this._hoveredTarget });
  7606. this._hoveredTarget.fire('mouseout');
  7607. }
  7608. this._hoveredTarget = target;
  7609. }
  7610. }
  7611. else if (this._hoveredTarget) {
  7612. this.fire('mouse:out', { target: this._hoveredTarget });
  7613. this._hoveredTarget.fire('mouseout');
  7614. this._hoveredTarget = null;
  7615. }
  7616. },
  7617. /**
  7618. * @private
  7619. */
  7620. _checkTarget: function(e, obj, pointer) {
  7621. if (obj &&
  7622. obj.visible &&
  7623. obj.evented &&
  7624. this.containsPoint(e, obj)){
  7625. if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
  7626. var isTransparent = this.isTargetTransparent(obj, pointer.x, pointer.y);
  7627. if (!isTransparent) {
  7628. return true;
  7629. }
  7630. }
  7631. else {
  7632. return true;
  7633. }
  7634. }
  7635. },
  7636. /**
  7637. * @private
  7638. */
  7639. _searchPossibleTargets: function(e) {
  7640. // Cache all targets where their bounding box contains point.
  7641. var target,
  7642. pointer = this.getPointer(e, true),
  7643. i = this._objects.length;
  7644. // Do not check for currently grouped objects, since we check the parent group itself.
  7645. while (i--) {
  7646. if (!this._objects[i].group && this._checkTarget(e, this._objects[i], pointer)){
  7647. this.relatedTarget = this._objects[i];
  7648. target = this._objects[i];
  7649. break;
  7650. }
  7651. }
  7652. return target;
  7653. },
  7654. /**
  7655. * Returns pointer coordinates relative to canvas.
  7656. * @param {Event} e
  7657. * @return {Object} object with "x" and "y" number values
  7658. */
  7659. getPointer: function (e, ignoreZoom, upperCanvasEl) {
  7660. if (!upperCanvasEl) {
  7661. upperCanvasEl = this.upperCanvasEl;
  7662. }
  7663. var pointer = getPointer(e, upperCanvasEl),
  7664. bounds = upperCanvasEl.getBoundingClientRect(),
  7665. boundsWidth = bounds.width || 0,
  7666. boundsHeight = bounds.height || 0,
  7667. cssScale;
  7668. if (!boundsWidth || !boundsHeight ) {
  7669. if ('top' in bounds && 'bottom' in bounds) {
  7670. boundsHeight = Math.abs( bounds.top - bounds.bottom );
  7671. }
  7672. if ('right' in bounds && 'left' in bounds) {
  7673. boundsWidth = Math.abs( bounds.right - bounds.left );
  7674. }
  7675. }
  7676. this.calcOffset();
  7677. pointer.x = pointer.x - this._offset.left;
  7678. pointer.y = pointer.y - this._offset.top;
  7679. if (!ignoreZoom) {
  7680. pointer = fabric.util.transformPoint(
  7681. pointer,
  7682. fabric.util.invertTransform(this.viewportTransform)
  7683. );
  7684. }
  7685. if (boundsWidth === 0 || boundsHeight === 0) {
  7686. // If bounds are not available (i.e. not visible), do not apply scale.
  7687. cssScale = { width: 1, height: 1 };
  7688. }
  7689. else {
  7690. cssScale = {
  7691. width: upperCanvasEl.width / boundsWidth,
  7692. height: upperCanvasEl.height / boundsHeight
  7693. };
  7694. }
  7695. return {
  7696. x: pointer.x * cssScale.width,
  7697. y: pointer.y * cssScale.height
  7698. };
  7699. },
  7700. /**
  7701. * @private
  7702. * @throws {CANVAS_INIT_ERROR} If canvas can not be initialized
  7703. */
  7704. _createUpperCanvas: function () {
  7705. var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/, '');
  7706. this.upperCanvasEl = this._createCanvasElement();
  7707. fabric.util.addClass(this.upperCanvasEl, 'upper-canvas ' + lowerCanvasClass);
  7708. this.wrapperEl.appendChild(this.upperCanvasEl);
  7709. this._copyCanvasStyle(this.lowerCanvasEl, this.upperCanvasEl);
  7710. this._applyCanvasStyle(this.upperCanvasEl);
  7711. this.contextTop = this.upperCanvasEl.getContext('2d');
  7712. },
  7713. /**
  7714. * @private
  7715. */
  7716. _createCacheCanvas: function () {
  7717. this.cacheCanvasEl = this._createCanvasElement();
  7718. this.cacheCanvasEl.setAttribute('width', this.width);
  7719. this.cacheCanvasEl.setAttribute('height', this.height);
  7720. this.contextCache = this.cacheCanvasEl.getContext('2d');
  7721. },
  7722. /**
  7723. * @private
  7724. */
  7725. _initWrapperElement: function () {
  7726. this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, 'div', {
  7727. 'class': this.containerClass
  7728. });
  7729. fabric.util.setStyle(this.wrapperEl, {
  7730. width: this.getWidth() + 'px',
  7731. height: this.getHeight() + 'px',
  7732. position: 'relative'
  7733. });
  7734. fabric.util.makeElementUnselectable(this.wrapperEl);
  7735. },
  7736. /**
  7737. * @private
  7738. * @param {HTMLElement} element canvas element to apply styles on
  7739. */
  7740. _applyCanvasStyle: function (element) {
  7741. var width = this.getWidth() || element.width,
  7742. height = this.getHeight() || element.height;
  7743. fabric.util.setStyle(element, {
  7744. position: 'absolute',
  7745. width: width + 'px',
  7746. height: height + 'px',
  7747. left: 0,
  7748. top: 0
  7749. });
  7750. element.width = width;
  7751. element.height = height;
  7752. fabric.util.makeElementUnselectable(element);
  7753. },
  7754. /**
  7755. * Copys the the entire inline style from one element (fromEl) to another (toEl)
  7756. * @private
  7757. * @param {Element} fromEl Element style is copied from
  7758. * @param {Element} toEl Element copied style is applied to
  7759. */
  7760. _copyCanvasStyle: function (fromEl, toEl) {
  7761. toEl.style.cssText = fromEl.style.cssText;
  7762. },
  7763. /**
  7764. * Returns context of canvas where object selection is drawn
  7765. * @return {CanvasRenderingContext2D}
  7766. */
  7767. getSelectionContext: function() {
  7768. return this.contextTop;
  7769. },
  7770. /**
  7771. * Returns &lt;canvas> element on which object selection is drawn
  7772. * @return {HTMLCanvasElement}
  7773. */
  7774. getSelectionElement: function () {
  7775. return this.upperCanvasEl;
  7776. },
  7777. /**
  7778. * @private
  7779. * @param {Object} object
  7780. */
  7781. _setActiveObject: function(object) {
  7782. if (this._activeObject) {
  7783. this._activeObject.set('active', false);
  7784. }
  7785. this._activeObject = object;
  7786. object.set('active', true);
  7787. },
  7788. /**
  7789. * Sets given object as the only active object on canvas
  7790. * @param {fabric.Object} object Object to set as an active one
  7791. * @param {Event} [e] Event (passed along when firing "object:selected")
  7792. * @return {fabric.Canvas} thisArg
  7793. * @chainable
  7794. */
  7795. setActiveObject: function (object, e) {
  7796. this._setActiveObject(object);
  7797. this.renderAll();
  7798. this.fire('object:selected', { target: object, e: e });
  7799. object.fire('selected', { e: e });
  7800. return this;
  7801. },
  7802. /**
  7803. * Returns currently active object
  7804. * @return {fabric.Object} active object
  7805. */
  7806. getActiveObject: function () {
  7807. return this._activeObject;
  7808. },
  7809. /**
  7810. * @private
  7811. */
  7812. _discardActiveObject: function() {
  7813. if (this._activeObject) {
  7814. this._activeObject.set('active', false);
  7815. }
  7816. this._activeObject = null;
  7817. },
  7818. /**
  7819. * Discards currently active object
  7820. * @return {fabric.Canvas} thisArg
  7821. * @chainable
  7822. */
  7823. discardActiveObject: function (e) {
  7824. this._discardActiveObject();
  7825. this.renderAll();
  7826. this.fire('selection:cleared', { e: e });
  7827. return this;
  7828. },
  7829. /**
  7830. * @private
  7831. * @param {fabric.Group} group
  7832. */
  7833. _setActiveGroup: function(group) {
  7834. this._activeGroup = group;
  7835. if (group) {
  7836. group.set('active', true);
  7837. }
  7838. },
  7839. /**
  7840. * Sets active group to a speicified one
  7841. * @param {fabric.Group} group Group to set as a current one
  7842. * @return {fabric.Canvas} thisArg
  7843. * @chainable
  7844. */
  7845. setActiveGroup: function (group, e) {
  7846. this._setActiveGroup(group);
  7847. if (group) {
  7848. this.fire('object:selected', { target: group, e: e });
  7849. group.fire('selected', { e: e });
  7850. }
  7851. return this;
  7852. },
  7853. /**
  7854. * Returns currently active group
  7855. * @return {fabric.Group} Current group
  7856. */
  7857. getActiveGroup: function () {
  7858. return this._activeGroup;
  7859. },
  7860. /**
  7861. * @private
  7862. */
  7863. _discardActiveGroup: function() {
  7864. var g = this.getActiveGroup();
  7865. if (g) {
  7866. g.destroy();
  7867. }
  7868. this.setActiveGroup(null);
  7869. },
  7870. /**
  7871. * Discards currently active group
  7872. * @return {fabric.Canvas} thisArg
  7873. */
  7874. discardActiveGroup: function (e) {
  7875. this._discardActiveGroup();
  7876. this.fire('selection:cleared', { e: e });
  7877. return this;
  7878. },
  7879. /**
  7880. * Deactivates all objects on canvas, removing any active group or object
  7881. * @return {fabric.Canvas} thisArg
  7882. */
  7883. deactivateAll: function () {
  7884. var allObjects = this.getObjects(),
  7885. i = 0,
  7886. len = allObjects.length;
  7887. for ( ; i < len; i++) {
  7888. allObjects[i].set('active', false);
  7889. }
  7890. this._discardActiveGroup();
  7891. this._discardActiveObject();
  7892. return this;
  7893. },
  7894. /**
  7895. * Deactivates all objects and dispatches appropriate events
  7896. * @return {fabric.Canvas} thisArg
  7897. */
  7898. deactivateAllWithDispatch: function (e) {
  7899. var activeObject = this.getActiveGroup() || this.getActiveObject();
  7900. if (activeObject) {
  7901. this.fire('before:selection:cleared', { target: activeObject, e: e });
  7902. }
  7903. this.deactivateAll();
  7904. if (activeObject) {
  7905. this.fire('selection:cleared', { e: e });
  7906. }
  7907. return this;
  7908. },
  7909. /**
  7910. * Draws objects' controls (borders/controls)
  7911. * @param {CanvasRenderingContext2D} ctx Context to render controls on
  7912. */
  7913. drawControls: function(ctx) {
  7914. var activeGroup = this.getActiveGroup();
  7915. if (activeGroup) {
  7916. this._drawGroupControls(ctx, activeGroup);
  7917. }
  7918. else {
  7919. this._drawObjectsControls(ctx);
  7920. }
  7921. },
  7922. /**
  7923. * @private
  7924. */
  7925. _drawGroupControls: function(ctx, activeGroup) {
  7926. activeGroup._renderControls(ctx);
  7927. },
  7928. /**
  7929. * @private
  7930. */
  7931. _drawObjectsControls: function(ctx) {
  7932. for (var i = 0, len = this._objects.length; i < len; ++i) {
  7933. if (!this._objects[i] || !this._objects[i].active) {
  7934. continue;
  7935. }
  7936. this._objects[i]._renderControls(ctx);
  7937. this.lastRenderedObjectWithControlsAboveOverlay = this._objects[i];
  7938. }
  7939. }
  7940. });
  7941. // copying static properties manually to work around Opera's bug,
  7942. // where "prototype" property is enumerable and overrides existing prototype
  7943. for (var prop in fabric.StaticCanvas) {
  7944. if (prop !== 'prototype') {
  7945. fabric.Canvas[prop] = fabric.StaticCanvas[prop];
  7946. }
  7947. }
  7948. if (fabric.isTouchSupported) {
  7949. /** @ignore */
  7950. fabric.Canvas.prototype._setCursorFromEvent = function() { };
  7951. }
  7952. /**
  7953. * @class fabric.Element
  7954. * @alias fabric.Canvas
  7955. * @deprecated Use {@link fabric.Canvas} instead.
  7956. * @constructor
  7957. */
  7958. fabric.Element = fabric.Canvas;
  7959. })();
  7960. (function() {
  7961. var cursorOffset = {
  7962. mt: 0, // n
  7963. tr: 1, // ne
  7964. mr: 2, // e
  7965. br: 3, // se
  7966. mb: 4, // s
  7967. bl: 5, // sw
  7968. ml: 6, // w
  7969. tl: 7 // nw
  7970. },
  7971. addListener = fabric.util.addListener,
  7972. removeListener = fabric.util.removeListener;
  7973. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  7974. /**
  7975. * Map of cursor style values for each of the object controls
  7976. * @private
  7977. */
  7978. cursorMap: [
  7979. 'n-resize',
  7980. 'ne-resize',
  7981. 'e-resize',
  7982. 'se-resize',
  7983. 's-resize',
  7984. 'sw-resize',
  7985. 'w-resize',
  7986. 'nw-resize'
  7987. ],
  7988. /**
  7989. * Adds mouse listeners to canvas
  7990. * @private
  7991. */
  7992. _initEventListeners: function () {
  7993. this._bindEvents();
  7994. addListener(fabric.window, 'resize', this._onResize);
  7995. // mouse events
  7996. addListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  7997. addListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  7998. addListener(this.upperCanvasEl, 'mousewheel', this._onMouseWheel);
  7999. // touch events
  8000. addListener(this.upperCanvasEl, 'touchstart', this._onMouseDown);
  8001. addListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  8002. if (typeof eventjs !== 'undefined' && 'add' in eventjs) {
  8003. eventjs.add(this.upperCanvasEl, 'gesture', this._onGesture);
  8004. eventjs.add(this.upperCanvasEl, 'drag', this._onDrag);
  8005. eventjs.add(this.upperCanvasEl, 'orientation', this._onOrientationChange);
  8006. eventjs.add(this.upperCanvasEl, 'shake', this._onShake);
  8007. eventjs.add(this.upperCanvasEl, 'longpress', this._onLongPress);
  8008. }
  8009. },
  8010. /**
  8011. * @private
  8012. */
  8013. _bindEvents: function() {
  8014. this._onMouseDown = this._onMouseDown.bind(this);
  8015. this._onMouseMove = this._onMouseMove.bind(this);
  8016. this._onMouseUp = this._onMouseUp.bind(this);
  8017. this._onResize = this._onResize.bind(this);
  8018. this._onGesture = this._onGesture.bind(this);
  8019. this._onDrag = this._onDrag.bind(this);
  8020. this._onShake = this._onShake.bind(this);
  8021. this._onLongPress = this._onLongPress.bind(this);
  8022. this._onOrientationChange = this._onOrientationChange.bind(this);
  8023. this._onMouseWheel = this._onMouseWheel.bind(this);
  8024. },
  8025. /**
  8026. * Removes all event listeners
  8027. */
  8028. removeListeners: function() {
  8029. removeListener(fabric.window, 'resize', this._onResize);
  8030. removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  8031. removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  8032. removeListener(this.upperCanvasEl, 'mousewheel', this._onMouseWheel);
  8033. removeListener(this.upperCanvasEl, 'touchstart', this._onMouseDown);
  8034. removeListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  8035. if (typeof eventjs !== 'undefined' && 'remove' in eventjs) {
  8036. eventjs.remove(this.upperCanvasEl, 'gesture', this._onGesture);
  8037. eventjs.remove(this.upperCanvasEl, 'drag', this._onDrag);
  8038. eventjs.remove(this.upperCanvasEl, 'orientation', this._onOrientationChange);
  8039. eventjs.remove(this.upperCanvasEl, 'shake', this._onShake);
  8040. eventjs.remove(this.upperCanvasEl, 'longpress', this._onLongPress);
  8041. }
  8042. },
  8043. /**
  8044. * @private
  8045. * @param {Event} [e] Event object fired on Event.js gesture
  8046. * @param {Event} [self] Inner Event object
  8047. */
  8048. _onGesture: function(e, self) {
  8049. this.__onTransformGesture && this.__onTransformGesture(e, self);
  8050. },
  8051. /**
  8052. * @private
  8053. * @param {Event} [e] Event object fired on Event.js drag
  8054. * @param {Event} [self] Inner Event object
  8055. */
  8056. _onDrag: function(e, self) {
  8057. this.__onDrag && this.__onDrag(e, self);
  8058. },
  8059. /**
  8060. * @private
  8061. * @param {Event} [e] Event object fired on Event.js wheel event
  8062. * @param {Event} [self] Inner Event object
  8063. */
  8064. _onMouseWheel: function(e, self) {
  8065. this.__onMouseWheel && this.__onMouseWheel(e, self);
  8066. },
  8067. /**
  8068. * @private
  8069. * @param {Event} [e] Event object fired on Event.js orientation change
  8070. * @param {Event} [self] Inner Event object
  8071. */
  8072. _onOrientationChange: function(e, self) {
  8073. this.__onOrientationChange && this.__onOrientationChange(e, self);
  8074. },
  8075. /**
  8076. * @private
  8077. * @param {Event} [e] Event object fired on Event.js shake
  8078. * @param {Event} [self] Inner Event object
  8079. */
  8080. _onShake: function(e, self) {
  8081. this.__onShake && this.__onShake(e, self);
  8082. },
  8083. /**
  8084. * @private
  8085. * @param {Event} [e] Event object fired on Event.js shake
  8086. * @param {Event} [self] Inner Event object
  8087. */
  8088. _onLongPress: function(e, self) {
  8089. this.__onLongPress && this.__onLongPress(e, self);
  8090. },
  8091. /**
  8092. * @private
  8093. * @param {Event} e Event object fired on mousedown
  8094. */
  8095. _onMouseDown: function (e) {
  8096. this.__onMouseDown(e);
  8097. addListener(fabric.document, 'touchend', this._onMouseUp);
  8098. addListener(fabric.document, 'touchmove', this._onMouseMove);
  8099. removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  8100. removeListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  8101. if (e.type === 'touchstart') {
  8102. // Unbind mousedown to prevent double triggers from touch devices
  8103. removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown);
  8104. }
  8105. else {
  8106. addListener(fabric.document, 'mouseup', this._onMouseUp);
  8107. addListener(fabric.document, 'mousemove', this._onMouseMove);
  8108. }
  8109. },
  8110. /**
  8111. * @private
  8112. * @param {Event} e Event object fired on mouseup
  8113. */
  8114. _onMouseUp: function (e) {
  8115. this.__onMouseUp(e);
  8116. removeListener(fabric.document, 'mouseup', this._onMouseUp);
  8117. removeListener(fabric.document, 'touchend', this._onMouseUp);
  8118. removeListener(fabric.document, 'mousemove', this._onMouseMove);
  8119. removeListener(fabric.document, 'touchmove', this._onMouseMove);
  8120. addListener(this.upperCanvasEl, 'mousemove', this._onMouseMove);
  8121. addListener(this.upperCanvasEl, 'touchmove', this._onMouseMove);
  8122. if (e.type === 'touchend') {
  8123. // Wait 400ms before rebinding mousedown to prevent double triggers
  8124. // from touch devices
  8125. var _this = this;
  8126. setTimeout(function() {
  8127. addListener(_this.upperCanvasEl, 'mousedown', _this._onMouseDown);
  8128. }, 400);
  8129. }
  8130. },
  8131. /**
  8132. * @private
  8133. * @param {Event} e Event object fired on mousemove
  8134. */
  8135. _onMouseMove: function (e) {
  8136. !this.allowTouchScrolling && e.preventDefault && e.preventDefault();
  8137. this.__onMouseMove(e);
  8138. },
  8139. /**
  8140. * @private
  8141. */
  8142. _onResize: function () {
  8143. this.calcOffset();
  8144. },
  8145. /**
  8146. * Decides whether the canvas should be redrawn in mouseup and mousedown events.
  8147. * @private
  8148. * @param {Object} target
  8149. * @param {Object} pointer
  8150. */
  8151. _shouldRender: function(target, pointer) {
  8152. var activeObject = this.getActiveGroup() || this.getActiveObject();
  8153. return !!(
  8154. (target && (
  8155. target.isMoving ||
  8156. target !== activeObject))
  8157. ||
  8158. (!target && !!activeObject)
  8159. ||
  8160. (!target && !activeObject && !this._groupSelector)
  8161. ||
  8162. (pointer &&
  8163. this._previousPointer &&
  8164. this.selection && (
  8165. pointer.x !== this._previousPointer.x ||
  8166. pointer.y !== this._previousPointer.y))
  8167. );
  8168. },
  8169. /**
  8170. * Method that defines the actions when mouse is released on canvas.
  8171. * The method resets the currentTransform parameters, store the image corner
  8172. * position in the image object and render the canvas on top.
  8173. * @private
  8174. * @param {Event} e Event object fired on mouseup
  8175. */
  8176. __onMouseUp: function (e) {
  8177. var target;
  8178. if (this.isDrawingMode && this._isCurrentlyDrawing) {
  8179. this._onMouseUpInDrawingMode(e);
  8180. return;
  8181. }
  8182. if (this._currentTransform) {
  8183. this._finalizeCurrentTransform();
  8184. target = this._currentTransform.target;
  8185. }
  8186. else {
  8187. target = this.findTarget(e, true);
  8188. }
  8189. var shouldRender = this._shouldRender(target, this.getPointer(e));
  8190. this._maybeGroupObjects(e);
  8191. if (target) {
  8192. target.isMoving = false;
  8193. }
  8194. shouldRender && this.renderAll();
  8195. this._handleCursorAndEvent(e, target);
  8196. },
  8197. _handleCursorAndEvent: function(e, target) {
  8198. this._setCursorFromEvent(e, target);
  8199. // TODO: why are we doing this?
  8200. var _this = this;
  8201. setTimeout(function () {
  8202. _this._setCursorFromEvent(e, target);
  8203. }, 50);
  8204. this.fire('mouse:up', { target: target, e: e });
  8205. target && target.fire('mouseup', { e: e });
  8206. },
  8207. /**
  8208. * @private
  8209. */
  8210. _finalizeCurrentTransform: function() {
  8211. var transform = this._currentTransform,
  8212. target = transform.target;
  8213. if (target._scaling) {
  8214. target._scaling = false;
  8215. }
  8216. target.setCoords();
  8217. // only fire :modified event if target coordinates were changed during mousedown-mouseup
  8218. if (this.stateful && target.hasStateChanged()) {
  8219. this.fire('object:modified', { target: target });
  8220. target.fire('modified');
  8221. }
  8222. this._restoreOriginXY(target);
  8223. },
  8224. /**
  8225. * @private
  8226. * @param {Object} target Object to restore
  8227. */
  8228. _restoreOriginXY: function(target) {
  8229. if (this._previousOriginX && this._previousOriginY) {
  8230. var originPoint = target.translateToOriginPoint(
  8231. target.getCenterPoint(),
  8232. this._previousOriginX,
  8233. this._previousOriginY);
  8234. target.originX = this._previousOriginX;
  8235. target.originY = this._previousOriginY;
  8236. target.left = originPoint.x;
  8237. target.top = originPoint.y;
  8238. this._previousOriginX = null;
  8239. this._previousOriginY = null;
  8240. }
  8241. },
  8242. /**
  8243. * @private
  8244. * @param {Event} e Event object fired on mousedown
  8245. */
  8246. _onMouseDownInDrawingMode: function(e) {
  8247. this._isCurrentlyDrawing = true;
  8248. this.discardActiveObject(e).renderAll();
  8249. if (this.clipTo) {
  8250. fabric.util.clipContext(this, this.contextTop);
  8251. }
  8252. var ivt = fabric.util.invertTransform(this.viewportTransform),
  8253. pointer = fabric.util.transformPoint(this.getPointer(e, true), ivt);
  8254. this.freeDrawingBrush.onMouseDown(pointer);
  8255. this.fire('mouse:down', { e: e });
  8256. var target = this.findTarget(e);
  8257. if (typeof target !== 'undefined') {
  8258. target.fire('mousedown', { e: e, target: target });
  8259. }
  8260. },
  8261. /**
  8262. * @private
  8263. * @param {Event} e Event object fired on mousemove
  8264. */
  8265. _onMouseMoveInDrawingMode: function(e) {
  8266. if (this._isCurrentlyDrawing) {
  8267. var ivt = fabric.util.invertTransform(this.viewportTransform),
  8268. pointer = fabric.util.transformPoint(this.getPointer(e, true), ivt);
  8269. this.freeDrawingBrush.onMouseMove(pointer);
  8270. }
  8271. this.setCursor(this.freeDrawingCursor);
  8272. this.fire('mouse:move', { e: e });
  8273. var target = this.findTarget(e);
  8274. if (typeof target !== 'undefined') {
  8275. target.fire('mousemove', { e: e, target: target });
  8276. }
  8277. },
  8278. /**
  8279. * @private
  8280. * @param {Event} e Event object fired on mouseup
  8281. */
  8282. _onMouseUpInDrawingMode: function(e) {
  8283. this._isCurrentlyDrawing = false;
  8284. if (this.clipTo) {
  8285. this.contextTop.restore();
  8286. }
  8287. this.freeDrawingBrush.onMouseUp();
  8288. this.fire('mouse:up', { e: e });
  8289. var target = this.findTarget(e);
  8290. if (typeof target !== 'undefined') {
  8291. target.fire('mouseup', { e: e, target: target });
  8292. }
  8293. },
  8294. /**
  8295. * Method that defines the actions when mouse is clic ked on canvas.
  8296. * The method inits the currentTransform parameters and renders all the
  8297. * canvas so the current image can be placed on the top canvas and the rest
  8298. * in on the container one.
  8299. * @private
  8300. * @param {Event} e Event object fired on mousedown
  8301. */
  8302. __onMouseDown: function (e) {
  8303. // accept only left clicks
  8304. var isLeftClick = 'which' in e ? e.which === 1 : e.button === 1;
  8305. if (!isLeftClick && !fabric.isTouchSupported) {
  8306. return;
  8307. }
  8308. if (this.isDrawingMode) {
  8309. this._onMouseDownInDrawingMode(e);
  8310. return;
  8311. }
  8312. // ignore if some object is being transformed at this moment
  8313. if (this._currentTransform) {
  8314. return;
  8315. }
  8316. var target = this.findTarget(e),
  8317. pointer = this.getPointer(e, true);
  8318. // save pointer for check in __onMouseUp event
  8319. this._previousPointer = pointer;
  8320. var shouldRender = this._shouldRender(target, pointer),
  8321. shouldGroup = this._shouldGroup(e, target);
  8322. if (this._shouldClearSelection(e, target)) {
  8323. this._clearSelection(e, target, pointer);
  8324. }
  8325. else if (shouldGroup) {
  8326. this._handleGrouping(e, target);
  8327. target = this.getActiveGroup();
  8328. }
  8329. if (target && target.selectable && !shouldGroup) {
  8330. this._beforeTransform(e, target);
  8331. this._setupCurrentTransform(e, target);
  8332. }
  8333. // we must renderAll so that active image is placed on the top canvas
  8334. shouldRender && this.renderAll();
  8335. this.fire('mouse:down', { target: target, e: e });
  8336. target && target.fire('mousedown', { e: e });
  8337. },
  8338. /**
  8339. * @private
  8340. */
  8341. _beforeTransform: function(e, target) {
  8342. this.stateful && target.saveState();
  8343. // determine if it's a drag or rotate case
  8344. if (target._findTargetCorner(this.getPointer(e))) {
  8345. this.onBeforeScaleRotate(target);
  8346. }
  8347. if (target !== this.getActiveGroup() && target !== this.getActiveObject()) {
  8348. this.deactivateAll();
  8349. this.setActiveObject(target, e);
  8350. }
  8351. },
  8352. /**
  8353. * @private
  8354. */
  8355. _clearSelection: function(e, target, pointer) {
  8356. this.deactivateAllWithDispatch(e);
  8357. if (target && target.selectable) {
  8358. this.setActiveObject(target, e);
  8359. }
  8360. else if (this.selection) {
  8361. this._groupSelector = {
  8362. ex: pointer.x,
  8363. ey: pointer.y,
  8364. top: 0,
  8365. left: 0
  8366. };
  8367. }
  8368. },
  8369. /**
  8370. * @private
  8371. * @param {Object} target Object for that origin is set to center
  8372. */
  8373. _setOriginToCenter: function(target) {
  8374. this._previousOriginX = this._currentTransform.target.originX;
  8375. this._previousOriginY = this._currentTransform.target.originY;
  8376. var center = target.getCenterPoint();
  8377. target.originX = 'center';
  8378. target.originY = 'center';
  8379. target.left = center.x;
  8380. target.top = center.y;
  8381. this._currentTransform.left = target.left;
  8382. this._currentTransform.top = target.top;
  8383. },
  8384. /**
  8385. * @private
  8386. * @param {Object} target Object for that center is set to origin
  8387. */
  8388. _setCenterToOrigin: function(target) {
  8389. var originPoint = target.translateToOriginPoint(
  8390. target.getCenterPoint(),
  8391. this._previousOriginX,
  8392. this._previousOriginY);
  8393. target.originX = this._previousOriginX;
  8394. target.originY = this._previousOriginY;
  8395. target.left = originPoint.x;
  8396. target.top = originPoint.y;
  8397. this._previousOriginX = null;
  8398. this._previousOriginY = null;
  8399. },
  8400. /**
  8401. * Method that defines the actions when mouse is hovering the canvas.
  8402. * The currentTransform parameter will definde whether the user is rotating/scaling/translating
  8403. * an image or neither of them (only hovering). A group selection is also possible and would cancel
  8404. * all any other type of action.
  8405. * In case of an image transformation only the top canvas will be rendered.
  8406. * @private
  8407. * @param {Event} e Event object fired on mousemove
  8408. */
  8409. __onMouseMove: function (e) {
  8410. var target, pointer;
  8411. if (this.isDrawingMode) {
  8412. this._onMouseMoveInDrawingMode(e);
  8413. return;
  8414. }
  8415. if (typeof e.touches !== 'undefined' && e.touches.length > 1) {
  8416. return;
  8417. }
  8418. var groupSelector = this._groupSelector;
  8419. // We initially clicked in an empty area, so we draw a box for multiple selection
  8420. if (groupSelector) {
  8421. pointer = this.getPointer(e, true);
  8422. groupSelector.left = pointer.x - groupSelector.ex;
  8423. groupSelector.top = pointer.y - groupSelector.ey;
  8424. this.renderTop();
  8425. }
  8426. else if (!this._currentTransform) {
  8427. target = this.findTarget(e);
  8428. if (!target || target && !target.selectable) {
  8429. this.setCursor(this.defaultCursor);
  8430. }
  8431. else {
  8432. this._setCursorFromEvent(e, target);
  8433. }
  8434. }
  8435. else {
  8436. this._transformObject(e);
  8437. }
  8438. this.fire('mouse:move', { target: target, e: e });
  8439. target && target.fire('mousemove', { e: e });
  8440. },
  8441. /**
  8442. * @private
  8443. * @param {Event} e Event fired on mousemove
  8444. */
  8445. _transformObject: function(e) {
  8446. var pointer = this.getPointer(e),
  8447. transform = this._currentTransform;
  8448. transform.reset = false,
  8449. transform.target.isMoving = true;
  8450. this._beforeScaleTransform(e, transform);
  8451. this._performTransformAction(e, transform, pointer);
  8452. this.renderAll();
  8453. },
  8454. /**
  8455. * @private
  8456. */
  8457. _performTransformAction: function(e, transform, pointer) {
  8458. var x = pointer.x,
  8459. y = pointer.y,
  8460. target = transform.target,
  8461. action = transform.action;
  8462. if (action === 'rotate') {
  8463. this._rotateObject(x, y);
  8464. this._fire('rotating', target, e);
  8465. }
  8466. else if (action === 'scale') {
  8467. this._onScale(e, transform, x, y);
  8468. this._fire('scaling', target, e);
  8469. }
  8470. else if (action === 'scaleX') {
  8471. this._scaleObject(x, y, 'x');
  8472. this._fire('scaling', target, e);
  8473. }
  8474. else if (action === 'scaleY') {
  8475. this._scaleObject(x, y, 'y');
  8476. this._fire('scaling', target, e);
  8477. }
  8478. else {
  8479. this._translateObject(x, y);
  8480. this._fire('moving', target, e);
  8481. this.setCursor(this.moveCursor);
  8482. }
  8483. },
  8484. /**
  8485. * @private
  8486. */
  8487. _fire: function(eventName, target, e) {
  8488. this.fire('object:' + eventName, { target: target, e: e });
  8489. target.fire(eventName, { e: e });
  8490. },
  8491. /**
  8492. * @private
  8493. */
  8494. _beforeScaleTransform: function(e, transform) {
  8495. if (transform.action === 'scale' || transform.action === 'scaleX' || transform.action === 'scaleY') {
  8496. var centerTransform = this._shouldCenterTransform(e, transform.target);
  8497. // Switch from a normal resize to center-based
  8498. if ((centerTransform && (transform.originX !== 'center' || transform.originY !== 'center')) ||
  8499. // Switch from center-based resize to normal one
  8500. (!centerTransform && transform.originX === 'center' && transform.originY === 'center')
  8501. ) {
  8502. this._resetCurrentTransform(e);
  8503. transform.reset = true;
  8504. }
  8505. }
  8506. },
  8507. /**
  8508. * @private
  8509. */
  8510. _onScale: function(e, transform, x, y) {
  8511. // rotate object only if shift key is not pressed
  8512. // and if it is not a group we are transforming
  8513. if ((e.shiftKey || this.uniScaleTransform) && !transform.target.get('lockUniScaling')) {
  8514. transform.currentAction = 'scale';
  8515. this._scaleObject(x, y);
  8516. }
  8517. else {
  8518. // Switch from a normal resize to proportional
  8519. if (!transform.reset && transform.currentAction === 'scale') {
  8520. this._resetCurrentTransform(e, transform.target);
  8521. }
  8522. transform.currentAction = 'scaleEqually';
  8523. this._scaleObject(x, y, 'equally');
  8524. }
  8525. },
  8526. /**
  8527. * Sets the cursor depending on where the canvas is being hovered.
  8528. * Note: very buggy in Opera
  8529. * @param {Event} e Event object
  8530. * @param {Object} target Object that the mouse is hovering, if so.
  8531. */
  8532. _setCursorFromEvent: function (e, target) {
  8533. if (!target || !target.selectable) {
  8534. this.setCursor(this.defaultCursor);
  8535. return false;
  8536. }
  8537. else {
  8538. var activeGroup = this.getActiveGroup(),
  8539. // only show proper corner when group selection is not active
  8540. corner = target._findTargetCorner
  8541. && (!activeGroup || !activeGroup.contains(target))
  8542. && target._findTargetCorner(this.getPointer(e, true));
  8543. if (!corner) {
  8544. this.setCursor(target.hoverCursor || this.hoverCursor);
  8545. }
  8546. else {
  8547. this._setCornerCursor(corner, target);
  8548. }
  8549. }
  8550. return true;
  8551. },
  8552. /**
  8553. * @private
  8554. */
  8555. _setCornerCursor: function(corner, target) {
  8556. if (corner in cursorOffset) {
  8557. this.setCursor(this._getRotatedCornerCursor(corner, target));
  8558. }
  8559. else if (corner === 'mtr' && target.hasRotatingPoint) {
  8560. this.setCursor(this.rotationCursor);
  8561. }
  8562. else {
  8563. this.setCursor(this.defaultCursor);
  8564. return false;
  8565. }
  8566. },
  8567. /**
  8568. * @private
  8569. */
  8570. _getRotatedCornerCursor: function(corner, target) {
  8571. var n = Math.round((target.getAngle() % 360) / 45);
  8572. if (n < 0) {
  8573. n += 8; // full circle ahead
  8574. }
  8575. n += cursorOffset[corner];
  8576. // normalize n to be from 0 to 7
  8577. n %= 8;
  8578. return this.cursorMap[n];
  8579. }
  8580. });
  8581. })();
  8582. (function() {
  8583. var min = Math.min,
  8584. max = Math.max;
  8585. fabric.util.object.extend(fabric.Canvas.prototype, /** @lends fabric.Canvas.prototype */ {
  8586. /**
  8587. * @private
  8588. * @param {Event} e Event object
  8589. * @param {fabric.Object} target
  8590. * @return {Boolean}
  8591. */
  8592. _shouldGroup: function(e, target) {
  8593. var activeObject = this.getActiveObject();
  8594. return e.shiftKey &&
  8595. (this.getActiveGroup() || (activeObject && activeObject !== target))
  8596. && this.selection;
  8597. },
  8598. /**
  8599. * @private
  8600. * @param {Event} e Event object
  8601. * @param {fabric.Object} target
  8602. */
  8603. _handleGrouping: function (e, target) {
  8604. if (target === this.getActiveGroup()) {
  8605. // if it's a group, find target again, this time skipping group
  8606. target = this.findTarget(e, true);
  8607. // if even object is not found, bail out
  8608. if (!target || target.isType('group')) {
  8609. return;
  8610. }
  8611. }
  8612. if (this.getActiveGroup()) {
  8613. this._updateActiveGroup(target, e);
  8614. }
  8615. else {
  8616. this._createActiveGroup(target, e);
  8617. }
  8618. if (this._activeGroup) {
  8619. this._activeGroup.saveCoords();
  8620. }
  8621. },
  8622. /**
  8623. * @private
  8624. */
  8625. _updateActiveGroup: function(target, e) {
  8626. var activeGroup = this.getActiveGroup();
  8627. if (activeGroup.contains(target)) {
  8628. activeGroup.removeWithUpdate(target);
  8629. this._resetObjectTransform(activeGroup);
  8630. target.set('active', false);
  8631. if (activeGroup.size() === 1) {
  8632. // remove group alltogether if after removal it only contains 1 object
  8633. this.discardActiveGroup(e);
  8634. // activate last remaining object
  8635. this.setActiveObject(activeGroup.item(0));
  8636. return;
  8637. }
  8638. }
  8639. else {
  8640. activeGroup.addWithUpdate(target);
  8641. this._resetObjectTransform(activeGroup);
  8642. }
  8643. this.fire('selection:created', { target: activeGroup, e: e });
  8644. activeGroup.set('active', true);
  8645. },
  8646. /**
  8647. * @private
  8648. */
  8649. _createActiveGroup: function(target, e) {
  8650. if (this._activeObject && target !== this._activeObject) {
  8651. var group = this._createGroup(target);
  8652. group.addWithUpdate();
  8653. this.setActiveGroup(group);
  8654. this._activeObject = null;
  8655. this.fire('selection:created', { target: group, e: e });
  8656. }
  8657. target.set('active', true);
  8658. },
  8659. /**
  8660. * @private
  8661. * @param {Object} target
  8662. */
  8663. _createGroup: function(target) {
  8664. var objects = this.getObjects(),
  8665. isActiveLower = objects.indexOf(this._activeObject) < objects.indexOf(target),
  8666. groupObjects = isActiveLower
  8667. ? [ this._activeObject, target ]
  8668. : [ target, this._activeObject ];
  8669. return new fabric.Group(groupObjects, {
  8670. canvas: this
  8671. });
  8672. },
  8673. /**
  8674. * @private
  8675. * @param {Event} e mouse event
  8676. */
  8677. _groupSelectedObjects: function (e) {
  8678. var group = this._collectObjects();
  8679. // do not create group for 1 element only
  8680. if (group.length === 1) {
  8681. this.setActiveObject(group[0], e);
  8682. }
  8683. else if (group.length > 1) {
  8684. group = new fabric.Group(group.reverse(), {
  8685. canvas: this
  8686. });
  8687. group.addWithUpdate();
  8688. this.setActiveGroup(group, e);
  8689. group.saveCoords();
  8690. this.fire('selection:created', { target: group });
  8691. this.renderAll();
  8692. }
  8693. },
  8694. /**
  8695. * @private
  8696. */
  8697. _collectObjects: function() {
  8698. var group = [ ],
  8699. currentObject,
  8700. x1 = this._groupSelector.ex,
  8701. y1 = this._groupSelector.ey,
  8702. x2 = x1 + this._groupSelector.left,
  8703. y2 = y1 + this._groupSelector.top,
  8704. selectionX1Y1 = new fabric.Point(min(x1, x2), min(y1, y2)),
  8705. selectionX2Y2 = new fabric.Point(max(x1, x2), max(y1, y2)),
  8706. isClick = x1 === x2 && y1 === y2;
  8707. for (var i = this._objects.length; i--; ) {
  8708. currentObject = this._objects[i];
  8709. if (!currentObject || !currentObject.selectable || !currentObject.visible) {
  8710. continue;
  8711. }
  8712. if (currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2) ||
  8713. currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2) ||
  8714. currentObject.containsPoint(selectionX1Y1) ||
  8715. currentObject.containsPoint(selectionX2Y2)
  8716. ) {
  8717. currentObject.set('active', true);
  8718. group.push(currentObject);
  8719. // only add one object if it's a click
  8720. if (isClick) {
  8721. break;
  8722. }
  8723. }
  8724. }
  8725. return group;
  8726. },
  8727. /**
  8728. * @private
  8729. */
  8730. _maybeGroupObjects: function(e) {
  8731. if (this.selection && this._groupSelector) {
  8732. this._groupSelectedObjects(e);
  8733. }
  8734. var activeGroup = this.getActiveGroup();
  8735. if (activeGroup) {
  8736. activeGroup.setObjectsCoords().setCoords();
  8737. activeGroup.isMoving = false;
  8738. this.setCursor(this.defaultCursor);
  8739. }
  8740. // clear selection and current transformation
  8741. this._groupSelector = null;
  8742. this._currentTransform = null;
  8743. }
  8744. });
  8745. })();
  8746. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  8747. /**
  8748. * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately
  8749. * @param {Object} [options] Options object
  8750. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  8751. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  8752. * @param {Number} [options.multiplier=1] Multiplier to scale by
  8753. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  8754. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  8755. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  8756. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  8757. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  8758. * @see {@link http://jsfiddle.net/fabricjs/NfZVb/|jsFiddle demo}
  8759. * @example <caption>Generate jpeg dataURL with lower quality</caption>
  8760. * var dataURL = canvas.toDataURL({
  8761. * format: 'jpeg',
  8762. * quality: 0.8
  8763. * });
  8764. * @example <caption>Generate cropped png dataURL (clipping of canvas)</caption>
  8765. * var dataURL = canvas.toDataURL({
  8766. * format: 'png',
  8767. * left: 100,
  8768. * top: 100,
  8769. * width: 200,
  8770. * height: 200
  8771. * });
  8772. * @example <caption>Generate double scaled png dataURL</caption>
  8773. * var dataURL = canvas.toDataURL({
  8774. * format: 'png',
  8775. * multiplier: 2
  8776. * });
  8777. */
  8778. toDataURL: function (options) {
  8779. options || (options = { });
  8780. var format = options.format || 'png',
  8781. quality = options.quality || 1,
  8782. multiplier = options.multiplier || 1,
  8783. cropping = {
  8784. left: options.left,
  8785. top: options.top,
  8786. width: options.width,
  8787. height: options.height
  8788. };
  8789. if (multiplier !== 1) {
  8790. return this.__toDataURLWithMultiplier(format, quality, cropping, multiplier);
  8791. }
  8792. else {
  8793. return this.__toDataURL(format, quality, cropping);
  8794. }
  8795. },
  8796. /**
  8797. * @private
  8798. */
  8799. __toDataURL: function(format, quality, cropping) {
  8800. this.renderAll(true);
  8801. var canvasEl = this.upperCanvasEl || this.lowerCanvasEl,
  8802. croppedCanvasEl = this.__getCroppedCanvas(canvasEl, cropping);
  8803. // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
  8804. if (format === 'jpg') {
  8805. format = 'jpeg';
  8806. }
  8807. var data = (fabric.StaticCanvas.supports('toDataURLWithQuality'))
  8808. ? (croppedCanvasEl || canvasEl).toDataURL('image/' + format, quality)
  8809. : (croppedCanvasEl || canvasEl).toDataURL('image/' + format);
  8810. this.contextTop && this.clearContext(this.contextTop);
  8811. this.renderAll();
  8812. if (croppedCanvasEl) {
  8813. croppedCanvasEl = null;
  8814. }
  8815. return data;
  8816. },
  8817. /**
  8818. * @private
  8819. */
  8820. __getCroppedCanvas: function(canvasEl, cropping) {
  8821. var croppedCanvasEl,
  8822. croppedCtx,
  8823. shouldCrop = 'left' in cropping ||
  8824. 'top' in cropping ||
  8825. 'width' in cropping ||
  8826. 'height' in cropping;
  8827. if (shouldCrop) {
  8828. croppedCanvasEl = fabric.util.createCanvasElement();
  8829. croppedCtx = croppedCanvasEl.getContext('2d');
  8830. croppedCanvasEl.width = cropping.width || this.width;
  8831. croppedCanvasEl.height = cropping.height || this.height;
  8832. croppedCtx.drawImage(canvasEl, -cropping.left || 0, -cropping.top || 0);
  8833. }
  8834. return croppedCanvasEl;
  8835. },
  8836. /**
  8837. * @private
  8838. */
  8839. __toDataURLWithMultiplier: function(format, quality, cropping, multiplier) {
  8840. var origWidth = this.getWidth(),
  8841. origHeight = this.getHeight(),
  8842. scaledWidth = origWidth * multiplier,
  8843. scaledHeight = origHeight * multiplier,
  8844. activeObject = this.getActiveObject(),
  8845. activeGroup = this.getActiveGroup(),
  8846. ctx = this.contextTop || this.contextContainer;
  8847. if (multiplier > 1) {
  8848. this.setWidth(scaledWidth).setHeight(scaledHeight);
  8849. }
  8850. ctx.scale(multiplier, multiplier);
  8851. if (cropping.left) {
  8852. cropping.left *= multiplier;
  8853. }
  8854. if (cropping.top) {
  8855. cropping.top *= multiplier;
  8856. }
  8857. if (cropping.width) {
  8858. cropping.width *= multiplier;
  8859. }
  8860. else if (multiplier < 1) {
  8861. cropping.width = scaledWidth;
  8862. }
  8863. if (cropping.height) {
  8864. cropping.height *= multiplier;
  8865. }
  8866. else if (multiplier < 1) {
  8867. cropping.height = scaledHeight;
  8868. }
  8869. if (activeGroup) {
  8870. // not removing group due to complications with restoring it with correct state afterwords
  8871. this._tempRemoveBordersControlsFromGroup(activeGroup);
  8872. }
  8873. else if (activeObject && this.deactivateAll) {
  8874. this.deactivateAll();
  8875. }
  8876. this.renderAll(true);
  8877. var data = this.__toDataURL(format, quality, cropping);
  8878. // restoring width, height for `renderAll` to draw
  8879. // background properly (while context is scaled)
  8880. this.width = origWidth;
  8881. this.height = origHeight;
  8882. ctx.scale(1 / multiplier, 1 / multiplier);
  8883. this.setWidth(origWidth).setHeight(origHeight);
  8884. if (activeGroup) {
  8885. this._restoreBordersControlsOnGroup(activeGroup);
  8886. }
  8887. else if (activeObject && this.setActiveObject) {
  8888. this.setActiveObject(activeObject);
  8889. }
  8890. this.contextTop && this.clearContext(this.contextTop);
  8891. this.renderAll();
  8892. return data;
  8893. },
  8894. /**
  8895. * Exports canvas element to a dataurl image (allowing to change image size via multiplier).
  8896. * @deprecated since 1.0.13
  8897. * @param {String} format (png|jpeg)
  8898. * @param {Number} multiplier
  8899. * @param {Number} quality (0..1)
  8900. * @return {String}
  8901. */
  8902. toDataURLWithMultiplier: function (format, multiplier, quality) {
  8903. return this.toDataURL({
  8904. format: format,
  8905. multiplier: multiplier,
  8906. quality: quality
  8907. });
  8908. },
  8909. /**
  8910. * @private
  8911. */
  8912. _tempRemoveBordersControlsFromGroup: function(group) {
  8913. group.origHasControls = group.hasControls;
  8914. group.origBorderColor = group.borderColor;
  8915. group.hasControls = true;
  8916. group.borderColor = 'rgba(0,0,0,0)';
  8917. group.forEachObject(function(o) {
  8918. o.origBorderColor = o.borderColor;
  8919. o.borderColor = 'rgba(0,0,0,0)';
  8920. });
  8921. },
  8922. /**
  8923. * @private
  8924. */
  8925. _restoreBordersControlsOnGroup: function(group) {
  8926. group.hideControls = group.origHideControls;
  8927. group.borderColor = group.origBorderColor;
  8928. group.forEachObject(function(o) {
  8929. o.borderColor = o.origBorderColor;
  8930. delete o.origBorderColor;
  8931. });
  8932. }
  8933. });
  8934. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  8935. /**
  8936. * Populates canvas with data from the specified dataless JSON.
  8937. * JSON format must conform to the one of {@link fabric.Canvas#toDatalessJSON}
  8938. * @deprecated since 1.2.2
  8939. * @param {String|Object} json JSON string or object
  8940. * @param {Function} callback Callback, invoked when json is parsed
  8941. * and corresponding objects (e.g: {@link fabric.Image})
  8942. * are initialized
  8943. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  8944. * @return {fabric.Canvas} instance
  8945. * @chainable
  8946. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#deserialization}
  8947. */
  8948. loadFromDatalessJSON: function (json, callback, reviver) {
  8949. return this.loadFromJSON(json, callback, reviver);
  8950. },
  8951. /**
  8952. * Populates canvas with data from the specified JSON.
  8953. * JSON format must conform to the one of {@link fabric.Canvas#toJSON}
  8954. * @param {String|Object} json JSON string or object
  8955. * @param {Function} callback Callback, invoked when json is parsed
  8956. * and corresponding objects (e.g: {@link fabric.Image})
  8957. * are initialized
  8958. * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created.
  8959. * @return {fabric.Canvas} instance
  8960. * @chainable
  8961. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#deserialization}
  8962. * @see {@link http://jsfiddle.net/fabricjs/fmgXt/|jsFiddle demo}
  8963. * @example <caption>loadFromJSON</caption>
  8964. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas));
  8965. * @example <caption>loadFromJSON with reviver</caption>
  8966. * canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), function(o, object) {
  8967. * // `o` = json object
  8968. * // `object` = fabric.Object instance
  8969. * // ... do some stuff ...
  8970. * });
  8971. */
  8972. loadFromJSON: function (json, callback, reviver) {
  8973. if (!json) {
  8974. return;
  8975. }
  8976. // serialize if it wasn't already
  8977. var serialized = (typeof json === 'string')
  8978. ? JSON.parse(json)
  8979. : json;
  8980. this.clear();
  8981. var _this = this;
  8982. this._enlivenObjects(serialized.objects, function () {
  8983. _this._setBgOverlay(serialized, callback);
  8984. }, reviver);
  8985. return this;
  8986. },
  8987. /**
  8988. * @private
  8989. * @param {Object} serialized Object with background and overlay information
  8990. * @param {Function} callback Invoked after all background and overlay images/patterns loaded
  8991. */
  8992. _setBgOverlay: function(serialized, callback) {
  8993. var _this = this,
  8994. loaded = {
  8995. backgroundColor: false,
  8996. overlayColor: false,
  8997. backgroundImage: false,
  8998. overlayImage: false
  8999. };
  9000. if (!serialized.backgroundImage && !serialized.overlayImage && !serialized.background && !serialized.overlay) {
  9001. callback && callback();
  9002. return;
  9003. }
  9004. var cbIfLoaded = function () {
  9005. if (loaded.backgroundImage && loaded.overlayImage && loaded.backgroundColor && loaded.overlayColor) {
  9006. _this.renderAll();
  9007. callback && callback();
  9008. }
  9009. };
  9010. this.__setBgOverlay('backgroundImage', serialized.backgroundImage, loaded, cbIfLoaded);
  9011. this.__setBgOverlay('overlayImage', serialized.overlayImage, loaded, cbIfLoaded);
  9012. this.__setBgOverlay('backgroundColor', serialized.background, loaded, cbIfLoaded);
  9013. this.__setBgOverlay('overlayColor', serialized.overlay, loaded, cbIfLoaded);
  9014. cbIfLoaded();
  9015. },
  9016. /**
  9017. * @private
  9018. * @param {String} property Property to set (backgroundImage, overlayImage, backgroundColor, overlayColor)
  9019. * @param {(Object|String)} value Value to set
  9020. * @param {Object} loaded Set loaded property to true if property is set
  9021. * @param {Object} callback Callback function to invoke after property is set
  9022. */
  9023. __setBgOverlay: function(property, value, loaded, callback) {
  9024. var _this = this;
  9025. if (!value) {
  9026. loaded[property] = true;
  9027. return;
  9028. }
  9029. if (property === 'backgroundImage' || property === 'overlayImage') {
  9030. fabric.Image.fromObject(value, function(img) {
  9031. _this[property] = img;
  9032. loaded[property] = true;
  9033. callback && callback();
  9034. });
  9035. }
  9036. else {
  9037. this['set' + fabric.util.string.capitalize(property, true)](value, function() {
  9038. loaded[property] = true;
  9039. callback && callback();
  9040. });
  9041. }
  9042. },
  9043. /**
  9044. * @private
  9045. * @param {Array} objects
  9046. * @param {Function} callback
  9047. * @param {Function} [reviver]
  9048. */
  9049. _enlivenObjects: function (objects, callback, reviver) {
  9050. var _this = this;
  9051. if (!objects || objects.length === 0) {
  9052. callback && callback();
  9053. return;
  9054. }
  9055. var renderOnAddRemove = this.renderOnAddRemove;
  9056. this.renderOnAddRemove = false;
  9057. fabric.util.enlivenObjects(objects, function(enlivenedObjects) {
  9058. enlivenedObjects.forEach(function(obj, index) {
  9059. _this.insertAt(obj, index, true);
  9060. });
  9061. _this.renderOnAddRemove = renderOnAddRemove;
  9062. callback && callback();
  9063. }, null, reviver);
  9064. },
  9065. /**
  9066. * @private
  9067. * @param {String} format
  9068. * @param {Function} callback
  9069. */
  9070. _toDataURL: function (format, callback) {
  9071. this.clone(function (clone) {
  9072. callback(clone.toDataURL(format));
  9073. });
  9074. },
  9075. /**
  9076. * @private
  9077. * @param {String} format
  9078. * @param {Number} multiplier
  9079. * @param {Function} callback
  9080. */
  9081. _toDataURLWithMultiplier: function (format, multiplier, callback) {
  9082. this.clone(function (clone) {
  9083. callback(clone.toDataURLWithMultiplier(format, multiplier));
  9084. });
  9085. },
  9086. /**
  9087. * Clones canvas instance
  9088. * @param {Object} [callback] Receives cloned instance as a first argument
  9089. * @param {Array} [properties] Array of properties to include in the cloned canvas and children
  9090. */
  9091. clone: function (callback, properties) {
  9092. var data = JSON.stringify(this.toJSON(properties));
  9093. this.cloneWithoutData(function(clone) {
  9094. clone.loadFromJSON(data, function() {
  9095. callback && callback(clone);
  9096. });
  9097. });
  9098. },
  9099. /**
  9100. * Clones canvas instance without cloning existing data.
  9101. * This essentially copies canvas dimensions, clipping properties, etc.
  9102. * but leaves data empty (so that you can populate it with your own)
  9103. * @param {Object} [callback] Receives cloned instance as a first argument
  9104. */
  9105. cloneWithoutData: function(callback) {
  9106. var el = fabric.document.createElement('canvas');
  9107. el.width = this.getWidth();
  9108. el.height = this.getHeight();
  9109. var clone = new fabric.Canvas(el);
  9110. clone.clipTo = this.clipTo;
  9111. if (this.backgroundImage) {
  9112. clone.setBackgroundImage(this.backgroundImage.src, function() {
  9113. clone.renderAll();
  9114. callback && callback(clone);
  9115. });
  9116. clone.backgroundImageOpacity = this.backgroundImageOpacity;
  9117. clone.backgroundImageStretch = this.backgroundImageStretch;
  9118. }
  9119. else {
  9120. callback && callback(clone);
  9121. }
  9122. }
  9123. });
  9124. (function(global) {
  9125. 'use strict';
  9126. var fabric = global.fabric || (global.fabric = { }),
  9127. extend = fabric.util.object.extend,
  9128. toFixed = fabric.util.toFixed,
  9129. capitalize = fabric.util.string.capitalize,
  9130. degreesToRadians = fabric.util.degreesToRadians,
  9131. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  9132. if (fabric.Object) {
  9133. return;
  9134. }
  9135. /**
  9136. * Root object class from which all 2d shape classes inherit from
  9137. * @class fabric.Object
  9138. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#objects}
  9139. * @see {@link fabric.Object#initialize} for constructor definition
  9140. *
  9141. * @fires added
  9142. * @fires removed
  9143. *
  9144. * @fires selected
  9145. * @fires modified
  9146. * @fires rotating
  9147. * @fires scaling
  9148. * @fires moving
  9149. *
  9150. * @fires mousedown
  9151. * @fires mouseup
  9152. */
  9153. fabric.Object = fabric.util.createClass(/** @lends fabric.Object.prototype */ {
  9154. /**
  9155. * Retrieves object's {@link fabric.Object#clipTo|clipping function}
  9156. * @method getClipTo
  9157. * @memberOf fabric.Object.prototype
  9158. * @return {Function}
  9159. */
  9160. /**
  9161. * Sets object's {@link fabric.Object#clipTo|clipping function}
  9162. * @method setClipTo
  9163. * @memberOf fabric.Object.prototype
  9164. * @param {Function} clipTo Clipping function
  9165. * @return {fabric.Object} thisArg
  9166. * @chainable
  9167. */
  9168. /**
  9169. * Retrieves object's {@link fabric.Object#transformMatrix|transformMatrix}
  9170. * @method getTransformMatrix
  9171. * @memberOf fabric.Object.prototype
  9172. * @return {Array} transformMatrix
  9173. */
  9174. /**
  9175. * Sets object's {@link fabric.Object#transformMatrix|transformMatrix}
  9176. * @method setTransformMatrix
  9177. * @memberOf fabric.Object.prototype
  9178. * @param {Array} transformMatrix
  9179. * @return {fabric.Object} thisArg
  9180. * @chainable
  9181. */
  9182. /**
  9183. * Retrieves object's {@link fabric.Object#visible|visible} state
  9184. * @method getVisible
  9185. * @memberOf fabric.Object.prototype
  9186. * @return {Boolean} True if visible
  9187. */
  9188. /**
  9189. * Sets object's {@link fabric.Object#visible|visible} state
  9190. * @method setVisible
  9191. * @memberOf fabric.Object.prototype
  9192. * @param {Boolean} value visible value
  9193. * @return {fabric.Object} thisArg
  9194. * @chainable
  9195. */
  9196. /**
  9197. * Retrieves object's {@link fabric.Object#shadow|shadow}
  9198. * @method getShadow
  9199. * @memberOf fabric.Object.prototype
  9200. * @return {Object} Shadow instance
  9201. */
  9202. /**
  9203. * Retrieves object's {@link fabric.Object#stroke|stroke}
  9204. * @method getStroke
  9205. * @memberOf fabric.Object.prototype
  9206. * @return {String} stroke value
  9207. */
  9208. /**
  9209. * Sets object's {@link fabric.Object#stroke|stroke}
  9210. * @method setStroke
  9211. * @memberOf fabric.Object.prototype
  9212. * @param {String} value stroke value
  9213. * @return {fabric.Object} thisArg
  9214. * @chainable
  9215. */
  9216. /**
  9217. * Retrieves object's {@link fabric.Object#strokeWidth|strokeWidth}
  9218. * @method getStrokeWidth
  9219. * @memberOf fabric.Object.prototype
  9220. * @return {Number} strokeWidth value
  9221. */
  9222. /**
  9223. * Sets object's {@link fabric.Object#strokeWidth|strokeWidth}
  9224. * @method setStrokeWidth
  9225. * @memberOf fabric.Object.prototype
  9226. * @param {Number} value strokeWidth value
  9227. * @return {fabric.Object} thisArg
  9228. * @chainable
  9229. */
  9230. /**
  9231. * Retrieves object's {@link fabric.Object#originX|originX}
  9232. * @method getOriginX
  9233. * @memberOf fabric.Object.prototype
  9234. * @return {String} originX value
  9235. */
  9236. /**
  9237. * Sets object's {@link fabric.Object#originX|originX}
  9238. * @method setOriginX
  9239. * @memberOf fabric.Object.prototype
  9240. * @param {String} value originX value
  9241. * @return {fabric.Object} thisArg
  9242. * @chainable
  9243. */
  9244. /**
  9245. * Retrieves object's {@link fabric.Object#originY|originY}
  9246. * @method getOriginY
  9247. * @memberOf fabric.Object.prototype
  9248. * @return {String} originY value
  9249. */
  9250. /**
  9251. * Sets object's {@link fabric.Object#originY|originY}
  9252. * @method setOriginY
  9253. * @memberOf fabric.Object.prototype
  9254. * @param {String} value originY value
  9255. * @return {fabric.Object} thisArg
  9256. * @chainable
  9257. */
  9258. /**
  9259. * Retrieves object's {@link fabric.Object#fill|fill}
  9260. * @method getFill
  9261. * @memberOf fabric.Object.prototype
  9262. * @return {String} Fill value
  9263. */
  9264. /**
  9265. * Sets object's {@link fabric.Object#fill|fill}
  9266. * @method setFill
  9267. * @memberOf fabric.Object.prototype
  9268. * @param {String} value Fill value
  9269. * @return {fabric.Object} thisArg
  9270. * @chainable
  9271. */
  9272. /**
  9273. * Retrieves object's {@link fabric.Object#opacity|opacity}
  9274. * @method getOpacity
  9275. * @memberOf fabric.Object.prototype
  9276. * @return {Number} Opacity value (0-1)
  9277. */
  9278. /**
  9279. * Sets object's {@link fabric.Object#opacity|opacity}
  9280. * @method setOpacity
  9281. * @memberOf fabric.Object.prototype
  9282. * @param {Number} value Opacity value (0-1)
  9283. * @return {fabric.Object} thisArg
  9284. * @chainable
  9285. */
  9286. /**
  9287. * Retrieves object's {@link fabric.Object#angle|angle} (in degrees)
  9288. * @method getAngle
  9289. * @memberOf fabric.Object.prototype
  9290. * @return {Number}
  9291. */
  9292. /**
  9293. * Retrieves object's {@link fabric.Object#top|top position}
  9294. * @method getTop
  9295. * @memberOf fabric.Object.prototype
  9296. * @return {Number} Top value (in pixels)
  9297. */
  9298. /**
  9299. * Sets object's {@link fabric.Object#top|top position}
  9300. * @method setTop
  9301. * @memberOf fabric.Object.prototype
  9302. * @param {Number} value Top value (in pixels)
  9303. * @return {fabric.Object} thisArg
  9304. * @chainable
  9305. */
  9306. /**
  9307. * Retrieves object's {@link fabric.Object#left|left position}
  9308. * @method getLeft
  9309. * @memberOf fabric.Object.prototype
  9310. * @return {Number} Left value (in pixels)
  9311. */
  9312. /**
  9313. * Sets object's {@link fabric.Object#left|left position}
  9314. * @method setLeft
  9315. * @memberOf fabric.Object.prototype
  9316. * @param {Number} value Left value (in pixels)
  9317. * @return {fabric.Object} thisArg
  9318. * @chainable
  9319. */
  9320. /**
  9321. * Retrieves object's {@link fabric.Object#scaleX|scaleX} value
  9322. * @method getScaleX
  9323. * @memberOf fabric.Object.prototype
  9324. * @return {Number} scaleX value
  9325. */
  9326. /**
  9327. * Sets object's {@link fabric.Object#scaleX|scaleX} value
  9328. * @method setScaleX
  9329. * @memberOf fabric.Object.prototype
  9330. * @param {Number} value scaleX value
  9331. * @return {fabric.Object} thisArg
  9332. * @chainable
  9333. */
  9334. /**
  9335. * Retrieves object's {@link fabric.Object#scaleY|scaleY} value
  9336. * @method getScaleY
  9337. * @memberOf fabric.Object.prototype
  9338. * @return {Number} scaleY value
  9339. */
  9340. /**
  9341. * Sets object's {@link fabric.Object#scaleY|scaleY} value
  9342. * @method setScaleY
  9343. * @memberOf fabric.Object.prototype
  9344. * @param {Number} value scaleY value
  9345. * @return {fabric.Object} thisArg
  9346. * @chainable
  9347. */
  9348. /**
  9349. * Retrieves object's {@link fabric.Object#flipX|flipX} value
  9350. * @method getFlipX
  9351. * @memberOf fabric.Object.prototype
  9352. * @return {Boolean} flipX value
  9353. */
  9354. /**
  9355. * Sets object's {@link fabric.Object#flipX|flipX} value
  9356. * @method setFlipX
  9357. * @memberOf fabric.Object.prototype
  9358. * @param {Boolean} value flipX value
  9359. * @return {fabric.Object} thisArg
  9360. * @chainable
  9361. */
  9362. /**
  9363. * Retrieves object's {@link fabric.Object#flipY|flipY} value
  9364. * @method getFlipY
  9365. * @memberOf fabric.Object.prototype
  9366. * @return {Boolean} flipY value
  9367. */
  9368. /**
  9369. * Sets object's {@link fabric.Object#flipY|flipY} value
  9370. * @method setFlipY
  9371. * @memberOf fabric.Object.prototype
  9372. * @param {Boolean} value flipY value
  9373. * @return {fabric.Object} thisArg
  9374. * @chainable
  9375. */
  9376. /**
  9377. * Type of an object (rect, circle, path, etc.).
  9378. * Note that this property is meant to be read-only and not meant to be modified.
  9379. * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly.
  9380. * @type String
  9381. * @default
  9382. */
  9383. type: 'object',
  9384. /**
  9385. * Horizontal origin of transformation of an object (one of "left", "right", "center")
  9386. * See http://jsfiddle.net/1ow02gea/40/ on how originX/originY affect objects in groups
  9387. * @type String
  9388. * @default
  9389. */
  9390. originX: 'left',
  9391. /**
  9392. * Vertical origin of transformation of an object (one of "top", "bottom", "center")
  9393. * See http://jsfiddle.net/1ow02gea/40/ on how originX/originY affect objects in groups
  9394. * @type String
  9395. * @default
  9396. */
  9397. originY: 'top',
  9398. /**
  9399. * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom}
  9400. * @type Number
  9401. * @default
  9402. */
  9403. top: 0,
  9404. /**
  9405. * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right}
  9406. * @type Number
  9407. * @default
  9408. */
  9409. left: 0,
  9410. /**
  9411. * Object width
  9412. * @type Number
  9413. * @default
  9414. */
  9415. width: 0,
  9416. /**
  9417. * Object height
  9418. * @type Number
  9419. * @default
  9420. */
  9421. height: 0,
  9422. /**
  9423. * Object scale factor (horizontal)
  9424. * @type Number
  9425. * @default
  9426. */
  9427. scaleX: 1,
  9428. /**
  9429. * Object scale factor (vertical)
  9430. * @type Number
  9431. * @default
  9432. */
  9433. scaleY: 1,
  9434. /**
  9435. * When true, an object is rendered as flipped horizontally
  9436. * @type Boolean
  9437. * @default
  9438. */
  9439. flipX: false,
  9440. /**
  9441. * When true, an object is rendered as flipped vertically
  9442. * @type Boolean
  9443. * @default
  9444. */
  9445. flipY: false,
  9446. /**
  9447. * Opacity of an object
  9448. * @type Number
  9449. * @default
  9450. */
  9451. opacity: 1,
  9452. /**
  9453. * Angle of rotation of an object (in degrees)
  9454. * @type Number
  9455. * @default
  9456. */
  9457. angle: 0,
  9458. /**
  9459. * Size of object's controlling corners (in pixels)
  9460. * @type Number
  9461. * @default
  9462. */
  9463. cornerSize: 12,
  9464. /**
  9465. * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill)
  9466. * @type Boolean
  9467. * @default
  9468. */
  9469. transparentCorners: true,
  9470. /**
  9471. * Default cursor value used when hovering over this object on canvas
  9472. * @type String
  9473. * @default
  9474. */
  9475. hoverCursor: null,
  9476. /**
  9477. * Padding between object and its controlling borders (in pixels)
  9478. * @type Number
  9479. * @default
  9480. */
  9481. padding: 0,
  9482. /**
  9483. * Color of controlling borders of an object (when it's active)
  9484. * @type String
  9485. * @default
  9486. */
  9487. borderColor: 'rgba(102,153,255,0.75)',
  9488. /**
  9489. * Color of controlling corners of an object (when it's active)
  9490. * @type String
  9491. * @default
  9492. */
  9493. cornerColor: 'rgba(102,153,255,0.5)',
  9494. /**
  9495. * When true, this object will use center point as the origin of transformation
  9496. * when being scaled via the controls.
  9497. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  9498. * @since 1.3.4
  9499. * @type Boolean
  9500. * @default
  9501. */
  9502. centeredScaling: false,
  9503. /**
  9504. * When true, this object will use center point as the origin of transformation
  9505. * when being rotated via the controls.
  9506. * <b>Backwards incompatibility note:</b> This property replaces "centerTransform" (Boolean).
  9507. * @since 1.3.4
  9508. * @type Boolean
  9509. * @default
  9510. */
  9511. centeredRotation: true,
  9512. /**
  9513. * Color of object's fill
  9514. * @type String
  9515. * @default
  9516. */
  9517. fill: 'rgb(0,0,0)',
  9518. /**
  9519. * Fill rule used to fill an object
  9520. * accepted values are nonzero, evenodd
  9521. * <b>Backwards incompatibility note:</b> This property was used for setting globalCompositeOperation until v1.4.12 (use `fabric.Object#globalCompositeOperation` instead)
  9522. * @type String
  9523. * @default
  9524. */
  9525. fillRule: 'nonzero',
  9526. /**
  9527. * Composite rule used for canvas globalCompositeOperation
  9528. * @type String
  9529. * @default
  9530. */
  9531. globalCompositeOperation: 'source-over',
  9532. /**
  9533. * Background color of an object. Only works with text objects at the moment.
  9534. * @type String
  9535. * @default
  9536. */
  9537. backgroundColor: '',
  9538. /**
  9539. * When defined, an object is rendered via stroke and this property specifies its color
  9540. * @type String
  9541. * @default
  9542. */
  9543. stroke: null,
  9544. /**
  9545. * Width of a stroke used to render this object
  9546. * @type Number
  9547. * @default
  9548. */
  9549. strokeWidth: 1,
  9550. /**
  9551. * Array specifying dash pattern of an object's stroke (stroke must be defined)
  9552. * @type Array
  9553. */
  9554. strokeDashArray: null,
  9555. /**
  9556. * Line endings style of an object's stroke (one of "butt", "round", "square")
  9557. * @type String
  9558. * @default
  9559. */
  9560. strokeLineCap: 'butt',
  9561. /**
  9562. * Corner style of an object's stroke (one of "bevil", "round", "miter")
  9563. * @type String
  9564. * @default
  9565. */
  9566. strokeLineJoin: 'miter',
  9567. /**
  9568. * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke
  9569. * @type Number
  9570. * @default
  9571. */
  9572. strokeMiterLimit: 10,
  9573. /**
  9574. * Shadow object representing shadow of this shape
  9575. * @type fabric.Shadow
  9576. * @default
  9577. */
  9578. shadow: null,
  9579. /**
  9580. * Opacity of object's controlling borders when object is active and moving
  9581. * @type Number
  9582. * @default
  9583. */
  9584. borderOpacityWhenMoving: 0.4,
  9585. /**
  9586. * Scale factor of object's controlling borders
  9587. * @type Number
  9588. * @default
  9589. */
  9590. borderScaleFactor: 1,
  9591. /**
  9592. * Transform matrix (similar to SVG's transform matrix)
  9593. * @type Array
  9594. */
  9595. transformMatrix: null,
  9596. /**
  9597. * Minimum allowed scale value of an object
  9598. * @type Number
  9599. * @default
  9600. */
  9601. minScaleLimit: 0.01,
  9602. /**
  9603. * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection).
  9604. * But events still fire on it.
  9605. * @type Boolean
  9606. * @default
  9607. */
  9608. selectable: true,
  9609. /**
  9610. * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4
  9611. * @type Boolean
  9612. * @default
  9613. */
  9614. evented: true,
  9615. /**
  9616. * When set to `false`, an object is not rendered on canvas
  9617. * @type Boolean
  9618. * @default
  9619. */
  9620. visible: true,
  9621. /**
  9622. * When set to `false`, object's controls are not displayed and can not be used to manipulate object
  9623. * @type Boolean
  9624. * @default
  9625. */
  9626. hasControls: true,
  9627. /**
  9628. * When set to `false`, object's controlling borders are not rendered
  9629. * @type Boolean
  9630. * @default
  9631. */
  9632. hasBorders: true,
  9633. /**
  9634. * When set to `false`, object's controlling rotating point will not be visible or selectable
  9635. * @type Boolean
  9636. * @default
  9637. */
  9638. hasRotatingPoint: true,
  9639. /**
  9640. * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`)
  9641. * @type Number
  9642. * @default
  9643. */
  9644. rotatingPointOffset: 40,
  9645. /**
  9646. * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box
  9647. * @type Boolean
  9648. * @default
  9649. */
  9650. perPixelTargetFind: false,
  9651. /**
  9652. * When `false`, default object's values are not included in its serialization
  9653. * @type Boolean
  9654. * @default
  9655. */
  9656. includeDefaultValues: true,
  9657. /**
  9658. * Function that determines clipping of an object (context is passed as a first argument)
  9659. * Note that context origin is at the object's center point (not left/top corner)
  9660. * @type Function
  9661. */
  9662. clipTo: null,
  9663. /**
  9664. * When `true`, object horizontal movement is locked
  9665. * @type Boolean
  9666. * @default
  9667. */
  9668. lockMovementX: false,
  9669. /**
  9670. * When `true`, object vertical movement is locked
  9671. * @type Boolean
  9672. * @default
  9673. */
  9674. lockMovementY: false,
  9675. /**
  9676. * When `true`, object rotation is locked
  9677. * @type Boolean
  9678. * @default
  9679. */
  9680. lockRotation: false,
  9681. /**
  9682. * When `true`, object horizontal scaling is locked
  9683. * @type Boolean
  9684. * @default
  9685. */
  9686. lockScalingX: false,
  9687. /**
  9688. * When `true`, object vertical scaling is locked
  9689. * @type Boolean
  9690. * @default
  9691. */
  9692. lockScalingY: false,
  9693. /**
  9694. * When `true`, object non-uniform scaling is locked
  9695. * @type Boolean
  9696. * @default
  9697. */
  9698. lockUniScaling: false,
  9699. /**
  9700. * When `true`, object cannot be flipped by scaling into negative values
  9701. * @type Boolean
  9702. * @default
  9703. */
  9704. lockScalingFlip: false,
  9705. /**
  9706. * List of properties to consider when checking if state
  9707. * of an object is changed (fabric.Object#hasStateChanged)
  9708. * as well as for history (undo/redo) purposes
  9709. * @type Array
  9710. */
  9711. stateProperties: (
  9712. 'top left width height scaleX scaleY flipX flipY originX originY transformMatrix ' +
  9713. 'stroke strokeWidth strokeDashArray strokeLineCap strokeLineJoin strokeMiterLimit ' +
  9714. 'angle opacity fill fillRule globalCompositeOperation shadow clipTo visible backgroundColor'
  9715. ).split(' '),
  9716. /**
  9717. * Constructor
  9718. * @param {Object} [options] Options object
  9719. */
  9720. initialize: function(options) {
  9721. if (options) {
  9722. this.setOptions(options);
  9723. }
  9724. },
  9725. /**
  9726. * @private
  9727. * @param {Object} [options] Options object
  9728. */
  9729. _initGradient: function(options) {
  9730. if (options.fill && options.fill.colorStops && !(options.fill instanceof fabric.Gradient)) {
  9731. this.set('fill', new fabric.Gradient(options.fill));
  9732. }
  9733. },
  9734. /**
  9735. * @private
  9736. * @param {Object} [options] Options object
  9737. */
  9738. _initPattern: function(options) {
  9739. if (options.fill && options.fill.source && !(options.fill instanceof fabric.Pattern)) {
  9740. this.set('fill', new fabric.Pattern(options.fill));
  9741. }
  9742. if (options.stroke && options.stroke.source && !(options.stroke instanceof fabric.Pattern)) {
  9743. this.set('stroke', new fabric.Pattern(options.stroke));
  9744. }
  9745. },
  9746. /**
  9747. * @private
  9748. * @param {Object} [options] Options object
  9749. */
  9750. _initClipping: function(options) {
  9751. if (!options.clipTo || typeof options.clipTo !== 'string') {
  9752. return;
  9753. }
  9754. var functionBody = fabric.util.getFunctionBody(options.clipTo);
  9755. if (typeof functionBody !== 'undefined') {
  9756. this.clipTo = new Function('ctx', functionBody);
  9757. }
  9758. },
  9759. /**
  9760. * Sets object's properties from options
  9761. * @param {Object} [options] Options object
  9762. */
  9763. setOptions: function(options) {
  9764. for (var prop in options) {
  9765. this.set(prop, options[prop]);
  9766. }
  9767. this._initGradient(options);
  9768. this._initPattern(options);
  9769. this._initClipping(options);
  9770. },
  9771. /**
  9772. * Transforms context when rendering an object
  9773. * @param {CanvasRenderingContext2D} ctx Context
  9774. * @param {Boolean} fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node
  9775. */
  9776. transform: function(ctx, fromLeft) {
  9777. var center = fromLeft ? this._getLeftTopCoords() : this.getCenterPoint();
  9778. ctx.translate(center.x, center.y);
  9779. ctx.rotate(degreesToRadians(this.angle));
  9780. ctx.scale(
  9781. this.scaleX * (this.flipX ? -1 : 1),
  9782. this.scaleY * (this.flipY ? -1 : 1)
  9783. );
  9784. },
  9785. /**
  9786. * Returns an object representation of an instance
  9787. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  9788. * @return {Object} Object representation of an instance
  9789. */
  9790. toObject: function(propertiesToInclude) {
  9791. var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  9792. object = {
  9793. type: this.type,
  9794. originX: this.originX,
  9795. originY: this.originY,
  9796. left: toFixed(this.left, NUM_FRACTION_DIGITS),
  9797. top: toFixed(this.top, NUM_FRACTION_DIGITS),
  9798. width: toFixed(this.width, NUM_FRACTION_DIGITS),
  9799. height: toFixed(this.height, NUM_FRACTION_DIGITS),
  9800. fill: (this.fill && this.fill.toObject) ? this.fill.toObject() : this.fill,
  9801. stroke: (this.stroke && this.stroke.toObject) ? this.stroke.toObject() : this.stroke,
  9802. strokeWidth: toFixed(this.strokeWidth, NUM_FRACTION_DIGITS),
  9803. strokeDashArray: this.strokeDashArray,
  9804. strokeLineCap: this.strokeLineCap,
  9805. strokeLineJoin: this.strokeLineJoin,
  9806. strokeMiterLimit: toFixed(this.strokeMiterLimit, NUM_FRACTION_DIGITS),
  9807. scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),
  9808. scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),
  9809. angle: toFixed(this.getAngle(), NUM_FRACTION_DIGITS),
  9810. flipX: this.flipX,
  9811. flipY: this.flipY,
  9812. opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),
  9813. shadow: (this.shadow && this.shadow.toObject) ? this.shadow.toObject() : this.shadow,
  9814. visible: this.visible,
  9815. clipTo: this.clipTo && String(this.clipTo),
  9816. backgroundColor: this.backgroundColor,
  9817. fillRule: this.fillRule,
  9818. globalCompositeOperation: this.globalCompositeOperation
  9819. };
  9820. if (!this.includeDefaultValues) {
  9821. object = this._removeDefaultValues(object);
  9822. }
  9823. fabric.util.populateWithProperties(this, object, propertiesToInclude);
  9824. return object;
  9825. },
  9826. /**
  9827. * Returns (dataless) object representation of an instance
  9828. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  9829. * @return {Object} Object representation of an instance
  9830. */
  9831. toDatalessObject: function(propertiesToInclude) {
  9832. // will be overwritten by subclasses
  9833. return this.toObject(propertiesToInclude);
  9834. },
  9835. /**
  9836. * @private
  9837. * @param {Object} object
  9838. */
  9839. _removeDefaultValues: function(object) {
  9840. var prototype = fabric.util.getKlass(object.type).prototype,
  9841. stateProperties = prototype.stateProperties;
  9842. stateProperties.forEach(function(prop) {
  9843. if (object[prop] === prototype[prop]) {
  9844. delete object[prop];
  9845. }
  9846. });
  9847. return object;
  9848. },
  9849. /**
  9850. * Returns a string representation of an instance
  9851. * @return {String}
  9852. */
  9853. toString: function() {
  9854. return '#<fabric.' + capitalize(this.type) + '>';
  9855. },
  9856. /**
  9857. * Basic getter
  9858. * @param {String} property Property name
  9859. * @return {Any} value of a property
  9860. */
  9861. get: function(property) {
  9862. return this[property];
  9863. },
  9864. /**
  9865. * @private
  9866. */
  9867. _setObject: function(obj) {
  9868. for (var prop in obj) {
  9869. this._set(prop, obj[prop]);
  9870. }
  9871. },
  9872. /**
  9873. * 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()`.
  9874. * @param {String|Object} key Property name or object (if object, iterate over the object properties)
  9875. * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one)
  9876. * @return {fabric.Object} thisArg
  9877. * @chainable
  9878. */
  9879. set: function(key, value) {
  9880. if (typeof key === 'object') {
  9881. this._setObject(key);
  9882. }
  9883. else {
  9884. if (typeof value === 'function' && key !== 'clipTo') {
  9885. this._set(key, value(this.get(key)));
  9886. }
  9887. else {
  9888. this._set(key, value);
  9889. }
  9890. }
  9891. return this;
  9892. },
  9893. /**
  9894. * @private
  9895. * @param {String} key
  9896. * @param {Any} value
  9897. * @return {fabric.Object} thisArg
  9898. */
  9899. _set: function(key, value) {
  9900. var shouldConstrainValue = (key === 'scaleX' || key === 'scaleY');
  9901. if (shouldConstrainValue) {
  9902. value = this._constrainScale(value);
  9903. }
  9904. if (key === 'scaleX' && value < 0) {
  9905. this.flipX = !this.flipX;
  9906. value *= -1;
  9907. }
  9908. else if (key === 'scaleY' && value < 0) {
  9909. this.flipY = !this.flipY;
  9910. value *= -1;
  9911. }
  9912. else if (key === 'width' || key === 'height') {
  9913. this.minScaleLimit = toFixed(Math.min(0.1, 1/Math.max(this.width, this.height)), 2);
  9914. }
  9915. else if (key === 'shadow' && value && !(value instanceof fabric.Shadow)) {
  9916. value = new fabric.Shadow(value);
  9917. }
  9918. this[key] = value;
  9919. return this;
  9920. },
  9921. /**
  9922. * Toggles specified property from `true` to `false` or from `false` to `true`
  9923. * @param {String} property Property to toggle
  9924. * @return {fabric.Object} thisArg
  9925. * @chainable
  9926. */
  9927. toggle: function(property) {
  9928. var value = this.get(property);
  9929. if (typeof value === 'boolean') {
  9930. this.set(property, !value);
  9931. }
  9932. return this;
  9933. },
  9934. /**
  9935. * Sets sourcePath of an object
  9936. * @param {String} value Value to set sourcePath to
  9937. * @return {fabric.Object} thisArg
  9938. * @chainable
  9939. */
  9940. setSourcePath: function(value) {
  9941. this.sourcePath = value;
  9942. return this;
  9943. },
  9944. /**
  9945. * Retrieves viewportTransform from Object's canvas if possible
  9946. * @method getViewportTransform
  9947. * @memberOf fabric.Object.prototype
  9948. * @return {Boolean} flipY value // TODO
  9949. */
  9950. getViewportTransform: function() {
  9951. if (this.canvas && this.canvas.viewportTransform) {
  9952. return this.canvas.viewportTransform;
  9953. }
  9954. return [1, 0, 0, 1, 0, 0];
  9955. },
  9956. /**
  9957. * Renders an object on a specified context
  9958. * @param {CanvasRenderingContext2D} ctx Context to render on
  9959. * @param {Boolean} [noTransform] When true, context is not transformed
  9960. */
  9961. render: function(ctx, noTransform) {
  9962. // do not render if width/height are zeros or object is not visible
  9963. if ((this.width === 0 && this.height === 0) || !this.visible) {
  9964. return;
  9965. }
  9966. ctx.save();
  9967. //setup fill rule for current object
  9968. this._setupCompositeOperation(ctx);
  9969. if (!noTransform) {
  9970. this.transform(ctx);
  9971. }
  9972. this._setStrokeStyles(ctx);
  9973. this._setFillStyles(ctx);
  9974. if (this.transformMatrix) {
  9975. ctx.transform.apply(ctx, this.transformMatrix);
  9976. }
  9977. this._setOpacity(ctx);
  9978. this._setShadow(ctx);
  9979. this.clipTo && fabric.util.clipContext(this, ctx);
  9980. this._render(ctx, noTransform);
  9981. this.clipTo && ctx.restore();
  9982. this._removeShadow(ctx);
  9983. this._restoreCompositeOperation(ctx);
  9984. ctx.restore();
  9985. },
  9986. /* @private
  9987. * @param {CanvasRenderingContext2D} ctx Context to render on
  9988. */
  9989. _setOpacity: function(ctx) {
  9990. if (this.group) {
  9991. this.group._setOpacity(ctx);
  9992. }
  9993. ctx.globalAlpha *= this.opacity;
  9994. },
  9995. _setStrokeStyles: function(ctx) {
  9996. if (this.stroke) {
  9997. ctx.lineWidth = this.strokeWidth;
  9998. ctx.lineCap = this.strokeLineCap;
  9999. ctx.lineJoin = this.strokeLineJoin;
  10000. ctx.miterLimit = this.strokeMiterLimit;
  10001. ctx.strokeStyle = this.stroke.toLive
  10002. ? this.stroke.toLive(ctx, this)
  10003. : this.stroke;
  10004. }
  10005. },
  10006. _setFillStyles: function(ctx) {
  10007. if (this.fill) {
  10008. ctx.fillStyle = this.fill.toLive
  10009. ? this.fill.toLive(ctx, this)
  10010. : this.fill;
  10011. }
  10012. },
  10013. /**
  10014. * Renders controls and borders for the object
  10015. * @param {CanvasRenderingContext2D} ctx Context to render on
  10016. * @param {Boolean} [noTransform] When true, context is not transformed
  10017. */
  10018. _renderControls: function(ctx, noTransform) {
  10019. if (!this.active || noTransform) {
  10020. return;
  10021. }
  10022. var vpt = this.getViewportTransform();
  10023. ctx.save();
  10024. var center;
  10025. if (this.group) {
  10026. center = fabric.util.transformPoint(this.group.getCenterPoint(), vpt);
  10027. ctx.translate(center.x, center.y);
  10028. ctx.rotate(degreesToRadians(this.group.angle));
  10029. }
  10030. center = fabric.util.transformPoint(this.getCenterPoint(), vpt, null != this.group);
  10031. if (this.group) {
  10032. center.x *= this.group.scaleX;
  10033. center.y *= this.group.scaleY;
  10034. }
  10035. ctx.translate(center.x, center.y);
  10036. ctx.rotate(degreesToRadians(this.angle));
  10037. this.drawBorders(ctx);
  10038. this.drawControls(ctx);
  10039. ctx.restore();
  10040. },
  10041. /**
  10042. * @private
  10043. * @param {CanvasRenderingContext2D} ctx Context to render on
  10044. */
  10045. _setShadow: function(ctx) {
  10046. if (!this.shadow) {
  10047. return;
  10048. }
  10049. var multX = (this.canvas && this.canvas.viewportTransform[0]) || 1,
  10050. multY = (this.canvas && this.canvas.viewportTransform[3]) || 1;
  10051. ctx.shadowColor = this.shadow.color;
  10052. ctx.shadowBlur = this.shadow.blur * (multX + multY) * (this.scaleX + this.scaleY) / 4;
  10053. ctx.shadowOffsetX = this.shadow.offsetX * multX * this.scaleX;
  10054. ctx.shadowOffsetY = this.shadow.offsetY * multY * this.scaleY;
  10055. },
  10056. /**
  10057. * @private
  10058. * @param {CanvasRenderingContext2D} ctx Context to render on
  10059. */
  10060. _removeShadow: function(ctx) {
  10061. if (!this.shadow) {
  10062. return;
  10063. }
  10064. ctx.shadowColor = '';
  10065. ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
  10066. },
  10067. /**
  10068. * @private
  10069. * @param {CanvasRenderingContext2D} ctx Context to render on
  10070. */
  10071. _renderFill: function(ctx) {
  10072. if (!this.fill) {
  10073. return;
  10074. }
  10075. ctx.save();
  10076. if (this.fill.gradientTransform) {
  10077. var g = this.fill.gradientTransform;
  10078. ctx.transform.apply(ctx, g);
  10079. }
  10080. if (this.fill.toLive) {
  10081. ctx.translate(
  10082. -this.width / 2 + this.fill.offsetX || 0,
  10083. -this.height / 2 + this.fill.offsetY || 0);
  10084. }
  10085. if (this.fillRule === 'evenodd') {
  10086. ctx.fill('evenodd');
  10087. }
  10088. else {
  10089. ctx.fill();
  10090. }
  10091. ctx.restore();
  10092. if (this.shadow && !this.shadow.affectStroke) {
  10093. this._removeShadow(ctx);
  10094. }
  10095. },
  10096. /**
  10097. * @private
  10098. * @param {CanvasRenderingContext2D} ctx Context to render on
  10099. */
  10100. _renderStroke: function(ctx) {
  10101. if (!this.stroke || this.strokeWidth === 0) {
  10102. return;
  10103. }
  10104. ctx.save();
  10105. if (this.strokeDashArray) {
  10106. // Spec requires the concatenation of two copies the dash list when the number of elements is odd
  10107. if (1 & this.strokeDashArray.length) {
  10108. this.strokeDashArray.push.apply(this.strokeDashArray, this.strokeDashArray);
  10109. }
  10110. if (supportsLineDash) {
  10111. ctx.setLineDash(this.strokeDashArray);
  10112. this._stroke && this._stroke(ctx);
  10113. }
  10114. else {
  10115. this._renderDashedStroke && this._renderDashedStroke(ctx);
  10116. }
  10117. ctx.stroke();
  10118. }
  10119. else {
  10120. if (this.stroke.gradientTransform) {
  10121. var g = this.stroke.gradientTransform;
  10122. ctx.transform.apply(ctx, g);
  10123. }
  10124. this._stroke ? this._stroke(ctx) : ctx.stroke();
  10125. }
  10126. this._removeShadow(ctx);
  10127. ctx.restore();
  10128. },
  10129. /**
  10130. * Clones an instance
  10131. * @param {Function} callback Callback is invoked with a clone as a first argument
  10132. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  10133. * @return {fabric.Object} clone of an instance
  10134. */
  10135. clone: function(callback, propertiesToInclude) {
  10136. if (this.constructor.fromObject) {
  10137. return this.constructor.fromObject(this.toObject(propertiesToInclude), callback);
  10138. }
  10139. return new fabric.Object(this.toObject(propertiesToInclude));
  10140. },
  10141. /**
  10142. * Creates an instance of fabric.Image out of an object
  10143. * @param {Function} callback callback, invoked with an instance as a first argument
  10144. * @return {fabric.Object} thisArg
  10145. */
  10146. cloneAsImage: function(callback) {
  10147. var dataUrl = this.toDataURL();
  10148. fabric.util.loadImage(dataUrl, function(img) {
  10149. if (callback) {
  10150. callback(new fabric.Image(img));
  10151. }
  10152. });
  10153. return this;
  10154. },
  10155. /**
  10156. * Converts an object into a data-url-like string
  10157. * @param {Object} options Options object
  10158. * @param {String} [options.format=png] The format of the output image. Either "jpeg" or "png"
  10159. * @param {Number} [options.quality=1] Quality level (0..1). Only used for jpeg.
  10160. * @param {Number} [options.multiplier=1] Multiplier to scale by
  10161. * @param {Number} [options.left] Cropping left offset. Introduced in v1.2.14
  10162. * @param {Number} [options.top] Cropping top offset. Introduced in v1.2.14
  10163. * @param {Number} [options.width] Cropping width. Introduced in v1.2.14
  10164. * @param {Number} [options.height] Cropping height. Introduced in v1.2.14
  10165. * @return {String} Returns a data: URL containing a representation of the object in the format specified by options.format
  10166. */
  10167. toDataURL: function(options) {
  10168. options || (options = { });
  10169. var el = fabric.util.createCanvasElement(),
  10170. boundingRect = this.getBoundingRect();
  10171. el.width = boundingRect.width;
  10172. el.height = boundingRect.height;
  10173. fabric.util.wrapElement(el, 'div');
  10174. var canvas = new fabric.StaticCanvas(el);
  10175. // to avoid common confusion https://github.com/kangax/fabric.js/issues/806
  10176. if (options.format === 'jpg') {
  10177. options.format = 'jpeg';
  10178. }
  10179. if (options.format === 'jpeg') {
  10180. canvas.backgroundColor = '#fff';
  10181. }
  10182. var origParams = {
  10183. active: this.get('active'),
  10184. left: this.getLeft(),
  10185. top: this.getTop()
  10186. };
  10187. this.set('active', false);
  10188. this.setPositionByOrigin(new fabric.Point(el.width / 2, el.height / 2), 'center', 'center');
  10189. var originalCanvas = this.canvas;
  10190. canvas.add(this);
  10191. var data = canvas.toDataURL(options);
  10192. this.set(origParams).setCoords();
  10193. this.canvas = originalCanvas;
  10194. canvas.dispose();
  10195. canvas = null;
  10196. return data;
  10197. },
  10198. /**
  10199. * Returns true if specified type is identical to the type of an instance
  10200. * @param {String} type Type to check against
  10201. * @return {Boolean}
  10202. */
  10203. isType: function(type) {
  10204. return this.type === type;
  10205. },
  10206. /**
  10207. * Returns complexity of an instance
  10208. * @return {Number} complexity of this instance
  10209. */
  10210. complexity: function() {
  10211. return 0;
  10212. },
  10213. /**
  10214. * Returns a JSON representation of an instance
  10215. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  10216. * @return {Object} JSON
  10217. */
  10218. toJSON: function(propertiesToInclude) {
  10219. // delegate, not alias
  10220. return this.toObject(propertiesToInclude);
  10221. },
  10222. /**
  10223. * Sets gradient (fill or stroke) of an object
  10224. * <b>Backwards incompatibility note:</b> This method was named "setGradientFill" until v1.1.0
  10225. * @param {String} property Property name 'stroke' or 'fill'
  10226. * @param {Object} [options] Options object
  10227. * @param {String} [options.type] Type of gradient 'radial' or 'linear'
  10228. * @param {Number} [options.x1=0] x-coordinate of start point
  10229. * @param {Number} [options.y1=0] y-coordinate of start point
  10230. * @param {Number} [options.x2=0] x-coordinate of end point
  10231. * @param {Number} [options.y2=0] y-coordinate of end point
  10232. * @param {Number} [options.r1=0] Radius of start point (only for radial gradients)
  10233. * @param {Number} [options.r2=0] Radius of end point (only for radial gradients)
  10234. * @param {Object} [options.colorStops] Color stops object eg. {0: 'ff0000', 1: '000000'}
  10235. * @return {fabric.Object} thisArg
  10236. * @chainable
  10237. * @see {@link http://jsfiddle.net/fabricjs/58y8b/|jsFiddle demo}
  10238. * @example <caption>Set linear gradient</caption>
  10239. * object.setGradient('fill', {
  10240. * type: 'linear',
  10241. * x1: -object.width / 2,
  10242. * y1: 0,
  10243. * x2: object.width / 2,
  10244. * y2: 0,
  10245. * colorStops: {
  10246. * 0: 'red',
  10247. * 0.5: '#005555',
  10248. * 1: 'rgba(0,0,255,0.5)'
  10249. * }
  10250. * });
  10251. * canvas.renderAll();
  10252. * @example <caption>Set radial gradient</caption>
  10253. * object.setGradient('fill', {
  10254. * type: 'radial',
  10255. * x1: 0,
  10256. * y1: 0,
  10257. * x2: 0,
  10258. * y2: 0,
  10259. * r1: object.width / 2,
  10260. * r2: 10,
  10261. * colorStops: {
  10262. * 0: 'red',
  10263. * 0.5: '#005555',
  10264. * 1: 'rgba(0,0,255,0.5)'
  10265. * }
  10266. * });
  10267. * canvas.renderAll();
  10268. */
  10269. setGradient: function(property, options) {
  10270. options || (options = { });
  10271. var gradient = { colorStops: [] };
  10272. gradient.type = options.type || (options.r1 || options.r2 ? 'radial' : 'linear');
  10273. gradient.coords = {
  10274. x1: options.x1,
  10275. y1: options.y1,
  10276. x2: options.x2,
  10277. y2: options.y2
  10278. };
  10279. if (options.r1 || options.r2) {
  10280. gradient.coords.r1 = options.r1;
  10281. gradient.coords.r2 = options.r2;
  10282. }
  10283. for (var position in options.colorStops) {
  10284. var color = new fabric.Color(options.colorStops[position]);
  10285. gradient.colorStops.push({
  10286. offset: position,
  10287. color: color.toRgb(),
  10288. opacity: color.getAlpha()
  10289. });
  10290. }
  10291. return this.set(property, fabric.Gradient.forObject(this, gradient));
  10292. },
  10293. /**
  10294. * Sets pattern fill of an object
  10295. * @param {Object} options Options object
  10296. * @param {(String|HTMLImageElement)} options.source Pattern source
  10297. * @param {String} [options.repeat=repeat] Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat)
  10298. * @param {Number} [options.offsetX=0] Pattern horizontal offset from object's left/top corner
  10299. * @param {Number} [options.offsetY=0] Pattern vertical offset from object's left/top corner
  10300. * @return {fabric.Object} thisArg
  10301. * @chainable
  10302. * @see {@link http://jsfiddle.net/fabricjs/QT3pa/|jsFiddle demo}
  10303. * @example <caption>Set pattern</caption>
  10304. * fabric.util.loadImage('http://fabricjs.com/assets/escheresque_ste.png', function(img) {
  10305. * object.setPatternFill({
  10306. * source: img,
  10307. * repeat: 'repeat'
  10308. * });
  10309. * canvas.renderAll();
  10310. * });
  10311. */
  10312. setPatternFill: function(options) {
  10313. return this.set('fill', new fabric.Pattern(options));
  10314. },
  10315. /**
  10316. * Sets {@link fabric.Object#shadow|shadow} of an object
  10317. * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)")
  10318. * @param {String} [options.color=rgb(0,0,0)] Shadow color
  10319. * @param {Number} [options.blur=0] Shadow blur
  10320. * @param {Number} [options.offsetX=0] Shadow horizontal offset
  10321. * @param {Number} [options.offsetY=0] Shadow vertical offset
  10322. * @return {fabric.Object} thisArg
  10323. * @chainable
  10324. * @see {@link http://jsfiddle.net/fabricjs/7gvJG/|jsFiddle demo}
  10325. * @example <caption>Set shadow with string notation</caption>
  10326. * object.setShadow('2px 2px 10px rgba(0,0,0,0.2)');
  10327. * canvas.renderAll();
  10328. * @example <caption>Set shadow with object notation</caption>
  10329. * object.setShadow({
  10330. * color: 'red',
  10331. * blur: 10,
  10332. * offsetX: 20,
  10333. * offsetY: 20
  10334. * });
  10335. * canvas.renderAll();
  10336. */
  10337. setShadow: function(options) {
  10338. return this.set('shadow', options ? new fabric.Shadow(options) : null);
  10339. },
  10340. /**
  10341. * Sets "color" of an instance (alias of `set('fill', &hellip;)`)
  10342. * @param {String} color Color value
  10343. * @return {fabric.Object} thisArg
  10344. * @chainable
  10345. */
  10346. setColor: function(color) {
  10347. this.set('fill', color);
  10348. return this;
  10349. },
  10350. /**
  10351. * Sets "angle" of an instance
  10352. * @param {Number} angle Angle value (in degrees)
  10353. * @return {fabric.Object} thisArg
  10354. * @chainable
  10355. */
  10356. setAngle: function(angle) {
  10357. var shouldCenterOrigin = (this.originX !== 'center' || this.originY !== 'center') && this.centeredRotation;
  10358. if (shouldCenterOrigin) {
  10359. this._setOriginToCenter();
  10360. }
  10361. this.set('angle', angle);
  10362. if (shouldCenterOrigin) {
  10363. this._resetOrigin();
  10364. }
  10365. return this;
  10366. },
  10367. /**
  10368. * Centers object horizontally on canvas to which it was added last.
  10369. * You might need to call `setCoords` on an object after centering, to update controls area.
  10370. * @return {fabric.Object} thisArg
  10371. * @chainable
  10372. */
  10373. centerH: function () {
  10374. this.canvas.centerObjectH(this);
  10375. return this;
  10376. },
  10377. /**
  10378. * Centers object vertically on canvas to which it was added last.
  10379. * You might need to call `setCoords` on an object after centering, to update controls area.
  10380. * @return {fabric.Object} thisArg
  10381. * @chainable
  10382. */
  10383. centerV: function () {
  10384. this.canvas.centerObjectV(this);
  10385. return this;
  10386. },
  10387. /**
  10388. * Centers object vertically and horizontally on canvas to which is was added last
  10389. * You might need to call `setCoords` on an object after centering, to update controls area.
  10390. * @return {fabric.Object} thisArg
  10391. * @chainable
  10392. */
  10393. center: function () {
  10394. this.canvas.centerObject(this);
  10395. return this;
  10396. },
  10397. /**
  10398. * Removes object from canvas to which it was added last
  10399. * @return {fabric.Object} thisArg
  10400. * @chainable
  10401. */
  10402. remove: function() {
  10403. this.canvas.remove(this);
  10404. return this;
  10405. },
  10406. /**
  10407. * Returns coordinates of a pointer relative to an object
  10408. * @param {Event} e Event to operate upon
  10409. * @param {Object} [pointer] Pointer to operate upon (instead of event)
  10410. * @return {Object} Coordinates of a pointer (x, y)
  10411. */
  10412. getLocalPointer: function(e, pointer) {
  10413. pointer = pointer || this.canvas.getPointer(e);
  10414. var objectLeftTop = this.translateToOriginPoint(this.getCenterPoint(), 'left', 'top');
  10415. return {
  10416. x: pointer.x - objectLeftTop.x,
  10417. y: pointer.y - objectLeftTop.y
  10418. };
  10419. },
  10420. /**
  10421. * Sets canvas globalCompositeOperation for specific object
  10422. * custom composition operation for the particular object can be specifed using globalCompositeOperation property
  10423. * @param {CanvasRenderingContext2D} ctx Rendering canvas context
  10424. */
  10425. _setupCompositeOperation: function (ctx) {
  10426. if (this.globalCompositeOperation) {
  10427. this._prevGlobalCompositeOperation = ctx.globalCompositeOperation;
  10428. ctx.globalCompositeOperation = this.globalCompositeOperation;
  10429. }
  10430. },
  10431. /**
  10432. * Restores previously saved canvas globalCompositeOperation after obeject rendering
  10433. * @param {CanvasRenderingContext2D} ctx Rendering canvas context
  10434. */
  10435. _restoreCompositeOperation: function (ctx) {
  10436. if (this.globalCompositeOperation && this._prevGlobalCompositeOperation) {
  10437. ctx.globalCompositeOperation = this._prevGlobalCompositeOperation;
  10438. }
  10439. }
  10440. });
  10441. fabric.util.createAccessors(fabric.Object);
  10442. /**
  10443. * Alias for {@link fabric.Object.prototype.setAngle}
  10444. * @alias rotate -> setAngle
  10445. * @memberof fabric.Object
  10446. */
  10447. fabric.Object.prototype.rotate = fabric.Object.prototype.setAngle;
  10448. extend(fabric.Object.prototype, fabric.Observable);
  10449. /**
  10450. * Defines the number of fraction digits to use when serializing object values.
  10451. * You can use it to increase/decrease precision of such values like left, top, scaleX, scaleY, etc.
  10452. * @static
  10453. * @memberof fabric.Object
  10454. * @constant
  10455. * @type Number
  10456. */
  10457. fabric.Object.NUM_FRACTION_DIGITS = 2;
  10458. /**
  10459. * Unique id used internally when creating SVG elements
  10460. * @static
  10461. * @memberof fabric.Object
  10462. * @type Number
  10463. */
  10464. fabric.Object.__uid = 0;
  10465. })(typeof exports !== 'undefined' ? exports : this);
  10466. (function() {
  10467. var degreesToRadians = fabric.util.degreesToRadians;
  10468. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  10469. /**
  10470. * Translates the coordinates from origin to center coordinates (based on the object's dimensions)
  10471. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  10472. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  10473. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  10474. * @return {fabric.Point}
  10475. */
  10476. translateToCenterPoint: function(point, originX, originY) {
  10477. var cx = point.x,
  10478. cy = point.y,
  10479. strokeWidth = this.stroke ? this.strokeWidth : 0;
  10480. if (originX === 'left') {
  10481. cx = point.x + (this.getWidth() + strokeWidth * this.scaleX) / 2;
  10482. }
  10483. else if (originX === 'right') {
  10484. cx = point.x - (this.getWidth() + strokeWidth * this.scaleX) / 2;
  10485. }
  10486. if (originY === 'top') {
  10487. cy = point.y + (this.getHeight() + strokeWidth * this.scaleY) / 2;
  10488. }
  10489. else if (originY === 'bottom') {
  10490. cy = point.y - (this.getHeight() + strokeWidth * this.scaleY) / 2;
  10491. }
  10492. // Apply the reverse rotation to the point (it's already scaled properly)
  10493. return fabric.util.rotatePoint(new fabric.Point(cx, cy), point, degreesToRadians(this.angle));
  10494. },
  10495. /**
  10496. * Translates the coordinates from center to origin coordinates (based on the object's dimensions)
  10497. * @param {fabric.Point} center The point which corresponds to center of the object
  10498. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  10499. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  10500. * @return {fabric.Point}
  10501. */
  10502. translateToOriginPoint: function(center, originX, originY) {
  10503. var x = center.x,
  10504. y = center.y,
  10505. strokeWidth = this.stroke ? this.strokeWidth : 0;
  10506. // Get the point coordinates
  10507. if (originX === 'left') {
  10508. x = center.x - (this.getWidth() + strokeWidth * this.scaleX) / 2;
  10509. }
  10510. else if (originX === 'right') {
  10511. x = center.x + (this.getWidth() + strokeWidth * this.scaleX) / 2;
  10512. }
  10513. if (originY === 'top') {
  10514. y = center.y - (this.getHeight() + strokeWidth * this.scaleY) / 2;
  10515. }
  10516. else if (originY === 'bottom') {
  10517. y = center.y + (this.getHeight() + strokeWidth * this.scaleY) / 2;
  10518. }
  10519. // Apply the rotation to the point (it's already scaled properly)
  10520. return fabric.util.rotatePoint(new fabric.Point(x, y), center, degreesToRadians(this.angle));
  10521. },
  10522. /**
  10523. * Returns the real center coordinates of the object
  10524. * @return {fabric.Point}
  10525. */
  10526. getCenterPoint: function() {
  10527. var leftTop = new fabric.Point(this.left, this.top);
  10528. return this.translateToCenterPoint(leftTop, this.originX, this.originY);
  10529. },
  10530. /**
  10531. * Returns the coordinates of the object based on center coordinates
  10532. * @param {fabric.Point} point The point which corresponds to the originX and originY params
  10533. * @return {fabric.Point}
  10534. */
  10535. // getOriginPoint: function(center) {
  10536. // return this.translateToOriginPoint(center, this.originX, this.originY);
  10537. // },
  10538. /**
  10539. * Returns the coordinates of the object as if it has a different origin
  10540. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  10541. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  10542. * @return {fabric.Point}
  10543. */
  10544. getPointByOrigin: function(originX, originY) {
  10545. var center = this.getCenterPoint();
  10546. return this.translateToOriginPoint(center, originX, originY);
  10547. },
  10548. /**
  10549. * Returns the point in local coordinates
  10550. * @param {fabric.Point} point The point relative to the global coordinate system
  10551. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  10552. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  10553. * @return {fabric.Point}
  10554. */
  10555. toLocalPoint: function(point, originX, originY) {
  10556. var center = this.getCenterPoint(),
  10557. strokeWidth = this.stroke ? this.strokeWidth : 0,
  10558. x, y;
  10559. if (originX && originY) {
  10560. if (originX === 'left') {
  10561. x = center.x - (this.getWidth() + strokeWidth * this.scaleX) / 2;
  10562. }
  10563. else if (originX === 'right') {
  10564. x = center.x + (this.getWidth() + strokeWidth * this.scaleX) / 2;
  10565. }
  10566. else {
  10567. x = center.x;
  10568. }
  10569. if (originY === 'top') {
  10570. y = center.y - (this.getHeight() + strokeWidth * this.scaleY) / 2;
  10571. }
  10572. else if (originY === 'bottom') {
  10573. y = center.y + (this.getHeight() + strokeWidth * this.scaleY) / 2;
  10574. }
  10575. else {
  10576. y = center.y;
  10577. }
  10578. }
  10579. else {
  10580. x = this.left;
  10581. y = this.top;
  10582. }
  10583. return fabric.util.rotatePoint(new fabric.Point(point.x, point.y), center, -degreesToRadians(this.angle))
  10584. .subtractEquals(new fabric.Point(x, y));
  10585. },
  10586. /**
  10587. * Returns the point in global coordinates
  10588. * @param {fabric.Point} The point relative to the local coordinate system
  10589. * @return {fabric.Point}
  10590. */
  10591. // toGlobalPoint: function(point) {
  10592. // return fabric.util.rotatePoint(point, this.getCenterPoint(), degreesToRadians(this.angle)).addEquals(new fabric.Point(this.left, this.top));
  10593. // },
  10594. /**
  10595. * Sets the position of the object taking into consideration the object's origin
  10596. * @param {fabric.Point} pos The new position of the object
  10597. * @param {String} originX Horizontal origin: 'left', 'center' or 'right'
  10598. * @param {String} originY Vertical origin: 'top', 'center' or 'bottom'
  10599. * @return {void}
  10600. */
  10601. setPositionByOrigin: function(pos, originX, originY) {
  10602. var center = this.translateToCenterPoint(pos, originX, originY),
  10603. position = this.translateToOriginPoint(center, this.originX, this.originY);
  10604. this.set('left', position.x);
  10605. this.set('top', position.y);
  10606. },
  10607. /**
  10608. * @param {String} to One of 'left', 'center', 'right'
  10609. */
  10610. adjustPosition: function(to) {
  10611. var angle = degreesToRadians(this.angle),
  10612. hypotHalf = this.getWidth() / 2,
  10613. xHalf = Math.cos(angle) * hypotHalf,
  10614. yHalf = Math.sin(angle) * hypotHalf,
  10615. hypotFull = this.getWidth(),
  10616. xFull = Math.cos(angle) * hypotFull,
  10617. yFull = Math.sin(angle) * hypotFull;
  10618. if (this.originX === 'center' && to === 'left' ||
  10619. this.originX === 'right' && to === 'center') {
  10620. // move half left
  10621. this.left -= xHalf;
  10622. this.top -= yHalf;
  10623. }
  10624. else if (this.originX === 'left' && to === 'center' ||
  10625. this.originX === 'center' && to === 'right') {
  10626. // move half right
  10627. this.left += xHalf;
  10628. this.top += yHalf;
  10629. }
  10630. else if (this.originX === 'left' && to === 'right') {
  10631. // move full right
  10632. this.left += xFull;
  10633. this.top += yFull;
  10634. }
  10635. else if (this.originX === 'right' && to === 'left') {
  10636. // move full left
  10637. this.left -= xFull;
  10638. this.top -= yFull;
  10639. }
  10640. this.setCoords();
  10641. this.originX = to;
  10642. },
  10643. /**
  10644. * Sets the origin/position of the object to it's center point
  10645. * @private
  10646. * @return {void}
  10647. */
  10648. _setOriginToCenter: function() {
  10649. this._originalOriginX = this.originX;
  10650. this._originalOriginY = this.originY;
  10651. var center = this.getCenterPoint();
  10652. this.originX = 'center';
  10653. this.originY = 'center';
  10654. this.left = center.x;
  10655. this.top = center.y;
  10656. },
  10657. /**
  10658. * Resets the origin/position of the object to it's original origin
  10659. * @private
  10660. * @return {void}
  10661. */
  10662. _resetOrigin: function() {
  10663. var originPoint = this.translateToOriginPoint(
  10664. this.getCenterPoint(),
  10665. this._originalOriginX,
  10666. this._originalOriginY);
  10667. this.originX = this._originalOriginX;
  10668. this.originY = this._originalOriginY;
  10669. this.left = originPoint.x;
  10670. this.top = originPoint.y;
  10671. this._originalOriginX = null;
  10672. this._originalOriginY = null;
  10673. },
  10674. /**
  10675. * @private
  10676. */
  10677. _getLeftTopCoords: function() {
  10678. return this.translateToOriginPoint(this.getCenterPoint(), 'left', 'center');
  10679. }
  10680. });
  10681. })();
  10682. (function() {
  10683. var degreesToRadians = fabric.util.degreesToRadians;
  10684. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  10685. /**
  10686. * Object containing coordinates of object's controls
  10687. * @type Object
  10688. * @default
  10689. */
  10690. oCoords: null,
  10691. /**
  10692. * Checks if object intersects with an area formed by 2 points
  10693. * @param {Object} pointTL top-left point of area
  10694. * @param {Object} pointBR bottom-right point of area
  10695. * @return {Boolean} true if object intersects with an area formed by 2 points
  10696. */
  10697. intersectsWithRect: function(pointTL, pointBR) {
  10698. var oCoords = this.oCoords,
  10699. tl = new fabric.Point(oCoords.tl.x, oCoords.tl.y),
  10700. tr = new fabric.Point(oCoords.tr.x, oCoords.tr.y),
  10701. bl = new fabric.Point(oCoords.bl.x, oCoords.bl.y),
  10702. br = new fabric.Point(oCoords.br.x, oCoords.br.y),
  10703. intersection = fabric.Intersection.intersectPolygonRectangle(
  10704. [tl, tr, br, bl],
  10705. pointTL,
  10706. pointBR
  10707. );
  10708. return intersection.status === 'Intersection';
  10709. },
  10710. /**
  10711. * Checks if object intersects with another object
  10712. * @param {Object} other Object to test
  10713. * @return {Boolean} true if object intersects with another object
  10714. */
  10715. intersectsWithObject: function(other) {
  10716. // extracts coords
  10717. function getCoords(oCoords) {
  10718. return {
  10719. tl: new fabric.Point(oCoords.tl.x, oCoords.tl.y),
  10720. tr: new fabric.Point(oCoords.tr.x, oCoords.tr.y),
  10721. bl: new fabric.Point(oCoords.bl.x, oCoords.bl.y),
  10722. br: new fabric.Point(oCoords.br.x, oCoords.br.y)
  10723. };
  10724. }
  10725. var thisCoords = getCoords(this.oCoords),
  10726. otherCoords = getCoords(other.oCoords),
  10727. intersection = fabric.Intersection.intersectPolygonPolygon(
  10728. [thisCoords.tl, thisCoords.tr, thisCoords.br, thisCoords.bl],
  10729. [otherCoords.tl, otherCoords.tr, otherCoords.br, otherCoords.bl]
  10730. );
  10731. return intersection.status === 'Intersection';
  10732. },
  10733. /**
  10734. * Checks if object is fully contained within area of another object
  10735. * @param {Object} other Object to test
  10736. * @return {Boolean} true if object is fully contained within area of another object
  10737. */
  10738. isContainedWithinObject: function(other) {
  10739. var boundingRect = other.getBoundingRect(),
  10740. point1 = new fabric.Point(boundingRect.left, boundingRect.top),
  10741. point2 = new fabric.Point(boundingRect.left + boundingRect.width, boundingRect.top + boundingRect.height);
  10742. return this.isContainedWithinRect(point1, point2);
  10743. },
  10744. /**
  10745. * Checks if object is fully contained within area formed by 2 points
  10746. * @param {Object} pointTL top-left point of area
  10747. * @param {Object} pointBR bottom-right point of area
  10748. * @return {Boolean} true if object is fully contained within area formed by 2 points
  10749. */
  10750. isContainedWithinRect: function(pointTL, pointBR) {
  10751. var boundingRect = this.getBoundingRect();
  10752. return (
  10753. boundingRect.left >= pointTL.x &&
  10754. boundingRect.left + boundingRect.width <= pointBR.x &&
  10755. boundingRect.top >= pointTL.y &&
  10756. boundingRect.top + boundingRect.height <= pointBR.y
  10757. );
  10758. },
  10759. /**
  10760. * Checks if point is inside the object
  10761. * @param {fabric.Point} point Point to check against
  10762. * @return {Boolean} true if point is inside the object
  10763. */
  10764. containsPoint: function(point) {
  10765. var lines = this._getImageLines(this.oCoords),
  10766. xPoints = this._findCrossPoints(point, lines);
  10767. // if xPoints is odd then point is inside the object
  10768. return (xPoints !== 0 && xPoints % 2 === 1);
  10769. },
  10770. /**
  10771. * Method that returns an object with the object edges in it, given the coordinates of the corners
  10772. * @private
  10773. * @param {Object} oCoords Coordinates of the object corners
  10774. */
  10775. _getImageLines: function(oCoords) {
  10776. return {
  10777. topline: {
  10778. o: oCoords.tl,
  10779. d: oCoords.tr
  10780. },
  10781. rightline: {
  10782. o: oCoords.tr,
  10783. d: oCoords.br
  10784. },
  10785. bottomline: {
  10786. o: oCoords.br,
  10787. d: oCoords.bl
  10788. },
  10789. leftline: {
  10790. o: oCoords.bl,
  10791. d: oCoords.tl
  10792. }
  10793. };
  10794. },
  10795. /**
  10796. * Helper method to determine how many cross points are between the 4 object edges
  10797. * and the horizontal line determined by a point on canvas
  10798. * @private
  10799. * @param {fabric.Point} point Point to check
  10800. * @param {Object} oCoords Coordinates of the object being evaluated
  10801. */
  10802. _findCrossPoints: function(point, oCoords) {
  10803. var b1, b2, a1, a2, xi, yi,
  10804. xcount = 0,
  10805. iLine;
  10806. for (var lineKey in oCoords) {
  10807. iLine = oCoords[lineKey];
  10808. // optimisation 1: line below point. no cross
  10809. if ((iLine.o.y < point.y) && (iLine.d.y < point.y)) {
  10810. continue;
  10811. }
  10812. // optimisation 2: line above point. no cross
  10813. if ((iLine.o.y >= point.y) && (iLine.d.y >= point.y)) {
  10814. continue;
  10815. }
  10816. // optimisation 3: vertical line case
  10817. if ((iLine.o.x === iLine.d.x) && (iLine.o.x >= point.x)) {
  10818. xi = iLine.o.x;
  10819. yi = point.y;
  10820. }
  10821. // calculate the intersection point
  10822. else {
  10823. b1 = 0;
  10824. b2 = (iLine.d.y - iLine.o.y) / (iLine.d.x - iLine.o.x);
  10825. a1 = point.y - b1 * point.x;
  10826. a2 = iLine.o.y - b2 * iLine.o.x;
  10827. xi = - (a1 - a2) / (b1 - b2);
  10828. yi = a1 + b1 * xi;
  10829. }
  10830. // dont count xi < point.x cases
  10831. if (xi >= point.x) {
  10832. xcount += 1;
  10833. }
  10834. // optimisation 4: specific for square images
  10835. if (xcount === 2) {
  10836. break;
  10837. }
  10838. }
  10839. return xcount;
  10840. },
  10841. /**
  10842. * Returns width of an object's bounding rectangle
  10843. * @deprecated since 1.0.4
  10844. * @return {Number} width value
  10845. */
  10846. getBoundingRectWidth: function() {
  10847. return this.getBoundingRect().width;
  10848. },
  10849. /**
  10850. * Returns height of an object's bounding rectangle
  10851. * @deprecated since 1.0.4
  10852. * @return {Number} height value
  10853. */
  10854. getBoundingRectHeight: function() {
  10855. return this.getBoundingRect().height;
  10856. },
  10857. /**
  10858. * Returns coordinates of object's bounding rectangle (left, top, width, height)
  10859. * @return {Object} Object with left, top, width, height properties
  10860. */
  10861. getBoundingRect: function() {
  10862. this.oCoords || this.setCoords();
  10863. var xCoords = [this.oCoords.tl.x, this.oCoords.tr.x, this.oCoords.br.x, this.oCoords.bl.x],
  10864. minX = fabric.util.array.min(xCoords),
  10865. maxX = fabric.util.array.max(xCoords),
  10866. width = Math.abs(minX - maxX),
  10867. yCoords = [this.oCoords.tl.y, this.oCoords.tr.y, this.oCoords.br.y, this.oCoords.bl.y],
  10868. minY = fabric.util.array.min(yCoords),
  10869. maxY = fabric.util.array.max(yCoords),
  10870. height = Math.abs(minY - maxY);
  10871. return {
  10872. left: minX,
  10873. top: minY,
  10874. width: width,
  10875. height: height
  10876. };
  10877. },
  10878. /**
  10879. * Returns width of an object
  10880. * @return {Number} width value
  10881. */
  10882. getWidth: function() {
  10883. return this.width * this.scaleX;
  10884. },
  10885. /**
  10886. * Returns height of an object
  10887. * @return {Number} height value
  10888. */
  10889. getHeight: function() {
  10890. return this.height * this.scaleY;
  10891. },
  10892. /**
  10893. * Makes sure the scale is valid and modifies it if necessary
  10894. * @private
  10895. * @param {Number} value
  10896. * @return {Number}
  10897. */
  10898. _constrainScale: function(value) {
  10899. if (Math.abs(value) < this.minScaleLimit) {
  10900. if (value < 0) {
  10901. return -this.minScaleLimit;
  10902. }
  10903. else {
  10904. return this.minScaleLimit;
  10905. }
  10906. }
  10907. return value;
  10908. },
  10909. /**
  10910. * Scales an object (equally by x and y)
  10911. * @param {Number} value Scale factor
  10912. * @return {fabric.Object} thisArg
  10913. * @chainable
  10914. */
  10915. scale: function(value) {
  10916. value = this._constrainScale(value);
  10917. if (value < 0) {
  10918. this.flipX = !this.flipX;
  10919. this.flipY = !this.flipY;
  10920. value *= -1;
  10921. }
  10922. this.scaleX = value;
  10923. this.scaleY = value;
  10924. this.setCoords();
  10925. return this;
  10926. },
  10927. /**
  10928. * Scales an object to a given width, with respect to bounding box (scaling by x/y equally)
  10929. * @param {Number} value New width value
  10930. * @return {fabric.Object} thisArg
  10931. * @chainable
  10932. */
  10933. scaleToWidth: function(value) {
  10934. // adjust to bounding rect factor so that rotated shapes would fit as well
  10935. var boundingRectFactor = this.getBoundingRectWidth() / this.getWidth();
  10936. return this.scale(value / this.width / boundingRectFactor);
  10937. },
  10938. /**
  10939. * Scales an object to a given height, with respect to bounding box (scaling by x/y equally)
  10940. * @param {Number} value New height value
  10941. * @return {fabric.Object} thisArg
  10942. * @chainable
  10943. */
  10944. scaleToHeight: function(value) {
  10945. // adjust to bounding rect factor so that rotated shapes would fit as well
  10946. var boundingRectFactor = this.getBoundingRectHeight() / this.getHeight();
  10947. return this.scale(value / this.height / boundingRectFactor);
  10948. },
  10949. /**
  10950. * Sets corner position coordinates based on current angle, width and height
  10951. * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords
  10952. * @return {fabric.Object} thisArg
  10953. * @chainable
  10954. */
  10955. setCoords: function() {
  10956. var theta = degreesToRadians(this.angle),
  10957. vpt = this.getViewportTransform(),
  10958. f = function (p) {
  10959. return fabric.util.transformPoint(p, vpt);
  10960. },
  10961. p = this._calculateCurrentDimensions(false),
  10962. currentWidth = p.x, currentHeight = p.y;
  10963. // If width is negative, make postive. Fixes path selection issue
  10964. if (currentWidth < 0) {
  10965. currentWidth = Math.abs(currentWidth);
  10966. }
  10967. var _hypotenuse = Math.sqrt(
  10968. Math.pow(currentWidth / 2, 2) +
  10969. Math.pow(currentHeight / 2, 2)),
  10970. _angle = Math.atan(
  10971. isFinite(currentHeight / currentWidth)
  10972. ? currentHeight / currentWidth
  10973. : 0),
  10974. // offset added for rotate and scale actions
  10975. offsetX = Math.cos(_angle + theta) * _hypotenuse,
  10976. offsetY = Math.sin(_angle + theta) * _hypotenuse,
  10977. sinTh = Math.sin(theta),
  10978. cosTh = Math.cos(theta),
  10979. coords = this.getCenterPoint(),
  10980. wh = new fabric.Point(currentWidth, currentHeight),
  10981. _tl = new fabric.Point(coords.x - offsetX, coords.y - offsetY),
  10982. _tr = new fabric.Point(_tl.x + (wh.x * cosTh), _tl.y + (wh.x * sinTh)),
  10983. bl = f(new fabric.Point(_tl.x - (wh.y * sinTh), _tl.y + (wh.y * cosTh))),
  10984. br = f(new fabric.Point(_tr.x - (wh.y * sinTh), _tr.y + (wh.y * cosTh))),
  10985. tl = f(_tl),
  10986. tr = f(_tr),
  10987. ml = new fabric.Point((tl.x + bl.x)/2, (tl.y + bl.y)/2),
  10988. mt = new fabric.Point((tr.x + tl.x)/2, (tr.y + tl.y)/2),
  10989. mr = new fabric.Point((br.x + tr.x)/2, (br.y + tr.y)/2),
  10990. mb = new fabric.Point((br.x + bl.x)/2, (br.y + bl.y)/2),
  10991. mtr = new fabric.Point(mt.x + sinTh * this.rotatingPointOffset, mt.y - cosTh * this.rotatingPointOffset);
  10992. // debugging
  10993. /* setTimeout(function() {
  10994. canvas.contextTop.fillStyle = 'green';
  10995. canvas.contextTop.fillRect(mb.x, mb.y, 3, 3);
  10996. canvas.contextTop.fillRect(bl.x, bl.y, 3, 3);
  10997. canvas.contextTop.fillRect(br.x, br.y, 3, 3);
  10998. canvas.contextTop.fillRect(tl.x, tl.y, 3, 3);
  10999. canvas.contextTop.fillRect(tr.x, tr.y, 3, 3);
  11000. canvas.contextTop.fillRect(ml.x, ml.y, 3, 3);
  11001. canvas.contextTop.fillRect(mr.x, mr.y, 3, 3);
  11002. canvas.contextTop.fillRect(mt.x, mt.y, 3, 3);
  11003. canvas.contextTop.fillRect(mtr.x, mtr.y, 3, 3);
  11004. }, 50); */
  11005. this.oCoords = {
  11006. // corners
  11007. tl: tl, tr: tr, br: br, bl: bl,
  11008. // middle
  11009. ml: ml, mt: mt, mr: mr, mb: mb,
  11010. // rotating point
  11011. mtr: mtr
  11012. };
  11013. // set coordinates of the draggable boxes in the corners used to scale/rotate the image
  11014. this._setCornerCoords && this._setCornerCoords();
  11015. return this;
  11016. }
  11017. });
  11018. })();
  11019. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  11020. /**
  11021. * Moves an object to the bottom of the stack of drawn objects
  11022. * @return {fabric.Object} thisArg
  11023. * @chainable
  11024. */
  11025. sendToBack: function() {
  11026. if (this.group) {
  11027. fabric.StaticCanvas.prototype.sendToBack.call(this.group, this);
  11028. }
  11029. else {
  11030. this.canvas.sendToBack(this);
  11031. }
  11032. return this;
  11033. },
  11034. /**
  11035. * Moves an object to the top of the stack of drawn objects
  11036. * @return {fabric.Object} thisArg
  11037. * @chainable
  11038. */
  11039. bringToFront: function() {
  11040. if (this.group) {
  11041. fabric.StaticCanvas.prototype.bringToFront.call(this.group, this);
  11042. }
  11043. else {
  11044. this.canvas.bringToFront(this);
  11045. }
  11046. return this;
  11047. },
  11048. /**
  11049. * Moves an object down in stack of drawn objects
  11050. * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object
  11051. * @return {fabric.Object} thisArg
  11052. * @chainable
  11053. */
  11054. sendBackwards: function(intersecting) {
  11055. if (this.group) {
  11056. fabric.StaticCanvas.prototype.sendBackwards.call(this.group, this, intersecting);
  11057. }
  11058. else {
  11059. this.canvas.sendBackwards(this, intersecting);
  11060. }
  11061. return this;
  11062. },
  11063. /**
  11064. * Moves an object up in stack of drawn objects
  11065. * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object
  11066. * @return {fabric.Object} thisArg
  11067. * @chainable
  11068. */
  11069. bringForward: function(intersecting) {
  11070. if (this.group) {
  11071. fabric.StaticCanvas.prototype.bringForward.call(this.group, this, intersecting);
  11072. }
  11073. else {
  11074. this.canvas.bringForward(this, intersecting);
  11075. }
  11076. return this;
  11077. },
  11078. /**
  11079. * Moves an object to specified level in stack of drawn objects
  11080. * @param {Number} index New position of object
  11081. * @return {fabric.Object} thisArg
  11082. * @chainable
  11083. */
  11084. moveTo: function(index) {
  11085. if (this.group) {
  11086. fabric.StaticCanvas.prototype.moveTo.call(this.group, this, index);
  11087. }
  11088. else {
  11089. this.canvas.moveTo(this, index);
  11090. }
  11091. return this;
  11092. }
  11093. });
  11094. /* _TO_SVG_START_ */
  11095. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  11096. /**
  11097. * Returns styles-string for svg-export
  11098. * @return {String}
  11099. */
  11100. getSvgStyles: function() {
  11101. var fill = this.fill
  11102. ? (this.fill.toLive ? 'url(#SVGID_' + this.fill.id + ')' : this.fill)
  11103. : 'none',
  11104. fillRule = this.fillRule,
  11105. stroke = this.stroke
  11106. ? (this.stroke.toLive ? 'url(#SVGID_' + this.stroke.id + ')' : this.stroke)
  11107. : 'none',
  11108. strokeWidth = this.strokeWidth ? this.strokeWidth : '0',
  11109. strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(' ') : '',
  11110. strokeLineCap = this.strokeLineCap ? this.strokeLineCap : 'butt',
  11111. strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : 'miter',
  11112. strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : '4',
  11113. opacity = typeof this.opacity !== 'undefined' ? this.opacity : '1',
  11114. visibility = this.visible ? '' : ' visibility: hidden;',
  11115. filter = this.shadow ? 'filter: url(#SVGID_' + this.shadow.id + ');' : '';
  11116. return [
  11117. 'stroke: ', stroke, '; ',
  11118. 'stroke-width: ', strokeWidth, '; ',
  11119. 'stroke-dasharray: ', strokeDashArray, '; ',
  11120. 'stroke-linecap: ', strokeLineCap, '; ',
  11121. 'stroke-linejoin: ', strokeLineJoin, '; ',
  11122. 'stroke-miterlimit: ', strokeMiterLimit, '; ',
  11123. 'fill: ', fill, '; ',
  11124. 'fill-rule: ', fillRule, '; ',
  11125. 'opacity: ', opacity, ';',
  11126. filter,
  11127. visibility
  11128. ].join('');
  11129. },
  11130. /**
  11131. * Returns transform-string for svg-export
  11132. * @return {String}
  11133. */
  11134. getSvgTransform: function() {
  11135. if (this.group && this.group.type === 'path-group') {
  11136. return '';
  11137. }
  11138. var toFixed = fabric.util.toFixed,
  11139. angle = this.getAngle(),
  11140. vpt = !this.canvas || this.canvas.svgViewportTransformation ? this.getViewportTransform() : [1, 0, 0, 1, 0, 0],
  11141. center = fabric.util.transformPoint(this.getCenterPoint(), vpt),
  11142. NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,
  11143. translatePart = this.type === 'path-group' ? '' : 'translate(' +
  11144. toFixed(center.x, NUM_FRACTION_DIGITS) +
  11145. ' ' +
  11146. toFixed(center.y, NUM_FRACTION_DIGITS) +
  11147. ')',
  11148. anglePart = angle !== 0
  11149. ? (' rotate(' + toFixed(angle, NUM_FRACTION_DIGITS) + ')')
  11150. : '',
  11151. scalePart = (this.scaleX === 1 && this.scaleY === 1 && vpt[0] === 1 && vpt[3] === 1)
  11152. ? '' :
  11153. (' scale(' +
  11154. toFixed(this.scaleX * vpt[0], NUM_FRACTION_DIGITS) +
  11155. ' ' +
  11156. toFixed(this.scaleY * vpt[3], NUM_FRACTION_DIGITS) +
  11157. ')'),
  11158. addTranslateX = this.type === 'path-group' ? this.width * vpt[0] : 0,
  11159. flipXPart = this.flipX ? ' matrix(-1 0 0 1 ' + addTranslateX + ' 0) ' : '',
  11160. addTranslateY = this.type === 'path-group' ? this.height * vpt[3] : 0,
  11161. flipYPart = this.flipY ? ' matrix(1 0 0 -1 0 ' + addTranslateY + ')' : '';
  11162. return [
  11163. translatePart, anglePart, scalePart, flipXPart, flipYPart
  11164. ].join('');
  11165. },
  11166. /**
  11167. * Returns transform-string for svg-export from the transform matrix of single elements
  11168. * @return {String}
  11169. */
  11170. getSvgTransformMatrix: function() {
  11171. return this.transformMatrix ? ' matrix(' + this.transformMatrix.join(' ') + ') ' : '';
  11172. },
  11173. /**
  11174. * @private
  11175. */
  11176. _createBaseSVGMarkup: function() {
  11177. var markup = [ ];
  11178. if (this.fill && this.fill.toLive) {
  11179. markup.push(this.fill.toSVG(this, false));
  11180. }
  11181. if (this.stroke && this.stroke.toLive) {
  11182. markup.push(this.stroke.toSVG(this, false));
  11183. }
  11184. if (this.shadow) {
  11185. markup.push(this.shadow.toSVG(this));
  11186. }
  11187. return markup;
  11188. }
  11189. });
  11190. /* _TO_SVG_END_ */
  11191. /*
  11192. Depends on `stateProperties`
  11193. */
  11194. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  11195. /**
  11196. * Returns true if object state (one of its state properties) was changed
  11197. * @return {Boolean} true if instance' state has changed since `{@link fabric.Object#saveState}` was called
  11198. */
  11199. hasStateChanged: function() {
  11200. return this.stateProperties.some(function(prop) {
  11201. return this.get(prop) !== this.originalState[prop];
  11202. }, this);
  11203. },
  11204. /**
  11205. * Saves state of an object
  11206. * @param {Object} [options] Object with additional `stateProperties` array to include when saving state
  11207. * @return {fabric.Object} thisArg
  11208. */
  11209. saveState: function(options) {
  11210. this.stateProperties.forEach(function(prop) {
  11211. this.originalState[prop] = this.get(prop);
  11212. }, this);
  11213. if (options && options.stateProperties) {
  11214. options.stateProperties.forEach(function(prop) {
  11215. this.originalState[prop] = this.get(prop);
  11216. }, this);
  11217. }
  11218. return this;
  11219. },
  11220. /**
  11221. * Setups state of an object
  11222. * @return {fabric.Object} thisArg
  11223. */
  11224. setupState: function() {
  11225. this.originalState = { };
  11226. this.saveState();
  11227. return this;
  11228. }
  11229. });
  11230. (function() {
  11231. var degreesToRadians = fabric.util.degreesToRadians,
  11232. //jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  11233. isVML = function() { return typeof G_vmlCanvasManager !== 'undefined'; };
  11234. //jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  11235. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  11236. /**
  11237. * The object interactivity controls.
  11238. * @private
  11239. */
  11240. _controlsVisibility: null,
  11241. /**
  11242. * Determines which corner has been clicked
  11243. * @private
  11244. * @param {Object} pointer The pointer indicating the mouse position
  11245. * @return {String|Boolean} corner code (tl, tr, bl, br, etc.), or false if nothing is found
  11246. */
  11247. _findTargetCorner: function(pointer) {
  11248. if (!this.hasControls || !this.active) {
  11249. return false;
  11250. }
  11251. var ex = pointer.x,
  11252. ey = pointer.y,
  11253. xPoints,
  11254. lines;
  11255. for (var i in this.oCoords) {
  11256. if (!this.isControlVisible(i)) {
  11257. continue;
  11258. }
  11259. if (i === 'mtr' && !this.hasRotatingPoint) {
  11260. continue;
  11261. }
  11262. if (this.get('lockUniScaling') &&
  11263. (i === 'mt' || i === 'mr' || i === 'mb' || i === 'ml')) {
  11264. continue;
  11265. }
  11266. lines = this._getImageLines(this.oCoords[i].corner);
  11267. // debugging
  11268. // canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);
  11269. // canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);
  11270. // canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);
  11271. // canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);
  11272. // canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);
  11273. // canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);
  11274. // canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);
  11275. // canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);
  11276. xPoints = this._findCrossPoints({ x: ex, y: ey }, lines);
  11277. if (xPoints !== 0 && xPoints % 2 === 1) {
  11278. this.__corner = i;
  11279. return i;
  11280. }
  11281. }
  11282. return false;
  11283. },
  11284. /**
  11285. * Sets the coordinates of the draggable boxes in the corners of
  11286. * the image used to scale/rotate it.
  11287. * @private
  11288. */
  11289. _setCornerCoords: function() {
  11290. var coords = this.oCoords,
  11291. newTheta = degreesToRadians(45 - this.angle),
  11292. cornerHypotenuse = Math.sqrt(2 * Math.pow(this.cornerSize, 2)) / 2,
  11293. cosHalfOffset = cornerHypotenuse * Math.cos(newTheta),
  11294. sinHalfOffset = cornerHypotenuse * Math.sin(newTheta),
  11295. x, y;
  11296. for (var point in coords) {
  11297. x = coords[point].x;
  11298. y = coords[point].y;
  11299. coords[point].corner = {
  11300. tl: {
  11301. x: x - sinHalfOffset,
  11302. y: y - cosHalfOffset
  11303. },
  11304. tr: {
  11305. x: x + cosHalfOffset,
  11306. y: y - sinHalfOffset
  11307. },
  11308. bl: {
  11309. x: x - cosHalfOffset,
  11310. y: y + sinHalfOffset
  11311. },
  11312. br: {
  11313. x: x + sinHalfOffset,
  11314. y: y + cosHalfOffset
  11315. }
  11316. };
  11317. }
  11318. },
  11319. _calculateCurrentDimensions: function(shouldTransform) {
  11320. var vpt = this.getViewportTransform(),
  11321. strokeWidth = this.strokeWidth,
  11322. w = this.width,
  11323. h = this.height,
  11324. capped = this.strokeLineCap === 'round' || this.strokeLineCap === 'square',
  11325. vLine = this.type === 'line' && this.width === 0,
  11326. hLine = this.type === 'line' && this.height === 0,
  11327. sLine = vLine || hLine,
  11328. strokeW = (capped && hLine) || !sLine,
  11329. strokeH = (capped && vLine) || !sLine;
  11330. if (vLine) {
  11331. w = strokeWidth;
  11332. }
  11333. else if (hLine) {
  11334. h = strokeWidth;
  11335. }
  11336. if (strokeW) {
  11337. w += (w < 0 ? -strokeWidth : strokeWidth);
  11338. }
  11339. if (strokeH) {
  11340. h += (h < 0 ? -strokeWidth : strokeWidth);
  11341. }
  11342. w = w * this.scaleX + 2 * this.padding;
  11343. h = h * this.scaleY + 2 * this.padding;
  11344. if (shouldTransform) {
  11345. return fabric.util.transformPoint(new fabric.Point(w, h), vpt, true);
  11346. }
  11347. return { x: w, y: h };
  11348. },
  11349. /**
  11350. * Draws borders of an object's bounding box.
  11351. * Requires public properties: width, height
  11352. * Requires public options: padding, borderColor
  11353. * @param {CanvasRenderingContext2D} ctx Context to draw on
  11354. * @return {fabric.Object} thisArg
  11355. * @chainable
  11356. */
  11357. drawBorders: function(ctx) {
  11358. if (!this.hasBorders) {
  11359. return this;
  11360. }
  11361. ctx.save();
  11362. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  11363. ctx.strokeStyle = this.borderColor;
  11364. ctx.lineWidth = 1 / this.borderScaleFactor;
  11365. var wh = this._calculateCurrentDimensions(true),
  11366. width = wh.x,
  11367. height = wh.y;
  11368. if (this.group) {
  11369. width = width * this.group.scaleX;
  11370. height = height * this.group.scaleY;
  11371. }
  11372. ctx.strokeRect(
  11373. ~~(-(width / 2)) - 0.5, // offset needed to make lines look sharper
  11374. ~~(-(height / 2)) - 0.5,
  11375. ~~(width) + 1, // double offset needed to make lines look sharper
  11376. ~~(height) + 1
  11377. );
  11378. if (this.hasRotatingPoint && this.isControlVisible('mtr') && !this.get('lockRotation') && this.hasControls) {
  11379. var rotateHeight = -height / 2;
  11380. ctx.beginPath();
  11381. ctx.moveTo(0, rotateHeight);
  11382. ctx.lineTo(0, rotateHeight - this.rotatingPointOffset);
  11383. ctx.closePath();
  11384. ctx.stroke();
  11385. }
  11386. ctx.restore();
  11387. return this;
  11388. },
  11389. /**
  11390. * Draws corners of an object's bounding box.
  11391. * Requires public properties: width, height
  11392. * Requires public options: cornerSize, padding
  11393. * @param {CanvasRenderingContext2D} ctx Context to draw on
  11394. * @return {fabric.Object} thisArg
  11395. * @chainable
  11396. */
  11397. drawControls: function(ctx) {
  11398. if (!this.hasControls) {
  11399. return this;
  11400. }
  11401. var wh = this._calculateCurrentDimensions(true),
  11402. width = wh.x,
  11403. height = wh.y,
  11404. left = -(width / 2),
  11405. top = -(height / 2),
  11406. scaleOffset = this.cornerSize / 2,
  11407. methodName = this.transparentCorners ? 'strokeRect' : 'fillRect';
  11408. ctx.save();
  11409. ctx.lineWidth = 1;
  11410. ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
  11411. ctx.strokeStyle = ctx.fillStyle = this.cornerColor;
  11412. // top-left
  11413. this._drawControl('tl', ctx, methodName,
  11414. left - scaleOffset,
  11415. top - scaleOffset);
  11416. // top-right
  11417. this._drawControl('tr', ctx, methodName,
  11418. left + width - scaleOffset,
  11419. top - scaleOffset);
  11420. // bottom-left
  11421. this._drawControl('bl', ctx, methodName,
  11422. left - scaleOffset,
  11423. top + height - scaleOffset);
  11424. // bottom-right
  11425. this._drawControl('br', ctx, methodName,
  11426. left + width - scaleOffset,
  11427. top + height - scaleOffset);
  11428. if (!this.get('lockUniScaling')) {
  11429. // middle-top
  11430. this._drawControl('mt', ctx, methodName,
  11431. left + width/2 - scaleOffset,
  11432. top - scaleOffset);
  11433. // middle-bottom
  11434. this._drawControl('mb', ctx, methodName,
  11435. left + width/2 - scaleOffset,
  11436. top + height - scaleOffset);
  11437. // middle-right
  11438. this._drawControl('mr', ctx, methodName,
  11439. left + width - scaleOffset,
  11440. top + height/2 - scaleOffset);
  11441. // middle-left
  11442. this._drawControl('ml', ctx, methodName,
  11443. left - scaleOffset,
  11444. top + height/2 - scaleOffset);
  11445. }
  11446. // middle-top-rotate
  11447. if (this.hasRotatingPoint) {
  11448. this._drawControl('mtr', ctx, methodName,
  11449. left + width/2 - scaleOffset,
  11450. top - this.rotatingPointOffset - scaleOffset);
  11451. }
  11452. ctx.restore();
  11453. return this;
  11454. },
  11455. /**
  11456. * @private
  11457. */
  11458. _drawControl: function(control, ctx, methodName, left, top) {
  11459. if (!this.isControlVisible(control)) {
  11460. return;
  11461. }
  11462. var size = this.cornerSize;
  11463. isVML() || this.transparentCorners || ctx.clearRect(left, top, size, size);
  11464. ctx[methodName](left, top, size, size);
  11465. },
  11466. /**
  11467. * Returns true if the specified control is visible, false otherwise.
  11468. * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  11469. * @returns {Boolean} true if the specified control is visible, false otherwise
  11470. */
  11471. isControlVisible: function(controlName) {
  11472. return this._getControlsVisibility()[controlName];
  11473. },
  11474. /**
  11475. * Sets the visibility of the specified control.
  11476. * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'.
  11477. * @param {Boolean} visible true to set the specified control visible, false otherwise
  11478. * @return {fabric.Object} thisArg
  11479. * @chainable
  11480. */
  11481. setControlVisible: function(controlName, visible) {
  11482. this._getControlsVisibility()[controlName] = visible;
  11483. return this;
  11484. },
  11485. /**
  11486. * Sets the visibility state of object controls.
  11487. * @param {Object} [options] Options object
  11488. * @param {Boolean} [options.bl] true to enable the bottom-left control, false to disable it
  11489. * @param {Boolean} [options.br] true to enable the bottom-right control, false to disable it
  11490. * @param {Boolean} [options.mb] true to enable the middle-bottom control, false to disable it
  11491. * @param {Boolean} [options.ml] true to enable the middle-left control, false to disable it
  11492. * @param {Boolean} [options.mr] true to enable the middle-right control, false to disable it
  11493. * @param {Boolean} [options.mt] true to enable the middle-top control, false to disable it
  11494. * @param {Boolean} [options.tl] true to enable the top-left control, false to disable it
  11495. * @param {Boolean} [options.tr] true to enable the top-right control, false to disable it
  11496. * @param {Boolean} [options.mtr] true to enable the middle-top-rotate control, false to disable it
  11497. * @return {fabric.Object} thisArg
  11498. * @chainable
  11499. */
  11500. setControlsVisibility: function(options) {
  11501. options || (options = { });
  11502. for (var p in options) {
  11503. this.setControlVisible(p, options[p]);
  11504. }
  11505. return this;
  11506. },
  11507. /**
  11508. * Returns the instance of the control visibility set for this object.
  11509. * @private
  11510. * @returns {Object}
  11511. */
  11512. _getControlsVisibility: function() {
  11513. if (!this._controlsVisibility) {
  11514. this._controlsVisibility = {
  11515. tl: true,
  11516. tr: true,
  11517. br: true,
  11518. bl: true,
  11519. ml: true,
  11520. mt: true,
  11521. mr: true,
  11522. mb: true,
  11523. mtr: true
  11524. };
  11525. }
  11526. return this._controlsVisibility;
  11527. }
  11528. });
  11529. })();
  11530. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  11531. /**
  11532. * Animation duration (in ms) for fx* methods
  11533. * @type Number
  11534. * @default
  11535. */
  11536. FX_DURATION: 500,
  11537. /**
  11538. * Centers object horizontally with animation.
  11539. * @param {fabric.Object} object Object to center
  11540. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  11541. * @param {Function} [callbacks.onComplete] Invoked on completion
  11542. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  11543. * @return {fabric.Canvas} thisArg
  11544. * @chainable
  11545. */
  11546. fxCenterObjectH: function (object, callbacks) {
  11547. callbacks = callbacks || { };
  11548. var empty = function() { },
  11549. onComplete = callbacks.onComplete || empty,
  11550. onChange = callbacks.onChange || empty,
  11551. _this = this;
  11552. fabric.util.animate({
  11553. startValue: object.get('left'),
  11554. endValue: this.getCenter().left,
  11555. duration: this.FX_DURATION,
  11556. onChange: function(value) {
  11557. object.set('left', value);
  11558. _this.renderAll();
  11559. onChange();
  11560. },
  11561. onComplete: function() {
  11562. object.setCoords();
  11563. onComplete();
  11564. }
  11565. });
  11566. return this;
  11567. },
  11568. /**
  11569. * Centers object vertically with animation.
  11570. * @param {fabric.Object} object Object to center
  11571. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  11572. * @param {Function} [callbacks.onComplete] Invoked on completion
  11573. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  11574. * @return {fabric.Canvas} thisArg
  11575. * @chainable
  11576. */
  11577. fxCenterObjectV: function (object, callbacks) {
  11578. callbacks = callbacks || { };
  11579. var empty = function() { },
  11580. onComplete = callbacks.onComplete || empty,
  11581. onChange = callbacks.onChange || empty,
  11582. _this = this;
  11583. fabric.util.animate({
  11584. startValue: object.get('top'),
  11585. endValue: this.getCenter().top,
  11586. duration: this.FX_DURATION,
  11587. onChange: function(value) {
  11588. object.set('top', value);
  11589. _this.renderAll();
  11590. onChange();
  11591. },
  11592. onComplete: function() {
  11593. object.setCoords();
  11594. onComplete();
  11595. }
  11596. });
  11597. return this;
  11598. },
  11599. /**
  11600. * Same as `fabric.Canvas#remove` but animated
  11601. * @param {fabric.Object} object Object to remove
  11602. * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties
  11603. * @param {Function} [callbacks.onComplete] Invoked on completion
  11604. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  11605. * @return {fabric.Canvas} thisArg
  11606. * @chainable
  11607. */
  11608. fxRemove: function (object, callbacks) {
  11609. callbacks = callbacks || { };
  11610. var empty = function() { },
  11611. onComplete = callbacks.onComplete || empty,
  11612. onChange = callbacks.onChange || empty,
  11613. _this = this;
  11614. fabric.util.animate({
  11615. startValue: object.get('opacity'),
  11616. endValue: 0,
  11617. duration: this.FX_DURATION,
  11618. onStart: function() {
  11619. object.set('active', false);
  11620. },
  11621. onChange: function(value) {
  11622. object.set('opacity', value);
  11623. _this.renderAll();
  11624. onChange();
  11625. },
  11626. onComplete: function () {
  11627. _this.remove(object);
  11628. onComplete();
  11629. }
  11630. });
  11631. return this;
  11632. }
  11633. });
  11634. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  11635. /**
  11636. * Animates object's properties
  11637. * @param {String|Object} property Property to animate (if string) or properties to animate (if object)
  11638. * @param {Number|Object} value Value to animate property to (if string was given first) or options object
  11639. * @return {fabric.Object} thisArg
  11640. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#animation}
  11641. * @chainable
  11642. *
  11643. * As object — multiple properties
  11644. *
  11645. * object.animate({ left: ..., top: ... });
  11646. * object.animate({ left: ..., top: ... }, { duration: ... });
  11647. *
  11648. * As string — one property
  11649. *
  11650. * object.animate('left', ...);
  11651. * object.animate('left', { duration: ... });
  11652. *
  11653. */
  11654. animate: function() {
  11655. if (arguments[0] && typeof arguments[0] === 'object') {
  11656. var propsToAnimate = [ ], prop, skipCallbacks;
  11657. for (prop in arguments[0]) {
  11658. propsToAnimate.push(prop);
  11659. }
  11660. for (var i = 0, len = propsToAnimate.length; i < len; i++) {
  11661. prop = propsToAnimate[i];
  11662. skipCallbacks = i !== len - 1;
  11663. this._animate(prop, arguments[0][prop], arguments[1], skipCallbacks);
  11664. }
  11665. }
  11666. else {
  11667. this._animate.apply(this, arguments);
  11668. }
  11669. return this;
  11670. },
  11671. /**
  11672. * @private
  11673. * @param {String} property Property to animate
  11674. * @param {String} to Value to animate to
  11675. * @param {Object} [options] Options object
  11676. * @param {Boolean} [skipCallbacks] When true, callbacks like onchange and oncomplete are not invoked
  11677. */
  11678. _animate: function(property, to, options, skipCallbacks) {
  11679. var _this = this, propPair;
  11680. to = to.toString();
  11681. if (!options) {
  11682. options = { };
  11683. }
  11684. else {
  11685. options = fabric.util.object.clone(options);
  11686. }
  11687. if (~property.indexOf('.')) {
  11688. propPair = property.split('.');
  11689. }
  11690. var currentValue = propPair
  11691. ? this.get(propPair[0])[propPair[1]]
  11692. : this.get(property);
  11693. if (!('from' in options)) {
  11694. options.from = currentValue;
  11695. }
  11696. if (~to.indexOf('=')) {
  11697. to = currentValue + parseFloat(to.replace('=', ''));
  11698. }
  11699. else {
  11700. to = parseFloat(to);
  11701. }
  11702. fabric.util.animate({
  11703. startValue: options.from,
  11704. endValue: to,
  11705. byValue: options.by,
  11706. easing: options.easing,
  11707. duration: options.duration,
  11708. abort: options.abort && function() {
  11709. return options.abort.call(_this);
  11710. },
  11711. onChange: function(value) {
  11712. if (propPair) {
  11713. _this[propPair[0]][propPair[1]] = value;
  11714. }
  11715. else {
  11716. _this.set(property, value);
  11717. }
  11718. if (skipCallbacks) {
  11719. return;
  11720. }
  11721. options.onChange && options.onChange();
  11722. },
  11723. onComplete: function() {
  11724. if (skipCallbacks) {
  11725. return;
  11726. }
  11727. _this.setCoords();
  11728. options.onComplete && options.onComplete();
  11729. }
  11730. });
  11731. }
  11732. });
  11733. (function(global) {
  11734. 'use strict';
  11735. var fabric = global.fabric || (global.fabric = { }),
  11736. extend = fabric.util.object.extend,
  11737. coordProps = { x1: 1, x2: 1, y1: 1, y2: 1 },
  11738. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  11739. if (fabric.Line) {
  11740. fabric.warn('fabric.Line is already defined');
  11741. return;
  11742. }
  11743. /**
  11744. * Line class
  11745. * @class fabric.Line
  11746. * @extends fabric.Object
  11747. * @see {@link fabric.Line#initialize} for constructor definition
  11748. */
  11749. fabric.Line = fabric.util.createClass(fabric.Object, /** @lends fabric.Line.prototype */ {
  11750. /**
  11751. * Type of an object
  11752. * @type String
  11753. * @default
  11754. */
  11755. type: 'line',
  11756. /**
  11757. * x value or first line edge
  11758. * @type Number
  11759. * @default
  11760. */
  11761. x1: 0,
  11762. /**
  11763. * y value or first line edge
  11764. * @type Number
  11765. * @default
  11766. */
  11767. y1: 0,
  11768. /**
  11769. * x value or second line edge
  11770. * @type Number
  11771. * @default
  11772. */
  11773. x2: 0,
  11774. /**
  11775. * y value or second line edge
  11776. * @type Number
  11777. * @default
  11778. */
  11779. y2: 0,
  11780. /**
  11781. * Constructor
  11782. * @param {Array} [points] Array of points
  11783. * @param {Object} [options] Options object
  11784. * @return {fabric.Line} thisArg
  11785. */
  11786. initialize: function(points, options) {
  11787. options = options || { };
  11788. if (!points) {
  11789. points = [0, 0, 0, 0];
  11790. }
  11791. this.callSuper('initialize', options);
  11792. this.set('x1', points[0]);
  11793. this.set('y1', points[1]);
  11794. this.set('x2', points[2]);
  11795. this.set('y2', points[3]);
  11796. this._setWidthHeight(options);
  11797. },
  11798. /**
  11799. * @private
  11800. * @param {Object} [options] Options
  11801. */
  11802. _setWidthHeight: function(options) {
  11803. options || (options = { });
  11804. this.width = Math.abs(this.x2 - this.x1);
  11805. this.height = Math.abs(this.y2 - this.y1);
  11806. this.left = 'left' in options
  11807. ? options.left
  11808. : this._getLeftToOriginX();
  11809. this.top = 'top' in options
  11810. ? options.top
  11811. : this._getTopToOriginY();
  11812. },
  11813. /**
  11814. * @private
  11815. * @param {String} key
  11816. * @param {Any} value
  11817. */
  11818. _set: function(key, value) {
  11819. this.callSuper('_set', key, value);
  11820. if (typeof coordProps[key] !== 'undefined') {
  11821. this._setWidthHeight();
  11822. }
  11823. return this;
  11824. },
  11825. /**
  11826. * @private
  11827. * @return {Number} leftToOriginX Distance from left edge of canvas to originX of Line.
  11828. */
  11829. _getLeftToOriginX: makeEdgeToOriginGetter(
  11830. { // property names
  11831. origin: 'originX',
  11832. axis1: 'x1',
  11833. axis2: 'x2',
  11834. dimension: 'width'
  11835. },
  11836. { // possible values of origin
  11837. nearest: 'left',
  11838. center: 'center',
  11839. farthest: 'right'
  11840. }
  11841. ),
  11842. /**
  11843. * @private
  11844. * @return {Number} topToOriginY Distance from top edge of canvas to originY of Line.
  11845. */
  11846. _getTopToOriginY: makeEdgeToOriginGetter(
  11847. { // property names
  11848. origin: 'originY',
  11849. axis1: 'y1',
  11850. axis2: 'y2',
  11851. dimension: 'height'
  11852. },
  11853. { // possible values of origin
  11854. nearest: 'top',
  11855. center: 'center',
  11856. farthest: 'bottom'
  11857. }
  11858. ),
  11859. /**
  11860. * @private
  11861. * @param {CanvasRenderingContext2D} ctx Context to render on
  11862. */
  11863. _render: function(ctx, noTransform) {
  11864. ctx.beginPath();
  11865. if (noTransform) {
  11866. // Line coords are distances from left-top of canvas to origin of line.
  11867. // To render line in a path-group, we need to translate them to
  11868. // distances from center of path-group to center of line.
  11869. var cp = this.getCenterPoint();
  11870. ctx.translate(
  11871. cp.x - this.strokeWidth / 2,
  11872. cp.y - this.strokeWidth / 2
  11873. );
  11874. }
  11875. if (!this.strokeDashArray || this.strokeDashArray && supportsLineDash) {
  11876. // move from center (of virtual box) to its left/top corner
  11877. // we can't assume x1, y1 is top left and x2, y2 is bottom right
  11878. var p = this.calcLinePoints();
  11879. ctx.moveTo(p.x1, p.y1);
  11880. ctx.lineTo(p.x2, p.y2);
  11881. }
  11882. ctx.lineWidth = this.strokeWidth;
  11883. // TODO: test this
  11884. // make sure setting "fill" changes color of a line
  11885. // (by copying fillStyle to strokeStyle, since line is stroked, not filled)
  11886. var origStrokeStyle = ctx.strokeStyle;
  11887. ctx.strokeStyle = this.stroke || ctx.fillStyle;
  11888. this.stroke && this._renderStroke(ctx);
  11889. ctx.strokeStyle = origStrokeStyle;
  11890. },
  11891. /**
  11892. * @private
  11893. * @param {CanvasRenderingContext2D} ctx Context to render on
  11894. */
  11895. _renderDashedStroke: function(ctx) {
  11896. var p = this.calcLinePoints();
  11897. ctx.beginPath();
  11898. fabric.util.drawDashedLine(ctx, p.x1, p.y1, p.x2, p.y2, this.strokeDashArray);
  11899. ctx.closePath();
  11900. },
  11901. /**
  11902. * Returns object representation of an instance
  11903. * @methd toObject
  11904. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  11905. * @return {Object} object representation of an instance
  11906. */
  11907. toObject: function(propertiesToInclude) {
  11908. return extend(this.callSuper('toObject', propertiesToInclude), this.calcLinePoints());
  11909. },
  11910. /**
  11911. * Recalculates line points given width and height
  11912. * @private
  11913. */
  11914. calcLinePoints: function() {
  11915. var xMult = this.x1 <= this.x2 ? -1 : 1,
  11916. yMult = this.y1 <= this.y2 ? -1 : 1,
  11917. x1 = (xMult * this.width * 0.5),
  11918. y1 = (yMult * this.height * 0.5),
  11919. x2 = (xMult * this.width * -0.5),
  11920. y2 = (yMult * this.height * -0.5);
  11921. return {
  11922. x1: x1,
  11923. x2: x2,
  11924. y1: y1,
  11925. y2: y2
  11926. };
  11927. },
  11928. /* _TO_SVG_START_ */
  11929. /**
  11930. * Returns SVG representation of an instance
  11931. * @param {Function} [reviver] Method for further parsing of svg representation.
  11932. * @return {String} svg representation of an instance
  11933. */
  11934. toSVG: function(reviver) {
  11935. var markup = this._createBaseSVGMarkup(),
  11936. p = { x1: this.x1, x2: this.x2, y1: this.y1, y2: this.y2 };
  11937. if (!(this.group && this.group.type === 'path-group')) {
  11938. p = this.calcLinePoints();
  11939. }
  11940. markup.push(
  11941. '<line ',
  11942. 'x1="', p.x1,
  11943. '" y1="', p.y1,
  11944. '" x2="', p.x2,
  11945. '" y2="', p.y2,
  11946. '" style="', this.getSvgStyles(),
  11947. '" transform="', this.getSvgTransform(),
  11948. this.getSvgTransformMatrix(),
  11949. '"/>\n'
  11950. );
  11951. return reviver ? reviver(markup.join('')) : markup.join('');
  11952. },
  11953. /* _TO_SVG_END_ */
  11954. /**
  11955. * Returns complexity of an instance
  11956. * @return {Number} complexity
  11957. */
  11958. complexity: function() {
  11959. return 1;
  11960. }
  11961. });
  11962. /* _FROM_SVG_START_ */
  11963. /**
  11964. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Line.fromElement})
  11965. * @static
  11966. * @memberOf fabric.Line
  11967. * @see http://www.w3.org/TR/SVG/shapes.html#LineElement
  11968. */
  11969. fabric.Line.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x1 y1 x2 y2'.split(' '));
  11970. /**
  11971. * Returns fabric.Line instance from an SVG element
  11972. * @static
  11973. * @memberOf fabric.Line
  11974. * @param {SVGElement} element Element to parse
  11975. * @param {Object} [options] Options object
  11976. * @return {fabric.Line} instance of fabric.Line
  11977. */
  11978. fabric.Line.fromElement = function(element, options) {
  11979. var parsedAttributes = fabric.parseAttributes(element, fabric.Line.ATTRIBUTE_NAMES),
  11980. points = [
  11981. parsedAttributes.x1 || 0,
  11982. parsedAttributes.y1 || 0,
  11983. parsedAttributes.x2 || 0,
  11984. parsedAttributes.y2 || 0
  11985. ];
  11986. return new fabric.Line(points, extend(parsedAttributes, options));
  11987. };
  11988. /* _FROM_SVG_END_ */
  11989. /**
  11990. * Returns fabric.Line instance from an object representation
  11991. * @static
  11992. * @memberOf fabric.Line
  11993. * @param {Object} object Object to create an instance from
  11994. * @return {fabric.Line} instance of fabric.Line
  11995. */
  11996. fabric.Line.fromObject = function(object) {
  11997. var points = [object.x1, object.y1, object.x2, object.y2];
  11998. return new fabric.Line(points, object);
  11999. };
  12000. /**
  12001. * Produces a function that calculates distance from canvas edge to Line origin.
  12002. */
  12003. function makeEdgeToOriginGetter(propertyNames, originValues) {
  12004. var origin = propertyNames.origin,
  12005. axis1 = propertyNames.axis1,
  12006. axis2 = propertyNames.axis2,
  12007. dimension = propertyNames.dimension,
  12008. nearest = originValues.nearest,
  12009. center = originValues.center,
  12010. farthest = originValues.farthest;
  12011. return function() {
  12012. switch (this.get(origin)) {
  12013. case nearest:
  12014. return Math.min(this.get(axis1), this.get(axis2));
  12015. case center:
  12016. return Math.min(this.get(axis1), this.get(axis2)) + (0.5 * this.get(dimension));
  12017. case farthest:
  12018. return Math.max(this.get(axis1), this.get(axis2));
  12019. }
  12020. };
  12021. }
  12022. })(typeof exports !== 'undefined' ? exports : this);
  12023. (function(global) {
  12024. 'use strict';
  12025. var fabric = global.fabric || (global.fabric = { }),
  12026. pi = Math.PI,
  12027. extend = fabric.util.object.extend;
  12028. if (fabric.Circle) {
  12029. fabric.warn('fabric.Circle is already defined.');
  12030. return;
  12031. }
  12032. /**
  12033. * Circle class
  12034. * @class fabric.Circle
  12035. * @extends fabric.Object
  12036. * @see {@link fabric.Circle#initialize} for constructor definition
  12037. */
  12038. fabric.Circle = fabric.util.createClass(fabric.Object, /** @lends fabric.Circle.prototype */ {
  12039. /**
  12040. * Type of an object
  12041. * @type String
  12042. * @default
  12043. */
  12044. type: 'circle',
  12045. /**
  12046. * Radius of this circle
  12047. * @type Number
  12048. * @default
  12049. */
  12050. radius: 0,
  12051. /**
  12052. * Start angle of the circle, moving clockwise
  12053. * @type Number
  12054. * @default 0
  12055. */
  12056. startAngle: 0,
  12057. /**
  12058. * End angle of the circle
  12059. * @type Number
  12060. * @default 2Pi
  12061. */
  12062. endAngle: pi * 2,
  12063. /**
  12064. * Constructor
  12065. * @param {Object} [options] Options object
  12066. * @return {fabric.Circle} thisArg
  12067. */
  12068. initialize: function(options) {
  12069. options = options || { };
  12070. this.callSuper('initialize', options);
  12071. this.set('radius', options.radius || 0);
  12072. this.startAngle = options.startAngle || this.startAngle;
  12073. this.endAngle = options.endAngle || this.endAngle;
  12074. },
  12075. /**
  12076. * @private
  12077. * @param {String} key
  12078. * @param {Any} value
  12079. * @return {fabric.Circle} thisArg
  12080. */
  12081. _set: function(key, value) {
  12082. this.callSuper('_set', key, value);
  12083. if (key === 'radius') {
  12084. this.setRadius(value);
  12085. }
  12086. return this;
  12087. },
  12088. /**
  12089. * Returns object representation of an instance
  12090. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  12091. * @return {Object} object representation of an instance
  12092. */
  12093. toObject: function(propertiesToInclude) {
  12094. return extend(this.callSuper('toObject', propertiesToInclude), {
  12095. radius: this.get('radius'),
  12096. startAngle: this.startAngle,
  12097. endAngle: this.endAngle
  12098. });
  12099. },
  12100. /* _TO_SVG_START_ */
  12101. /**
  12102. * Returns svg representation of an instance
  12103. * @param {Function} [reviver] Method for further parsing of svg representation.
  12104. * @return {String} svg representation of an instance
  12105. */
  12106. toSVG: function(reviver) {
  12107. var markup = this._createBaseSVGMarkup(), x = 0, y = 0,
  12108. angle = (this.endAngle - this.startAngle) % ( 2 * pi);
  12109. if (angle === 0) {
  12110. if (this.group && this.group.type === 'path-group') {
  12111. x = this.left + this.radius;
  12112. y = this.top + this.radius;
  12113. }
  12114. markup.push(
  12115. '<circle ',
  12116. 'cx="' + x + '" cy="' + y + '" ',
  12117. 'r="', this.radius,
  12118. '" style="', this.getSvgStyles(),
  12119. '" transform="', this.getSvgTransform(),
  12120. ' ', this.getSvgTransformMatrix(),
  12121. '"/>\n'
  12122. );
  12123. }
  12124. else {
  12125. var startX = Math.cos(this.startAngle) * this.radius,
  12126. startY = Math.sin(this.startAngle) * this.radius,
  12127. endX = Math.cos(this.endAngle) * this.radius,
  12128. endY = Math.sin(this.endAngle) * this.radius,
  12129. largeFlag = angle > pi ? '1' : '0';
  12130. markup.push(
  12131. '<path d="M ' + startX + ' ' + startY,
  12132. ' A ' + this.radius + ' ' + this.radius,
  12133. ' 0 ', + largeFlag + ' 1', ' ' + endX + ' ' + endY,
  12134. '" style="', this.getSvgStyles(),
  12135. '" transform="', this.getSvgTransform(),
  12136. ' ', this.getSvgTransformMatrix(),
  12137. '"/>\n'
  12138. );
  12139. }
  12140. return reviver ? reviver(markup.join('')) : markup.join('');
  12141. },
  12142. /* _TO_SVG_END_ */
  12143. /**
  12144. * @private
  12145. * @param {CanvasRenderingContext2D} ctx context to render on
  12146. * @param {Boolean} [noTransform] When true, context is not transformed
  12147. */
  12148. _render: function(ctx, noTransform) {
  12149. ctx.beginPath();
  12150. ctx.arc(noTransform ? this.left + this.radius : 0,
  12151. noTransform ? this.top + this.radius : 0,
  12152. this.radius,
  12153. this.startAngle,
  12154. this.endAngle, false);
  12155. this._renderFill(ctx);
  12156. this._renderStroke(ctx);
  12157. },
  12158. /**
  12159. * Returns horizontal radius of an object (according to how an object is scaled)
  12160. * @return {Number}
  12161. */
  12162. getRadiusX: function() {
  12163. return this.get('radius') * this.get('scaleX');
  12164. },
  12165. /**
  12166. * Returns vertical radius of an object (according to how an object is scaled)
  12167. * @return {Number}
  12168. */
  12169. getRadiusY: function() {
  12170. return this.get('radius') * this.get('scaleY');
  12171. },
  12172. /**
  12173. * Sets radius of an object (and updates width accordingly)
  12174. * @return {Number}
  12175. */
  12176. setRadius: function(value) {
  12177. this.radius = value;
  12178. this.set('width', value * 2).set('height', value * 2);
  12179. },
  12180. /**
  12181. * Returns complexity of an instance
  12182. * @return {Number} complexity of this instance
  12183. */
  12184. complexity: function() {
  12185. return 1;
  12186. }
  12187. });
  12188. /* _FROM_SVG_START_ */
  12189. /**
  12190. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement})
  12191. * @static
  12192. * @memberOf fabric.Circle
  12193. * @see: http://www.w3.org/TR/SVG/shapes.html#CircleElement
  12194. */
  12195. fabric.Circle.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy r'.split(' '));
  12196. /**
  12197. * Returns {@link fabric.Circle} instance from an SVG element
  12198. * @static
  12199. * @memberOf fabric.Circle
  12200. * @param {SVGElement} element Element to parse
  12201. * @param {Object} [options] Options object
  12202. * @throws {Error} If value of `r` attribute is missing or invalid
  12203. * @return {fabric.Circle} Instance of fabric.Circle
  12204. */
  12205. fabric.Circle.fromElement = function(element, options) {
  12206. options || (options = { });
  12207. var parsedAttributes = fabric.parseAttributes(element, fabric.Circle.ATTRIBUTE_NAMES);
  12208. if (!isValidRadius(parsedAttributes)) {
  12209. throw new Error('value of `r` attribute is required and can not be negative');
  12210. }
  12211. parsedAttributes.left = parsedAttributes.left || 0;
  12212. parsedAttributes.top = parsedAttributes.top || 0;
  12213. var obj = new fabric.Circle(extend(parsedAttributes, options));
  12214. obj.left -= obj.radius;
  12215. obj.top -= obj.radius;
  12216. return obj;
  12217. };
  12218. /**
  12219. * @private
  12220. */
  12221. function isValidRadius(attributes) {
  12222. return (('radius' in attributes) && (attributes.radius >= 0));
  12223. }
  12224. /* _FROM_SVG_END_ */
  12225. /**
  12226. * Returns {@link fabric.Circle} instance from an object representation
  12227. * @static
  12228. * @memberOf fabric.Circle
  12229. * @param {Object} object Object to create an instance from
  12230. * @return {Object} Instance of fabric.Circle
  12231. */
  12232. fabric.Circle.fromObject = function(object) {
  12233. return new fabric.Circle(object);
  12234. };
  12235. })(typeof exports !== 'undefined' ? exports : this);
  12236. (function(global) {
  12237. 'use strict';
  12238. var fabric = global.fabric || (global.fabric = { });
  12239. if (fabric.Triangle) {
  12240. fabric.warn('fabric.Triangle is already defined');
  12241. return;
  12242. }
  12243. /**
  12244. * Triangle class
  12245. * @class fabric.Triangle
  12246. * @extends fabric.Object
  12247. * @return {fabric.Triangle} thisArg
  12248. * @see {@link fabric.Triangle#initialize} for constructor definition
  12249. */
  12250. fabric.Triangle = fabric.util.createClass(fabric.Object, /** @lends fabric.Triangle.prototype */ {
  12251. /**
  12252. * Type of an object
  12253. * @type String
  12254. * @default
  12255. */
  12256. type: 'triangle',
  12257. /**
  12258. * Constructor
  12259. * @param {Object} [options] Options object
  12260. * @return {Object} thisArg
  12261. */
  12262. initialize: function(options) {
  12263. options = options || { };
  12264. this.callSuper('initialize', options);
  12265. this.set('width', options.width || 100)
  12266. .set('height', options.height || 100);
  12267. },
  12268. /**
  12269. * @private
  12270. * @param {CanvasRenderingContext2D} ctx Context to render on
  12271. */
  12272. _render: function(ctx) {
  12273. var widthBy2 = this.width / 2,
  12274. heightBy2 = this.height / 2;
  12275. ctx.beginPath();
  12276. ctx.moveTo(-widthBy2, heightBy2);
  12277. ctx.lineTo(0, -heightBy2);
  12278. ctx.lineTo(widthBy2, heightBy2);
  12279. ctx.closePath();
  12280. this._renderFill(ctx);
  12281. this._renderStroke(ctx);
  12282. },
  12283. /**
  12284. * @private
  12285. * @param {CanvasRenderingContext2D} ctx Context to render on
  12286. */
  12287. _renderDashedStroke: function(ctx) {
  12288. var widthBy2 = this.width / 2,
  12289. heightBy2 = this.height / 2;
  12290. ctx.beginPath();
  12291. fabric.util.drawDashedLine(ctx, -widthBy2, heightBy2, 0, -heightBy2, this.strokeDashArray);
  12292. fabric.util.drawDashedLine(ctx, 0, -heightBy2, widthBy2, heightBy2, this.strokeDashArray);
  12293. fabric.util.drawDashedLine(ctx, widthBy2, heightBy2, -widthBy2, heightBy2, this.strokeDashArray);
  12294. ctx.closePath();
  12295. },
  12296. /* _TO_SVG_START_ */
  12297. /**
  12298. * Returns SVG representation of an instance
  12299. * @param {Function} [reviver] Method for further parsing of svg representation.
  12300. * @return {String} svg representation of an instance
  12301. */
  12302. toSVG: function(reviver) {
  12303. var markup = this._createBaseSVGMarkup(),
  12304. widthBy2 = this.width / 2,
  12305. heightBy2 = this.height / 2,
  12306. points = [
  12307. -widthBy2 + ' ' + heightBy2,
  12308. '0 ' + -heightBy2,
  12309. widthBy2 + ' ' + heightBy2
  12310. ]
  12311. .join(',');
  12312. markup.push(
  12313. '<polygon ',
  12314. 'points="', points,
  12315. '" style="', this.getSvgStyles(),
  12316. '" transform="', this.getSvgTransform(),
  12317. '"/>'
  12318. );
  12319. return reviver ? reviver(markup.join('')) : markup.join('');
  12320. },
  12321. /* _TO_SVG_END_ */
  12322. /**
  12323. * Returns complexity of an instance
  12324. * @return {Number} complexity of this instance
  12325. */
  12326. complexity: function() {
  12327. return 1;
  12328. }
  12329. });
  12330. /**
  12331. * Returns fabric.Triangle instance from an object representation
  12332. * @static
  12333. * @memberOf fabric.Triangle
  12334. * @param {Object} object Object to create an instance from
  12335. * @return {Object} instance of Canvas.Triangle
  12336. */
  12337. fabric.Triangle.fromObject = function(object) {
  12338. return new fabric.Triangle(object);
  12339. };
  12340. })(typeof exports !== 'undefined' ? exports : this);
  12341. (function(global) {
  12342. 'use strict';
  12343. var fabric = global.fabric || (global.fabric = { }),
  12344. piBy2 = Math.PI * 2,
  12345. extend = fabric.util.object.extend;
  12346. if (fabric.Ellipse) {
  12347. fabric.warn('fabric.Ellipse is already defined.');
  12348. return;
  12349. }
  12350. /**
  12351. * Ellipse class
  12352. * @class fabric.Ellipse
  12353. * @extends fabric.Object
  12354. * @return {fabric.Ellipse} thisArg
  12355. * @see {@link fabric.Ellipse#initialize} for constructor definition
  12356. */
  12357. fabric.Ellipse = fabric.util.createClass(fabric.Object, /** @lends fabric.Ellipse.prototype */ {
  12358. /**
  12359. * Type of an object
  12360. * @type String
  12361. * @default
  12362. */
  12363. type: 'ellipse',
  12364. /**
  12365. * Horizontal radius
  12366. * @type Number
  12367. * @default
  12368. */
  12369. rx: 0,
  12370. /**
  12371. * Vertical radius
  12372. * @type Number
  12373. * @default
  12374. */
  12375. ry: 0,
  12376. /**
  12377. * Constructor
  12378. * @param {Object} [options] Options object
  12379. * @return {fabric.Ellipse} thisArg
  12380. */
  12381. initialize: function(options) {
  12382. options = options || { };
  12383. this.callSuper('initialize', options);
  12384. this.set('rx', options.rx || 0);
  12385. this.set('ry', options.ry || 0);
  12386. },
  12387. /**
  12388. * @private
  12389. * @param {String} key
  12390. * @param {Any} value
  12391. * @return {fabric.Ellipse} thisArg
  12392. */
  12393. _set: function(key, value) {
  12394. this.callSuper('_set', key, value);
  12395. switch (key) {
  12396. case 'rx':
  12397. this.rx = value;
  12398. this.set('width', value * 2);
  12399. break;
  12400. case 'ry':
  12401. this.ry = value;
  12402. this.set('height', value * 2);
  12403. break;
  12404. }
  12405. return this;
  12406. },
  12407. /**
  12408. * Returns horizontal radius of an object (according to how an object is scaled)
  12409. * @return {Number}
  12410. */
  12411. getRx: function() {
  12412. return this.get('rx') * this.get('scaleX');
  12413. },
  12414. /**
  12415. * Returns Vertical radius of an object (according to how an object is scaled)
  12416. * @return {Number}
  12417. */
  12418. getRy: function() {
  12419. return this.get('ry') * this.get('scaleY');
  12420. },
  12421. /**
  12422. * Returns object representation of an instance
  12423. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  12424. * @return {Object} object representation of an instance
  12425. */
  12426. toObject: function(propertiesToInclude) {
  12427. return extend(this.callSuper('toObject', propertiesToInclude), {
  12428. rx: this.get('rx'),
  12429. ry: this.get('ry')
  12430. });
  12431. },
  12432. /* _TO_SVG_START_ */
  12433. /**
  12434. * Returns svg representation of an instance
  12435. * @param {Function} [reviver] Method for further parsing of svg representation.
  12436. * @return {String} svg representation of an instance
  12437. */
  12438. toSVG: function(reviver) {
  12439. var markup = this._createBaseSVGMarkup(), x = 0, y = 0;
  12440. if (this.group && this.group.type === 'path-group') {
  12441. x = this.left + this.rx;
  12442. y = this.top + this.ry;
  12443. }
  12444. markup.push(
  12445. '<ellipse ',
  12446. 'cx="', x, '" cy="', y, '" ',
  12447. 'rx="', this.rx,
  12448. '" ry="', this.ry,
  12449. '" style="', this.getSvgStyles(),
  12450. '" transform="', this.getSvgTransform(),
  12451. this.getSvgTransformMatrix(),
  12452. '"/>\n'
  12453. );
  12454. return reviver ? reviver(markup.join('')) : markup.join('');
  12455. },
  12456. /* _TO_SVG_END_ */
  12457. /**
  12458. * @private
  12459. * @param {CanvasRenderingContext2D} ctx context to render on
  12460. * @param {Boolean} [noTransform] When true, context is not transformed
  12461. */
  12462. _render: function(ctx, noTransform) {
  12463. ctx.beginPath();
  12464. ctx.save();
  12465. ctx.transform(1, 0, 0, this.ry/this.rx, 0, 0);
  12466. ctx.arc(
  12467. noTransform ? this.left + this.rx : 0,
  12468. noTransform ? (this.top + this.ry) * this.rx/this.ry : 0,
  12469. this.rx,
  12470. 0,
  12471. piBy2,
  12472. false);
  12473. ctx.restore();
  12474. this._renderFill(ctx);
  12475. this._renderStroke(ctx);
  12476. },
  12477. /**
  12478. * Returns complexity of an instance
  12479. * @return {Number} complexity
  12480. */
  12481. complexity: function() {
  12482. return 1;
  12483. }
  12484. });
  12485. /* _FROM_SVG_START_ */
  12486. /**
  12487. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement})
  12488. * @static
  12489. * @memberOf fabric.Ellipse
  12490. * @see http://www.w3.org/TR/SVG/shapes.html#EllipseElement
  12491. */
  12492. fabric.Ellipse.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('cx cy rx ry'.split(' '));
  12493. /**
  12494. * Returns {@link fabric.Ellipse} instance from an SVG element
  12495. * @static
  12496. * @memberOf fabric.Ellipse
  12497. * @param {SVGElement} element Element to parse
  12498. * @param {Object} [options] Options object
  12499. * @return {fabric.Ellipse}
  12500. */
  12501. fabric.Ellipse.fromElement = function(element, options) {
  12502. options || (options = { });
  12503. var parsedAttributes = fabric.parseAttributes(element, fabric.Ellipse.ATTRIBUTE_NAMES);
  12504. parsedAttributes.left = parsedAttributes.left || 0;
  12505. parsedAttributes.top = parsedAttributes.top || 0;
  12506. var ellipse = new fabric.Ellipse(extend(parsedAttributes, options));
  12507. ellipse.top -= ellipse.ry;
  12508. ellipse.left -= ellipse.rx;
  12509. return ellipse;
  12510. };
  12511. /* _FROM_SVG_END_ */
  12512. /**
  12513. * Returns {@link fabric.Ellipse} instance from an object representation
  12514. * @static
  12515. * @memberOf fabric.Ellipse
  12516. * @param {Object} object Object to create an instance from
  12517. * @return {fabric.Ellipse}
  12518. */
  12519. fabric.Ellipse.fromObject = function(object) {
  12520. return new fabric.Ellipse(object);
  12521. };
  12522. })(typeof exports !== 'undefined' ? exports : this);
  12523. (function(global) {
  12524. 'use strict';
  12525. var fabric = global.fabric || (global.fabric = { }),
  12526. extend = fabric.util.object.extend;
  12527. if (fabric.Rect) {
  12528. console.warn('fabric.Rect is already defined');
  12529. return;
  12530. }
  12531. var stateProperties = fabric.Object.prototype.stateProperties.concat();
  12532. stateProperties.push('rx', 'ry', 'x', 'y');
  12533. /**
  12534. * Rectangle class
  12535. * @class fabric.Rect
  12536. * @extends fabric.Object
  12537. * @return {fabric.Rect} thisArg
  12538. * @see {@link fabric.Rect#initialize} for constructor definition
  12539. */
  12540. fabric.Rect = fabric.util.createClass(fabric.Object, /** @lends fabric.Rect.prototype */ {
  12541. /**
  12542. * List of properties to consider when checking if state of an object is changed ({@link fabric.Object#hasStateChanged})
  12543. * as well as for history (undo/redo) purposes
  12544. * @type Array
  12545. */
  12546. stateProperties: stateProperties,
  12547. /**
  12548. * Type of an object
  12549. * @type String
  12550. * @default
  12551. */
  12552. type: 'rect',
  12553. /**
  12554. * Horizontal border radius
  12555. * @type Number
  12556. * @default
  12557. */
  12558. rx: 0,
  12559. /**
  12560. * Vertical border radius
  12561. * @type Number
  12562. * @default
  12563. */
  12564. ry: 0,
  12565. /**
  12566. * Used to specify dash pattern for stroke on this object
  12567. * @type Array
  12568. */
  12569. strokeDashArray: null,
  12570. /**
  12571. * Constructor
  12572. * @param {Object} [options] Options object
  12573. * @return {Object} thisArg
  12574. */
  12575. initialize: function(options) {
  12576. options = options || { };
  12577. this.callSuper('initialize', options);
  12578. this._initRxRy();
  12579. },
  12580. /**
  12581. * Initializes rx/ry attributes
  12582. * @private
  12583. */
  12584. _initRxRy: function() {
  12585. if (this.rx && !this.ry) {
  12586. this.ry = this.rx;
  12587. }
  12588. else if (this.ry && !this.rx) {
  12589. this.rx = this.ry;
  12590. }
  12591. },
  12592. /**
  12593. * @private
  12594. * @param {CanvasRenderingContext2D} ctx Context to render on
  12595. */
  12596. _render: function(ctx, noTransform) {
  12597. // optimize 1x1 case (used in spray brush)
  12598. if (this.width === 1 && this.height === 1) {
  12599. ctx.fillRect(0, 0, 1, 1);
  12600. return;
  12601. }
  12602. var rx = this.rx ? Math.min(this.rx, this.width / 2) : 0,
  12603. ry = this.ry ? Math.min(this.ry, this.height / 2) : 0,
  12604. w = this.width,
  12605. h = this.height,
  12606. x = noTransform ? this.left : -this.width / 2,
  12607. y = noTransform ? this.top : -this.height / 2,
  12608. isRounded = rx !== 0 || ry !== 0,
  12609. k = 1 - 0.5522847498 /* "magic number" for bezier approximations of arcs (http://itc.ktu.lt/itc354/Riskus354.pdf) */;
  12610. ctx.beginPath();
  12611. ctx.moveTo(x + rx, y);
  12612. ctx.lineTo(x + w - rx, y);
  12613. isRounded && ctx.bezierCurveTo(x + w - k * rx, y, x + w, y + k * ry, x + w, y + ry);
  12614. ctx.lineTo(x + w, y + h - ry);
  12615. isRounded && ctx.bezierCurveTo(x + w, y + h - k * ry, x + w - k * rx, y + h, x + w - rx, y + h);
  12616. ctx.lineTo(x + rx, y + h);
  12617. isRounded && ctx.bezierCurveTo(x + k * rx, y + h, x, y + h - k * ry, x, y + h - ry);
  12618. ctx.lineTo(x, y + ry);
  12619. isRounded && ctx.bezierCurveTo(x, y + k * ry, x + k * rx, y, x + rx, y);
  12620. ctx.closePath();
  12621. this._renderFill(ctx);
  12622. this._renderStroke(ctx);
  12623. },
  12624. /**
  12625. * @private
  12626. * @param {CanvasRenderingContext2D} ctx Context to render on
  12627. */
  12628. _renderDashedStroke: function(ctx) {
  12629. var x = -this.width / 2,
  12630. y = -this.height / 2,
  12631. w = this.width,
  12632. h = this.height;
  12633. ctx.beginPath();
  12634. fabric.util.drawDashedLine(ctx, x, y, x + w, y, this.strokeDashArray);
  12635. fabric.util.drawDashedLine(ctx, x + w, y, x + w, y + h, this.strokeDashArray);
  12636. fabric.util.drawDashedLine(ctx, x + w, y + h, x, y + h, this.strokeDashArray);
  12637. fabric.util.drawDashedLine(ctx, x, y + h, x, y, this.strokeDashArray);
  12638. ctx.closePath();
  12639. },
  12640. /**
  12641. * Returns object representation of an instance
  12642. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  12643. * @return {Object} object representation of an instance
  12644. */
  12645. toObject: function(propertiesToInclude) {
  12646. var object = extend(this.callSuper('toObject', propertiesToInclude), {
  12647. rx: this.get('rx') || 0,
  12648. ry: this.get('ry') || 0
  12649. });
  12650. if (!this.includeDefaultValues) {
  12651. this._removeDefaultValues(object);
  12652. }
  12653. return object;
  12654. },
  12655. /* _TO_SVG_START_ */
  12656. /**
  12657. * Returns svg representation of an instance
  12658. * @param {Function} [reviver] Method for further parsing of svg representation.
  12659. * @return {String} svg representation of an instance
  12660. */
  12661. toSVG: function(reviver) {
  12662. var markup = this._createBaseSVGMarkup(), x = this.left, y = this.top;
  12663. if (!(this.group && this.group.type === 'path-group')) {
  12664. x = -this.width / 2;
  12665. y = -this.height / 2;
  12666. }
  12667. markup.push(
  12668. '<rect ',
  12669. 'x="', x, '" y="', y,
  12670. '" rx="', this.get('rx'), '" ry="', this.get('ry'),
  12671. '" width="', this.width, '" height="', this.height,
  12672. '" style="', this.getSvgStyles(),
  12673. '" transform="', this.getSvgTransform(),
  12674. this.getSvgTransformMatrix(),
  12675. '"/>\n');
  12676. return reviver ? reviver(markup.join('')) : markup.join('');
  12677. },
  12678. /* _TO_SVG_END_ */
  12679. /**
  12680. * Returns complexity of an instance
  12681. * @return {Number} complexity
  12682. */
  12683. complexity: function() {
  12684. return 1;
  12685. }
  12686. });
  12687. /* _FROM_SVG_START_ */
  12688. /**
  12689. * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`)
  12690. * @static
  12691. * @memberOf fabric.Rect
  12692. * @see: http://www.w3.org/TR/SVG/shapes.html#RectElement
  12693. */
  12694. fabric.Rect.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat('x y rx ry width height'.split(' '));
  12695. /**
  12696. * Returns {@link fabric.Rect} instance from an SVG element
  12697. * @static
  12698. * @memberOf fabric.Rect
  12699. * @param {SVGElement} element Element to parse
  12700. * @param {Object} [options] Options object
  12701. * @return {fabric.Rect} Instance of fabric.Rect
  12702. */
  12703. fabric.Rect.fromElement = function(element, options) {
  12704. if (!element) {
  12705. return null;
  12706. }
  12707. options = options || { };
  12708. var parsedAttributes = fabric.parseAttributes(element, fabric.Rect.ATTRIBUTE_NAMES);
  12709. parsedAttributes.left = parsedAttributes.left || 0;
  12710. parsedAttributes.top = parsedAttributes.top || 0;
  12711. var rect = new fabric.Rect(extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));
  12712. rect.visible = rect.width > 0 && rect.height > 0;
  12713. return rect;
  12714. };
  12715. /* _FROM_SVG_END_ */
  12716. /**
  12717. * Returns {@link fabric.Rect} instance from an object representation
  12718. * @static
  12719. * @memberOf fabric.Rect
  12720. * @param {Object} object Object to create an instance from
  12721. * @return {Object} instance of fabric.Rect
  12722. */
  12723. fabric.Rect.fromObject = function(object) {
  12724. return new fabric.Rect(object);
  12725. };
  12726. })(typeof exports !== 'undefined' ? exports : this);
  12727. (function(global) {
  12728. 'use strict';
  12729. var fabric = global.fabric || (global.fabric = { });
  12730. if (fabric.Polyline) {
  12731. fabric.warn('fabric.Polyline is already defined');
  12732. return;
  12733. }
  12734. /**
  12735. * Polyline class
  12736. * @class fabric.Polyline
  12737. * @extends fabric.Object
  12738. * @see {@link fabric.Polyline#initialize} for constructor definition
  12739. */
  12740. fabric.Polyline = fabric.util.createClass(fabric.Object, /** @lends fabric.Polyline.prototype */ {
  12741. /**
  12742. * Type of an object
  12743. * @type String
  12744. * @default
  12745. */
  12746. type: 'polyline',
  12747. /**
  12748. * Points array
  12749. * @type Array
  12750. * @default
  12751. */
  12752. points: null,
  12753. /**
  12754. * Minimum X from points values, necessary to offset points
  12755. * @type Number
  12756. * @default
  12757. */
  12758. minX: 0,
  12759. /**
  12760. * Minimum Y from points values, necessary to offset points
  12761. * @type Number
  12762. * @default
  12763. */
  12764. minY: 0,
  12765. /**
  12766. * Constructor
  12767. * @param {Array} points Array of points (where each point is an object with x and y)
  12768. * @param {Object} [options] Options object
  12769. * @param {Boolean} [skipOffset] Whether points offsetting should be skipped
  12770. * @return {fabric.Polyline} thisArg
  12771. * @example
  12772. * var poly = new fabric.Polyline([
  12773. * { x: 10, y: 10 },
  12774. * { x: 50, y: 30 },
  12775. * { x: 40, y: 70 },
  12776. * { x: 60, y: 50 },
  12777. * { x: 100, y: 150 },
  12778. * { x: 40, y: 100 }
  12779. * ], {
  12780. * stroke: 'red',
  12781. * left: 100,
  12782. * top: 100
  12783. * });
  12784. */
  12785. initialize: function(points, options) {
  12786. return fabric.Polygon.prototype.initialize.call(this, points, options);
  12787. },
  12788. /**
  12789. * @private
  12790. */
  12791. _calcDimensions: function() {
  12792. return fabric.Polygon.prototype._calcDimensions.call(this);
  12793. },
  12794. /**
  12795. * @private
  12796. */
  12797. _applyPointOffset: function() {
  12798. return fabric.Polygon.prototype._applyPointOffset.call(this);
  12799. },
  12800. /**
  12801. * Returns object representation of an instance
  12802. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  12803. * @return {Object} Object representation of an instance
  12804. */
  12805. toObject: function(propertiesToInclude) {
  12806. return fabric.Polygon.prototype.toObject.call(this, propertiesToInclude);
  12807. },
  12808. /* _TO_SVG_START_ */
  12809. /**
  12810. * Returns SVG representation of an instance
  12811. * @param {Function} [reviver] Method for further parsing of svg representation.
  12812. * @return {String} svg representation of an instance
  12813. */
  12814. toSVG: function(reviver) {
  12815. return fabric.Polygon.prototype.toSVG.call(this, reviver);
  12816. },
  12817. /* _TO_SVG_END_ */
  12818. /**
  12819. * @private
  12820. * @param {CanvasRenderingContext2D} ctx Context to render on
  12821. */
  12822. _render: function(ctx) {
  12823. if (!fabric.Polygon.prototype.commonRender.call(this, ctx)) {
  12824. return;
  12825. }
  12826. this._renderFill(ctx);
  12827. this._renderStroke(ctx);
  12828. },
  12829. /**
  12830. * @private
  12831. * @param {CanvasRenderingContext2D} ctx Context to render on
  12832. */
  12833. _renderDashedStroke: function(ctx) {
  12834. var p1, p2;
  12835. ctx.beginPath();
  12836. for (var i = 0, len = this.points.length; i < len; i++) {
  12837. p1 = this.points[i];
  12838. p2 = this.points[i + 1] || p1;
  12839. fabric.util.drawDashedLine(ctx, p1.x, p1.y, p2.x, p2.y, this.strokeDashArray);
  12840. }
  12841. },
  12842. /**
  12843. * Returns complexity of an instance
  12844. * @return {Number} complexity of this instance
  12845. */
  12846. complexity: function() {
  12847. return this.get('points').length;
  12848. }
  12849. });
  12850. /* _FROM_SVG_START_ */
  12851. /**
  12852. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Polyline.fromElement})
  12853. * @static
  12854. * @memberOf fabric.Polyline
  12855. * @see: http://www.w3.org/TR/SVG/shapes.html#PolylineElement
  12856. */
  12857. fabric.Polyline.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();
  12858. /**
  12859. * Returns fabric.Polyline instance from an SVG element
  12860. * @static
  12861. * @memberOf fabric.Polyline
  12862. * @param {SVGElement} element Element to parse
  12863. * @param {Object} [options] Options object
  12864. * @return {fabric.Polyline} Instance of fabric.Polyline
  12865. */
  12866. fabric.Polyline.fromElement = function(element, options) {
  12867. if (!element) {
  12868. return null;
  12869. }
  12870. options || (options = { });
  12871. var points = fabric.parsePointsAttribute(element.getAttribute('points')),
  12872. parsedAttributes = fabric.parseAttributes(element, fabric.Polyline.ATTRIBUTE_NAMES);
  12873. return new fabric.Polyline(points, fabric.util.object.extend(parsedAttributes, options));
  12874. };
  12875. /* _FROM_SVG_END_ */
  12876. /**
  12877. * Returns fabric.Polyline instance from an object representation
  12878. * @static
  12879. * @memberOf fabric.Polyline
  12880. * @param {Object} object Object to create an instance from
  12881. * @return {fabric.Polyline} Instance of fabric.Polyline
  12882. */
  12883. fabric.Polyline.fromObject = function(object) {
  12884. var points = object.points;
  12885. return new fabric.Polyline(points, object, true);
  12886. };
  12887. })(typeof exports !== 'undefined' ? exports : this);
  12888. (function(global) {
  12889. 'use strict';
  12890. var fabric = global.fabric || (global.fabric = { }),
  12891. extend = fabric.util.object.extend,
  12892. min = fabric.util.array.min,
  12893. max = fabric.util.array.max,
  12894. toFixed = fabric.util.toFixed;
  12895. if (fabric.Polygon) {
  12896. fabric.warn('fabric.Polygon is already defined');
  12897. return;
  12898. }
  12899. /**
  12900. * Polygon class
  12901. * @class fabric.Polygon
  12902. * @extends fabric.Object
  12903. * @see {@link fabric.Polygon#initialize} for constructor definition
  12904. */
  12905. fabric.Polygon = fabric.util.createClass(fabric.Object, /** @lends fabric.Polygon.prototype */ {
  12906. /**
  12907. * Type of an object
  12908. * @type String
  12909. * @default
  12910. */
  12911. type: 'polygon',
  12912. /**
  12913. * Points array
  12914. * @type Array
  12915. * @default
  12916. */
  12917. points: null,
  12918. /**
  12919. * Minimum X from points values, necessary to offset points
  12920. * @type Number
  12921. * @default
  12922. */
  12923. minX: 0,
  12924. /**
  12925. * Minimum Y from points values, necessary to offset points
  12926. * @type Number
  12927. * @default
  12928. */
  12929. minY: 0,
  12930. /**
  12931. * Constructor
  12932. * @param {Array} points Array of points
  12933. * @param {Object} [options] Options object
  12934. * @return {fabric.Polygon} thisArg
  12935. */
  12936. initialize: function(points, options) {
  12937. options = options || { };
  12938. this.points = points || [ ];
  12939. this.callSuper('initialize', options);
  12940. this._calcDimensions();
  12941. if (!('top' in options)) {
  12942. this.top = this.minY;
  12943. }
  12944. if (!('left' in options)) {
  12945. this.left = this.minX;
  12946. }
  12947. },
  12948. /**
  12949. * @private
  12950. */
  12951. _calcDimensions: function() {
  12952. var points = this.points,
  12953. minX = min(points, 'x'),
  12954. minY = min(points, 'y'),
  12955. maxX = max(points, 'x'),
  12956. maxY = max(points, 'y');
  12957. this.width = (maxX - minX) || 0;
  12958. this.height = (maxY - minY) || 0;
  12959. this.minX = minX || 0,
  12960. this.minY = minY || 0;
  12961. },
  12962. /**
  12963. * @private
  12964. */
  12965. _applyPointOffset: function() {
  12966. // change points to offset polygon into a bounding box
  12967. // executed one time
  12968. this.points.forEach(function(p) {
  12969. p.x -= (this.minX + this.width / 2);
  12970. p.y -= (this.minY + this.height / 2);
  12971. }, this);
  12972. },
  12973. /**
  12974. * Returns object representation of an instance
  12975. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  12976. * @return {Object} Object representation of an instance
  12977. */
  12978. toObject: function(propertiesToInclude) {
  12979. return extend(this.callSuper('toObject', propertiesToInclude), {
  12980. points: this.points.concat()
  12981. });
  12982. },
  12983. /* _TO_SVG_START_ */
  12984. /**
  12985. * Returns svg representation of an instance
  12986. * @param {Function} [reviver] Method for further parsing of svg representation.
  12987. * @return {String} svg representation of an instance
  12988. */
  12989. toSVG: function(reviver) {
  12990. var points = [],
  12991. markup = this._createBaseSVGMarkup();
  12992. for (var i = 0, len = this.points.length; i < len; i++) {
  12993. points.push(toFixed(this.points[i].x, 2), ',', toFixed(this.points[i].y, 2), ' ');
  12994. }
  12995. markup.push(
  12996. '<', this.type, ' ',
  12997. 'points="', points.join(''),
  12998. '" style="', this.getSvgStyles(),
  12999. '" transform="', this.getSvgTransform(),
  13000. ' ', this.getSvgTransformMatrix(),
  13001. '"/>\n'
  13002. );
  13003. return reviver ? reviver(markup.join('')) : markup.join('');
  13004. },
  13005. /* _TO_SVG_END_ */
  13006. /**
  13007. * @private
  13008. * @param {CanvasRenderingContext2D} ctx Context to render on
  13009. */
  13010. _render: function(ctx) {
  13011. if (!this.commonRender(ctx)) {
  13012. return;
  13013. }
  13014. this._renderFill(ctx);
  13015. if (this.stroke || this.strokeDashArray) {
  13016. ctx.closePath();
  13017. this._renderStroke(ctx);
  13018. }
  13019. },
  13020. /**
  13021. * @private
  13022. * @param {CanvasRenderingContext2D} ctx Context to render on
  13023. */
  13024. commonRender: function(ctx) {
  13025. var point, len = this.points.length;
  13026. if (!len || isNaN(this.points[len - 1].y)) {
  13027. // do not draw if no points or odd points
  13028. // NaN comes from parseFloat of a empty string in parser
  13029. return false;
  13030. }
  13031. ctx.beginPath();
  13032. if (this._applyPointOffset) {
  13033. if (!(this.group && this.group.type === 'path-group')) {
  13034. this._applyPointOffset();
  13035. }
  13036. this._applyPointOffset = null;
  13037. }
  13038. ctx.moveTo(this.points[0].x, this.points[0].y);
  13039. for (var i = 0; i < len; i++) {
  13040. point = this.points[i];
  13041. ctx.lineTo(point.x, point.y);
  13042. }
  13043. return true;
  13044. },
  13045. /**
  13046. * @private
  13047. * @param {CanvasRenderingContext2D} ctx Context to render on
  13048. */
  13049. _renderDashedStroke: function(ctx) {
  13050. fabric.Polyline.prototype._renderDashedStroke.call(this, ctx);
  13051. ctx.closePath();
  13052. },
  13053. /**
  13054. * Returns complexity of an instance
  13055. * @return {Number} complexity of this instance
  13056. */
  13057. complexity: function() {
  13058. return this.points.length;
  13059. }
  13060. });
  13061. /* _FROM_SVG_START_ */
  13062. /**
  13063. * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`)
  13064. * @static
  13065. * @memberOf fabric.Polygon
  13066. * @see: http://www.w3.org/TR/SVG/shapes.html#PolygonElement
  13067. */
  13068. fabric.Polygon.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat();
  13069. /**
  13070. * Returns {@link fabric.Polygon} instance from an SVG element
  13071. * @static
  13072. * @memberOf fabric.Polygon
  13073. * @param {SVGElement} element Element to parse
  13074. * @param {Object} [options] Options object
  13075. * @return {fabric.Polygon} Instance of fabric.Polygon
  13076. */
  13077. fabric.Polygon.fromElement = function(element, options) {
  13078. if (!element) {
  13079. return null;
  13080. }
  13081. options || (options = { });
  13082. var points = fabric.parsePointsAttribute(element.getAttribute('points')),
  13083. parsedAttributes = fabric.parseAttributes(element, fabric.Polygon.ATTRIBUTE_NAMES);
  13084. return new fabric.Polygon(points, extend(parsedAttributes, options));
  13085. };
  13086. /* _FROM_SVG_END_ */
  13087. /**
  13088. * Returns fabric.Polygon instance from an object representation
  13089. * @static
  13090. * @memberOf fabric.Polygon
  13091. * @param {Object} object Object to create an instance from
  13092. * @return {fabric.Polygon} Instance of fabric.Polygon
  13093. */
  13094. fabric.Polygon.fromObject = function(object) {
  13095. return new fabric.Polygon(object.points, object, true);
  13096. };
  13097. })(typeof exports !== 'undefined' ? exports : this);
  13098. (function(global) {
  13099. 'use strict';
  13100. var fabric = global.fabric || (global.fabric = { }),
  13101. min = fabric.util.array.min,
  13102. max = fabric.util.array.max,
  13103. extend = fabric.util.object.extend,
  13104. _toString = Object.prototype.toString,
  13105. drawArc = fabric.util.drawArc,
  13106. commandLengths = {
  13107. m: 2,
  13108. l: 2,
  13109. h: 1,
  13110. v: 1,
  13111. c: 6,
  13112. s: 4,
  13113. q: 4,
  13114. t: 2,
  13115. a: 7
  13116. },
  13117. repeatedCommands = {
  13118. m: 'l',
  13119. M: 'L'
  13120. };
  13121. if (fabric.Path) {
  13122. fabric.warn('fabric.Path is already defined');
  13123. return;
  13124. }
  13125. /**
  13126. * Path class
  13127. * @class fabric.Path
  13128. * @extends fabric.Object
  13129. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#path_and_pathgroup}
  13130. * @see {@link fabric.Path#initialize} for constructor definition
  13131. */
  13132. fabric.Path = fabric.util.createClass(fabric.Object, /** @lends fabric.Path.prototype */ {
  13133. /**
  13134. * Type of an object
  13135. * @type String
  13136. * @default
  13137. */
  13138. type: 'path',
  13139. /**
  13140. * Array of path points
  13141. * @type Array
  13142. * @default
  13143. */
  13144. path: null,
  13145. /**
  13146. * Minimum X from points values, necessary to offset points
  13147. * @type Number
  13148. * @default
  13149. */
  13150. minX: 0,
  13151. /**
  13152. * Minimum Y from points values, necessary to offset points
  13153. * @type Number
  13154. * @default
  13155. */
  13156. minY: 0,
  13157. /**
  13158. * Constructor
  13159. * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens)
  13160. * @param {Object} [options] Options object
  13161. * @return {fabric.Path} thisArg
  13162. */
  13163. initialize: function(path, options) {
  13164. options = options || { };
  13165. this.setOptions(options);
  13166. if (!path) {
  13167. throw new Error('`path` argument is required');
  13168. }
  13169. var fromArray = _toString.call(path) === '[object Array]';
  13170. this.path = fromArray
  13171. ? path
  13172. // one of commands (m,M,l,L,q,Q,c,C,etc.) followed by non-command characters (i.e. command values)
  13173. : path.match && path.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);
  13174. if (!this.path) {
  13175. return;
  13176. }
  13177. if (!fromArray) {
  13178. this.path = this._parsePath();
  13179. }
  13180. this._setPositionDimensions();
  13181. if (options.sourcePath) {
  13182. this.setSourcePath(options.sourcePath);
  13183. }
  13184. },
  13185. /**
  13186. * @private
  13187. */
  13188. _setPositionDimensions: function() {
  13189. var calcDim = this._parseDimensions();
  13190. this.minX = calcDim.left;
  13191. this.minY = calcDim.top;
  13192. this.width = calcDim.width;
  13193. this.height = calcDim.height;
  13194. calcDim.left += this.originX === 'center'
  13195. ? this.width / 2
  13196. : this.originX === 'right'
  13197. ? this.width
  13198. : 0;
  13199. calcDim.top += this.originY === 'center'
  13200. ? this.height / 2
  13201. : this.originY === 'bottom'
  13202. ? this.height
  13203. : 0;
  13204. this.top = this.top || calcDim.top;
  13205. this.left = this.left || calcDim.left;
  13206. this.pathOffset = this.pathOffset || {
  13207. x: this.minX + this.width / 2,
  13208. y: this.minY + this.height / 2
  13209. };
  13210. },
  13211. /**
  13212. * @private
  13213. * @param {CanvasRenderingContext2D} ctx context to render path on
  13214. */
  13215. _render: function(ctx) {
  13216. var current, // current instruction
  13217. previous = null,
  13218. subpathStartX = 0,
  13219. subpathStartY = 0,
  13220. x = 0, // current x
  13221. y = 0, // current y
  13222. controlX = 0, // current control point x
  13223. controlY = 0, // current control point y
  13224. tempX,
  13225. tempY,
  13226. l = -this.pathOffset.x,
  13227. t = -this.pathOffset.y;
  13228. if (this.group && this.group.type === 'path-group') {
  13229. l = 0;
  13230. t = 0;
  13231. }
  13232. ctx.beginPath();
  13233. for (var i = 0, len = this.path.length; i < len; ++i) {
  13234. current = this.path[i];
  13235. switch (current[0]) { // first letter
  13236. case 'l': // lineto, relative
  13237. x += current[1];
  13238. y += current[2];
  13239. ctx.lineTo(x + l, y + t);
  13240. break;
  13241. case 'L': // lineto, absolute
  13242. x = current[1];
  13243. y = current[2];
  13244. ctx.lineTo(x + l, y + t);
  13245. break;
  13246. case 'h': // horizontal lineto, relative
  13247. x += current[1];
  13248. ctx.lineTo(x + l, y + t);
  13249. break;
  13250. case 'H': // horizontal lineto, absolute
  13251. x = current[1];
  13252. ctx.lineTo(x + l, y + t);
  13253. break;
  13254. case 'v': // vertical lineto, relative
  13255. y += current[1];
  13256. ctx.lineTo(x + l, y + t);
  13257. break;
  13258. case 'V': // verical lineto, absolute
  13259. y = current[1];
  13260. ctx.lineTo(x + l, y + t);
  13261. break;
  13262. case 'm': // moveTo, relative
  13263. x += current[1];
  13264. y += current[2];
  13265. subpathStartX = x;
  13266. subpathStartY = y;
  13267. ctx.moveTo(x + l, y + t);
  13268. break;
  13269. case 'M': // moveTo, absolute
  13270. x = current[1];
  13271. y = current[2];
  13272. subpathStartX = x;
  13273. subpathStartY = y;
  13274. ctx.moveTo(x + l, y + t);
  13275. break;
  13276. case 'c': // bezierCurveTo, relative
  13277. tempX = x + current[5];
  13278. tempY = y + current[6];
  13279. controlX = x + current[3];
  13280. controlY = y + current[4];
  13281. ctx.bezierCurveTo(
  13282. x + current[1] + l, // x1
  13283. y + current[2] + t, // y1
  13284. controlX + l, // x2
  13285. controlY + t, // y2
  13286. tempX + l,
  13287. tempY + t
  13288. );
  13289. x = tempX;
  13290. y = tempY;
  13291. break;
  13292. case 'C': // bezierCurveTo, absolute
  13293. x = current[5];
  13294. y = current[6];
  13295. controlX = current[3];
  13296. controlY = current[4];
  13297. ctx.bezierCurveTo(
  13298. current[1] + l,
  13299. current[2] + t,
  13300. controlX + l,
  13301. controlY + t,
  13302. x + l,
  13303. y + t
  13304. );
  13305. break;
  13306. case 's': // shorthand cubic bezierCurveTo, relative
  13307. // transform to absolute x,y
  13308. tempX = x + current[3];
  13309. tempY = y + current[4];
  13310. if (previous[0].match(/[CcSs]/) === null) {
  13311. // If there is no previous command or if the previous command was not a C, c, S, or s,
  13312. // the control point is coincident with the current point
  13313. controlX = x;
  13314. controlY = y;
  13315. }
  13316. else {
  13317. // calculate reflection of previous control points
  13318. controlX = 2 * x - controlX;
  13319. controlY = 2 * y - controlY;
  13320. }
  13321. ctx.bezierCurveTo(
  13322. controlX + l,
  13323. controlY + t,
  13324. x + current[1] + l,
  13325. y + current[2] + t,
  13326. tempX + l,
  13327. tempY + t
  13328. );
  13329. // set control point to 2nd one of this command
  13330. // "... the first control point is assumed to be
  13331. // the reflection of the second control point on
  13332. // the previous command relative to the current point."
  13333. controlX = x + current[1];
  13334. controlY = y + current[2];
  13335. x = tempX;
  13336. y = tempY;
  13337. break;
  13338. case 'S': // shorthand cubic bezierCurveTo, absolute
  13339. tempX = current[3];
  13340. tempY = current[4];
  13341. if (previous[0].match(/[CcSs]/) === null) {
  13342. // If there is no previous command or if the previous command was not a C, c, S, or s,
  13343. // the control point is coincident with the current point
  13344. controlX = x;
  13345. controlY = y;
  13346. }
  13347. else {
  13348. // calculate reflection of previous control points
  13349. controlX = 2 * x - controlX;
  13350. controlY = 2 * y - controlY;
  13351. }
  13352. ctx.bezierCurveTo(
  13353. controlX + l,
  13354. controlY + t,
  13355. current[1] + l,
  13356. current[2] + t,
  13357. tempX + l,
  13358. tempY + t
  13359. );
  13360. x = tempX;
  13361. y = tempY;
  13362. // set control point to 2nd one of this command
  13363. // "... the first control point is assumed to be
  13364. // the reflection of the second control point on
  13365. // the previous command relative to the current point."
  13366. controlX = current[1];
  13367. controlY = current[2];
  13368. break;
  13369. case 'q': // quadraticCurveTo, relative
  13370. // transform to absolute x,y
  13371. tempX = x + current[3];
  13372. tempY = y + current[4];
  13373. controlX = x + current[1];
  13374. controlY = y + current[2];
  13375. ctx.quadraticCurveTo(
  13376. controlX + l,
  13377. controlY + t,
  13378. tempX + l,
  13379. tempY + t
  13380. );
  13381. x = tempX;
  13382. y = tempY;
  13383. break;
  13384. case 'Q': // quadraticCurveTo, absolute
  13385. tempX = current[3];
  13386. tempY = current[4];
  13387. ctx.quadraticCurveTo(
  13388. current[1] + l,
  13389. current[2] + t,
  13390. tempX + l,
  13391. tempY + t
  13392. );
  13393. x = tempX;
  13394. y = tempY;
  13395. controlX = current[1];
  13396. controlY = current[2];
  13397. break;
  13398. case 't': // shorthand quadraticCurveTo, relative
  13399. // transform to absolute x,y
  13400. tempX = x + current[1];
  13401. tempY = y + current[2];
  13402. if (previous[0].match(/[QqTt]/) === null) {
  13403. // If there is no previous command or if the previous command was not a Q, q, T or t,
  13404. // assume the control point is coincident with the current point
  13405. controlX = x;
  13406. controlY = y;
  13407. }
  13408. else {
  13409. // calculate reflection of previous control point
  13410. controlX = 2 * x - controlX;
  13411. controlY = 2 * y - controlY;
  13412. }
  13413. ctx.quadraticCurveTo(
  13414. controlX + l,
  13415. controlY + t,
  13416. tempX + l,
  13417. tempY + t
  13418. );
  13419. x = tempX;
  13420. y = tempY;
  13421. break;
  13422. case 'T':
  13423. tempX = current[1];
  13424. tempY = current[2];
  13425. if (previous[0].match(/[QqTt]/) === null) {
  13426. // If there is no previous command or if the previous command was not a Q, q, T or t,
  13427. // assume the control point is coincident with the current point
  13428. controlX = x;
  13429. controlY = y;
  13430. }
  13431. else {
  13432. // calculate reflection of previous control point
  13433. controlX = 2 * x - controlX;
  13434. controlY = 2 * y - controlY;
  13435. }
  13436. ctx.quadraticCurveTo(
  13437. controlX + l,
  13438. controlY + t,
  13439. tempX + l,
  13440. tempY + t
  13441. );
  13442. x = tempX;
  13443. y = tempY;
  13444. break;
  13445. case 'a':
  13446. // TODO: optimize this
  13447. drawArc(ctx, x + l, y + t, [
  13448. current[1],
  13449. current[2],
  13450. current[3],
  13451. current[4],
  13452. current[5],
  13453. current[6] + x + l,
  13454. current[7] + y + t
  13455. ]);
  13456. x += current[6];
  13457. y += current[7];
  13458. break;
  13459. case 'A':
  13460. // TODO: optimize this
  13461. drawArc(ctx, x + l, y + t, [
  13462. current[1],
  13463. current[2],
  13464. current[3],
  13465. current[4],
  13466. current[5],
  13467. current[6] + l,
  13468. current[7] + t
  13469. ]);
  13470. x = current[6];
  13471. y = current[7];
  13472. break;
  13473. case 'z':
  13474. case 'Z':
  13475. x = subpathStartX;
  13476. y = subpathStartY;
  13477. ctx.closePath();
  13478. break;
  13479. }
  13480. previous = current;
  13481. }
  13482. this._renderFill(ctx);
  13483. this._renderStroke(ctx);
  13484. },
  13485. /**
  13486. * Returns string representation of an instance
  13487. * @return {String} string representation of an instance
  13488. */
  13489. toString: function() {
  13490. return '#<fabric.Path (' + this.complexity() +
  13491. '): { "top": ' + this.top + ', "left": ' + this.left + ' }>';
  13492. },
  13493. /**
  13494. * Returns object representation of an instance
  13495. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  13496. * @return {Object} object representation of an instance
  13497. */
  13498. toObject: function(propertiesToInclude) {
  13499. var o = extend(this.callSuper('toObject', propertiesToInclude), {
  13500. path: this.path.map(function(item) { return item.slice() }),
  13501. pathOffset: this.pathOffset
  13502. });
  13503. if (this.sourcePath) {
  13504. o.sourcePath = this.sourcePath;
  13505. }
  13506. if (this.transformMatrix) {
  13507. o.transformMatrix = this.transformMatrix;
  13508. }
  13509. return o;
  13510. },
  13511. /**
  13512. * Returns dataless object representation of an instance
  13513. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  13514. * @return {Object} object representation of an instance
  13515. */
  13516. toDatalessObject: function(propertiesToInclude) {
  13517. var o = this.toObject(propertiesToInclude);
  13518. if (this.sourcePath) {
  13519. o.path = this.sourcePath;
  13520. }
  13521. delete o.sourcePath;
  13522. return o;
  13523. },
  13524. /* _TO_SVG_START_ */
  13525. /**
  13526. * Returns svg representation of an instance
  13527. * @param {Function} [reviver] Method for further parsing of svg representation.
  13528. * @return {String} svg representation of an instance
  13529. */
  13530. toSVG: function(reviver) {
  13531. var chunks = [],
  13532. markup = this._createBaseSVGMarkup(), addTransform = '';
  13533. for (var i = 0, len = this.path.length; i < len; i++) {
  13534. chunks.push(this.path[i].join(' '));
  13535. }
  13536. var path = chunks.join(' ');
  13537. if (!(this.group && this.group.type === 'path-group')) {
  13538. addTransform = ' translate(' + (-this.pathOffset.x) + ', ' + (-this.pathOffset.y) + ') ';
  13539. }
  13540. markup.push(
  13541. //jscs:disable validateIndentation
  13542. '<path ',
  13543. 'd="', path,
  13544. '" style="', this.getSvgStyles(),
  13545. '" transform="', this.getSvgTransform(), addTransform,
  13546. this.getSvgTransformMatrix(), '" stroke-linecap="round" ',
  13547. '/>\n'
  13548. //jscs:enable validateIndentation
  13549. );
  13550. return reviver ? reviver(markup.join('')) : markup.join('');
  13551. },
  13552. /* _TO_SVG_END_ */
  13553. /**
  13554. * Returns number representation of an instance complexity
  13555. * @return {Number} complexity of this instance
  13556. */
  13557. complexity: function() {
  13558. return this.path.length;
  13559. },
  13560. /**
  13561. * @private
  13562. */
  13563. _parsePath: function() {
  13564. var result = [ ],
  13565. coords = [ ],
  13566. currentPath,
  13567. parsed,
  13568. re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/ig,
  13569. match,
  13570. coordsStr;
  13571. for (var i = 0, coordsParsed, len = this.path.length; i < len; i++) {
  13572. currentPath = this.path[i];
  13573. coordsStr = currentPath.slice(1).trim();
  13574. coords.length = 0;
  13575. while ((match = re.exec(coordsStr))) {
  13576. coords.push(match[0]);
  13577. }
  13578. coordsParsed = [ currentPath.charAt(0) ];
  13579. for (var j = 0, jlen = coords.length; j < jlen; j++) {
  13580. parsed = parseFloat(coords[j]);
  13581. if (!isNaN(parsed)) {
  13582. coordsParsed.push(parsed);
  13583. }
  13584. }
  13585. var command = coordsParsed[0],
  13586. commandLength = commandLengths[command.toLowerCase()],
  13587. repeatedCommand = repeatedCommands[command] || command;
  13588. if (coordsParsed.length - 1 > commandLength) {
  13589. for (var k = 1, klen = coordsParsed.length; k < klen; k += commandLength) {
  13590. result.push([ command ].concat(coordsParsed.slice(k, k + commandLength)));
  13591. command = repeatedCommand;
  13592. }
  13593. }
  13594. else {
  13595. result.push(coordsParsed);
  13596. }
  13597. }
  13598. return result;
  13599. },
  13600. /**
  13601. * @private
  13602. */
  13603. _parseDimensions: function() {
  13604. var aX = [],
  13605. aY = [],
  13606. current, // current instruction
  13607. previous = null,
  13608. subpathStartX = 0,
  13609. subpathStartY = 0,
  13610. x = 0, // current x
  13611. y = 0, // current y
  13612. controlX = 0, // current control point x
  13613. controlY = 0, // current control point y
  13614. tempX,
  13615. tempY,
  13616. bounds;
  13617. for (var i = 0, len = this.path.length; i < len; ++i) {
  13618. current = this.path[i];
  13619. switch (current[0]) { // first letter
  13620. case 'l': // lineto, relative
  13621. x += current[1];
  13622. y += current[2];
  13623. bounds = [ ];
  13624. break;
  13625. case 'L': // lineto, absolute
  13626. x = current[1];
  13627. y = current[2];
  13628. bounds = [ ];
  13629. break;
  13630. case 'h': // horizontal lineto, relative
  13631. x += current[1];
  13632. bounds = [ ];
  13633. break;
  13634. case 'H': // horizontal lineto, absolute
  13635. x = current[1];
  13636. bounds = [ ];
  13637. break;
  13638. case 'v': // vertical lineto, relative
  13639. y += current[1];
  13640. bounds = [ ];
  13641. break;
  13642. case 'V': // verical lineto, absolute
  13643. y = current[1];
  13644. bounds = [ ];
  13645. break;
  13646. case 'm': // moveTo, relative
  13647. x += current[1];
  13648. y += current[2];
  13649. subpathStartX = x;
  13650. subpathStartY = y;
  13651. bounds = [ ];
  13652. break;
  13653. case 'M': // moveTo, absolute
  13654. x = current[1];
  13655. y = current[2];
  13656. subpathStartX = x;
  13657. subpathStartY = y;
  13658. bounds = [ ];
  13659. break;
  13660. case 'c': // bezierCurveTo, relative
  13661. tempX = x + current[5];
  13662. tempY = y + current[6];
  13663. controlX = x + current[3];
  13664. controlY = y + current[4];
  13665. bounds = fabric.util.getBoundsOfCurve(x, y,
  13666. x + current[1], // x1
  13667. y + current[2], // y1
  13668. controlX, // x2
  13669. controlY, // y2
  13670. tempX,
  13671. tempY
  13672. );
  13673. x = tempX;
  13674. y = tempY;
  13675. break;
  13676. case 'C': // bezierCurveTo, absolute
  13677. x = current[5];
  13678. y = current[6];
  13679. controlX = current[3];
  13680. controlY = current[4];
  13681. bounds = fabric.util.getBoundsOfCurve(x, y,
  13682. current[1],
  13683. current[2],
  13684. controlX,
  13685. controlY,
  13686. x,
  13687. y
  13688. );
  13689. break;
  13690. case 's': // shorthand cubic bezierCurveTo, relative
  13691. // transform to absolute x,y
  13692. tempX = x + current[3];
  13693. tempY = y + current[4];
  13694. if (previous[0].match(/[CcSs]/) === null) {
  13695. // If there is no previous command or if the previous command was not a C, c, S, or s,
  13696. // the control point is coincident with the current point
  13697. controlX = x;
  13698. controlY = y;
  13699. }
  13700. else {
  13701. // calculate reflection of previous control points
  13702. controlX = 2 * x - controlX;
  13703. controlY = 2 * y - controlY;
  13704. }
  13705. bounds = fabric.util.getBoundsOfCurve(x, y,
  13706. controlX,
  13707. controlY,
  13708. x + current[1],
  13709. y + current[2],
  13710. tempX,
  13711. tempY
  13712. );
  13713. // set control point to 2nd one of this command
  13714. // "... the first control point is assumed to be
  13715. // the reflection of the second control point on
  13716. // the previous command relative to the current point."
  13717. controlX = x + current[1];
  13718. controlY = y + current[2];
  13719. x = tempX;
  13720. y = tempY;
  13721. break;
  13722. case 'S': // shorthand cubic bezierCurveTo, absolute
  13723. tempX = current[3];
  13724. tempY = current[4];
  13725. if (previous[0].match(/[CcSs]/) === null) {
  13726. // If there is no previous command or if the previous command was not a C, c, S, or s,
  13727. // the control point is coincident with the current point
  13728. controlX = x;
  13729. controlY = y;
  13730. }
  13731. else {
  13732. // calculate reflection of previous control points
  13733. controlX = 2 * x - controlX;
  13734. controlY = 2 * y - controlY;
  13735. }
  13736. bounds = fabric.util.getBoundsOfCurve(x, y,
  13737. controlX,
  13738. controlY,
  13739. current[1],
  13740. current[2],
  13741. tempX,
  13742. tempY
  13743. );
  13744. x = tempX;
  13745. y = tempY;
  13746. // set control point to 2nd one of this command
  13747. // "... the first control point is assumed to be
  13748. // the reflection of the second control point on
  13749. // the previous command relative to the current point."
  13750. controlX = current[1];
  13751. controlY = current[2];
  13752. break;
  13753. case 'q': // quadraticCurveTo, relative
  13754. // transform to absolute x,y
  13755. tempX = x + current[3];
  13756. tempY = y + current[4];
  13757. controlX = x + current[1];
  13758. controlY = y + current[2];
  13759. bounds = fabric.util.getBoundsOfCurve(x, y,
  13760. controlX,
  13761. controlY,
  13762. controlX,
  13763. controlY,
  13764. tempX,
  13765. tempY
  13766. );
  13767. x = tempX;
  13768. y = tempY;
  13769. break;
  13770. case 'Q': // quadraticCurveTo, absolute
  13771. controlX = current[1];
  13772. controlY = current[2];
  13773. bounds = fabric.util.getBoundsOfCurve(x, y,
  13774. controlX,
  13775. controlY,
  13776. controlX,
  13777. controlY,
  13778. current[3],
  13779. current[4]
  13780. );
  13781. x = current[3];
  13782. y = current[4];
  13783. break;
  13784. case 't': // shorthand quadraticCurveTo, relative
  13785. // transform to absolute x,y
  13786. tempX = x + current[1];
  13787. tempY = y + current[2];
  13788. if (previous[0].match(/[QqTt]/) === null) {
  13789. // If there is no previous command or if the previous command was not a Q, q, T or t,
  13790. // assume the control point is coincident with the current point
  13791. controlX = x;
  13792. controlY = y;
  13793. }
  13794. else {
  13795. // calculate reflection of previous control point
  13796. controlX = 2 * x - controlX;
  13797. controlY = 2 * y - controlY;
  13798. }
  13799. bounds = fabric.util.getBoundsOfCurve(x, y,
  13800. controlX,
  13801. controlY,
  13802. controlX,
  13803. controlY,
  13804. tempX,
  13805. tempY
  13806. );
  13807. x = tempX;
  13808. y = tempY;
  13809. break;
  13810. case 'T':
  13811. tempX = current[1];
  13812. tempY = current[2];
  13813. if (previous[0].match(/[QqTt]/) === null) {
  13814. // If there is no previous command or if the previous command was not a Q, q, T or t,
  13815. // assume the control point is coincident with the current point
  13816. controlX = x;
  13817. controlY = y;
  13818. }
  13819. else {
  13820. // calculate reflection of previous control point
  13821. controlX = 2 * x - controlX;
  13822. controlY = 2 * y - controlY;
  13823. }
  13824. bounds = fabric.util.getBoundsOfCurve(x, y,
  13825. controlX,
  13826. controlY,
  13827. controlX,
  13828. controlY,
  13829. tempX,
  13830. tempY
  13831. );
  13832. x = tempX;
  13833. y = tempY;
  13834. break;
  13835. case 'a':
  13836. // TODO: optimize this
  13837. bounds = fabric.util.getBoundsOfArc(x, y,
  13838. current[1],
  13839. current[2],
  13840. current[3],
  13841. current[4],
  13842. current[5],
  13843. current[6] + x,
  13844. current[7] + y
  13845. );
  13846. x += current[6];
  13847. y += current[7];
  13848. break;
  13849. case 'A':
  13850. // TODO: optimize this
  13851. bounds = fabric.util.getBoundsOfArc(x, y,
  13852. current[1],
  13853. current[2],
  13854. current[3],
  13855. current[4],
  13856. current[5],
  13857. current[6],
  13858. current[7]
  13859. );
  13860. x = current[6];
  13861. y = current[7];
  13862. break;
  13863. case 'z':
  13864. case 'Z':
  13865. x = subpathStartX;
  13866. y = subpathStartY;
  13867. break;
  13868. }
  13869. previous = current;
  13870. bounds.forEach(function (point) {
  13871. aX.push(point.x);
  13872. aY.push(point.y);
  13873. });
  13874. aX.push(x);
  13875. aY.push(y);
  13876. }
  13877. var minX = min(aX),
  13878. minY = min(aY),
  13879. maxX = max(aX),
  13880. maxY = max(aY),
  13881. deltaX = maxX - minX,
  13882. deltaY = maxY - minY,
  13883. o = {
  13884. left: minX,
  13885. top: minY,
  13886. width: deltaX,
  13887. height: deltaY
  13888. };
  13889. return o;
  13890. }
  13891. });
  13892. /**
  13893. * Creates an instance of fabric.Path from an object
  13894. * @static
  13895. * @memberOf fabric.Path
  13896. * @param {Object} object
  13897. * @param {Function} callback Callback to invoke when an fabric.Path instance is created
  13898. */
  13899. fabric.Path.fromObject = function(object, callback) {
  13900. if (typeof object.path === 'string') {
  13901. fabric.loadSVGFromURL(object.path, function (elements) {
  13902. var path = elements[0],
  13903. pathUrl = object.path;
  13904. delete object.path;
  13905. fabric.util.object.extend(path, object);
  13906. path.setSourcePath(pathUrl);
  13907. callback(path);
  13908. });
  13909. }
  13910. else {
  13911. callback(new fabric.Path(object.path, object));
  13912. }
  13913. };
  13914. /* _FROM_SVG_START_ */
  13915. /**
  13916. * List of attribute names to account for when parsing SVG element (used by `fabric.Path.fromElement`)
  13917. * @static
  13918. * @memberOf fabric.Path
  13919. * @see http://www.w3.org/TR/SVG/paths.html#PathElement
  13920. */
  13921. fabric.Path.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(['d']);
  13922. /**
  13923. * Creates an instance of fabric.Path from an SVG <path> element
  13924. * @static
  13925. * @memberOf fabric.Path
  13926. * @param {SVGElement} element to parse
  13927. * @param {Function} callback Callback to invoke when an fabric.Path instance is created
  13928. * @param {Object} [options] Options object
  13929. */
  13930. fabric.Path.fromElement = function(element, callback, options) {
  13931. var parsedAttributes = fabric.parseAttributes(element, fabric.Path.ATTRIBUTE_NAMES);
  13932. callback && callback(new fabric.Path(parsedAttributes.d, extend(parsedAttributes, options)));
  13933. };
  13934. /* _FROM_SVG_END_ */
  13935. /**
  13936. * Indicates that instances of this type are async
  13937. * @static
  13938. * @memberOf fabric.Path
  13939. * @type Boolean
  13940. * @default
  13941. */
  13942. fabric.Path.async = true;
  13943. })(typeof exports !== 'undefined' ? exports : this);
  13944. (function(global) {
  13945. 'use strict';
  13946. var fabric = global.fabric || (global.fabric = { }),
  13947. extend = fabric.util.object.extend,
  13948. invoke = fabric.util.array.invoke,
  13949. parentToObject = fabric.Object.prototype.toObject;
  13950. if (fabric.PathGroup) {
  13951. fabric.warn('fabric.PathGroup is already defined');
  13952. return;
  13953. }
  13954. /**
  13955. * Path group class
  13956. * @class fabric.PathGroup
  13957. * @extends fabric.Path
  13958. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#path_and_pathgroup}
  13959. * @see {@link fabric.PathGroup#initialize} for constructor definition
  13960. */
  13961. fabric.PathGroup = fabric.util.createClass(fabric.Path, /** @lends fabric.PathGroup.prototype */ {
  13962. /**
  13963. * Type of an object
  13964. * @type String
  13965. * @default
  13966. */
  13967. type: 'path-group',
  13968. /**
  13969. * Fill value
  13970. * @type String
  13971. * @default
  13972. */
  13973. fill: '',
  13974. /**
  13975. * Constructor
  13976. * @param {Array} paths
  13977. * @param {Object} [options] Options object
  13978. * @return {fabric.PathGroup} thisArg
  13979. */
  13980. initialize: function(paths, options) {
  13981. options = options || { };
  13982. this.paths = paths || [ ];
  13983. for (var i = this.paths.length; i--;) {
  13984. this.paths[i].group = this;
  13985. }
  13986. if (options.toBeParsed) {
  13987. this.parseDimensionsFromPaths(options);
  13988. delete options.toBeParsed;
  13989. }
  13990. this.setOptions(options);
  13991. this.setCoords();
  13992. if (options.sourcePath) {
  13993. this.setSourcePath(options.sourcePath);
  13994. }
  13995. },
  13996. /**
  13997. * Calculate width and height based on paths contained
  13998. */
  13999. parseDimensionsFromPaths: function(options) {
  14000. var points, p, xC = [ ], yC = [ ], path, height, width,
  14001. m = this.transformMatrix;
  14002. for (var j = this.paths.length; j--;) {
  14003. path = this.paths[j];
  14004. height = path.height + path.strokeWidth;
  14005. width = path.width + path.strokeWidth;
  14006. points = [
  14007. { x: path.left, y: path.top },
  14008. { x: path.left + width, y: path.top },
  14009. { x: path.left, y: path.top + height },
  14010. { x: path.left + width, y: path.top + height }
  14011. ];
  14012. for (var i = 0; i < points.length; i++) {
  14013. p = points[i];
  14014. if (m) {
  14015. p = fabric.util.transformPoint(p, m, false);
  14016. }
  14017. xC.push(p.x);
  14018. yC.push(p.y);
  14019. }
  14020. }
  14021. options.width = Math.max.apply(null, xC);
  14022. options.height = Math.max.apply(null, yC);
  14023. },
  14024. /**
  14025. * Renders this group on a specified context
  14026. * @param {CanvasRenderingContext2D} ctx Context to render this instance on
  14027. */
  14028. render: function(ctx) {
  14029. // do not render if object is not visible
  14030. if (!this.visible) {
  14031. return;
  14032. }
  14033. ctx.save();
  14034. if (this.transformMatrix) {
  14035. ctx.transform.apply(ctx, this.transformMatrix);
  14036. }
  14037. this.transform(ctx);
  14038. this._setShadow(ctx);
  14039. this.clipTo && fabric.util.clipContext(this, ctx);
  14040. ctx.translate(-this.width/2, -this.height/2);
  14041. for (var i = 0, l = this.paths.length; i < l; ++i) {
  14042. this.paths[i].render(ctx, true);
  14043. }
  14044. this.clipTo && ctx.restore();
  14045. this._removeShadow(ctx);
  14046. ctx.restore();
  14047. },
  14048. /**
  14049. * Sets certain property to a certain value
  14050. * @param {String} prop
  14051. * @param {Any} value
  14052. * @return {fabric.PathGroup} thisArg
  14053. */
  14054. _set: function(prop, value) {
  14055. if (prop === 'fill' && value && this.isSameColor()) {
  14056. var i = this.paths.length;
  14057. while (i--) {
  14058. this.paths[i]._set(prop, value);
  14059. }
  14060. }
  14061. return this.callSuper('_set', prop, value);
  14062. },
  14063. /**
  14064. * Returns object representation of this path group
  14065. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14066. * @return {Object} object representation of an instance
  14067. */
  14068. toObject: function(propertiesToInclude) {
  14069. var o = extend(parentToObject.call(this, propertiesToInclude), {
  14070. paths: invoke(this.getObjects(), 'toObject', propertiesToInclude)
  14071. });
  14072. if (this.sourcePath) {
  14073. o.sourcePath = this.sourcePath;
  14074. }
  14075. return o;
  14076. },
  14077. /**
  14078. * Returns dataless object representation of this path group
  14079. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14080. * @return {Object} dataless object representation of an instance
  14081. */
  14082. toDatalessObject: function(propertiesToInclude) {
  14083. var o = this.toObject(propertiesToInclude);
  14084. if (this.sourcePath) {
  14085. o.paths = this.sourcePath;
  14086. }
  14087. return o;
  14088. },
  14089. /* _TO_SVG_START_ */
  14090. /**
  14091. * Returns svg representation of an instance
  14092. * @param {Function} [reviver] Method for further parsing of svg representation.
  14093. * @return {String} svg representation of an instance
  14094. */
  14095. toSVG: function(reviver) {
  14096. var objects = this.getObjects(),
  14097. p = this.getPointByOrigin('left', 'top'),
  14098. translatePart = 'translate(' + p.x + ' ' + p.y + ')',
  14099. markup = [
  14100. //jscs:disable validateIndentation
  14101. '<g ',
  14102. 'style="', this.getSvgStyles(), '" ',
  14103. 'transform="', this.getSvgTransformMatrix(), translatePart, this.getSvgTransform(), '" ',
  14104. '>\n'
  14105. //jscs:enable validateIndentation
  14106. ];
  14107. for (var i = 0, len = objects.length; i < len; i++) {
  14108. markup.push(objects[i].toSVG(reviver));
  14109. }
  14110. markup.push('</g>\n');
  14111. return reviver ? reviver(markup.join('')) : markup.join('');
  14112. },
  14113. /* _TO_SVG_END_ */
  14114. /**
  14115. * Returns a string representation of this path group
  14116. * @return {String} string representation of an object
  14117. */
  14118. toString: function() {
  14119. return '#<fabric.PathGroup (' + this.complexity() +
  14120. '): { top: ' + this.top + ', left: ' + this.left + ' }>';
  14121. },
  14122. /**
  14123. * Returns true if all paths in this group are of same color
  14124. * @return {Boolean} true if all paths are of the same color (`fill`)
  14125. */
  14126. isSameColor: function() {
  14127. var firstPathFill = (this.getObjects()[0].get('fill') || '').toLowerCase();
  14128. return this.getObjects().every(function(path) {
  14129. return (path.get('fill') || '').toLowerCase() === firstPathFill;
  14130. });
  14131. },
  14132. /**
  14133. * Returns number representation of object's complexity
  14134. * @return {Number} complexity
  14135. */
  14136. complexity: function() {
  14137. return this.paths.reduce(function(total, path) {
  14138. return total + ((path && path.complexity) ? path.complexity() : 0);
  14139. }, 0);
  14140. },
  14141. /**
  14142. * Returns all paths in this path group
  14143. * @return {Array} array of path objects included in this path group
  14144. */
  14145. getObjects: function() {
  14146. return this.paths;
  14147. }
  14148. });
  14149. /**
  14150. * Creates fabric.PathGroup instance from an object representation
  14151. * @static
  14152. * @memberOf fabric.PathGroup
  14153. * @param {Object} object Object to create an instance from
  14154. * @param {Function} callback Callback to invoke when an fabric.PathGroup instance is created
  14155. */
  14156. fabric.PathGroup.fromObject = function(object, callback) {
  14157. if (typeof object.paths === 'string') {
  14158. fabric.loadSVGFromURL(object.paths, function (elements) {
  14159. var pathUrl = object.paths;
  14160. delete object.paths;
  14161. var pathGroup = fabric.util.groupSVGElements(elements, object, pathUrl);
  14162. callback(pathGroup);
  14163. });
  14164. }
  14165. else {
  14166. fabric.util.enlivenObjects(object.paths, function(enlivenedObjects) {
  14167. delete object.paths;
  14168. callback(new fabric.PathGroup(enlivenedObjects, object));
  14169. });
  14170. }
  14171. };
  14172. /**
  14173. * Indicates that instances of this type are async
  14174. * @static
  14175. * @memberOf fabric.PathGroup
  14176. * @type Boolean
  14177. * @default
  14178. */
  14179. fabric.PathGroup.async = true;
  14180. })(typeof exports !== 'undefined' ? exports : this);
  14181. (function(global) {
  14182. 'use strict';
  14183. var fabric = global.fabric || (global.fabric = { }),
  14184. extend = fabric.util.object.extend,
  14185. min = fabric.util.array.min,
  14186. max = fabric.util.array.max,
  14187. invoke = fabric.util.array.invoke;
  14188. if (fabric.Group) {
  14189. return;
  14190. }
  14191. // lock-related properties, for use in fabric.Group#get
  14192. // to enable locking behavior on group
  14193. // when one of its objects has lock-related properties set
  14194. var _lockProperties = {
  14195. lockMovementX: true,
  14196. lockMovementY: true,
  14197. lockRotation: true,
  14198. lockScalingX: true,
  14199. lockScalingY: true,
  14200. lockUniScaling: true
  14201. };
  14202. /**
  14203. * Group class
  14204. * @class fabric.Group
  14205. * @extends fabric.Object
  14206. * @mixes fabric.Collection
  14207. * @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#groups}
  14208. * @see {@link fabric.Group#initialize} for constructor definition
  14209. */
  14210. fabric.Group = fabric.util.createClass(fabric.Object, fabric.Collection, /** @lends fabric.Group.prototype */ {
  14211. /**
  14212. * Type of an object
  14213. * @type String
  14214. * @default
  14215. */
  14216. type: 'group',
  14217. /**
  14218. * Constructor
  14219. * @param {Object} objects Group objects
  14220. * @param {Object} [options] Options object
  14221. * @return {Object} thisArg
  14222. */
  14223. initialize: function(objects, options) {
  14224. options = options || { };
  14225. this._objects = objects || [];
  14226. for (var i = this._objects.length; i--; ) {
  14227. this._objects[i].group = this;
  14228. }
  14229. this.originalState = { };
  14230. this.callSuper('initialize');
  14231. if (options.originX) {
  14232. this.originX = options.originX;
  14233. }
  14234. if (options.originY) {
  14235. this.originY = options.originY;
  14236. }
  14237. this._calcBounds();
  14238. this._updateObjectsCoords();
  14239. this.callSuper('initialize', options);
  14240. this.setCoords();
  14241. this.saveCoords();
  14242. },
  14243. /**
  14244. * @private
  14245. */
  14246. _updateObjectsCoords: function() {
  14247. this.forEachObject(this._updateObjectCoords, this);
  14248. },
  14249. /**
  14250. * @private
  14251. */
  14252. _updateObjectCoords: function(object) {
  14253. var objectLeft = object.getLeft(),
  14254. objectTop = object.getTop(),
  14255. center = this.getCenterPoint();
  14256. object.set({
  14257. originalLeft: objectLeft,
  14258. originalTop: objectTop,
  14259. left: objectLeft - center.x,
  14260. top: objectTop - center.y
  14261. });
  14262. object.setCoords();
  14263. // do not display corners of objects enclosed in a group
  14264. object.__origHasControls = object.hasControls;
  14265. object.hasControls = false;
  14266. },
  14267. /**
  14268. * Returns string represenation of a group
  14269. * @return {String}
  14270. */
  14271. toString: function() {
  14272. return '#<fabric.Group: (' + this.complexity() + ')>';
  14273. },
  14274. /**
  14275. * Adds an object to a group; Then recalculates group's dimension, position.
  14276. * @param {Object} object
  14277. * @return {fabric.Group} thisArg
  14278. * @chainable
  14279. */
  14280. addWithUpdate: function(object) {
  14281. this._restoreObjectsState();
  14282. if (object) {
  14283. this._objects.push(object);
  14284. object.group = this;
  14285. }
  14286. // since _restoreObjectsState set objects inactive
  14287. this.forEachObject(this._setObjectActive, this);
  14288. this._calcBounds();
  14289. this._updateObjectsCoords();
  14290. return this;
  14291. },
  14292. /**
  14293. * @private
  14294. */
  14295. _setObjectActive: function(object) {
  14296. object.set('active', true);
  14297. object.group = this;
  14298. },
  14299. /**
  14300. * Removes an object from a group; Then recalculates group's dimension, position.
  14301. * @param {Object} object
  14302. * @return {fabric.Group} thisArg
  14303. * @chainable
  14304. */
  14305. removeWithUpdate: function(object) {
  14306. this._moveFlippedObject(object);
  14307. this._restoreObjectsState();
  14308. // since _restoreObjectsState set objects inactive
  14309. this.forEachObject(this._setObjectActive, this);
  14310. this.remove(object);
  14311. this._calcBounds();
  14312. this._updateObjectsCoords();
  14313. return this;
  14314. },
  14315. /**
  14316. * @private
  14317. */
  14318. _onObjectAdded: function(object) {
  14319. object.group = this;
  14320. },
  14321. /**
  14322. * @private
  14323. */
  14324. _onObjectRemoved: function(object) {
  14325. delete object.group;
  14326. object.set('active', false);
  14327. },
  14328. /**
  14329. * Properties that are delegated to group objects when reading/writing
  14330. * @param {Object} delegatedProperties
  14331. */
  14332. delegatedProperties: {
  14333. fill: true,
  14334. opacity: true,
  14335. fontFamily: true,
  14336. fontWeight: true,
  14337. fontSize: true,
  14338. fontStyle: true,
  14339. lineHeight: true,
  14340. textDecoration: true,
  14341. textAlign: true,
  14342. backgroundColor: true
  14343. },
  14344. /**
  14345. * @private
  14346. */
  14347. _set: function(key, value) {
  14348. if (key in this.delegatedProperties) {
  14349. var i = this._objects.length;
  14350. while (i--) {
  14351. this._objects[i].set(key, value);
  14352. }
  14353. }
  14354. this.callSuper('_set', key, value);
  14355. },
  14356. /**
  14357. * Returns object representation of an instance
  14358. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14359. * @return {Object} object representation of an instance
  14360. */
  14361. toObject: function(propertiesToInclude) {
  14362. return extend(this.callSuper('toObject', propertiesToInclude), {
  14363. objects: invoke(this._objects, 'toObject', propertiesToInclude)
  14364. });
  14365. },
  14366. /**
  14367. * Renders instance on a given context
  14368. * @param {CanvasRenderingContext2D} ctx context to render instance on
  14369. */
  14370. render: function(ctx) {
  14371. // do not render if object is not visible
  14372. if (!this.visible) {
  14373. return;
  14374. }
  14375. ctx.save();
  14376. this.clipTo && fabric.util.clipContext(this, ctx);
  14377. this.transform(ctx);
  14378. // the array is now sorted in order of highest first, so start from end
  14379. for (var i = 0, len = this._objects.length; i < len; i++) {
  14380. this._renderObject(this._objects[i], ctx);
  14381. }
  14382. this.clipTo && ctx.restore();
  14383. ctx.restore();
  14384. },
  14385. /**
  14386. * Renders controls and borders for the object
  14387. * @param {CanvasRenderingContext2D} ctx Context to render on
  14388. * @param {Boolean} [noTransform] When true, context is not transformed
  14389. */
  14390. _renderControls: function(ctx, noTransform) {
  14391. this.callSuper('_renderControls', ctx, noTransform);
  14392. for (var i = 0, len = this._objects.length; i < len; i++) {
  14393. this._objects[i]._renderControls(ctx);
  14394. }
  14395. },
  14396. /**
  14397. * @private
  14398. */
  14399. _renderObject: function(object, ctx) {
  14400. var originalHasRotatingPoint = object.hasRotatingPoint;
  14401. // do not render if object is not visible
  14402. if (!object.visible) {
  14403. return;
  14404. }
  14405. object.hasRotatingPoint = false;
  14406. object.render(ctx);
  14407. object.hasRotatingPoint = originalHasRotatingPoint;
  14408. },
  14409. /**
  14410. * Retores original state of each of group objects (original state is that which was before group was created).
  14411. * @private
  14412. * @return {fabric.Group} thisArg
  14413. * @chainable
  14414. */
  14415. _restoreObjectsState: function() {
  14416. this._objects.forEach(this._restoreObjectState, this);
  14417. return this;
  14418. },
  14419. /**
  14420. * Realises the transform from this group onto the supplied object
  14421. * i.e. it tells you what would happen if the supplied object was in
  14422. * the group, and then the group was destroyed. It mutates the supplied
  14423. * object.
  14424. * @param {fabric.Object} object
  14425. * @return {fabric.Object} transformedObject
  14426. */
  14427. realizeTransform: function(object) {
  14428. this._moveFlippedObject(object);
  14429. this._setObjectPosition(object);
  14430. return object;
  14431. },
  14432. /**
  14433. * Moves a flipped object to the position where it's displayed
  14434. * @private
  14435. * @param {fabric.Object} object
  14436. * @return {fabric.Group} thisArg
  14437. */
  14438. _moveFlippedObject: function(object) {
  14439. var oldOriginX = object.get('originX'),
  14440. oldOriginY = object.get('originY'),
  14441. center = object.getCenterPoint();
  14442. object.set({
  14443. originX: 'center',
  14444. originY: 'center',
  14445. left: center.x,
  14446. top: center.y
  14447. });
  14448. this._toggleFlipping(object);
  14449. var newOrigin = object.getPointByOrigin(oldOriginX, oldOriginY);
  14450. object.set({
  14451. originX: oldOriginX,
  14452. originY: oldOriginY,
  14453. left: newOrigin.x,
  14454. top: newOrigin.y
  14455. });
  14456. return this;
  14457. },
  14458. /**
  14459. * @private
  14460. */
  14461. _toggleFlipping: function(object) {
  14462. if (this.flipX) {
  14463. object.toggle('flipX');
  14464. object.set('left', -object.get('left'));
  14465. object.setAngle(-object.getAngle());
  14466. }
  14467. if (this.flipY) {
  14468. object.toggle('flipY');
  14469. object.set('top', -object.get('top'));
  14470. object.setAngle(-object.getAngle());
  14471. }
  14472. },
  14473. /**
  14474. * Restores original state of a specified object in group
  14475. * @private
  14476. * @param {fabric.Object} object
  14477. * @return {fabric.Group} thisArg
  14478. */
  14479. _restoreObjectState: function(object) {
  14480. this._setObjectPosition(object);
  14481. object.setCoords();
  14482. object.hasControls = object.__origHasControls;
  14483. delete object.__origHasControls;
  14484. object.set('active', false);
  14485. object.setCoords();
  14486. delete object.group;
  14487. return this;
  14488. },
  14489. /**
  14490. * @private
  14491. */
  14492. _setObjectPosition: function(object) {
  14493. var center = this.getCenterPoint(),
  14494. rotated = this._getRotatedLeftTop(object);
  14495. object.set({
  14496. angle: object.getAngle() + this.getAngle(),
  14497. left: center.x + rotated.left,
  14498. top: center.y + rotated.top,
  14499. scaleX: object.get('scaleX') * this.get('scaleX'),
  14500. scaleY: object.get('scaleY') * this.get('scaleY')
  14501. });
  14502. },
  14503. /**
  14504. * @private
  14505. */
  14506. _getRotatedLeftTop: function(object) {
  14507. var groupAngle = this.getAngle() * (Math.PI / 180);
  14508. return {
  14509. left: (-Math.sin(groupAngle) * object.getTop() * this.get('scaleY') +
  14510. Math.cos(groupAngle) * object.getLeft() * this.get('scaleX')),
  14511. top: (Math.cos(groupAngle) * object.getTop() * this.get('scaleY') +
  14512. Math.sin(groupAngle) * object.getLeft() * this.get('scaleX'))
  14513. };
  14514. },
  14515. /**
  14516. * Destroys a group (restoring state of its objects)
  14517. * @return {fabric.Group} thisArg
  14518. * @chainable
  14519. */
  14520. destroy: function() {
  14521. this._objects.forEach(this._moveFlippedObject, this);
  14522. return this._restoreObjectsState();
  14523. },
  14524. /**
  14525. * Saves coordinates of this instance (to be used together with `hasMoved`)
  14526. * @saveCoords
  14527. * @return {fabric.Group} thisArg
  14528. * @chainable
  14529. */
  14530. saveCoords: function() {
  14531. this._originalLeft = this.get('left');
  14532. this._originalTop = this.get('top');
  14533. return this;
  14534. },
  14535. /**
  14536. * Checks whether this group was moved (since `saveCoords` was called last)
  14537. * @return {Boolean} true if an object was moved (since fabric.Group#saveCoords was called)
  14538. */
  14539. hasMoved: function() {
  14540. return this._originalLeft !== this.get('left') ||
  14541. this._originalTop !== this.get('top');
  14542. },
  14543. /**
  14544. * Sets coordinates of all group objects
  14545. * @return {fabric.Group} thisArg
  14546. * @chainable
  14547. */
  14548. setObjectsCoords: function() {
  14549. this.forEachObject(function(object) {
  14550. object.setCoords();
  14551. });
  14552. return this;
  14553. },
  14554. /**
  14555. * @private
  14556. */
  14557. _calcBounds: function(onlyWidthHeight) {
  14558. var aX = [],
  14559. aY = [],
  14560. o, prop,
  14561. props = ['tr', 'br', 'bl', 'tl'];
  14562. for (var i = 0, len = this._objects.length; i < len; ++i) {
  14563. o = this._objects[i];
  14564. o.setCoords();
  14565. for (var j = 0; j < props.length; j++) {
  14566. prop = props[j];
  14567. aX.push(o.oCoords[prop].x);
  14568. aY.push(o.oCoords[prop].y);
  14569. }
  14570. }
  14571. this.set(this._getBounds(aX, aY, onlyWidthHeight));
  14572. },
  14573. /**
  14574. * @private
  14575. */
  14576. _getBounds: function(aX, aY, onlyWidthHeight) {
  14577. var ivt = fabric.util.invertTransform(this.getViewportTransform()),
  14578. minXY = fabric.util.transformPoint(new fabric.Point(min(aX), min(aY)), ivt),
  14579. maxXY = fabric.util.transformPoint(new fabric.Point(max(aX), max(aY)), ivt),
  14580. obj = {
  14581. width: (maxXY.x - minXY.x) || 0,
  14582. height: (maxXY.y - minXY.y) || 0
  14583. };
  14584. if (!onlyWidthHeight) {
  14585. obj.left = minXY.x || 0;
  14586. obj.top = minXY.y || 0;
  14587. if (this.originX === 'center') {
  14588. obj.left += obj.width / 2;
  14589. }
  14590. if (this.originX === 'right') {
  14591. obj.left += obj.width;
  14592. }
  14593. if (this.originY === 'center') {
  14594. obj.top += obj.height / 2;
  14595. }
  14596. if (this.originY === 'bottom') {
  14597. obj.top += obj.height;
  14598. }
  14599. }
  14600. return obj;
  14601. },
  14602. /* _TO_SVG_START_ */
  14603. /**
  14604. * Returns svg representation of an instance
  14605. * @param {Function} [reviver] Method for further parsing of svg representation.
  14606. * @return {String} svg representation of an instance
  14607. */
  14608. toSVG: function(reviver) {
  14609. var markup = [
  14610. //jscs:disable validateIndentation
  14611. '<g ',
  14612. 'transform="', this.getSvgTransform(),
  14613. '">\n'
  14614. //jscs:enable validateIndentation
  14615. ];
  14616. for (var i = 0, len = this._objects.length; i < len; i++) {
  14617. markup.push(this._objects[i].toSVG(reviver));
  14618. }
  14619. markup.push('</g>\n');
  14620. return reviver ? reviver(markup.join('')) : markup.join('');
  14621. },
  14622. /* _TO_SVG_END_ */
  14623. /**
  14624. * Returns requested property
  14625. * @param {String} prop Property to get
  14626. * @return {Any}
  14627. */
  14628. get: function(prop) {
  14629. if (prop in _lockProperties) {
  14630. if (this[prop]) {
  14631. return this[prop];
  14632. }
  14633. else {
  14634. for (var i = 0, len = this._objects.length; i < len; i++) {
  14635. if (this._objects[i][prop]) {
  14636. return true;
  14637. }
  14638. }
  14639. return false;
  14640. }
  14641. }
  14642. else {
  14643. if (prop in this.delegatedProperties) {
  14644. return this._objects[0] && this._objects[0].get(prop);
  14645. }
  14646. return this[prop];
  14647. }
  14648. }
  14649. });
  14650. /**
  14651. * Returns {@link fabric.Group} instance from an object representation
  14652. * @static
  14653. * @memberOf fabric.Group
  14654. * @param {Object} object Object to create a group from
  14655. * @param {Function} [callback] Callback to invoke when an group instance is created
  14656. * @return {fabric.Group} An instance of fabric.Group
  14657. */
  14658. fabric.Group.fromObject = function(object, callback) {
  14659. fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
  14660. delete object.objects;
  14661. callback && callback(new fabric.Group(enlivenedObjects, object));
  14662. });
  14663. };
  14664. /**
  14665. * Indicates that instances of this type are async
  14666. * @static
  14667. * @memberOf fabric.Group
  14668. * @type Boolean
  14669. * @default
  14670. */
  14671. fabric.Group.async = true;
  14672. })(typeof exports !== 'undefined' ? exports : this);
  14673. (function(global) {
  14674. 'use strict';
  14675. var extend = fabric.util.object.extend;
  14676. if (!global.fabric) {
  14677. global.fabric = { };
  14678. }
  14679. if (global.fabric.Image) {
  14680. fabric.warn('fabric.Image is already defined.');
  14681. return;
  14682. }
  14683. /**
  14684. * Image class
  14685. * @class fabric.Image
  14686. * @extends fabric.Object
  14687. * @tutorial {@link http://fabricjs.com/fabric-intro-part-1/#images}
  14688. * @see {@link fabric.Image#initialize} for constructor definition
  14689. */
  14690. fabric.Image = fabric.util.createClass(fabric.Object, /** @lends fabric.Image.prototype */ {
  14691. /**
  14692. * Type of an object
  14693. * @type String
  14694. * @default
  14695. */
  14696. type: 'image',
  14697. /**
  14698. * crossOrigin value (one of "", "anonymous", "allow-credentials")
  14699. * @see https://developer.mozilla.org/en-US/docs/HTML/CORS_settings_attributes
  14700. * @type String
  14701. * @default
  14702. */
  14703. crossOrigin: '',
  14704. /**
  14705. * AlignX value, part of preserveAspectRatio (one of "none", "mid", "min", "max")
  14706. * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  14707. * This parameter defines how the picture is aligned to its viewport when image element width differs from image width.
  14708. * @type String
  14709. * @default
  14710. */
  14711. alignX: 'none',
  14712. /**
  14713. * AlignY value, part of preserveAspectRatio (one of "none", "mid", "min", "max")
  14714. * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  14715. * This parameter defines how the picture is aligned to its viewport when image element height differs from image height.
  14716. * @type String
  14717. * @default
  14718. */
  14719. alignY: 'none',
  14720. /**
  14721. * meetOrSlice value, part of preserveAspectRatio (one of "meet", "slice").
  14722. * if meet the image is always fully visibile, if slice the viewport is always filled with image.
  14723. * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
  14724. * @type String
  14725. * @default
  14726. */
  14727. meetOrSlice: 'meet',
  14728. /**
  14729. * private
  14730. * contains last value of scaleX to detect
  14731. * if the Image got resized after the last Render
  14732. * @type Number
  14733. */
  14734. _lastScaleX: 1,
  14735. /**
  14736. * private
  14737. * contains last value of scaleY to detect
  14738. * if the Image got resized after the last Render
  14739. * @type Number
  14740. */
  14741. _lastScaleY: 1,
  14742. /**
  14743. * Constructor
  14744. * @param {HTMLImageElement | String} element Image element
  14745. * @param {Object} [options] Options object
  14746. * @return {fabric.Image} thisArg
  14747. */
  14748. initialize: function(element, options) {
  14749. options || (options = { });
  14750. this.filters = [ ];
  14751. this.resizeFilters = [ ];
  14752. this.callSuper('initialize', options);
  14753. this._initElement(element, options);
  14754. this._initConfig(options);
  14755. if (options.filters) {
  14756. this.filters = options.filters;
  14757. this.applyFilters();
  14758. }
  14759. },
  14760. /**
  14761. * Returns image element which this instance if based on
  14762. * @return {HTMLImageElement} Image element
  14763. */
  14764. getElement: function() {
  14765. return this._element;
  14766. },
  14767. /**
  14768. * Sets image element for this instance to a specified one.
  14769. * If filters defined they are applied to new image.
  14770. * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area.
  14771. * @param {HTMLImageElement} element
  14772. * @param {Function} [callback] Callback is invoked when all filters have been applied and new image is generated
  14773. * @param {Object} [options] Options object
  14774. * @return {fabric.Image} thisArg
  14775. * @chainable
  14776. */
  14777. setElement: function(element, callback, options) {
  14778. this._element = element;
  14779. this._originalElement = element;
  14780. this._initConfig(options);
  14781. if (this.filters.length !== 0) {
  14782. this.applyFilters(callback);
  14783. }
  14784. else if (callback) {
  14785. callback();
  14786. }
  14787. return this;
  14788. },
  14789. /**
  14790. * Sets crossOrigin value (on an instance and corresponding image element)
  14791. * @return {fabric.Image} thisArg
  14792. * @chainable
  14793. */
  14794. setCrossOrigin: function(value) {
  14795. this.crossOrigin = value;
  14796. this._element.crossOrigin = value;
  14797. return this;
  14798. },
  14799. /**
  14800. * Returns original size of an image
  14801. * @return {Object} Object with "width" and "height" properties
  14802. */
  14803. getOriginalSize: function() {
  14804. var element = this.getElement();
  14805. return {
  14806. width: element.width,
  14807. height: element.height
  14808. };
  14809. },
  14810. /**
  14811. * @private
  14812. * @param {CanvasRenderingContext2D} ctx Context to render on
  14813. */
  14814. _stroke: function(ctx) {
  14815. ctx.save();
  14816. this._setStrokeStyles(ctx);
  14817. ctx.beginPath();
  14818. ctx.strokeRect(-this.width / 2, -this.height / 2, this.width, this.height);
  14819. ctx.closePath();
  14820. ctx.restore();
  14821. },
  14822. /**
  14823. * @private
  14824. * @param {CanvasRenderingContext2D} ctx Context to render on
  14825. */
  14826. _renderDashedStroke: function(ctx) {
  14827. var x = -this.width / 2,
  14828. y = -this.height / 2,
  14829. w = this.width,
  14830. h = this.height;
  14831. ctx.save();
  14832. this._setStrokeStyles(ctx);
  14833. ctx.beginPath();
  14834. fabric.util.drawDashedLine(ctx, x, y, x + w, y, this.strokeDashArray);
  14835. fabric.util.drawDashedLine(ctx, x + w, y, x + w, y + h, this.strokeDashArray);
  14836. fabric.util.drawDashedLine(ctx, x + w, y + h, x, y + h, this.strokeDashArray);
  14837. fabric.util.drawDashedLine(ctx, x, y + h, x, y, this.strokeDashArray);
  14838. ctx.closePath();
  14839. ctx.restore();
  14840. },
  14841. /**
  14842. * Returns object representation of an instance
  14843. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14844. * @return {Object} Object representation of an instance
  14845. */
  14846. toObject: function(propertiesToInclude) {
  14847. return extend(this.callSuper('toObject', propertiesToInclude), {
  14848. src: this._originalElement.src || this._originalElement._src,
  14849. filters: this.filters.map(function(filterObj) {
  14850. return filterObj && filterObj.toObject();
  14851. }),
  14852. crossOrigin: this.crossOrigin,
  14853. alignX: this.alignX,
  14854. alignY: this.alignY,
  14855. meetOrSlice: this.meetOrSlice
  14856. });
  14857. },
  14858. /* _TO_SVG_START_ */
  14859. /**
  14860. * Returns SVG representation of an instance
  14861. * @param {Function} [reviver] Method for further parsing of svg representation.
  14862. * @return {String} svg representation of an instance
  14863. */
  14864. toSVG: function(reviver) {
  14865. var markup = [], x = -this.width / 2, y = -this.height / 2,
  14866. preserveAspectRatio = 'none';
  14867. if (this.group && this.group.type === 'path-group') {
  14868. x = this.left;
  14869. y = this.top;
  14870. }
  14871. if (this.alignX !== 'none' && this.alignY !== 'none') {
  14872. preserveAspectRatio = 'x' + this.alignX + 'Y' + this.alignY + ' ' + this.meetOrSlice;
  14873. }
  14874. markup.push(
  14875. '<g transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '">\n',
  14876. '<image xlink:href="', this.getSvgSrc(),
  14877. '" x="', x, '" y="', y,
  14878. '" style="', this.getSvgStyles(),
  14879. // we're essentially moving origin of transformation from top/left corner to the center of the shape
  14880. // by wrapping it in container <g> element with actual transformation, then offsetting object to the top/left
  14881. // so that object's center aligns with container's left/top
  14882. '" width="', this.width,
  14883. '" height="', this.height,
  14884. '" preserveAspectRatio="', preserveAspectRatio, '"',
  14885. '></image>\n'
  14886. );
  14887. if (this.stroke || this.strokeDashArray) {
  14888. var origFill = this.fill;
  14889. this.fill = null;
  14890. markup.push(
  14891. '<rect ',
  14892. 'x="', x, '" y="', y,
  14893. '" width="', this.width, '" height="', this.height,
  14894. '" style="', this.getSvgStyles(),
  14895. '"/>\n'
  14896. );
  14897. this.fill = origFill;
  14898. }
  14899. markup.push('</g>\n');
  14900. return reviver ? reviver(markup.join('')) : markup.join('');
  14901. },
  14902. /* _TO_SVG_END_ */
  14903. /**
  14904. * Returns source of an image
  14905. * @return {String} Source of an image
  14906. */
  14907. getSrc: function() {
  14908. if (this.getElement()) {
  14909. return this.getElement().src || this.getElement()._src;
  14910. }
  14911. },
  14912. /**
  14913. * Sets source of an image
  14914. * @param {String} src Source string (URL)
  14915. * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied)
  14916. * @param {Object} [options] Options object
  14917. * @return {fabric.Image} thisArg
  14918. * @chainable
  14919. */
  14920. setSrc: function(src, callback, options) {
  14921. fabric.util.loadImage(src, function(img) {
  14922. return this.setElement(img, callback, options);
  14923. }, this, options && options.crossOrigin);
  14924. },
  14925. /**
  14926. * Returns string representation of an instance
  14927. * @return {String} String representation of an instance
  14928. */
  14929. toString: function() {
  14930. return '#<fabric.Image: { src: "' + this.getSrc() + '" }>';
  14931. },
  14932. /**
  14933. * Returns a clone of an instance
  14934. * @param {Function} callback Callback is invoked with a clone as a first argument
  14935. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  14936. */
  14937. clone: function(callback, propertiesToInclude) {
  14938. this.constructor.fromObject(this.toObject(propertiesToInclude), callback);
  14939. },
  14940. /**
  14941. * Applies filters assigned to this image (from "filters" array)
  14942. * @method applyFilters
  14943. * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated
  14944. * @return {fabric.Image} thisArg
  14945. * @chainable
  14946. */
  14947. applyFilters: function(callback, filters, imgElement, forResizing) {
  14948. filters = filters || this.filters;
  14949. imgElement = imgElement || this._originalElement;
  14950. if (!imgElement) {
  14951. return;
  14952. }
  14953. var imgEl = imgElement,
  14954. canvasEl = fabric.util.createCanvasElement(),
  14955. replacement = fabric.util.createImage(),
  14956. _this = this;
  14957. canvasEl.width = imgEl.width;
  14958. canvasEl.height = imgEl.height;
  14959. canvasEl.getContext('2d').drawImage(imgEl, 0, 0, imgEl.width, imgEl.height);
  14960. if (filters.length === 0) {
  14961. this._element = imgElement;
  14962. callback && callback();
  14963. return canvasEl;
  14964. }
  14965. filters.forEach(function(filter) {
  14966. filter && filter.applyTo(canvasEl, filter.scaleX || _this.scaleX, filter.scaleY || _this.scaleY);
  14967. if (!forResizing && filter && filter.type === 'Resize') {
  14968. _this.width *= filter.scaleX;
  14969. _this.height *= filter.scaleY;
  14970. }
  14971. });
  14972. /** @ignore */
  14973. replacement.width = canvasEl.width;
  14974. replacement.height = canvasEl.height;
  14975. if (fabric.isLikelyNode) {
  14976. replacement.src = canvasEl.toBuffer(undefined, fabric.Image.pngCompression);
  14977. // onload doesn't fire in some node versions, so we invoke callback manually
  14978. _this._element = replacement;
  14979. !forResizing && (_this._filteredEl = replacement);
  14980. callback && callback();
  14981. }
  14982. else {
  14983. replacement.onload = function() {
  14984. _this._element = replacement;
  14985. !forResizing && (_this._filteredEl = replacement);
  14986. callback && callback();
  14987. replacement.onload = canvasEl = imgEl = null;
  14988. };
  14989. replacement.src = canvasEl.toDataURL('image/png');
  14990. }
  14991. return canvasEl;
  14992. },
  14993. /**
  14994. * @private
  14995. * @param {CanvasRenderingContext2D} ctx Context to render on
  14996. */
  14997. _render: function(ctx, noTransform) {
  14998. var x, y, imageMargins = this._findMargins(), elementToDraw;
  14999. x = (noTransform ? this.left : -this.width / 2);
  15000. y = (noTransform ? this.top : -this.height / 2);
  15001. if (this.meetOrSlice === 'slice') {
  15002. ctx.beginPath();
  15003. ctx.rect(x, y, this.width, this.height);
  15004. ctx.clip();
  15005. }
  15006. if (this.isMoving === false && this.resizeFilters.length && this._needsResize()) {
  15007. this._lastScaleX = this.scaleX;
  15008. this._lastScaleY = this.scaleY;
  15009. elementToDraw = this.applyFilters(null, this.resizeFilters, this._filteredEl || this._originalElement, true);
  15010. }
  15011. else {
  15012. elementToDraw = this._element;
  15013. }
  15014. elementToDraw && ctx.drawImage(elementToDraw,
  15015. x + imageMargins.marginX,
  15016. y + imageMargins.marginY,
  15017. imageMargins.width,
  15018. imageMargins.height
  15019. );
  15020. this._renderStroke(ctx);
  15021. },
  15022. /**
  15023. * @private, needed to check if image needs resize
  15024. */
  15025. _needsResize: function() {
  15026. return (this.scaleX !== this._lastScaleX || this.scaleY !== this._lastScaleY);
  15027. },
  15028. /**
  15029. * @private
  15030. */
  15031. _findMargins: function() {
  15032. var width = this.width, height = this.height, scales,
  15033. scale, marginX = 0, marginY = 0;
  15034. if (this.alignX !== 'none' || this.alignY !== 'none') {
  15035. scales = [this.width / this._element.width, this.height / this._element.height];
  15036. scale = this.meetOrSlice === 'meet'
  15037. ? Math.min.apply(null, scales) : Math.max.apply(null, scales);
  15038. width = this._element.width * scale;
  15039. height = this._element.height * scale;
  15040. if (this.alignX === 'Mid') {
  15041. marginX = (this.width - width) / 2;
  15042. }
  15043. if (this.alignX === 'Max') {
  15044. marginX = this.width - width;
  15045. }
  15046. if (this.alignY === 'Mid') {
  15047. marginY = (this.height - height) / 2;
  15048. }
  15049. if (this.alignY === 'Max') {
  15050. marginY = this.height - height;
  15051. }
  15052. }
  15053. return {
  15054. width: width,
  15055. height: height,
  15056. marginX: marginX,
  15057. marginY: marginY
  15058. };
  15059. },
  15060. /**
  15061. * @private
  15062. */
  15063. _resetWidthHeight: function() {
  15064. var element = this.getElement();
  15065. this.set('width', element.width);
  15066. this.set('height', element.height);
  15067. },
  15068. /**
  15069. * The Image class's initialization method. This method is automatically
  15070. * called by the constructor.
  15071. * @private
  15072. * @param {HTMLImageElement|String} element The element representing the image
  15073. */
  15074. _initElement: function(element) {
  15075. this.setElement(fabric.util.getById(element));
  15076. fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);
  15077. },
  15078. /**
  15079. * @private
  15080. * @param {Object} [options] Options object
  15081. */
  15082. _initConfig: function(options) {
  15083. options || (options = { });
  15084. this.setOptions(options);
  15085. this._setWidthHeight(options);
  15086. if (this._element && this.crossOrigin) {
  15087. this._element.crossOrigin = this.crossOrigin;
  15088. }
  15089. },
  15090. /**
  15091. * @private
  15092. * @param {Object} object Object with filters property
  15093. * @param {Function} callback Callback to invoke when all fabric.Image.filters instances are created
  15094. */
  15095. _initFilters: function(object, callback) {
  15096. if (object.filters && object.filters.length) {
  15097. fabric.util.enlivenObjects(object.filters, function(enlivenedObjects) {
  15098. callback && callback(enlivenedObjects);
  15099. }, 'fabric.Image.filters');
  15100. }
  15101. else {
  15102. callback && callback();
  15103. }
  15104. },
  15105. /**
  15106. * @private
  15107. * @param {Object} [options] Object with width/height properties
  15108. */
  15109. _setWidthHeight: function(options) {
  15110. this.width = 'width' in options
  15111. ? options.width
  15112. : (this.getElement()
  15113. ? this.getElement().width || 0
  15114. : 0);
  15115. this.height = 'height' in options
  15116. ? options.height
  15117. : (this.getElement()
  15118. ? this.getElement().height || 0
  15119. : 0);
  15120. },
  15121. /**
  15122. * Returns complexity of an instance
  15123. * @return {Number} complexity of this instance
  15124. */
  15125. complexity: function() {
  15126. return 1;
  15127. }
  15128. });
  15129. /**
  15130. * Default CSS class name for canvas
  15131. * @static
  15132. * @type String
  15133. * @default
  15134. */
  15135. fabric.Image.CSS_CANVAS = 'canvas-img';
  15136. /**
  15137. * Alias for getSrc
  15138. * @static
  15139. */
  15140. fabric.Image.prototype.getSvgSrc = fabric.Image.prototype.getSrc;
  15141. /**
  15142. * Creates an instance of fabric.Image from its object representation
  15143. * @static
  15144. * @param {Object} object Object to create an instance from
  15145. * @param {Function} [callback] Callback to invoke when an image instance is created
  15146. */
  15147. fabric.Image.fromObject = function(object, callback) {
  15148. fabric.util.loadImage(object.src, function(img) {
  15149. fabric.Image.prototype._initFilters.call(object, object, function(filters) {
  15150. object.filters = filters || [ ];
  15151. var instance = new fabric.Image(img, object);
  15152. callback && callback(instance);
  15153. });
  15154. }, null, object.crossOrigin);
  15155. };
  15156. /**
  15157. * Creates an instance of fabric.Image from an URL string
  15158. * @static
  15159. * @param {String} url URL to create an image from
  15160. * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument)
  15161. * @param {Object} [imgOptions] Options object
  15162. */
  15163. fabric.Image.fromURL = function(url, callback, imgOptions) {
  15164. fabric.util.loadImage(url, function(img) {
  15165. callback && callback(new fabric.Image(img, imgOptions));
  15166. }, null, imgOptions && imgOptions.crossOrigin);
  15167. };
  15168. /* _FROM_SVG_START_ */
  15169. /**
  15170. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Image.fromElement})
  15171. * @static
  15172. * @see {@link http://www.w3.org/TR/SVG/struct.html#ImageElement}
  15173. */
  15174. fabric.Image.ATTRIBUTE_NAMES =
  15175. fabric.SHARED_ATTRIBUTES.concat('x y width height preserveAspectRatio xlink:href'.split(' '));
  15176. /**
  15177. * Returns {@link fabric.Image} instance from an SVG element
  15178. * @static
  15179. * @param {SVGElement} element Element to parse
  15180. * @param {Function} callback Callback to execute when fabric.Image object is created
  15181. * @param {Object} [options] Options object
  15182. * @return {fabric.Image} Instance of fabric.Image
  15183. */
  15184. fabric.Image.fromElement = function(element, callback, options) {
  15185. var parsedAttributes = fabric.parseAttributes(element, fabric.Image.ATTRIBUTE_NAMES),
  15186. align = 'xMidYMid', meetOrSlice = 'meet', alignX, alignY, aspectRatioAttrs;
  15187. if (parsedAttributes.preserveAspectRatio) {
  15188. aspectRatioAttrs = parsedAttributes.preserveAspectRatio.split(' ');
  15189. }
  15190. if (aspectRatioAttrs && aspectRatioAttrs.length) {
  15191. meetOrSlice = aspectRatioAttrs.pop();
  15192. if (meetOrSlice !== 'meet' && meetOrSlice !== 'slice') {
  15193. align = meetOrSlice;
  15194. meetOrSlice = 'meet';
  15195. }
  15196. else if (aspectRatioAttrs.length) {
  15197. align = aspectRatioAttrs.pop();
  15198. }
  15199. }
  15200. //divide align in alignX and alignY
  15201. alignX = align !== 'none' ? align.slice(1, 4) : 'none';
  15202. alignY = align !== 'none' ? align.slice(5, 8) : 'none';
  15203. parsedAttributes.alignX = alignX;
  15204. parsedAttributes.alignY = alignY;
  15205. parsedAttributes.meetOrSlice = meetOrSlice;
  15206. fabric.Image.fromURL(parsedAttributes['xlink:href'], callback,
  15207. extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes));
  15208. };
  15209. /* _FROM_SVG_END_ */
  15210. /**
  15211. * Indicates that instances of this type are async
  15212. * @static
  15213. * @type Boolean
  15214. * @default
  15215. */
  15216. fabric.Image.async = true;
  15217. /**
  15218. * Indicates compression level used when generating PNG under Node (in applyFilters). Any of 0-9
  15219. * @static
  15220. * @type Number
  15221. * @default
  15222. */
  15223. fabric.Image.pngCompression = 1;
  15224. })(typeof exports !== 'undefined' ? exports : this);
  15225. fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {
  15226. /**
  15227. * @private
  15228. * @return {Number} angle value
  15229. */
  15230. _getAngleValueForStraighten: function() {
  15231. var angle = this.getAngle() % 360;
  15232. if (angle > 0) {
  15233. return Math.round((angle - 1) / 90) * 90;
  15234. }
  15235. return Math.round(angle / 90) * 90;
  15236. },
  15237. /**
  15238. * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer)
  15239. * @return {fabric.Object} thisArg
  15240. * @chainable
  15241. */
  15242. straighten: function() {
  15243. this.setAngle(this._getAngleValueForStraighten());
  15244. return this;
  15245. },
  15246. /**
  15247. * Same as {@link fabric.Object.prototype.straighten} but with animation
  15248. * @param {Object} callbacks Object with callback functions
  15249. * @param {Function} [callbacks.onComplete] Invoked on completion
  15250. * @param {Function} [callbacks.onChange] Invoked on every step of animation
  15251. * @return {fabric.Object} thisArg
  15252. * @chainable
  15253. */
  15254. fxStraighten: function(callbacks) {
  15255. callbacks = callbacks || { };
  15256. var empty = function() { },
  15257. onComplete = callbacks.onComplete || empty,
  15258. onChange = callbacks.onChange || empty,
  15259. _this = this;
  15260. fabric.util.animate({
  15261. startValue: this.get('angle'),
  15262. endValue: this._getAngleValueForStraighten(),
  15263. duration: this.FX_DURATION,
  15264. onChange: function(value) {
  15265. _this.setAngle(value);
  15266. onChange();
  15267. },
  15268. onComplete: function() {
  15269. _this.setCoords();
  15270. onComplete();
  15271. },
  15272. onStart: function() {
  15273. _this.set('active', false);
  15274. }
  15275. });
  15276. return this;
  15277. }
  15278. });
  15279. fabric.util.object.extend(fabric.StaticCanvas.prototype, /** @lends fabric.StaticCanvas.prototype */ {
  15280. /**
  15281. * Straightens object, then rerenders canvas
  15282. * @param {fabric.Object} object Object to straighten
  15283. * @return {fabric.Canvas} thisArg
  15284. * @chainable
  15285. */
  15286. straightenObject: function (object) {
  15287. object.straighten();
  15288. this.renderAll();
  15289. return this;
  15290. },
  15291. /**
  15292. * Same as {@link fabric.Canvas.prototype.straightenObject}, but animated
  15293. * @param {fabric.Object} object Object to straighten
  15294. * @return {fabric.Canvas} thisArg
  15295. * @chainable
  15296. */
  15297. fxStraightenObject: function (object) {
  15298. object.fxStraighten({
  15299. onChange: this.renderAll.bind(this)
  15300. });
  15301. return this;
  15302. }
  15303. });
  15304. /**
  15305. * @namespace fabric.Image.filters
  15306. * @memberOf fabric.Image
  15307. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#image_filters}
  15308. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15309. */
  15310. fabric.Image.filters = fabric.Image.filters || { };
  15311. /**
  15312. * Root filter class from which all filter classes inherit from
  15313. * @class fabric.Image.filters.BaseFilter
  15314. * @memberOf fabric.Image.filters
  15315. */
  15316. fabric.Image.filters.BaseFilter = fabric.util.createClass(/** @lends fabric.Image.filters.BaseFilter.prototype */ {
  15317. /**
  15318. * Filter type
  15319. * @param {String} type
  15320. * @default
  15321. */
  15322. type: 'BaseFilter',
  15323. /**
  15324. * Constructor
  15325. * @param {Object} [options] Options object
  15326. */
  15327. initialize: function(options) {
  15328. if (options) {
  15329. this.setOptions(options);
  15330. }
  15331. },
  15332. /**
  15333. * Sets filter's properties from options
  15334. * @param {Object} [options] Options object
  15335. */
  15336. setOptions: function(options) {
  15337. for (var prop in options) {
  15338. this[prop] = options[prop];
  15339. }
  15340. },
  15341. /**
  15342. * Returns object representation of an instance
  15343. * @return {Object} Object representation of an instance
  15344. */
  15345. toObject: function() {
  15346. return { type: this.type };
  15347. },
  15348. /**
  15349. * Returns a JSON representation of an instance
  15350. * @return {Object} JSON
  15351. */
  15352. toJSON: function() {
  15353. // delegate, not alias
  15354. return this.toObject();
  15355. }
  15356. });
  15357. (function(global) {
  15358. 'use strict';
  15359. var fabric = global.fabric || (global.fabric = { }),
  15360. extend = fabric.util.object.extend;
  15361. /**
  15362. * Brightness filter class
  15363. * @class fabric.Image.filters.Brightness
  15364. * @memberOf fabric.Image.filters
  15365. * @extends fabric.Image.filters.BaseFilter
  15366. * @see {@link fabric.Image.filters.Brightness#initialize} for constructor definition
  15367. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15368. * @example
  15369. * var filter = new fabric.Image.filters.Brightness({
  15370. * brightness: 200
  15371. * });
  15372. * object.filters.push(filter);
  15373. * object.applyFilters(canvas.renderAll.bind(canvas));
  15374. */
  15375. fabric.Image.filters.Brightness = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ {
  15376. /**
  15377. * Filter type
  15378. * @param {String} type
  15379. * @default
  15380. */
  15381. type: 'Brightness',
  15382. /**
  15383. * Constructor
  15384. * @memberOf fabric.Image.filters.Brightness.prototype
  15385. * @param {Object} [options] Options object
  15386. * @param {Number} [options.brightness=0] Value to brighten the image up (0..255)
  15387. */
  15388. initialize: function(options) {
  15389. options = options || { };
  15390. this.brightness = options.brightness || 0;
  15391. },
  15392. /**
  15393. * Applies filter to canvas element
  15394. * @param {Object} canvasEl Canvas element to apply filter to
  15395. */
  15396. applyTo: function(canvasEl) {
  15397. var context = canvasEl.getContext('2d'),
  15398. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15399. data = imageData.data,
  15400. brightness = this.brightness;
  15401. for (var i = 0, len = data.length; i < len; i += 4) {
  15402. data[i] += brightness;
  15403. data[i + 1] += brightness;
  15404. data[i + 2] += brightness;
  15405. }
  15406. context.putImageData(imageData, 0, 0);
  15407. },
  15408. /**
  15409. * Returns object representation of an instance
  15410. * @return {Object} Object representation of an instance
  15411. */
  15412. toObject: function() {
  15413. return extend(this.callSuper('toObject'), {
  15414. brightness: this.brightness
  15415. });
  15416. }
  15417. });
  15418. /**
  15419. * Returns filter instance from an object representation
  15420. * @static
  15421. * @param {Object} object Object to create an instance from
  15422. * @return {fabric.Image.filters.Brightness} Instance of fabric.Image.filters.Brightness
  15423. */
  15424. fabric.Image.filters.Brightness.fromObject = function(object) {
  15425. return new fabric.Image.filters.Brightness(object);
  15426. };
  15427. })(typeof exports !== 'undefined' ? exports : this);
  15428. (function(global) {
  15429. 'use strict';
  15430. var fabric = global.fabric || (global.fabric = { }),
  15431. extend = fabric.util.object.extend;
  15432. /**
  15433. * Adapted from <a href="http://www.html5rocks.com/en/tutorials/canvas/imagefilters/">html5rocks article</a>
  15434. * @class fabric.Image.filters.Convolute
  15435. * @memberOf fabric.Image.filters
  15436. * @extends fabric.Image.filters.BaseFilter
  15437. * @see {@link fabric.Image.filters.Convolute#initialize} for constructor definition
  15438. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15439. * @example <caption>Sharpen filter</caption>
  15440. * var filter = new fabric.Image.filters.Convolute({
  15441. * matrix: [ 0, -1, 0,
  15442. * -1, 5, -1,
  15443. * 0, -1, 0 ]
  15444. * });
  15445. * object.filters.push(filter);
  15446. * object.applyFilters(canvas.renderAll.bind(canvas));
  15447. * @example <caption>Blur filter</caption>
  15448. * var filter = new fabric.Image.filters.Convolute({
  15449. * matrix: [ 1/9, 1/9, 1/9,
  15450. * 1/9, 1/9, 1/9,
  15451. * 1/9, 1/9, 1/9 ]
  15452. * });
  15453. * object.filters.push(filter);
  15454. * object.applyFilters(canvas.renderAll.bind(canvas));
  15455. * @example <caption>Emboss filter</caption>
  15456. * var filter = new fabric.Image.filters.Convolute({
  15457. * matrix: [ 1, 1, 1,
  15458. * 1, 0.7, -1,
  15459. * -1, -1, -1 ]
  15460. * });
  15461. * object.filters.push(filter);
  15462. * object.applyFilters(canvas.renderAll.bind(canvas));
  15463. * @example <caption>Emboss filter with opaqueness</caption>
  15464. * var filter = new fabric.Image.filters.Convolute({
  15465. * opaque: true,
  15466. * matrix: [ 1, 1, 1,
  15467. * 1, 0.7, -1,
  15468. * -1, -1, -1 ]
  15469. * });
  15470. * object.filters.push(filter);
  15471. * object.applyFilters(canvas.renderAll.bind(canvas));
  15472. */
  15473. fabric.Image.filters.Convolute = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Convolute.prototype */ {
  15474. /**
  15475. * Filter type
  15476. * @param {String} type
  15477. * @default
  15478. */
  15479. type: 'Convolute',
  15480. /**
  15481. * Constructor
  15482. * @memberOf fabric.Image.filters.Convolute.prototype
  15483. * @param {Object} [options] Options object
  15484. * @param {Boolean} [options.opaque=false] Opaque value (true/false)
  15485. * @param {Array} [options.matrix] Filter matrix
  15486. */
  15487. initialize: function(options) {
  15488. options = options || { };
  15489. this.opaque = options.opaque;
  15490. this.matrix = options.matrix || [
  15491. 0, 0, 0,
  15492. 0, 1, 0,
  15493. 0, 0, 0
  15494. ];
  15495. var canvasEl = fabric.util.createCanvasElement();
  15496. this.tmpCtx = canvasEl.getContext('2d');
  15497. },
  15498. /**
  15499. * @private
  15500. */
  15501. _createImageData: function(w, h) {
  15502. return this.tmpCtx.createImageData(w, h);
  15503. },
  15504. /**
  15505. * Applies filter to canvas element
  15506. * @param {Object} canvasEl Canvas element to apply filter to
  15507. */
  15508. applyTo: function(canvasEl) {
  15509. var weights = this.matrix,
  15510. context = canvasEl.getContext('2d'),
  15511. pixels = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15512. side = Math.round(Math.sqrt(weights.length)),
  15513. halfSide = Math.floor(side/2),
  15514. src = pixels.data,
  15515. sw = pixels.width,
  15516. sh = pixels.height,
  15517. // pad output by the convolution matrix
  15518. w = sw,
  15519. h = sh,
  15520. output = this._createImageData(w, h),
  15521. dst = output.data,
  15522. // go through the destination image pixels
  15523. alphaFac = this.opaque ? 1 : 0;
  15524. for (var y = 0; y < h; y++) {
  15525. for (var x = 0; x < w; x++) {
  15526. var sy = y,
  15527. sx = x,
  15528. dstOff = (y * w + x) * 4,
  15529. // calculate the weighed sum of the source image pixels that
  15530. // fall under the convolution matrix
  15531. r = 0, g = 0, b = 0, a = 0;
  15532. for (var cy = 0; cy < side; cy++) {
  15533. for (var cx = 0; cx < side; cx++) {
  15534. var scy = sy + cy - halfSide,
  15535. scx = sx + cx - halfSide;
  15536. /* jshint maxdepth:5 */
  15537. if (scy < 0 || scy > sh || scx < 0 || scx > sw) {
  15538. continue;
  15539. }
  15540. var srcOff = (scy * sw + scx) * 4,
  15541. wt = weights[cy * side + cx];
  15542. r += src[srcOff] * wt;
  15543. g += src[srcOff + 1] * wt;
  15544. b += src[srcOff + 2] * wt;
  15545. a += src[srcOff + 3] * wt;
  15546. }
  15547. }
  15548. dst[dstOff] = r;
  15549. dst[dstOff + 1] = g;
  15550. dst[dstOff + 2] = b;
  15551. dst[dstOff + 3] = a + alphaFac * (255 - a);
  15552. }
  15553. }
  15554. context.putImageData(output, 0, 0);
  15555. },
  15556. /**
  15557. * Returns object representation of an instance
  15558. * @return {Object} Object representation of an instance
  15559. */
  15560. toObject: function() {
  15561. return extend(this.callSuper('toObject'), {
  15562. opaque: this.opaque,
  15563. matrix: this.matrix
  15564. });
  15565. }
  15566. });
  15567. /**
  15568. * Returns filter instance from an object representation
  15569. * @static
  15570. * @param {Object} object Object to create an instance from
  15571. * @return {fabric.Image.filters.Convolute} Instance of fabric.Image.filters.Convolute
  15572. */
  15573. fabric.Image.filters.Convolute.fromObject = function(object) {
  15574. return new fabric.Image.filters.Convolute(object);
  15575. };
  15576. })(typeof exports !== 'undefined' ? exports : this);
  15577. (function(global) {
  15578. 'use strict';
  15579. var fabric = global.fabric || (global.fabric = { }),
  15580. extend = fabric.util.object.extend;
  15581. /**
  15582. * GradientTransparency filter class
  15583. * @class fabric.Image.filters.GradientTransparency
  15584. * @memberOf fabric.Image.filters
  15585. * @extends fabric.Image.filters.BaseFilter
  15586. * @see {@link fabric.Image.filters.GradientTransparency#initialize} for constructor definition
  15587. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15588. * @example
  15589. * var filter = new fabric.Image.filters.GradientTransparency({
  15590. * threshold: 200
  15591. * });
  15592. * object.filters.push(filter);
  15593. * object.applyFilters(canvas.renderAll.bind(canvas));
  15594. */
  15595. fabric.Image.filters.GradientTransparency = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.GradientTransparency.prototype */ {
  15596. /**
  15597. * Filter type
  15598. * @param {String} type
  15599. * @default
  15600. */
  15601. type: 'GradientTransparency',
  15602. /**
  15603. * Constructor
  15604. * @memberOf fabric.Image.filters.GradientTransparency.prototype
  15605. * @param {Object} [options] Options object
  15606. * @param {Number} [options.threshold=100] Threshold value
  15607. */
  15608. initialize: function(options) {
  15609. options = options || { };
  15610. this.threshold = options.threshold || 100;
  15611. },
  15612. /**
  15613. * Applies filter to canvas element
  15614. * @param {Object} canvasEl Canvas element to apply filter to
  15615. */
  15616. applyTo: function(canvasEl) {
  15617. var context = canvasEl.getContext('2d'),
  15618. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15619. data = imageData.data,
  15620. threshold = this.threshold,
  15621. total = data.length;
  15622. for (var i = 0, len = data.length; i < len; i += 4) {
  15623. data[i + 3] = threshold + 255 * (total - i) / total;
  15624. }
  15625. context.putImageData(imageData, 0, 0);
  15626. },
  15627. /**
  15628. * Returns object representation of an instance
  15629. * @return {Object} Object representation of an instance
  15630. */
  15631. toObject: function() {
  15632. return extend(this.callSuper('toObject'), {
  15633. threshold: this.threshold
  15634. });
  15635. }
  15636. });
  15637. /**
  15638. * Returns filter instance from an object representation
  15639. * @static
  15640. * @param {Object} object Object to create an instance from
  15641. * @return {fabric.Image.filters.GradientTransparency} Instance of fabric.Image.filters.GradientTransparency
  15642. */
  15643. fabric.Image.filters.GradientTransparency.fromObject = function(object) {
  15644. return new fabric.Image.filters.GradientTransparency(object);
  15645. };
  15646. })(typeof exports !== 'undefined' ? exports : this);
  15647. (function(global) {
  15648. 'use strict';
  15649. var fabric = global.fabric || (global.fabric = { });
  15650. /**
  15651. * Grayscale image filter class
  15652. * @class fabric.Image.filters.Grayscale
  15653. * @memberOf fabric.Image.filters
  15654. * @extends fabric.Image.filters.BaseFilter
  15655. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15656. * @example
  15657. * var filter = new fabric.Image.filters.Grayscale();
  15658. * object.filters.push(filter);
  15659. * object.applyFilters(canvas.renderAll.bind(canvas));
  15660. */
  15661. fabric.Image.filters.Grayscale = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Grayscale.prototype */ {
  15662. /**
  15663. * Filter type
  15664. * @param {String} type
  15665. * @default
  15666. */
  15667. type: 'Grayscale',
  15668. /**
  15669. * Applies filter to canvas element
  15670. * @memberOf fabric.Image.filters.Grayscale.prototype
  15671. * @param {Object} canvasEl Canvas element to apply filter to
  15672. */
  15673. applyTo: function(canvasEl) {
  15674. var context = canvasEl.getContext('2d'),
  15675. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15676. data = imageData.data,
  15677. len = imageData.width * imageData.height * 4,
  15678. index = 0,
  15679. average;
  15680. while (index < len) {
  15681. average = (data[index] + data[index + 1] + data[index + 2]) / 3;
  15682. data[index] = average;
  15683. data[index + 1] = average;
  15684. data[index + 2] = average;
  15685. index += 4;
  15686. }
  15687. context.putImageData(imageData, 0, 0);
  15688. }
  15689. });
  15690. /**
  15691. * Returns filter instance from an object representation
  15692. * @static
  15693. * @return {fabric.Image.filters.Grayscale} Instance of fabric.Image.filters.Grayscale
  15694. */
  15695. fabric.Image.filters.Grayscale.fromObject = function() {
  15696. return new fabric.Image.filters.Grayscale();
  15697. };
  15698. })(typeof exports !== 'undefined' ? exports : this);
  15699. (function(global) {
  15700. 'use strict';
  15701. var fabric = global.fabric || (global.fabric = { });
  15702. /**
  15703. * Invert filter class
  15704. * @class fabric.Image.filters.Invert
  15705. * @memberOf fabric.Image.filters
  15706. * @extends fabric.Image.filters.BaseFilter
  15707. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15708. * @example
  15709. * var filter = new fabric.Image.filters.Invert();
  15710. * object.filters.push(filter);
  15711. * object.applyFilters(canvas.renderAll.bind(canvas));
  15712. */
  15713. fabric.Image.filters.Invert = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Invert.prototype */ {
  15714. /**
  15715. * Filter type
  15716. * @param {String} type
  15717. * @default
  15718. */
  15719. type: 'Invert',
  15720. /**
  15721. * Applies filter to canvas element
  15722. * @memberOf fabric.Image.filters.Invert.prototype
  15723. * @param {Object} canvasEl Canvas element to apply filter to
  15724. */
  15725. applyTo: function(canvasEl) {
  15726. var context = canvasEl.getContext('2d'),
  15727. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15728. data = imageData.data,
  15729. iLen = data.length, i;
  15730. for (i = 0; i < iLen; i+=4) {
  15731. data[i] = 255 - data[i];
  15732. data[i + 1] = 255 - data[i + 1];
  15733. data[i + 2] = 255 - data[i + 2];
  15734. }
  15735. context.putImageData(imageData, 0, 0);
  15736. }
  15737. });
  15738. /**
  15739. * Returns filter instance from an object representation
  15740. * @static
  15741. * @return {fabric.Image.filters.Invert} Instance of fabric.Image.filters.Invert
  15742. */
  15743. fabric.Image.filters.Invert.fromObject = function() {
  15744. return new fabric.Image.filters.Invert();
  15745. };
  15746. })(typeof exports !== 'undefined' ? exports : this);
  15747. (function(global) {
  15748. 'use strict';
  15749. var fabric = global.fabric || (global.fabric = { }),
  15750. extend = fabric.util.object.extend;
  15751. /**
  15752. * Mask filter class
  15753. * See http://resources.aleph-1.com/mask/
  15754. * @class fabric.Image.filters.Mask
  15755. * @memberOf fabric.Image.filters
  15756. * @extends fabric.Image.filters.BaseFilter
  15757. * @see {@link fabric.Image.filters.Mask#initialize} for constructor definition
  15758. */
  15759. fabric.Image.filters.Mask = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Mask.prototype */ {
  15760. /**
  15761. * Filter type
  15762. * @param {String} type
  15763. * @default
  15764. */
  15765. type: 'Mask',
  15766. /**
  15767. * Constructor
  15768. * @memberOf fabric.Image.filters.Mask.prototype
  15769. * @param {Object} [options] Options object
  15770. * @param {fabric.Image} [options.mask] Mask image object
  15771. * @param {Number} [options.channel=0] Rgb channel (0, 1, 2 or 3)
  15772. */
  15773. initialize: function(options) {
  15774. options = options || { };
  15775. this.mask = options.mask;
  15776. this.channel = [ 0, 1, 2, 3 ].indexOf(options.channel) > -1 ? options.channel : 0;
  15777. },
  15778. /**
  15779. * Applies filter to canvas element
  15780. * @param {Object} canvasEl Canvas element to apply filter to
  15781. */
  15782. applyTo: function(canvasEl) {
  15783. if (!this.mask) {
  15784. return;
  15785. }
  15786. var context = canvasEl.getContext('2d'),
  15787. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15788. data = imageData.data,
  15789. maskEl = this.mask.getElement(),
  15790. maskCanvasEl = fabric.util.createCanvasElement(),
  15791. channel = this.channel,
  15792. i,
  15793. iLen = imageData.width * imageData.height * 4;
  15794. maskCanvasEl.width = maskEl.width;
  15795. maskCanvasEl.height = maskEl.height;
  15796. maskCanvasEl.getContext('2d').drawImage(maskEl, 0, 0, maskEl.width, maskEl.height);
  15797. var maskImageData = maskCanvasEl.getContext('2d').getImageData(0, 0, maskEl.width, maskEl.height),
  15798. maskData = maskImageData.data;
  15799. for (i = 0; i < iLen; i += 4) {
  15800. data[i + 3] = maskData[i + channel];
  15801. }
  15802. context.putImageData(imageData, 0, 0);
  15803. },
  15804. /**
  15805. * Returns object representation of an instance
  15806. * @return {Object} Object representation of an instance
  15807. */
  15808. toObject: function() {
  15809. return extend(this.callSuper('toObject'), {
  15810. mask: this.mask.toObject(),
  15811. channel: this.channel
  15812. });
  15813. }
  15814. });
  15815. /**
  15816. * Returns filter instance from an object representation
  15817. * @static
  15818. * @param {Object} object Object to create an instance from
  15819. * @param {Function} [callback] Callback to invoke when a mask filter instance is created
  15820. */
  15821. fabric.Image.filters.Mask.fromObject = function(object, callback) {
  15822. fabric.util.loadImage(object.mask.src, function(img) {
  15823. object.mask = new fabric.Image(img, object.mask);
  15824. callback && callback(new fabric.Image.filters.Mask(object));
  15825. });
  15826. };
  15827. /**
  15828. * Indicates that instances of this type are async
  15829. * @static
  15830. * @type Boolean
  15831. * @default
  15832. */
  15833. fabric.Image.filters.Mask.async = true;
  15834. })(typeof exports !== 'undefined' ? exports : this);
  15835. (function(global) {
  15836. 'use strict';
  15837. var fabric = global.fabric || (global.fabric = { }),
  15838. extend = fabric.util.object.extend;
  15839. /**
  15840. * Noise filter class
  15841. * @class fabric.Image.filters.Noise
  15842. * @memberOf fabric.Image.filters
  15843. * @extends fabric.Image.filters.BaseFilter
  15844. * @see {@link fabric.Image.filters.Noise#initialize} for constructor definition
  15845. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15846. * @example
  15847. * var filter = new fabric.Image.filters.Noise({
  15848. * noise: 700
  15849. * });
  15850. * object.filters.push(filter);
  15851. * object.applyFilters(canvas.renderAll.bind(canvas));
  15852. */
  15853. fabric.Image.filters.Noise = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Noise.prototype */ {
  15854. /**
  15855. * Filter type
  15856. * @param {String} type
  15857. * @default
  15858. */
  15859. type: 'Noise',
  15860. /**
  15861. * Constructor
  15862. * @memberOf fabric.Image.filters.Noise.prototype
  15863. * @param {Object} [options] Options object
  15864. * @param {Number} [options.noise=0] Noise value
  15865. */
  15866. initialize: function(options) {
  15867. options = options || { };
  15868. this.noise = options.noise || 0;
  15869. },
  15870. /**
  15871. * Applies filter to canvas element
  15872. * @param {Object} canvasEl Canvas element to apply filter to
  15873. */
  15874. applyTo: function(canvasEl) {
  15875. var context = canvasEl.getContext('2d'),
  15876. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15877. data = imageData.data,
  15878. noise = this.noise, rand;
  15879. for (var i = 0, len = data.length; i < len; i += 4) {
  15880. rand = (0.5 - Math.random()) * noise;
  15881. data[i] += rand;
  15882. data[i + 1] += rand;
  15883. data[i + 2] += rand;
  15884. }
  15885. context.putImageData(imageData, 0, 0);
  15886. },
  15887. /**
  15888. * Returns object representation of an instance
  15889. * @return {Object} Object representation of an instance
  15890. */
  15891. toObject: function() {
  15892. return extend(this.callSuper('toObject'), {
  15893. noise: this.noise
  15894. });
  15895. }
  15896. });
  15897. /**
  15898. * Returns filter instance from an object representation
  15899. * @static
  15900. * @param {Object} object Object to create an instance from
  15901. * @return {fabric.Image.filters.Noise} Instance of fabric.Image.filters.Noise
  15902. */
  15903. fabric.Image.filters.Noise.fromObject = function(object) {
  15904. return new fabric.Image.filters.Noise(object);
  15905. };
  15906. })(typeof exports !== 'undefined' ? exports : this);
  15907. (function(global) {
  15908. 'use strict';
  15909. var fabric = global.fabric || (global.fabric = { }),
  15910. extend = fabric.util.object.extend;
  15911. /**
  15912. * Pixelate filter class
  15913. * @class fabric.Image.filters.Pixelate
  15914. * @memberOf fabric.Image.filters
  15915. * @extends fabric.Image.filters.BaseFilter
  15916. * @see {@link fabric.Image.filters.Pixelate#initialize} for constructor definition
  15917. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  15918. * @example
  15919. * var filter = new fabric.Image.filters.Pixelate({
  15920. * blocksize: 8
  15921. * });
  15922. * object.filters.push(filter);
  15923. * object.applyFilters(canvas.renderAll.bind(canvas));
  15924. */
  15925. fabric.Image.filters.Pixelate = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Pixelate.prototype */ {
  15926. /**
  15927. * Filter type
  15928. * @param {String} type
  15929. * @default
  15930. */
  15931. type: 'Pixelate',
  15932. /**
  15933. * Constructor
  15934. * @memberOf fabric.Image.filters.Pixelate.prototype
  15935. * @param {Object} [options] Options object
  15936. * @param {Number} [options.blocksize=4] Blocksize for pixelate
  15937. */
  15938. initialize: function(options) {
  15939. options = options || { };
  15940. this.blocksize = options.blocksize || 4;
  15941. },
  15942. /**
  15943. * Applies filter to canvas element
  15944. * @param {Object} canvasEl Canvas element to apply filter to
  15945. */
  15946. applyTo: function(canvasEl) {
  15947. var context = canvasEl.getContext('2d'),
  15948. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  15949. data = imageData.data,
  15950. iLen = imageData.height,
  15951. jLen = imageData.width,
  15952. index, i, j, r, g, b, a;
  15953. for (i = 0; i < iLen; i += this.blocksize) {
  15954. for (j = 0; j < jLen; j += this.blocksize) {
  15955. index = (i * 4) * jLen + (j * 4);
  15956. r = data[index];
  15957. g = data[index + 1];
  15958. b = data[index + 2];
  15959. a = data[index + 3];
  15960. /*
  15961. blocksize: 4
  15962. [1,x,x,x,1]
  15963. [x,x,x,x,1]
  15964. [x,x,x,x,1]
  15965. [x,x,x,x,1]
  15966. [1,1,1,1,1]
  15967. */
  15968. for (var _i = i, _ilen = i + this.blocksize; _i < _ilen; _i++) {
  15969. for (var _j = j, _jlen = j + this.blocksize; _j < _jlen; _j++) {
  15970. index = (_i * 4) * jLen + (_j * 4);
  15971. data[index] = r;
  15972. data[index + 1] = g;
  15973. data[index + 2] = b;
  15974. data[index + 3] = a;
  15975. }
  15976. }
  15977. }
  15978. }
  15979. context.putImageData(imageData, 0, 0);
  15980. },
  15981. /**
  15982. * Returns object representation of an instance
  15983. * @return {Object} Object representation of an instance
  15984. */
  15985. toObject: function() {
  15986. return extend(this.callSuper('toObject'), {
  15987. blocksize: this.blocksize
  15988. });
  15989. }
  15990. });
  15991. /**
  15992. * Returns filter instance from an object representation
  15993. * @static
  15994. * @param {Object} object Object to create an instance from
  15995. * @return {fabric.Image.filters.Pixelate} Instance of fabric.Image.filters.Pixelate
  15996. */
  15997. fabric.Image.filters.Pixelate.fromObject = function(object) {
  15998. return new fabric.Image.filters.Pixelate(object);
  15999. };
  16000. })(typeof exports !== 'undefined' ? exports : this);
  16001. (function(global) {
  16002. 'use strict';
  16003. var fabric = global.fabric || (global.fabric = { }),
  16004. extend = fabric.util.object.extend;
  16005. /**
  16006. * Remove white filter class
  16007. * @class fabric.Image.filters.RemoveWhite
  16008. * @memberOf fabric.Image.filters
  16009. * @extends fabric.Image.filters.BaseFilter
  16010. * @see {@link fabric.Image.filters.RemoveWhite#initialize} for constructor definition
  16011. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  16012. * @example
  16013. * var filter = new fabric.Image.filters.RemoveWhite({
  16014. * threshold: 40,
  16015. * distance: 140
  16016. * });
  16017. * object.filters.push(filter);
  16018. * object.applyFilters(canvas.renderAll.bind(canvas));
  16019. */
  16020. fabric.Image.filters.RemoveWhite = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.RemoveWhite.prototype */ {
  16021. /**
  16022. * Filter type
  16023. * @param {String} type
  16024. * @default
  16025. */
  16026. type: 'RemoveWhite',
  16027. /**
  16028. * Constructor
  16029. * @memberOf fabric.Image.filters.RemoveWhite.prototype
  16030. * @param {Object} [options] Options object
  16031. * @param {Number} [options.threshold=30] Threshold value
  16032. * @param {Number} [options.distance=20] Distance value
  16033. */
  16034. initialize: function(options) {
  16035. options = options || { };
  16036. this.threshold = options.threshold || 30;
  16037. this.distance = options.distance || 20;
  16038. },
  16039. /**
  16040. * Applies filter to canvas element
  16041. * @param {Object} canvasEl Canvas element to apply filter to
  16042. */
  16043. applyTo: function(canvasEl) {
  16044. var context = canvasEl.getContext('2d'),
  16045. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  16046. data = imageData.data,
  16047. threshold = this.threshold,
  16048. distance = this.distance,
  16049. limit = 255 - threshold,
  16050. abs = Math.abs,
  16051. r, g, b;
  16052. for (var i = 0, len = data.length; i < len; i += 4) {
  16053. r = data[i];
  16054. g = data[i + 1];
  16055. b = data[i + 2];
  16056. if (r > limit &&
  16057. g > limit &&
  16058. b > limit &&
  16059. abs(r - g) < distance &&
  16060. abs(r - b) < distance &&
  16061. abs(g - b) < distance
  16062. ) {
  16063. data[i + 3] = 1;
  16064. }
  16065. }
  16066. context.putImageData(imageData, 0, 0);
  16067. },
  16068. /**
  16069. * Returns object representation of an instance
  16070. * @return {Object} Object representation of an instance
  16071. */
  16072. toObject: function() {
  16073. return extend(this.callSuper('toObject'), {
  16074. threshold: this.threshold,
  16075. distance: this.distance
  16076. });
  16077. }
  16078. });
  16079. /**
  16080. * Returns filter instance from an object representation
  16081. * @static
  16082. * @param {Object} object Object to create an instance from
  16083. * @return {fabric.Image.filters.RemoveWhite} Instance of fabric.Image.filters.RemoveWhite
  16084. */
  16085. fabric.Image.filters.RemoveWhite.fromObject = function(object) {
  16086. return new fabric.Image.filters.RemoveWhite(object);
  16087. };
  16088. })(typeof exports !== 'undefined' ? exports : this);
  16089. (function(global) {
  16090. 'use strict';
  16091. var fabric = global.fabric || (global.fabric = { });
  16092. /**
  16093. * Sepia filter class
  16094. * @class fabric.Image.filters.Sepia
  16095. * @memberOf fabric.Image.filters
  16096. * @extends fabric.Image.filters.BaseFilter
  16097. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  16098. * @example
  16099. * var filter = new fabric.Image.filters.Sepia();
  16100. * object.filters.push(filter);
  16101. * object.applyFilters(canvas.renderAll.bind(canvas));
  16102. */
  16103. fabric.Image.filters.Sepia = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Sepia.prototype */ {
  16104. /**
  16105. * Filter type
  16106. * @param {String} type
  16107. * @default
  16108. */
  16109. type: 'Sepia',
  16110. /**
  16111. * Applies filter to canvas element
  16112. * @memberOf fabric.Image.filters.Sepia.prototype
  16113. * @param {Object} canvasEl Canvas element to apply filter to
  16114. */
  16115. applyTo: function(canvasEl) {
  16116. var context = canvasEl.getContext('2d'),
  16117. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  16118. data = imageData.data,
  16119. iLen = data.length, i, avg;
  16120. for (i = 0; i < iLen; i+=4) {
  16121. avg = 0.3 * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
  16122. data[i] = avg + 100;
  16123. data[i + 1] = avg + 50;
  16124. data[i + 2] = avg + 255;
  16125. }
  16126. context.putImageData(imageData, 0, 0);
  16127. }
  16128. });
  16129. /**
  16130. * Returns filter instance from an object representation
  16131. * @static
  16132. * @return {fabric.Image.filters.Sepia} Instance of fabric.Image.filters.Sepia
  16133. */
  16134. fabric.Image.filters.Sepia.fromObject = function() {
  16135. return new fabric.Image.filters.Sepia();
  16136. };
  16137. })(typeof exports !== 'undefined' ? exports : this);
  16138. (function(global) {
  16139. 'use strict';
  16140. var fabric = global.fabric || (global.fabric = { });
  16141. /**
  16142. * Sepia2 filter class
  16143. * @class fabric.Image.filters.Sepia2
  16144. * @memberOf fabric.Image.filters
  16145. * @extends fabric.Image.filters.BaseFilter
  16146. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  16147. * @example
  16148. * var filter = new fabric.Image.filters.Sepia2();
  16149. * object.filters.push(filter);
  16150. * object.applyFilters(canvas.renderAll.bind(canvas));
  16151. */
  16152. fabric.Image.filters.Sepia2 = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Sepia2.prototype */ {
  16153. /**
  16154. * Filter type
  16155. * @param {String} type
  16156. * @default
  16157. */
  16158. type: 'Sepia2',
  16159. /**
  16160. * Applies filter to canvas element
  16161. * @memberOf fabric.Image.filters.Sepia.prototype
  16162. * @param {Object} canvasEl Canvas element to apply filter to
  16163. */
  16164. applyTo: function(canvasEl) {
  16165. var context = canvasEl.getContext('2d'),
  16166. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  16167. data = imageData.data,
  16168. iLen = data.length, i, r, g, b;
  16169. for (i = 0; i < iLen; i+=4) {
  16170. r = data[i];
  16171. g = data[i + 1];
  16172. b = data[i + 2];
  16173. data[i] = (r * 0.393 + g * 0.769 + b * 0.189 ) / 1.351;
  16174. data[i + 1] = (r * 0.349 + g * 0.686 + b * 0.168 ) / 1.203;
  16175. data[i + 2] = (r * 0.272 + g * 0.534 + b * 0.131 ) / 2.140;
  16176. }
  16177. context.putImageData(imageData, 0, 0);
  16178. }
  16179. });
  16180. /**
  16181. * Returns filter instance from an object representation
  16182. * @static
  16183. * @return {fabric.Image.filters.Sepia2} Instance of fabric.Image.filters.Sepia2
  16184. */
  16185. fabric.Image.filters.Sepia2.fromObject = function() {
  16186. return new fabric.Image.filters.Sepia2();
  16187. };
  16188. })(typeof exports !== 'undefined' ? exports : this);
  16189. (function(global) {
  16190. 'use strict';
  16191. var fabric = global.fabric || (global.fabric = { }),
  16192. extend = fabric.util.object.extend;
  16193. /**
  16194. * Tint filter class
  16195. * Adapted from <a href="https://github.com/mezzoblue/PaintbrushJS">https://github.com/mezzoblue/PaintbrushJS</a>
  16196. * @class fabric.Image.filters.Tint
  16197. * @memberOf fabric.Image.filters
  16198. * @extends fabric.Image.filters.BaseFilter
  16199. * @see {@link fabric.Image.filters.Tint#initialize} for constructor definition
  16200. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  16201. * @example <caption>Tint filter with hex color and opacity</caption>
  16202. * var filter = new fabric.Image.filters.Tint({
  16203. * color: '#3513B0',
  16204. * opacity: 0.5
  16205. * });
  16206. * object.filters.push(filter);
  16207. * object.applyFilters(canvas.renderAll.bind(canvas));
  16208. * @example <caption>Tint filter with rgba color</caption>
  16209. * var filter = new fabric.Image.filters.Tint({
  16210. * color: 'rgba(53, 21, 176, 0.5)'
  16211. * });
  16212. * object.filters.push(filter);
  16213. * object.applyFilters(canvas.renderAll.bind(canvas));
  16214. */
  16215. fabric.Image.filters.Tint = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Tint.prototype */ {
  16216. /**
  16217. * Filter type
  16218. * @param {String} type
  16219. * @default
  16220. */
  16221. type: 'Tint',
  16222. /**
  16223. * Constructor
  16224. * @memberOf fabric.Image.filters.Tint.prototype
  16225. * @param {Object} [options] Options object
  16226. * @param {String} [options.color=#000000] Color to tint the image with
  16227. * @param {Number} [options.opacity] Opacity value that controls the tint effect's transparency (0..1)
  16228. */
  16229. initialize: function(options) {
  16230. options = options || { };
  16231. this.color = options.color || '#000000';
  16232. this.opacity = typeof options.opacity !== 'undefined'
  16233. ? options.opacity
  16234. : new fabric.Color(this.color).getAlpha();
  16235. },
  16236. /**
  16237. * Applies filter to canvas element
  16238. * @param {Object} canvasEl Canvas element to apply filter to
  16239. */
  16240. applyTo: function(canvasEl) {
  16241. var context = canvasEl.getContext('2d'),
  16242. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  16243. data = imageData.data,
  16244. iLen = data.length, i,
  16245. tintR, tintG, tintB,
  16246. r, g, b, alpha1,
  16247. source;
  16248. source = new fabric.Color(this.color).getSource();
  16249. tintR = source[0] * this.opacity;
  16250. tintG = source[1] * this.opacity;
  16251. tintB = source[2] * this.opacity;
  16252. alpha1 = 1 - this.opacity;
  16253. for (i = 0; i < iLen; i+=4) {
  16254. r = data[i];
  16255. g = data[i + 1];
  16256. b = data[i + 2];
  16257. // alpha compositing
  16258. data[i] = tintR + r * alpha1;
  16259. data[i + 1] = tintG + g * alpha1;
  16260. data[i + 2] = tintB + b * alpha1;
  16261. }
  16262. context.putImageData(imageData, 0, 0);
  16263. },
  16264. /**
  16265. * Returns object representation of an instance
  16266. * @return {Object} Object representation of an instance
  16267. */
  16268. toObject: function() {
  16269. return extend(this.callSuper('toObject'), {
  16270. color: this.color,
  16271. opacity: this.opacity
  16272. });
  16273. }
  16274. });
  16275. /**
  16276. * Returns filter instance from an object representation
  16277. * @static
  16278. * @param {Object} object Object to create an instance from
  16279. * @return {fabric.Image.filters.Tint} Instance of fabric.Image.filters.Tint
  16280. */
  16281. fabric.Image.filters.Tint.fromObject = function(object) {
  16282. return new fabric.Image.filters.Tint(object);
  16283. };
  16284. })(typeof exports !== 'undefined' ? exports : this);
  16285. (function(global) {
  16286. 'use strict';
  16287. var fabric = global.fabric || (global.fabric = { }),
  16288. extend = fabric.util.object.extend;
  16289. /**
  16290. * Multiply filter class
  16291. * Adapted from <a href="http://www.laurenscorijn.com/articles/colormath-basics">http://www.laurenscorijn.com/articles/colormath-basics</a>
  16292. * @class fabric.Image.filters.Multiply
  16293. * @memberOf fabric.Image.filters
  16294. * @extends fabric.Image.filters.BaseFilter
  16295. * @example <caption>Multiply filter with hex color</caption>
  16296. * var filter = new fabric.Image.filters.Multiply({
  16297. * color: '#F0F'
  16298. * });
  16299. * object.filters.push(filter);
  16300. * object.applyFilters(canvas.renderAll.bind(canvas));
  16301. * @example <caption>Multiply filter with rgb color</caption>
  16302. * var filter = new fabric.Image.filters.Multiply({
  16303. * color: 'rgb(53, 21, 176)'
  16304. * });
  16305. * object.filters.push(filter);
  16306. * object.applyFilters(canvas.renderAll.bind(canvas));
  16307. */
  16308. fabric.Image.filters.Multiply = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Multiply.prototype */ {
  16309. /**
  16310. * Filter type
  16311. * @param {String} type
  16312. * @default
  16313. */
  16314. type: 'Multiply',
  16315. /**
  16316. * Constructor
  16317. * @memberOf fabric.Image.filters.Multiply.prototype
  16318. * @param {Object} [options] Options object
  16319. * @param {String} [options.color=#000000] Color to multiply the image pixels with
  16320. */
  16321. initialize: function(options) {
  16322. options = options || { };
  16323. this.color = options.color || '#000000';
  16324. },
  16325. /**
  16326. * Applies filter to canvas element
  16327. * @param {Object} canvasEl Canvas element to apply filter to
  16328. */
  16329. applyTo: function(canvasEl) {
  16330. var context = canvasEl.getContext('2d'),
  16331. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  16332. data = imageData.data,
  16333. iLen = data.length, i,
  16334. source;
  16335. source = new fabric.Color(this.color).getSource();
  16336. for (i = 0; i < iLen; i+=4) {
  16337. data[i] *= source[0] / 255;
  16338. data[i + 1] *= source[1] / 255;
  16339. data[i + 2] *= source[2] / 255;
  16340. }
  16341. context.putImageData(imageData, 0, 0);
  16342. },
  16343. /**
  16344. * Returns object representation of an instance
  16345. * @return {Object} Object representation of an instance
  16346. */
  16347. toObject: function() {
  16348. return extend(this.callSuper('toObject'), {
  16349. color: this.color
  16350. });
  16351. }
  16352. });
  16353. /**
  16354. * Returns filter instance from an object representation
  16355. * @static
  16356. * @param {Object} object Object to create an instance from
  16357. * @return {fabric.Image.filters.Multiply} Instance of fabric.Image.filters.Multiply
  16358. */
  16359. fabric.Image.filters.Multiply.fromObject = function(object) {
  16360. return new fabric.Image.filters.Multiply(object);
  16361. };
  16362. })(typeof exports !== 'undefined' ? exports : this);
  16363. (function(global) {
  16364. 'use strict';
  16365. var fabric = global.fabric;
  16366. /**
  16367. * Color Blend filter class
  16368. * @class fabric.Image.filter.Blend
  16369. * @memberOf fabric.Image.filters
  16370. * @extends fabric.Image.filters.BaseFilter
  16371. * @example
  16372. * var filter = new fabric.Image.filters.Blend({
  16373. * color: '#000',
  16374. * mode: 'multiply'
  16375. * });
  16376. *
  16377. * var filter = new fabric.Image.filters.Blend({
  16378. * image: fabricImageObject,
  16379. * mode: 'multiply',
  16380. * alpha: 0.5
  16381. * });
  16382. * object.filters.push(filter);
  16383. * object.applyFilters(canvas.renderAll.bind(canvas));
  16384. */
  16385. fabric.Image.filters.Blend = fabric.util.createClass({
  16386. type: 'Blend',
  16387. initialize: function(options) {
  16388. options = options || {};
  16389. this.color = options.color || '#000';
  16390. this.image = options.image || false;
  16391. this.mode = options.mode || 'multiply';
  16392. this.alpha = options.alpha || 1;
  16393. },
  16394. applyTo: function(canvasEl) {
  16395. var context = canvasEl.getContext('2d'),
  16396. imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
  16397. data = imageData.data,
  16398. tr, tg, tb,
  16399. r, g, b,
  16400. _r, _g, _b,
  16401. source,
  16402. isImage = false;
  16403. if (this.image) {
  16404. // Blend images
  16405. isImage = true;
  16406. var _el = fabric.util.createCanvasElement();
  16407. _el.width = this.image.width;
  16408. _el.height = this.image.height;
  16409. var tmpCanvas = new fabric.StaticCanvas(_el);
  16410. tmpCanvas.add(this.image);
  16411. var context2 = tmpCanvas.getContext('2d');
  16412. source = context2.getImageData(0, 0, tmpCanvas.width, tmpCanvas.height).data;
  16413. }
  16414. else {
  16415. // Blend color
  16416. source = new fabric.Color(this.color).getSource();
  16417. tr = source[0] * this.alpha;
  16418. tg = source[1] * this.alpha;
  16419. tb = source[2] * this.alpha;
  16420. }
  16421. for (var i = 0, len = data.length; i < len; i += 4) {
  16422. r = data[i];
  16423. g = data[i + 1];
  16424. b = data[i + 2];
  16425. if (isImage) {
  16426. tr = source[i] * this.alpha;
  16427. tg = source[i + 1] * this.alpha;
  16428. tb = source[i + 2] * this.alpha;
  16429. }
  16430. switch (this.mode) {
  16431. case 'multiply':
  16432. data[i] = r * tr / 255;
  16433. data[i + 1] = g * tg / 255;
  16434. data[i + 2] = b * tb / 255;
  16435. break;
  16436. case 'screen':
  16437. data[i] = 1 - (1 - r) * (1 - tr);
  16438. data[i + 1] = 1 - (1 - g) * (1 - tg);
  16439. data[i + 2] = 1 - (1 - b) * (1 - tb);
  16440. break;
  16441. case 'add':
  16442. data[i] = Math.min(255, r + tr);
  16443. data[i + 1] = Math.min(255, g + tg);
  16444. data[i + 2] = Math.min(255, b + tb);
  16445. break;
  16446. case 'diff':
  16447. case 'difference':
  16448. data[i] = Math.abs(r - tr);
  16449. data[i + 1] = Math.abs(g - tg);
  16450. data[i + 2] = Math.abs(b - tb);
  16451. break;
  16452. case 'subtract':
  16453. _r = r - tr;
  16454. _g = g - tg;
  16455. _b = b - tb;
  16456. data[i] = (_r < 0) ? 0 : _r;
  16457. data[i + 1] = (_g < 0) ? 0 : _g;
  16458. data[i + 2] = (_b < 0) ? 0 : _b;
  16459. break;
  16460. case 'darken':
  16461. data[i] = Math.min(r, tr);
  16462. data[i + 1] = Math.min(g, tg);
  16463. data[i + 2] = Math.min(b, tb);
  16464. break;
  16465. case 'lighten':
  16466. data[i] = Math.max(r, tr);
  16467. data[i + 1] = Math.max(g, tg);
  16468. data[i + 2] = Math.max(b, tb);
  16469. break;
  16470. }
  16471. }
  16472. context.putImageData(imageData, 0, 0);
  16473. },
  16474. /**
  16475. * Returns object representation of an instance
  16476. * @return {Object} Object representation of an instance
  16477. */
  16478. toObject: function() {
  16479. return {
  16480. color: this.color,
  16481. image: this.image,
  16482. mode: this.mode,
  16483. alpha: this.alpha
  16484. };
  16485. }
  16486. });
  16487. fabric.Image.filters.Blend.fromObject = function(object) {
  16488. return new fabric.Image.filters.Blend(object);
  16489. };
  16490. })(typeof exports !== 'undefined' ? exports : this);
  16491. (function(global) {
  16492. 'use strict';
  16493. var fabric = global.fabric || (global.fabric = { }), pow = Math.pow, floor = Math.floor,
  16494. sqrt = Math.sqrt, abs = Math.abs, max = Math.max, round = Math.round, sin = Math.sin,
  16495. ceil = Math.ceil;
  16496. /**
  16497. * Resize image filter class
  16498. * @class fabric.Image.filters.Resize
  16499. * @memberOf fabric.Image.filters
  16500. * @extends fabric.Image.filters.BaseFilter
  16501. * @see {@link http://fabricjs.com/image-filters/|ImageFilters demo}
  16502. * @example
  16503. * var filter = new fabric.Image.filters.Resize();
  16504. * object.filters.push(filter);
  16505. * object.applyFilters(canvas.renderAll.bind(canvas));
  16506. */
  16507. fabric.Image.filters.Resize = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Resize.prototype */ {
  16508. /**
  16509. * Filter type
  16510. * @param {String} type
  16511. * @default
  16512. */
  16513. type: 'Resize',
  16514. /**
  16515. * Resize type
  16516. * @param {String} resizeType
  16517. * @default
  16518. */
  16519. resizeType: 'hermite',
  16520. /**
  16521. * Scale factor for resizing, x axis
  16522. * @param {Number} scaleX
  16523. * @default
  16524. */
  16525. scaleX: 0,
  16526. /**
  16527. * Scale factor for resizing, y axis
  16528. * @param {Number} scaleY
  16529. * @default
  16530. */
  16531. scaleY: 0,
  16532. /**
  16533. * LanczosLobes parameter for lanczos filter
  16534. * @param {Number} lanczosLobes
  16535. * @default
  16536. */
  16537. lanczosLobes: 3,
  16538. /**
  16539. * Applies filter to canvas element
  16540. * @memberOf fabric.Image.filters.Resize.prototype
  16541. * @param {Object} canvasEl Canvas element to apply filter to
  16542. */
  16543. applyTo: function(canvasEl, scaleX, scaleY) {
  16544. this.rcpScaleX = 1 / scaleX;
  16545. this.rcpScaleY = 1 / scaleY;
  16546. var oW = canvasEl.width, oH = canvasEl.height,
  16547. dW = round(oW * scaleX), dH = round(oH * scaleY),
  16548. imageData;
  16549. if (this.resizeType === 'sliceHack') {
  16550. imageData = this.sliceByTwo(canvasEl, oW, oH, dW, dH);
  16551. }
  16552. if (this.resizeType === 'hermite') {
  16553. imageData = this.hermiteFastResize(canvasEl, oW, oH, dW, dH);
  16554. }
  16555. if (this.resizeType === 'bilinear') {
  16556. imageData = this.bilinearFiltering(canvasEl, oW, oH, dW, dH);
  16557. }
  16558. if (this.resizeType === 'lanczos') {
  16559. imageData = this.lanczosResize(canvasEl, oW, oH, dW, dH);
  16560. }
  16561. canvasEl.width = dW;
  16562. canvasEl.height = dH;
  16563. canvasEl.getContext('2d').putImageData(imageData, 0, 0);
  16564. },
  16565. sliceByTwo: function(canvasEl, width, height, newWidth, newHeight) {
  16566. var context = canvasEl.getContext('2d'), imageData,
  16567. multW = 0.5, multH = 0.5, signW = 1, signH = 1,
  16568. doneW = false, doneH = false, stepW = width, stepH = height,
  16569. tmpCanvas = fabric.util.createCanvasElement(),
  16570. tmpCtx = tmpCanvas.getContext('2d');
  16571. newWidth = floor(newWidth);
  16572. newHeight = floor(newHeight);
  16573. tmpCanvas.width = max(newWidth, width);
  16574. tmpCanvas.height = max(newHeight, height);
  16575. if (newWidth > width) {
  16576. multW = 2;
  16577. signW = -1;
  16578. }
  16579. if (newHeight > height) {
  16580. multH = 2;
  16581. signH = -1;
  16582. }
  16583. imageData = context.getImageData(0, 0, width, height);
  16584. canvasEl.width = max(newWidth, width);
  16585. canvasEl.height = max(newHeight, height);
  16586. context.putImageData(imageData, 0, 0);
  16587. while (!doneW || !doneH) {
  16588. width = stepW;
  16589. height = stepH;
  16590. if (newWidth * signW < floor(stepW * multW * signW)) {
  16591. stepW = floor(stepW * multW);
  16592. }
  16593. else {
  16594. stepW = newWidth;
  16595. doneW = true;
  16596. }
  16597. if (newHeight * signH < floor(stepH * multH * signH)) {
  16598. stepH = floor(stepH * multH);
  16599. }
  16600. else {
  16601. stepH = newHeight;
  16602. doneH = true;
  16603. }
  16604. imageData = context.getImageData(0, 0, width, height);
  16605. tmpCtx.putImageData(imageData, 0, 0);
  16606. context.clearRect(0, 0, stepW, stepH);
  16607. context.drawImage(tmpCanvas, 0, 0, width, height, 0, 0, stepW, stepH);
  16608. }
  16609. return context.getImageData(0, 0, newWidth, newHeight);
  16610. },
  16611. lanczosResize: function(canvasEl, oW, oH, dW, dH) {
  16612. function lanczosCreate(lobes) {
  16613. return function(x) {
  16614. if (x > lobes) {
  16615. return 0;
  16616. }
  16617. x *= Math.PI;
  16618. if (abs(x) < 1e-16) {
  16619. return 1;
  16620. }
  16621. var xx = x / lobes;
  16622. return sin(x) * sin(xx) / x / xx;
  16623. };
  16624. }
  16625. function process(u) {
  16626. var v, i, weight, idx, a, red, green,
  16627. blue, alpha, fX, fY;
  16628. center.x = (u + 0.5) * ratioX;
  16629. icenter.x = floor(center.x);
  16630. for (v = 0; v < dH; v++) {
  16631. center.y = (v + 0.5) * ratioY;
  16632. icenter.y = floor(center.y);
  16633. a = 0, red = 0, green = 0, blue = 0, alpha = 0;
  16634. for (i = icenter.x - range2X; i <= icenter.x + range2X; i++) {
  16635. if (i < 0 || i >= oW) {
  16636. continue;
  16637. }
  16638. fX = floor(1000 * abs(i - center.x));
  16639. if (!cacheLanc[fX]) {
  16640. cacheLanc[fX] = { };
  16641. }
  16642. for (var j = icenter.y - range2Y; j <= icenter.y + range2Y; j++) {
  16643. if (j < 0 || j >= oH) {
  16644. continue;
  16645. }
  16646. fY = floor(1000 * abs(j - center.y));
  16647. if (!cacheLanc[fX][fY]) {
  16648. cacheLanc[fX][fY] = lanczos(sqrt(pow(fX * rcpRatioX, 2) + pow(fY * rcpRatioY, 2)) / 1000);
  16649. }
  16650. weight = cacheLanc[fX][fY];
  16651. if (weight > 0) {
  16652. idx = (j * oW + i) * 4;
  16653. a += weight;
  16654. red += weight * srcData[idx];
  16655. green += weight * srcData[idx + 1];
  16656. blue += weight * srcData[idx + 2];
  16657. alpha += weight * srcData[idx + 3];
  16658. }
  16659. }
  16660. }
  16661. idx = (v * dW + u) * 4;
  16662. destData[idx] = red / a;
  16663. destData[idx + 1] = green / a;
  16664. destData[idx + 2] = blue / a;
  16665. destData[idx + 3] = alpha / a;
  16666. }
  16667. if (++u < dW) {
  16668. return process(u);
  16669. }
  16670. else {
  16671. return destImg;
  16672. }
  16673. }
  16674. var context = canvasEl.getContext('2d'),
  16675. srcImg = context.getImageData(0, 0, oW, oH),
  16676. destImg = context.getImageData(0, 0, dW, dH),
  16677. srcData = srcImg.data, destData = destImg.data,
  16678. lanczos = lanczosCreate(this.lanczosLobes),
  16679. ratioX = this.rcpScaleX, ratioY = this.rcpScaleY,
  16680. rcpRatioX = 2 / this.rcpScaleX, rcpRatioY = 2 / this.rcpScaleY,
  16681. range2X = ceil(ratioX * this.lanczosLobes / 2),
  16682. range2Y = ceil(ratioY * this.lanczosLobes / 2),
  16683. cacheLanc = { }, center = { }, icenter = { };
  16684. return process(0);
  16685. },
  16686. bilinearFiltering: function(canvasEl, w, h, w2, h2) {
  16687. var a, b, c, d, x, y, i, j, xDiff, yDiff, chnl,
  16688. color, offset = 0, origPix, ratioX = this.rcpScaleX,
  16689. ratioY = this.rcpScaleY, context = canvasEl.getContext('2d'),
  16690. w4 = 4 * (w - 1), img = context.getImageData(0, 0, w, h),
  16691. pixels = img.data, destImage = context.getImageData(0, 0, w2, h2),
  16692. destPixels = destImage.data;
  16693. for (i = 0; i < h2; i++) {
  16694. for (j = 0; j < w2; j++) {
  16695. x = floor(ratioX * j);
  16696. y = floor(ratioY * i);
  16697. xDiff = ratioX * j - x;
  16698. yDiff = ratioY * i - y;
  16699. origPix = 4 * (y * w + x);
  16700. for (chnl = 0; chnl < 4; chnl++) {
  16701. a = pixels[origPix + chnl];
  16702. b = pixels[origPix + 4 + chnl];
  16703. c = pixels[origPix + w4 + chnl];
  16704. d = pixels[origPix + w4 + 4 + chnl];
  16705. color = a * (1 - xDiff) * (1 - yDiff) + b * xDiff * (1 - yDiff) +
  16706. c * yDiff * (1 - xDiff) + d * xDiff * yDiff;
  16707. destPixels[offset++] = color;
  16708. }
  16709. }
  16710. }
  16711. return destImage;
  16712. },
  16713. hermiteFastResize: function(canvasEl, oW, oH, dW, dH) {
  16714. var ratioW = this.rcpScaleX, ratioH = this.rcpScaleY,
  16715. ratioWHalf = ceil(ratioW / 2),
  16716. ratioHHalf = ceil(ratioH / 2),
  16717. context = canvasEl.getContext('2d'),
  16718. img = context.getImageData(0, 0, oW, oH), data = img.data,
  16719. img2 = context.getImageData(0, 0, dW, dH), data2 = img2.data;
  16720. for (var j = 0; j < dH; j++) {
  16721. for (var i = 0; i < dW; i++) {
  16722. var x2 = (i + j * dW) * 4, weight = 0, weights = 0, weightsAlpha = 0,
  16723. gxR = 0, gxG = 0, gxB = 0, gxA = 0, centerY = (j + 0.5) * ratioH;
  16724. for (var yy = floor(j * ratioH); yy < (j + 1) * ratioH; yy++) {
  16725. var dy = abs(centerY - (yy + 0.5)) / ratioHHalf,
  16726. centerX = (i + 0.5) * ratioW, w0 = dy * dy;
  16727. for (var xx = floor(i * ratioW); xx < (i + 1) * ratioW; xx++) {
  16728. var dx = abs(centerX - (xx + 0.5)) / ratioWHalf,
  16729. w = sqrt(w0 + dx * dx);
  16730. /*jshint maxdepth:5 */
  16731. if (w > 1 && w < -1) {
  16732. continue;
  16733. }
  16734. //hermite filter
  16735. weight = 2 * w * w * w - 3 * w * w + 1;
  16736. if (weight > 0) {
  16737. dx = 4 * (xx + yy * oW);
  16738. //alpha
  16739. gxA += weight * data[dx + 3];
  16740. weightsAlpha += weight;
  16741. //colors
  16742. /*jshint maxdepth:6 */
  16743. if (data[dx + 3] < 255) {
  16744. weight = weight * data[dx + 3] / 250;
  16745. }
  16746. /*jshint maxdepth:5 */
  16747. gxR += weight * data[dx];
  16748. gxG += weight * data[dx + 1];
  16749. gxB += weight * data[dx + 2];
  16750. weights += weight;
  16751. }
  16752. /*jshint maxdepth:4 */
  16753. }
  16754. }
  16755. data2[x2] = gxR / weights;
  16756. data2[x2 + 1] = gxG / weights;
  16757. data2[x2 + 2] = gxB / weights;
  16758. data2[x2 + 3] = gxA / weightsAlpha;
  16759. }
  16760. }
  16761. return img2;
  16762. },
  16763. /**
  16764. * Returns object representation of an instance
  16765. * @return {Object} Object representation of an instance
  16766. */
  16767. toObject: function() {
  16768. return {
  16769. type: this.type,
  16770. scaleX: this.scaleX,
  16771. scaley: this.scaleY,
  16772. resizeType: this.resizeType,
  16773. lanczosLobes: this.lanczosLobes
  16774. };
  16775. }
  16776. });
  16777. /**
  16778. * Returns filter instance from an object representation
  16779. * @static
  16780. * @return {fabric.Image.filters.Resize} Instance of fabric.Image.filters.Resize
  16781. */
  16782. fabric.Image.filters.Resize.fromObject = function() {
  16783. return new fabric.Image.filters.Resize();
  16784. };
  16785. })(typeof exports !== 'undefined' ? exports : this);
  16786. (function(global) {
  16787. 'use strict';
  16788. var fabric = global.fabric || (global.fabric = { }),
  16789. extend = fabric.util.object.extend,
  16790. clone = fabric.util.object.clone,
  16791. toFixed = fabric.util.toFixed,
  16792. supportsLineDash = fabric.StaticCanvas.supports('setLineDash');
  16793. if (fabric.Text) {
  16794. fabric.warn('fabric.Text is already defined');
  16795. return;
  16796. }
  16797. var stateProperties = fabric.Object.prototype.stateProperties.concat();
  16798. stateProperties.push(
  16799. 'fontFamily',
  16800. 'fontWeight',
  16801. 'fontSize',
  16802. 'text',
  16803. 'textDecoration',
  16804. 'textAlign',
  16805. 'fontStyle',
  16806. 'lineHeight',
  16807. 'textBackgroundColor'
  16808. );
  16809. /**
  16810. * Text class
  16811. * @class fabric.Text
  16812. * @extends fabric.Object
  16813. * @return {fabric.Text} thisArg
  16814. * @tutorial {@link http://fabricjs.com/fabric-intro-part-2/#text}
  16815. * @see {@link fabric.Text#initialize} for constructor definition
  16816. */
  16817. fabric.Text = fabric.util.createClass(fabric.Object, /** @lends fabric.Text.prototype */ {
  16818. /**
  16819. * Properties which when set cause object to change dimensions
  16820. * @type Object
  16821. * @private
  16822. */
  16823. _dimensionAffectingProps: {
  16824. fontSize: true,
  16825. fontWeight: true,
  16826. fontFamily: true,
  16827. fontStyle: true,
  16828. lineHeight: true,
  16829. stroke: true,
  16830. strokeWidth: true,
  16831. text: true,
  16832. textAlign: true
  16833. },
  16834. /**
  16835. * @private
  16836. */
  16837. _reNewline: /\r?\n/,
  16838. /**
  16839. * Retrieves object's fontSize
  16840. * @method getFontSize
  16841. * @memberOf fabric.Text.prototype
  16842. * @return {String} Font size (in pixels)
  16843. */
  16844. /**
  16845. * Sets object's fontSize
  16846. * @method setFontSize
  16847. * @memberOf fabric.Text.prototype
  16848. * @param {Number} fontSize Font size (in pixels)
  16849. * @return {fabric.Text}
  16850. * @chainable
  16851. */
  16852. /**
  16853. * Retrieves object's fontWeight
  16854. * @method getFontWeight
  16855. * @memberOf fabric.Text.prototype
  16856. * @return {(String|Number)} Font weight
  16857. */
  16858. /**
  16859. * Sets object's fontWeight
  16860. * @method setFontWeight
  16861. * @memberOf fabric.Text.prototype
  16862. * @param {(Number|String)} fontWeight Font weight
  16863. * @return {fabric.Text}
  16864. * @chainable
  16865. */
  16866. /**
  16867. * Retrieves object's fontFamily
  16868. * @method getFontFamily
  16869. * @memberOf fabric.Text.prototype
  16870. * @return {String} Font family
  16871. */
  16872. /**
  16873. * Sets object's fontFamily
  16874. * @method setFontFamily
  16875. * @memberOf fabric.Text.prototype
  16876. * @param {String} fontFamily Font family
  16877. * @return {fabric.Text}
  16878. * @chainable
  16879. */
  16880. /**
  16881. * Retrieves object's text
  16882. * @method getText
  16883. * @memberOf fabric.Text.prototype
  16884. * @return {String} text
  16885. */
  16886. /**
  16887. * Sets object's text
  16888. * @method setText
  16889. * @memberOf fabric.Text.prototype
  16890. * @param {String} text Text
  16891. * @return {fabric.Text}
  16892. * @chainable
  16893. */
  16894. /**
  16895. * Retrieves object's textDecoration
  16896. * @method getTextDecoration
  16897. * @memberOf fabric.Text.prototype
  16898. * @return {String} Text decoration
  16899. */
  16900. /**
  16901. * Sets object's textDecoration
  16902. * @method setTextDecoration
  16903. * @memberOf fabric.Text.prototype
  16904. * @param {String} textDecoration Text decoration
  16905. * @return {fabric.Text}
  16906. * @chainable
  16907. */
  16908. /**
  16909. * Retrieves object's fontStyle
  16910. * @method getFontStyle
  16911. * @memberOf fabric.Text.prototype
  16912. * @return {String} Font style
  16913. */
  16914. /**
  16915. * Sets object's fontStyle
  16916. * @method setFontStyle
  16917. * @memberOf fabric.Text.prototype
  16918. * @param {String} fontStyle Font style
  16919. * @return {fabric.Text}
  16920. * @chainable
  16921. */
  16922. /**
  16923. * Retrieves object's lineHeight
  16924. * @method getLineHeight
  16925. * @memberOf fabric.Text.prototype
  16926. * @return {Number} Line height
  16927. */
  16928. /**
  16929. * Sets object's lineHeight
  16930. * @method setLineHeight
  16931. * @memberOf fabric.Text.prototype
  16932. * @param {Number} lineHeight Line height
  16933. * @return {fabric.Text}
  16934. * @chainable
  16935. */
  16936. /**
  16937. * Retrieves object's textAlign
  16938. * @method getTextAlign
  16939. * @memberOf fabric.Text.prototype
  16940. * @return {String} Text alignment
  16941. */
  16942. /**
  16943. * Sets object's textAlign
  16944. * @method setTextAlign
  16945. * @memberOf fabric.Text.prototype
  16946. * @param {String} textAlign Text alignment
  16947. * @return {fabric.Text}
  16948. * @chainable
  16949. */
  16950. /**
  16951. * Retrieves object's textBackgroundColor
  16952. * @method getTextBackgroundColor
  16953. * @memberOf fabric.Text.prototype
  16954. * @return {String} Text background color
  16955. */
  16956. /**
  16957. * Sets object's textBackgroundColor
  16958. * @method setTextBackgroundColor
  16959. * @memberOf fabric.Text.prototype
  16960. * @param {String} textBackgroundColor Text background color
  16961. * @return {fabric.Text}
  16962. * @chainable
  16963. */
  16964. /**
  16965. * Type of an object
  16966. * @type String
  16967. * @default
  16968. */
  16969. type: 'text',
  16970. /**
  16971. * Font size (in pixels)
  16972. * @type Number
  16973. * @default
  16974. */
  16975. fontSize: 40,
  16976. /**
  16977. * Font weight (e.g. bold, normal, 400, 600, 800)
  16978. * @type {(Number|String)}
  16979. * @default
  16980. */
  16981. fontWeight: 'normal',
  16982. /**
  16983. * Font family
  16984. * @type String
  16985. * @default
  16986. */
  16987. fontFamily: 'Times New Roman',
  16988. /**
  16989. * Text decoration Possible values: "", "underline", "overline" or "line-through".
  16990. * @type String
  16991. * @default
  16992. */
  16993. textDecoration: '',
  16994. /**
  16995. * Text alignment. Possible values: "left", "center", or "right".
  16996. * @type String
  16997. * @default
  16998. */
  16999. textAlign: 'left',
  17000. /**
  17001. * Font style . Possible values: "", "normal", "italic" or "oblique".
  17002. * @type String
  17003. * @default
  17004. */
  17005. fontStyle: '',
  17006. /**
  17007. * Line height
  17008. * @type Number
  17009. * @default
  17010. */
  17011. lineHeight: 1.16,
  17012. /**
  17013. * Background color of text lines
  17014. * @type String
  17015. * @default
  17016. */
  17017. textBackgroundColor: '',
  17018. /**
  17019. * List of properties to consider when checking if
  17020. * state of an object is changed ({@link fabric.Object#hasStateChanged})
  17021. * as well as for history (undo/redo) purposes
  17022. * @type Array
  17023. */
  17024. stateProperties: stateProperties,
  17025. /**
  17026. * When defined, an object is rendered via stroke and this property specifies its color.
  17027. * <b>Backwards incompatibility note:</b> This property was named "strokeStyle" until v1.1.6
  17028. * @type String
  17029. * @default
  17030. */
  17031. stroke: null,
  17032. /**
  17033. * Shadow object representing shadow of this shape.
  17034. * <b>Backwards incompatibility note:</b> This property was named "textShadow" (String) until v1.2.11
  17035. * @type fabric.Shadow
  17036. * @default
  17037. */
  17038. shadow: null,
  17039. /**
  17040. * @private
  17041. */
  17042. _fontSizeFraction: 0.25,
  17043. /**
  17044. * Text Line proportion to font Size (in pixels)
  17045. * @type Number
  17046. * @default
  17047. */
  17048. _fontSizeMult: 1.13,
  17049. /**
  17050. * Constructor
  17051. * @param {String} text Text string
  17052. * @param {Object} [options] Options object
  17053. * @return {fabric.Text} thisArg
  17054. */
  17055. initialize: function(text, options) {
  17056. options = options || { };
  17057. this.text = text;
  17058. this.__skipDimension = true;
  17059. this.setOptions(options);
  17060. this.__skipDimension = false;
  17061. this._initDimensions();
  17062. },
  17063. /**
  17064. * Renders text object on offscreen canvas, so that it would get dimensions
  17065. * @private
  17066. */
  17067. _initDimensions: function(ctx) {
  17068. if (this.__skipDimension) {
  17069. return;
  17070. }
  17071. if (!ctx) {
  17072. ctx = fabric.util.createCanvasElement().getContext('2d');
  17073. this._setTextStyles(ctx);
  17074. }
  17075. this._textLines = this.text.split(this._reNewline);
  17076. this._clearCache();
  17077. var currentTextAlign = this.textAlign;
  17078. this.textAlign = 'left';
  17079. this.width = this._getTextWidth(ctx);
  17080. this.textAlign = currentTextAlign;
  17081. this.height = this._getTextHeight(ctx);
  17082. },
  17083. /**
  17084. * Returns string representation of an instance
  17085. * @return {String} String representation of text object
  17086. */
  17087. toString: function() {
  17088. return '#<fabric.Text (' + this.complexity() +
  17089. '): { "text": "' + this.text + '", "fontFamily": "' + this.fontFamily + '" }>';
  17090. },
  17091. /**
  17092. * @private
  17093. * @param {CanvasRenderingContext2D} ctx Context to render on
  17094. */
  17095. _render: function(ctx) {
  17096. this.clipTo && fabric.util.clipContext(this, ctx);
  17097. this._renderTextBackground(ctx);
  17098. this._renderText(ctx);
  17099. this._renderTextDecoration(ctx);
  17100. this.clipTo && ctx.restore();
  17101. },
  17102. /**
  17103. * @private
  17104. * @param {CanvasRenderingContext2D} ctx Context to render on
  17105. */
  17106. _renderText: function(ctx) {
  17107. ctx.save();
  17108. this._translateForTextAlign(ctx);
  17109. this._setOpacity(ctx);
  17110. this._setShadow(ctx);
  17111. this._setupCompositeOperation(ctx);
  17112. this._renderTextFill(ctx);
  17113. this._renderTextStroke(ctx);
  17114. this._restoreCompositeOperation(ctx);
  17115. this._removeShadow(ctx);
  17116. ctx.restore();
  17117. },
  17118. /**
  17119. * @private
  17120. * @param {CanvasRenderingContext2D} ctx Context to render on
  17121. */
  17122. _translateForTextAlign: function(ctx) {
  17123. if (this.textAlign !== 'left' && this.textAlign !== 'justify') {
  17124. ctx.translate(this.textAlign === 'center' ? (this.width / 2) : this.width, 0);
  17125. }
  17126. },
  17127. /**
  17128. * @private
  17129. * @param {CanvasRenderingContext2D} ctx Context to render on
  17130. */
  17131. _setTextStyles: function(ctx) {
  17132. ctx.textBaseline = 'alphabetic';
  17133. if (!this.skipTextAlign) {
  17134. ctx.textAlign = this.textAlign;
  17135. }
  17136. ctx.font = this._getFontDeclaration();
  17137. },
  17138. /**
  17139. * @private
  17140. * @param {CanvasRenderingContext2D} ctx Context to render on
  17141. * @return {Number} Height of fabric.Text object
  17142. */
  17143. _getTextHeight: function() {
  17144. return this._textLines.length * this._getHeightOfLine();
  17145. },
  17146. /**
  17147. * @private
  17148. * @param {CanvasRenderingContext2D} ctx Context to render on
  17149. * @return {Number} Maximum width of fabric.Text object
  17150. */
  17151. _getTextWidth: function(ctx) {
  17152. var maxWidth = this._getLineWidth(ctx, 0);
  17153. for (var i = 1, len = this._textLines.length; i < len; i++) {
  17154. var currentLineWidth = this._getLineWidth(ctx, i);
  17155. if (currentLineWidth > maxWidth) {
  17156. maxWidth = currentLineWidth;
  17157. }
  17158. }
  17159. return maxWidth;
  17160. },
  17161. /**
  17162. * @private
  17163. * @param {String} method Method name ("fillText" or "strokeText")
  17164. * @param {CanvasRenderingContext2D} ctx Context to render on
  17165. * @param {String} chars Chars to render
  17166. * @param {Number} left Left position of text
  17167. * @param {Number} top Top position of text
  17168. */
  17169. _renderChars: function(method, ctx, chars, left, top) {
  17170. ctx[method](chars, left, top);
  17171. },
  17172. /**
  17173. * @private
  17174. * @param {String} method Method name ("fillText" or "strokeText")
  17175. * @param {CanvasRenderingContext2D} ctx Context to render on
  17176. * @param {String} line Text to render
  17177. * @param {Number} left Left position of text
  17178. * @param {Number} top Top position of text
  17179. * @param {Number} lineIndex Index of a line in a text
  17180. */
  17181. _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
  17182. // lift the line by quarter of fontSize
  17183. top -= this.fontSize * this._fontSizeFraction;
  17184. // short-circuit
  17185. if (this.textAlign !== 'justify') {
  17186. this._renderChars(method, ctx, line, left, top, lineIndex);
  17187. return;
  17188. }
  17189. var lineWidth = this._getLineWidth(ctx, lineIndex),
  17190. totalWidth = this.width;
  17191. if (totalWidth >= lineWidth) {
  17192. // stretch the line
  17193. var words = line.split(/\s+/),
  17194. wordsWidth = this._getWidthOfWords(ctx, line, lineIndex),
  17195. widthDiff = totalWidth - wordsWidth,
  17196. numSpaces = words.length - 1,
  17197. spaceWidth = widthDiff / numSpaces,
  17198. leftOffset = 0;
  17199. for (var i = 0, len = words.length; i < len; i++) {
  17200. this._renderChars(method, ctx, words[i], left + leftOffset, top, lineIndex);
  17201. leftOffset += ctx.measureText(words[i]).width + spaceWidth;
  17202. }
  17203. }
  17204. else {
  17205. this._renderChars(method, ctx, line, left, top, lineIndex);
  17206. }
  17207. },
  17208. /**
  17209. * @private
  17210. * @param {CanvasRenderingContext2D} ctx Context to render on
  17211. * @param {Number} line
  17212. */
  17213. _getWidthOfWords: function (ctx, line) {
  17214. return ctx.measureText(line.replace(/\s+/g, '')).width;
  17215. },
  17216. /**
  17217. * @private
  17218. * @return {Number} Left offset
  17219. */
  17220. _getLeftOffset: function() {
  17221. return -this.width / 2;
  17222. },
  17223. /**
  17224. * @private
  17225. * @return {Number} Top offset
  17226. */
  17227. _getTopOffset: function() {
  17228. return -this.height / 2;
  17229. },
  17230. /**
  17231. * @private
  17232. * @param {CanvasRenderingContext2D} ctx Context to render on
  17233. */
  17234. _renderTextFill: function(ctx) {
  17235. if (!this.fill && !this._skipFillStrokeCheck) {
  17236. return;
  17237. }
  17238. var lineHeights = 0;
  17239. for (var i = 0, len = this._textLines.length; i < len; i++) {
  17240. var heightOfLine = this._getHeightOfLine(ctx, i),
  17241. maxHeight = heightOfLine / this.lineHeight;
  17242. this._renderTextLine(
  17243. 'fillText',
  17244. ctx,
  17245. this._textLines[i],
  17246. this._getLeftOffset(),
  17247. this._getTopOffset() + lineHeights + maxHeight,
  17248. i
  17249. );
  17250. lineHeights += heightOfLine;
  17251. }
  17252. if (this.shadow && !this.shadow.affectStroke) {
  17253. this._removeShadow(ctx);
  17254. }
  17255. },
  17256. /**
  17257. * @private
  17258. * @param {CanvasRenderingContext2D} ctx Context to render on
  17259. */
  17260. _renderTextStroke: function(ctx) {
  17261. if ((!this.stroke || this.strokeWidth === 0) && !this._skipFillStrokeCheck) {
  17262. return;
  17263. }
  17264. var lineHeights = 0;
  17265. ctx.save();
  17266. if (this.strokeDashArray) {
  17267. // Spec requires the concatenation of two copies the dash list when the number of elements is odd
  17268. if (1 & this.strokeDashArray.length) {
  17269. this.strokeDashArray.push.apply(this.strokeDashArray, this.strokeDashArray);
  17270. }
  17271. supportsLineDash && ctx.setLineDash(this.strokeDashArray);
  17272. }
  17273. ctx.beginPath();
  17274. for (var i = 0, len = this._textLines.length; i < len; i++) {
  17275. var heightOfLine = this._getHeightOfLine(ctx, i),
  17276. maxHeight = heightOfLine / this.lineHeight;
  17277. this._renderTextLine(
  17278. 'strokeText',
  17279. ctx,
  17280. this._textLines[i],
  17281. this._getLeftOffset(),
  17282. this._getTopOffset() + lineHeights + maxHeight,
  17283. i
  17284. );
  17285. lineHeights += heightOfLine;
  17286. }
  17287. ctx.closePath();
  17288. ctx.restore();
  17289. },
  17290. _getHeightOfLine: function() {
  17291. return this.fontSize * this._fontSizeMult * this.lineHeight;
  17292. },
  17293. /**
  17294. * @private
  17295. * @param {CanvasRenderingContext2D} ctx Context to render on
  17296. * @param {Array} textLines Array of all text lines
  17297. */
  17298. _renderTextBackground: function(ctx) {
  17299. this._renderTextBoxBackground(ctx);
  17300. this._renderTextLinesBackground(ctx);
  17301. },
  17302. /**
  17303. * @private
  17304. * @param {CanvasRenderingContext2D} ctx Context to render on
  17305. */
  17306. _renderTextBoxBackground: function(ctx) {
  17307. if (!this.backgroundColor) {
  17308. return;
  17309. }
  17310. ctx.save();
  17311. ctx.fillStyle = this.backgroundColor;
  17312. ctx.fillRect(
  17313. this._getLeftOffset(),
  17314. this._getTopOffset(),
  17315. this.width,
  17316. this.height
  17317. );
  17318. ctx.restore();
  17319. },
  17320. /**
  17321. * @private
  17322. * @param {CanvasRenderingContext2D} ctx Context to render on
  17323. */
  17324. _renderTextLinesBackground: function(ctx) {
  17325. var lineTopOffset = 0, heightOfLine = this._getHeightOfLine();
  17326. if (!this.textBackgroundColor) {
  17327. return;
  17328. }
  17329. ctx.save();
  17330. ctx.fillStyle = this.textBackgroundColor;
  17331. for (var i = 0, len = this._textLines.length; i < len; i++) {
  17332. if (this._textLines[i] !== '') {
  17333. var lineWidth = this._getLineWidth(ctx, i),
  17334. lineLeftOffset = this._getLineLeftOffset(lineWidth);
  17335. ctx.fillRect(
  17336. this._getLeftOffset() + lineLeftOffset,
  17337. this._getTopOffset() + lineTopOffset,
  17338. lineWidth,
  17339. this.fontSize * this._fontSizeMult
  17340. );
  17341. }
  17342. lineTopOffset += heightOfLine;
  17343. }
  17344. ctx.restore();
  17345. },
  17346. /**
  17347. * @private
  17348. * @param {Number} lineWidth Width of text line
  17349. * @return {Number} Line left offset
  17350. */
  17351. _getLineLeftOffset: function(lineWidth) {
  17352. if (this.textAlign === 'center') {
  17353. return (this.width - lineWidth) / 2;
  17354. }
  17355. if (this.textAlign === 'right') {
  17356. return this.width - lineWidth;
  17357. }
  17358. return 0;
  17359. },
  17360. /**
  17361. * @private
  17362. */
  17363. _clearCache: function() {
  17364. this.__lineWidths = [ ];
  17365. this.__lineHeights = [ ];
  17366. this.__lineOffsets = [ ];
  17367. },
  17368. /**
  17369. * @private
  17370. */
  17371. _shouldClearCache: function() {
  17372. var shouldClear = false;
  17373. for (var prop in this._dimensionAffectingProps) {
  17374. if (this['__' + prop] !== this[prop]) {
  17375. this['__' + prop] = this[prop];
  17376. shouldClear = true;
  17377. }
  17378. }
  17379. return shouldClear;
  17380. },
  17381. /**
  17382. * @private
  17383. * @param {CanvasRenderingContext2D} ctx Context to render on
  17384. * @return {Number} Line width
  17385. */
  17386. _getLineWidth: function(ctx, lineIndex) {
  17387. if (this.__lineWidths[lineIndex]) {
  17388. return this.__lineWidths[lineIndex];
  17389. }
  17390. this.__lineWidths[lineIndex] = ctx.measureText(this._textLines[lineIndex]).width;
  17391. return this.__lineWidths[lineIndex];
  17392. },
  17393. /**
  17394. * @private
  17395. * @param {CanvasRenderingContext2D} ctx Context to render on
  17396. */
  17397. _renderTextDecoration: function(ctx) {
  17398. if (!this.textDecoration) {
  17399. return;
  17400. }
  17401. var halfOfVerticalBox = this.height / 2,
  17402. _this = this, offsets = [];
  17403. /** @ignore */
  17404. function renderLinesAtOffset(offsets) {
  17405. var i, lineHeight = 0, len, j, oLen;
  17406. for (i = 0, len = _this._textLines.length; i < len; i++) {
  17407. var lineWidth = _this._getLineWidth(ctx, i),
  17408. lineLeftOffset = _this._getLineLeftOffset(lineWidth),
  17409. heightOfLine = _this._getHeightOfLine(ctx, i);
  17410. for (j = 0, oLen = offsets.length; j < oLen; j++) {
  17411. ctx.fillRect(
  17412. _this._getLeftOffset() + lineLeftOffset,
  17413. lineHeight + (_this._fontSizeMult - 1 + offsets[j] ) * _this.fontSize - halfOfVerticalBox,
  17414. lineWidth,
  17415. _this.fontSize / 15);
  17416. }
  17417. lineHeight += heightOfLine;
  17418. }
  17419. }
  17420. if (this.textDecoration.indexOf('underline') > -1) {
  17421. offsets.push(0.85); // 1 - 3/16
  17422. }
  17423. if (this.textDecoration.indexOf('line-through') > -1) {
  17424. offsets.push(0.43);
  17425. }
  17426. if (this.textDecoration.indexOf('overline') > -1) {
  17427. offsets.push(-0.12);
  17428. }
  17429. if (offsets.length > 0) {
  17430. renderLinesAtOffset(offsets);
  17431. }
  17432. },
  17433. /**
  17434. * @private
  17435. */
  17436. _getFontDeclaration: function() {
  17437. return [
  17438. // node-canvas needs "weight style", while browsers need "style weight"
  17439. (fabric.isLikelyNode ? this.fontWeight : this.fontStyle),
  17440. (fabric.isLikelyNode ? this.fontStyle : this.fontWeight),
  17441. this.fontSize + 'px',
  17442. (fabric.isLikelyNode ? ('"' + this.fontFamily + '"') : this.fontFamily)
  17443. ].join(' ');
  17444. },
  17445. /**
  17446. * Renders text instance on a specified context
  17447. * @param {CanvasRenderingContext2D} ctx Context to render on
  17448. */
  17449. render: function(ctx, noTransform) {
  17450. // do not render if object is not visible
  17451. if (!this.visible) {
  17452. return;
  17453. }
  17454. ctx.save();
  17455. this._setTextStyles(ctx);
  17456. if (this._shouldClearCache()) {
  17457. this._initDimensions(ctx);
  17458. }
  17459. if (!noTransform) {
  17460. this.transform(ctx);
  17461. }
  17462. this._setStrokeStyles(ctx);
  17463. this._setFillStyles(ctx);
  17464. if (this.transformMatrix) {
  17465. ctx.transform.apply(ctx, this.transformMatrix);
  17466. }
  17467. if (this.group && this.group.type === 'path-group') {
  17468. ctx.translate(this.left, this.top);
  17469. }
  17470. this._render(ctx);
  17471. ctx.restore();
  17472. },
  17473. /**
  17474. * Returns object representation of an instance
  17475. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  17476. * @return {Object} Object representation of an instance
  17477. */
  17478. toObject: function(propertiesToInclude) {
  17479. var object = extend(this.callSuper('toObject', propertiesToInclude), {
  17480. text: this.text,
  17481. fontSize: this.fontSize,
  17482. fontWeight: this.fontWeight,
  17483. fontFamily: this.fontFamily,
  17484. fontStyle: this.fontStyle,
  17485. lineHeight: this.lineHeight,
  17486. textDecoration: this.textDecoration,
  17487. textAlign: this.textAlign,
  17488. textBackgroundColor: this.textBackgroundColor
  17489. });
  17490. if (!this.includeDefaultValues) {
  17491. this._removeDefaultValues(object);
  17492. }
  17493. return object;
  17494. },
  17495. /* _TO_SVG_START_ */
  17496. /**
  17497. * Returns SVG representation of an instance
  17498. * @param {Function} [reviver] Method for further parsing of svg representation.
  17499. * @return {String} svg representation of an instance
  17500. */
  17501. toSVG: function(reviver) {
  17502. var markup = this._createBaseSVGMarkup(),
  17503. offsets = this._getSVGLeftTopOffsets(this.ctx),
  17504. textAndBg = this._getSVGTextAndBg(offsets.textTop, offsets.textLeft);
  17505. this._wrapSVGTextAndBg(markup, textAndBg);
  17506. return reviver ? reviver(markup.join('')) : markup.join('');
  17507. },
  17508. /**
  17509. * @private
  17510. */
  17511. _getSVGLeftTopOffsets: function(ctx) {
  17512. var lineTop = this._getHeightOfLine(ctx, 0),
  17513. textLeft = -this.width / 2,
  17514. textTop = 0;
  17515. return {
  17516. textLeft: textLeft + (this.group && this.group.type === 'path-group' ? this.left : 0),
  17517. textTop: textTop + (this.group && this.group.type === 'path-group' ? -this.top : 0),
  17518. lineTop: lineTop
  17519. };
  17520. },
  17521. /**
  17522. * @private
  17523. */
  17524. _wrapSVGTextAndBg: function(markup, textAndBg) {
  17525. markup.push(
  17526. '\t<g transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '">\n',
  17527. textAndBg.textBgRects.join(''),
  17528. '\t\t<text ',
  17529. (this.fontFamily ? 'font-family="' + this.fontFamily.replace(/"/g, '\'') + '" ': ''),
  17530. (this.fontSize ? 'font-size="' + this.fontSize + '" ': ''),
  17531. (this.fontStyle ? 'font-style="' + this.fontStyle + '" ': ''),
  17532. (this.fontWeight ? 'font-weight="' + this.fontWeight + '" ': ''),
  17533. (this.textDecoration ? 'text-decoration="' + this.textDecoration + '" ': ''),
  17534. 'style="', this.getSvgStyles(), '" >',
  17535. textAndBg.textSpans.join(''),
  17536. '</text>\n',
  17537. '\t</g>\n'
  17538. );
  17539. },
  17540. /**
  17541. * @private
  17542. * @param {Number} textTopOffset Text top offset
  17543. * @param {Number} textLeftOffset Text left offset
  17544. * @return {Object}
  17545. */
  17546. _getSVGTextAndBg: function(textTopOffset, textLeftOffset) {
  17547. var textSpans = [ ],
  17548. textBgRects = [ ],
  17549. height = 0;
  17550. // bounding-box background
  17551. this._setSVGBg(textBgRects);
  17552. // text and text-background
  17553. for (var i = 0, len = this._textLines.length; i < len; i++) {
  17554. if (this.textBackgroundColor) {
  17555. this._setSVGTextLineBg(textBgRects, i, textLeftOffset, textTopOffset, height);
  17556. }
  17557. this._setSVGTextLineText(i, textSpans, height, textLeftOffset, textTopOffset, textBgRects);
  17558. height += this._getHeightOfLine(this.ctx, i);
  17559. }
  17560. return {
  17561. textSpans: textSpans,
  17562. textBgRects: textBgRects
  17563. };
  17564. },
  17565. _setSVGTextLineText: function(i, textSpans, height, textLeftOffset, textTopOffset) {
  17566. var yPos = this.fontSize * (this._fontSizeMult - this._fontSizeFraction)
  17567. - textTopOffset + height - this.height / 2;
  17568. textSpans.push(
  17569. '<tspan x="',
  17570. toFixed(textLeftOffset + this._getLineLeftOffset(this.__lineWidths[i]), 4), '" ',
  17571. 'y="',
  17572. toFixed(yPos, 4),
  17573. '" ',
  17574. // doing this on <tspan> elements since setting opacity
  17575. // on containing <text> one doesn't work in Illustrator
  17576. this._getFillAttributes(this.fill), '>',
  17577. fabric.util.string.escapeXml(this._textLines[i]),
  17578. '</tspan>'
  17579. );
  17580. },
  17581. _setSVGTextLineBg: function(textBgRects, i, textLeftOffset, textTopOffset, height) {
  17582. textBgRects.push(
  17583. '\t\t<rect ',
  17584. this._getFillAttributes(this.textBackgroundColor),
  17585. ' x="',
  17586. toFixed(textLeftOffset + this._getLineLeftOffset(this.__lineWidths[i]), 4),
  17587. '" y="',
  17588. toFixed(height - this.height / 2, 4),
  17589. '" width="',
  17590. toFixed(this.__lineWidths[i], 4),
  17591. '" height="',
  17592. toFixed(this._getHeightOfLine(this.ctx, i) / this.lineHeight, 4),
  17593. '"></rect>\n');
  17594. },
  17595. _setSVGBg: function(textBgRects) {
  17596. if (this.backgroundColor) {
  17597. textBgRects.push(
  17598. '\t\t<rect ',
  17599. this._getFillAttributes(this.backgroundColor),
  17600. ' x="',
  17601. toFixed(-this.width / 2, 4),
  17602. '" y="',
  17603. toFixed(-this.height / 2, 4),
  17604. '" width="',
  17605. toFixed(this.width, 4),
  17606. '" height="',
  17607. toFixed(this.height, 4),
  17608. '"></rect>\n');
  17609. }
  17610. },
  17611. /**
  17612. * Adobe Illustrator (at least CS5) is unable to render rgba()-based fill values
  17613. * we work around it by "moving" alpha channel into opacity attribute and setting fill's alpha to 1
  17614. *
  17615. * @private
  17616. * @param {Any} value
  17617. * @return {String}
  17618. */
  17619. _getFillAttributes: function(value) {
  17620. var fillColor = (value && typeof value === 'string') ? new fabric.Color(value) : '';
  17621. if (!fillColor || !fillColor.getSource() || fillColor.getAlpha() === 1) {
  17622. return 'fill="' + value + '"';
  17623. }
  17624. return 'opacity="' + fillColor.getAlpha() + '" fill="' + fillColor.setAlpha(1).toRgb() + '"';
  17625. },
  17626. /* _TO_SVG_END_ */
  17627. /**
  17628. * Sets specified property to a specified value
  17629. * @param {String} key
  17630. * @param {Any} value
  17631. * @return {fabric.Text} thisArg
  17632. * @chainable
  17633. */
  17634. _set: function(key, value) {
  17635. this.callSuper('_set', key, value);
  17636. if (key in this._dimensionAffectingProps) {
  17637. this._initDimensions();
  17638. this.setCoords();
  17639. }
  17640. },
  17641. /**
  17642. * Returns complexity of an instance
  17643. * @return {Number} complexity
  17644. */
  17645. complexity: function() {
  17646. return 1;
  17647. }
  17648. });
  17649. /* _FROM_SVG_START_ */
  17650. /**
  17651. * List of attribute names to account for when parsing SVG element (used by {@link fabric.Text.fromElement})
  17652. * @static
  17653. * @memberOf fabric.Text
  17654. * @see: http://www.w3.org/TR/SVG/text.html#TextElement
  17655. */
  17656. fabric.Text.ATTRIBUTE_NAMES = fabric.SHARED_ATTRIBUTES.concat(
  17657. 'x y dx dy font-family font-style font-weight font-size text-decoration text-anchor'.split(' '));
  17658. /**
  17659. * Default SVG font size
  17660. * @static
  17661. * @memberOf fabric.Text
  17662. */
  17663. fabric.Text.DEFAULT_SVG_FONT_SIZE = 16;
  17664. /**
  17665. * Returns fabric.Text instance from an SVG element (<b>not yet implemented</b>)
  17666. * @static
  17667. * @memberOf fabric.Text
  17668. * @param {SVGElement} element Element to parse
  17669. * @param {Object} [options] Options object
  17670. * @return {fabric.Text} Instance of fabric.Text
  17671. */
  17672. fabric.Text.fromElement = function(element, options) {
  17673. if (!element) {
  17674. return null;
  17675. }
  17676. var parsedAttributes = fabric.parseAttributes(element, fabric.Text.ATTRIBUTE_NAMES);
  17677. options = fabric.util.object.extend((options ? fabric.util.object.clone(options) : { }), parsedAttributes);
  17678. options.top = options.top || 0;
  17679. options.left = options.left || 0;
  17680. if ('dx' in parsedAttributes) {
  17681. options.left += parsedAttributes.dx;
  17682. }
  17683. if ('dy' in parsedAttributes) {
  17684. options.top += parsedAttributes.dy;
  17685. }
  17686. if (!('fontSize' in options)) {
  17687. options.fontSize = fabric.Text.DEFAULT_SVG_FONT_SIZE;
  17688. }
  17689. if (!options.originX) {
  17690. options.originX = 'left';
  17691. }
  17692. var textContent = element.textContent.replace(/^\s+|\s+$|\n+/g, '').replace(/\s+/g, ' '),
  17693. text = new fabric.Text(textContent, options),
  17694. /*
  17695. Adjust positioning:
  17696. x/y attributes in SVG correspond to the bottom-left corner of text bounding box
  17697. top/left properties in Fabric correspond to center point of text bounding box
  17698. */
  17699. offX = 0;
  17700. if (text.originX === 'left') {
  17701. offX = text.getWidth() / 2;
  17702. }
  17703. if (text.originX === 'right') {
  17704. offX = -text.getWidth() / 2;
  17705. }
  17706. text.set({
  17707. left: text.getLeft() + offX,
  17708. top: text.getTop() - text.getHeight() / 2 + text.fontSize * (0.18 + text._fontSizeFraction) /* 0.3 is the old lineHeight */
  17709. });
  17710. return text;
  17711. };
  17712. /* _FROM_SVG_END_ */
  17713. /**
  17714. * Returns fabric.Text instance from an object representation
  17715. * @static
  17716. * @memberOf fabric.Text
  17717. * @param {Object} object Object to create an instance from
  17718. * @return {fabric.Text} Instance of fabric.Text
  17719. */
  17720. fabric.Text.fromObject = function(object) {
  17721. return new fabric.Text(object.text, clone(object));
  17722. };
  17723. fabric.util.createAccessors(fabric.Text);
  17724. })(typeof exports !== 'undefined' ? exports : this);
  17725. (function() {
  17726. var clone = fabric.util.object.clone;
  17727. /**
  17728. * IText class (introduced in <b>v1.4</b>) Events are also fired with "text:"
  17729. * prefix when observing canvas.
  17730. * @class fabric.IText
  17731. * @extends fabric.Text
  17732. * @mixes fabric.Observable
  17733. *
  17734. * @fires changed
  17735. * @fires selection:changed
  17736. * @fires editing:entered
  17737. * @fires editing:exited
  17738. *
  17739. * @return {fabric.IText} thisArg
  17740. * @see {@link fabric.IText#initialize} for constructor definition
  17741. *
  17742. * <p>Supported key combinations:</p>
  17743. * <pre>
  17744. * Move cursor: left, right, up, down
  17745. * Select character: shift + left, shift + right
  17746. * Select text vertically: shift + up, shift + down
  17747. * Move cursor by word: alt + left, alt + right
  17748. * Select words: shift + alt + left, shift + alt + right
  17749. * Move cursor to line start/end: cmd + left, cmd + right or home, end
  17750. * Select till start/end of line: cmd + shift + left, cmd + shift + right or shift + home, shift + end
  17751. * Jump to start/end of text: cmd + up, cmd + down
  17752. * Select till start/end of text: cmd + shift + up, cmd + shift + down or shift + pgUp, shift + pgDown
  17753. * Delete character: backspace
  17754. * Delete word: alt + backspace
  17755. * Delete line: cmd + backspace
  17756. * Forward delete: delete
  17757. * Copy text: ctrl/cmd + c
  17758. * Paste text: ctrl/cmd + v
  17759. * Cut text: ctrl/cmd + x
  17760. * Select entire text: ctrl/cmd + a
  17761. * Quit editing tab or esc
  17762. * </pre>
  17763. *
  17764. * <p>Supported mouse/touch combination</p>
  17765. * <pre>
  17766. * Position cursor: click/touch
  17767. * Create selection: click/touch & drag
  17768. * Create selection: click & shift + click
  17769. * Select word: double click
  17770. * Select line: triple click
  17771. * </pre>
  17772. */
  17773. fabric.IText = fabric.util.createClass(fabric.Text, fabric.Observable, /** @lends fabric.IText.prototype */ {
  17774. /**
  17775. * Type of an object
  17776. * @type String
  17777. * @default
  17778. */
  17779. type: 'i-text',
  17780. /**
  17781. * Index where text selection starts (or where cursor is when there is no selection)
  17782. * @type Nubmer
  17783. * @default
  17784. */
  17785. selectionStart: 0,
  17786. /**
  17787. * Index where text selection ends
  17788. * @type Nubmer
  17789. * @default
  17790. */
  17791. selectionEnd: 0,
  17792. /**
  17793. * Color of text selection
  17794. * @type String
  17795. * @default
  17796. */
  17797. selectionColor: 'rgba(17,119,255,0.3)',
  17798. /**
  17799. * Indicates whether text is in editing mode
  17800. * @type Boolean
  17801. * @default
  17802. */
  17803. isEditing: false,
  17804. /**
  17805. * Indicates whether a text can be edited
  17806. * @type Boolean
  17807. * @default
  17808. */
  17809. editable: true,
  17810. /**
  17811. * Border color of text object while it's in editing mode
  17812. * @type String
  17813. * @default
  17814. */
  17815. editingBorderColor: 'rgba(102,153,255,0.25)',
  17816. /**
  17817. * Width of cursor (in px)
  17818. * @type Number
  17819. * @default
  17820. */
  17821. cursorWidth: 2,
  17822. /**
  17823. * Color of default cursor (when not overwritten by character style)
  17824. * @type String
  17825. * @default
  17826. */
  17827. cursorColor: '#333',
  17828. /**
  17829. * Delay between cursor blink (in ms)
  17830. * @type Number
  17831. * @default
  17832. */
  17833. cursorDelay: 1000,
  17834. /**
  17835. * Duration of cursor fadein (in ms)
  17836. * @type Number
  17837. * @default
  17838. */
  17839. cursorDuration: 600,
  17840. /**
  17841. * Object containing character styles
  17842. * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line)
  17843. * @type Object
  17844. * @default
  17845. */
  17846. styles: null,
  17847. /**
  17848. * Indicates whether internal text char widths can be cached
  17849. * @type Boolean
  17850. * @default
  17851. */
  17852. caching: true,
  17853. /**
  17854. * @private
  17855. * @type Boolean
  17856. * @default
  17857. */
  17858. _skipFillStrokeCheck: false,
  17859. /**
  17860. * @private
  17861. */
  17862. _reSpace: /\s|\n/,
  17863. /**
  17864. * @private
  17865. */
  17866. _currentCursorOpacity: 0,
  17867. /**
  17868. * @private
  17869. */
  17870. _selectionDirection: null,
  17871. /**
  17872. * @private
  17873. */
  17874. _abortCursorAnimation: false,
  17875. /**
  17876. * @private
  17877. */
  17878. _charWidthsCache: { },
  17879. /**
  17880. * Constructor
  17881. * @param {String} text Text string
  17882. * @param {Object} [options] Options object
  17883. * @return {fabric.IText} thisArg
  17884. */
  17885. initialize: function(text, options) {
  17886. this.styles = options ? (options.styles || { }) : { };
  17887. this.callSuper('initialize', text, options);
  17888. this.initBehavior();
  17889. },
  17890. /**
  17891. * @private
  17892. */
  17893. _clearCache: function() {
  17894. this.callSuper('_clearCache');
  17895. this.__maxFontHeights = [ ];
  17896. this.__widthOfSpace = [ ];
  17897. },
  17898. /**
  17899. * Returns true if object has no styling
  17900. */
  17901. isEmptyStyles: function() {
  17902. if (!this.styles) {
  17903. return true;
  17904. }
  17905. var obj = this.styles;
  17906. for (var p1 in obj) {
  17907. for (var p2 in obj[p1]) {
  17908. /*jshint unused:false */
  17909. for (var p3 in obj[p1][p2]) {
  17910. return false;
  17911. }
  17912. }
  17913. }
  17914. return true;
  17915. },
  17916. /**
  17917. * Sets selection start (left boundary of a selection)
  17918. * @param {Number} index Index to set selection start to
  17919. */
  17920. setSelectionStart: function(index) {
  17921. index = Math.max(index, 0);
  17922. if (this.selectionStart !== index) {
  17923. this.fire('selection:changed');
  17924. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  17925. this.selectionStart = index;
  17926. }
  17927. this._updateTextarea();
  17928. },
  17929. /**
  17930. * Sets selection end (right boundary of a selection)
  17931. * @param {Number} index Index to set selection end to
  17932. */
  17933. setSelectionEnd: function(index) {
  17934. index = Math.min(index, this.text.length);
  17935. if (this.selectionEnd !== index) {
  17936. this.fire('selection:changed');
  17937. this.canvas && this.canvas.fire('text:selection:changed', { target: this });
  17938. this.selectionEnd = index;
  17939. }
  17940. this._updateTextarea();
  17941. },
  17942. /**
  17943. * Gets style of a current selection/cursor (at the start position)
  17944. * @param {Number} [startIndex] Start index to get styles at
  17945. * @param {Number} [endIndex] End index to get styles at
  17946. * @return {Object} styles Style object at a specified (or current) index
  17947. */
  17948. getSelectionStyles: function(startIndex, endIndex) {
  17949. if (arguments.length === 2) {
  17950. var styles = [ ];
  17951. for (var i = startIndex; i < endIndex; i++) {
  17952. styles.push(this.getSelectionStyles(i));
  17953. }
  17954. return styles;
  17955. }
  17956. var loc = this.get2DCursorLocation(startIndex);
  17957. if (this.styles[loc.lineIndex]) {
  17958. return this.styles[loc.lineIndex][loc.charIndex] || { };
  17959. }
  17960. return { };
  17961. },
  17962. /**
  17963. * Sets style of a current selection
  17964. * @param {Object} [styles] Styles object
  17965. * @return {fabric.IText} thisArg
  17966. * @chainable
  17967. */
  17968. setSelectionStyles: function(styles) {
  17969. if (this.selectionStart === this.selectionEnd) {
  17970. this._extendStyles(this.selectionStart, styles);
  17971. }
  17972. else {
  17973. for (var i = this.selectionStart; i < this.selectionEnd; i++) {
  17974. this._extendStyles(i, styles);
  17975. }
  17976. }
  17977. /* not included in _extendStyles to avoid clearing cache more than once */
  17978. this._clearCache();
  17979. return this;
  17980. },
  17981. /**
  17982. * @private
  17983. */
  17984. _extendStyles: function(index, styles) {
  17985. var loc = this.get2DCursorLocation(index);
  17986. if (!this.styles[loc.lineIndex]) {
  17987. this.styles[loc.lineIndex] = { };
  17988. }
  17989. if (!this.styles[loc.lineIndex][loc.charIndex]) {
  17990. this.styles[loc.lineIndex][loc.charIndex] = { };
  17991. }
  17992. fabric.util.object.extend(this.styles[loc.lineIndex][loc.charIndex], styles);
  17993. },
  17994. /**
  17995. * @private
  17996. * @param {CanvasRenderingContext2D} ctx Context to render on
  17997. */
  17998. _render: function(ctx) {
  17999. this.callSuper('_render', ctx);
  18000. this.ctx = ctx;
  18001. this.isEditing && this.renderCursorOrSelection();
  18002. },
  18003. /**
  18004. * Renders cursor or selection (depending on what exists)
  18005. */
  18006. renderCursorOrSelection: function() {
  18007. if (!this.active) {
  18008. return;
  18009. }
  18010. var chars = this.text.split(''),
  18011. boundaries, ctx;
  18012. if (this.canvas.contextTop) {
  18013. ctx = this.canvas.contextTop;
  18014. ctx.save();
  18015. ctx.transform.apply(ctx, this.canvas.viewportTransform);
  18016. this.transform(ctx);
  18017. }
  18018. else {
  18019. ctx = this.ctx;
  18020. ctx.save();
  18021. }
  18022. if (this.selectionStart === this.selectionEnd) {
  18023. boundaries = this._getCursorBoundaries(chars, 'cursor');
  18024. this.renderCursor(boundaries, ctx);
  18025. }
  18026. else {
  18027. boundaries = this._getCursorBoundaries(chars, 'selection');
  18028. this.renderSelection(chars, boundaries, ctx);
  18029. }
  18030. ctx.restore();
  18031. },
  18032. /**
  18033. * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start)
  18034. * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used.
  18035. */
  18036. get2DCursorLocation: function(selectionStart) {
  18037. if (typeof selectionStart === 'undefined') {
  18038. selectionStart = this.selectionStart;
  18039. }
  18040. var textBeforeCursor = this.text.slice(0, selectionStart),
  18041. linesBeforeCursor = textBeforeCursor.split(this._reNewline);
  18042. return {
  18043. lineIndex: linesBeforeCursor.length - 1,
  18044. charIndex: linesBeforeCursor[linesBeforeCursor.length - 1].length
  18045. };
  18046. },
  18047. /**
  18048. * Returns complete style of char at the current cursor
  18049. * @param {Number} lineIndex Line index
  18050. * @param {Number} charIndex Char index
  18051. * @return {Object} Character style
  18052. */
  18053. getCurrentCharStyle: function(lineIndex, charIndex) {
  18054. var style = this.styles[lineIndex] && this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)];
  18055. return {
  18056. fontSize: style && style.fontSize || this.fontSize,
  18057. fill: style && style.fill || this.fill,
  18058. textBackgroundColor: style && style.textBackgroundColor || this.textBackgroundColor,
  18059. textDecoration: style && style.textDecoration || this.textDecoration,
  18060. fontFamily: style && style.fontFamily || this.fontFamily,
  18061. fontWeight: style && style.fontWeight || this.fontWeight,
  18062. fontStyle: style && style.fontStyle || this.fontStyle,
  18063. stroke: style && style.stroke || this.stroke,
  18064. strokeWidth: style && style.strokeWidth || this.strokeWidth
  18065. };
  18066. },
  18067. /**
  18068. * Returns fontSize of char at the current cursor
  18069. * @param {Number} lineIndex Line index
  18070. * @param {Number} charIndex Char index
  18071. * @return {Number} Character font size
  18072. */
  18073. getCurrentCharFontSize: function(lineIndex, charIndex) {
  18074. return (
  18075. this.styles[lineIndex] &&
  18076. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)] &&
  18077. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)].fontSize) || this.fontSize;
  18078. },
  18079. /**
  18080. * Returns color (fill) of char at the current cursor
  18081. * @param {Number} lineIndex Line index
  18082. * @param {Number} charIndex Char index
  18083. * @return {String} Character color (fill)
  18084. */
  18085. getCurrentCharColor: function(lineIndex, charIndex) {
  18086. return (
  18087. this.styles[lineIndex] &&
  18088. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)] &&
  18089. this.styles[lineIndex][charIndex === 0 ? 0 : (charIndex - 1)].fill) || this.cursorColor;
  18090. },
  18091. /**
  18092. * Returns cursor boundaries (left, top, leftOffset, topOffset)
  18093. * @private
  18094. * @param {Array} chars Array of characters
  18095. * @param {String} typeOfBoundaries
  18096. */
  18097. _getCursorBoundaries: function(chars, typeOfBoundaries) {
  18098. // left/top are left/top of entire text box
  18099. // leftOffset/topOffset are offset from that left/top point of a text box
  18100. var left = Math.round(this._getLeftOffset()),
  18101. top = this._getTopOffset(),
  18102. offsets = this._getCursorBoundariesOffsets(
  18103. chars, typeOfBoundaries);
  18104. return {
  18105. left: left,
  18106. top: top,
  18107. leftOffset: offsets.left + offsets.lineLeft,
  18108. topOffset: offsets.top
  18109. };
  18110. },
  18111. /**
  18112. * @private
  18113. */
  18114. _getCursorBoundariesOffsets: function(chars, typeOfBoundaries) {
  18115. var lineLeftOffset = 0,
  18116. lineIndex = 0,
  18117. charIndex = 0,
  18118. topOffset = 0,
  18119. leftOffset = 0;
  18120. for (var i = 0; i < this.selectionStart; i++) {
  18121. if (chars[i] === '\n') {
  18122. leftOffset = 0;
  18123. topOffset += this._getHeightOfLine(this.ctx, lineIndex);
  18124. lineIndex++;
  18125. charIndex = 0;
  18126. }
  18127. else {
  18128. leftOffset += this._getWidthOfChar(this.ctx, chars[i], lineIndex, charIndex);
  18129. charIndex++;
  18130. }
  18131. lineLeftOffset = this._getCachedLineOffset(lineIndex);
  18132. }
  18133. if (typeOfBoundaries === 'cursor') {
  18134. topOffset += (1 - this._fontSizeFraction) * this._getHeightOfLine(this.ctx, lineIndex) / this.lineHeight
  18135. - this.getCurrentCharFontSize(lineIndex, charIndex) * (1 - this._fontSizeFraction);
  18136. }
  18137. return {
  18138. top: topOffset,
  18139. left: leftOffset,
  18140. lineLeft: lineLeftOffset
  18141. };
  18142. },
  18143. /**
  18144. * @private
  18145. */
  18146. _getCachedLineOffset: function(lineIndex) {
  18147. var widthOfLine = this._getLineWidth(this.ctx, lineIndex);
  18148. return this.__lineOffsets[lineIndex] ||
  18149. (this.__lineOffsets[lineIndex] = this._getLineLeftOffset(widthOfLine));
  18150. },
  18151. /**
  18152. * Renders cursor
  18153. * @param {Object} boundaries
  18154. * @param {CanvasRenderingContext2D} ctx transformed context to draw on
  18155. */
  18156. renderCursor: function(boundaries, ctx) {
  18157. var cursorLocation = this.get2DCursorLocation(),
  18158. lineIndex = cursorLocation.lineIndex,
  18159. charIndex = cursorLocation.charIndex,
  18160. charHeight = this.getCurrentCharFontSize(lineIndex, charIndex),
  18161. leftOffset = (lineIndex === 0 && charIndex === 0)
  18162. ? this._getCachedLineOffset(lineIndex)
  18163. : boundaries.leftOffset;
  18164. ctx.fillStyle = this.getCurrentCharColor(lineIndex, charIndex);
  18165. ctx.globalAlpha = this.__isMousedown ? 1 : this._currentCursorOpacity;
  18166. ctx.fillRect(
  18167. boundaries.left + leftOffset,
  18168. boundaries.top + boundaries.topOffset,
  18169. this.cursorWidth / this.scaleX,
  18170. charHeight);
  18171. },
  18172. /**
  18173. * Renders text selection
  18174. * @param {Array} chars Array of characters
  18175. * @param {Object} boundaries Object with left/top/leftOffset/topOffset
  18176. * @param {CanvasRenderingContext2D} ctx transformed context to draw on
  18177. */
  18178. renderSelection: function(chars, boundaries, ctx) {
  18179. ctx.fillStyle = this.selectionColor;
  18180. var start = this.get2DCursorLocation(this.selectionStart),
  18181. end = this.get2DCursorLocation(this.selectionEnd),
  18182. startLine = start.lineIndex,
  18183. endLine = end.lineIndex;
  18184. for (var i = startLine; i <= endLine; i++) {
  18185. var lineOffset = this._getCachedLineOffset(i) || 0,
  18186. lineHeight = this._getHeightOfLine(this.ctx, i),
  18187. boxWidth = 0, line = this._textLines[i];
  18188. if (i === startLine) {
  18189. for (var j = 0, len = line.length; j < len; j++) {
  18190. if (j >= start.charIndex && (i !== endLine || j < end.charIndex)) {
  18191. boxWidth += this._getWidthOfChar(ctx, line[j], i, j);
  18192. }
  18193. if (j < start.charIndex) {
  18194. lineOffset += this._getWidthOfChar(ctx, line[j], i, j);
  18195. }
  18196. }
  18197. }
  18198. else if (i > startLine && i < endLine) {
  18199. boxWidth += this._getLineWidth(ctx, i) || 5;
  18200. }
  18201. else if (i === endLine) {
  18202. for (var j2 = 0, j2len = end.charIndex; j2 < j2len; j2++) {
  18203. boxWidth += this._getWidthOfChar(ctx, line[j2], i, j2);
  18204. }
  18205. }
  18206. ctx.fillRect(
  18207. boundaries.left + lineOffset,
  18208. boundaries.top + boundaries.topOffset,
  18209. boxWidth,
  18210. lineHeight);
  18211. boundaries.topOffset += lineHeight;
  18212. }
  18213. },
  18214. /**
  18215. * @private
  18216. * @param {String} method
  18217. * @param {CanvasRenderingContext2D} ctx Context to render on
  18218. */
  18219. _renderChars: function(method, ctx, line, left, top, lineIndex) {
  18220. if (this.isEmptyStyles()) {
  18221. return this._renderCharsFast(method, ctx, line, left, top);
  18222. }
  18223. this.skipTextAlign = true;
  18224. // set proper box offset
  18225. left -= this.textAlign === 'center'
  18226. ? (this.width / 2)
  18227. : (this.textAlign === 'right')
  18228. ? this.width
  18229. : 0;
  18230. // set proper line offset
  18231. var lineHeight = this._getHeightOfLine(ctx, lineIndex),
  18232. lineLeftOffset = this._getCachedLineOffset(lineIndex),
  18233. chars = line.split(''),
  18234. prevStyle,
  18235. charsToRender = '';
  18236. left += lineLeftOffset || 0;
  18237. ctx.save();
  18238. top -= lineHeight / this.lineHeight * this._fontSizeFraction;
  18239. for (var i = 0, len = chars.length; i <= len; i++) {
  18240. prevStyle = prevStyle || this.getCurrentCharStyle(lineIndex, i);
  18241. var thisStyle = this.getCurrentCharStyle(lineIndex, i + 1);
  18242. if (this._hasStyleChanged(prevStyle, thisStyle) || i === len) {
  18243. this._renderChar(method, ctx, lineIndex, i - 1, charsToRender, left, top, lineHeight);
  18244. charsToRender = '';
  18245. prevStyle = thisStyle;
  18246. }
  18247. charsToRender += chars[i];
  18248. }
  18249. ctx.restore();
  18250. },
  18251. /**
  18252. * @private
  18253. * @param {String} method
  18254. * @param {CanvasRenderingContext2D} ctx Context to render on
  18255. * @param {String} line Content of the line
  18256. * @param {Number} left Left coordinate
  18257. * @param {Number} top Top coordinate
  18258. */
  18259. _renderCharsFast: function(method, ctx, line, left, top) {
  18260. this.skipTextAlign = false;
  18261. if (method === 'fillText' && this.fill) {
  18262. this.callSuper('_renderChars', method, ctx, line, left, top);
  18263. }
  18264. if (method === 'strokeText' && ((this.stroke && this.strokeWidth > 0) || this.skipFillStrokeCheck)) {
  18265. this.callSuper('_renderChars', method, ctx, line, left, top);
  18266. }
  18267. },
  18268. /**
  18269. * @private
  18270. * @param {String} method
  18271. * @param {CanvasRenderingContext2D} ctx Context to render on
  18272. * @param {Number} lineIndex
  18273. * @param {Number} i
  18274. * @param {String} _char
  18275. * @param {Number} left Left coordinate
  18276. * @param {Number} top Top coordinate
  18277. * @param {Number} lineHeight Height of the line
  18278. */
  18279. _renderChar: function(method, ctx, lineIndex, i, _char, left, top, lineHeight) {
  18280. var decl, charWidth, charHeight,
  18281. offset = this._fontSizeFraction * lineHeight / this.lineHeight;
  18282. if (this.styles && this.styles[lineIndex] && (decl = this.styles[lineIndex][i])) {
  18283. var shouldStroke = decl.stroke || this.stroke,
  18284. shouldFill = decl.fill || this.fill;
  18285. ctx.save();
  18286. charWidth = this._applyCharStylesGetWidth(ctx, _char, lineIndex, i, decl);
  18287. charHeight = this._getHeightOfChar(ctx, _char, lineIndex, i);
  18288. if (shouldFill) {
  18289. ctx.fillText(_char, left, top);
  18290. }
  18291. if (shouldStroke) {
  18292. ctx.strokeText(_char, left, top);
  18293. }
  18294. this._renderCharDecoration(ctx, decl, left, top, offset, charWidth, charHeight);
  18295. ctx.restore();
  18296. ctx.translate(charWidth, 0);
  18297. }
  18298. else {
  18299. if (method === 'strokeText' && this.stroke) {
  18300. ctx[method](_char, left, top);
  18301. }
  18302. if (method === 'fillText' && this.fill) {
  18303. ctx[method](_char, left, top);
  18304. }
  18305. charWidth = this._applyCharStylesGetWidth(ctx, _char, lineIndex, i);
  18306. this._renderCharDecoration(ctx, null, left, top, offset, charWidth, this.fontSize);
  18307. ctx.translate(ctx.measureText(_char).width, 0);
  18308. }
  18309. },
  18310. /**
  18311. * @private
  18312. * @param {Object} prevStyle
  18313. * @param {Object} thisStyle
  18314. */
  18315. _hasStyleChanged: function(prevStyle, thisStyle) {
  18316. return (prevStyle.fill !== thisStyle.fill ||
  18317. prevStyle.fontSize !== thisStyle.fontSize ||
  18318. prevStyle.textBackgroundColor !== thisStyle.textBackgroundColor ||
  18319. prevStyle.textDecoration !== thisStyle.textDecoration ||
  18320. prevStyle.fontFamily !== thisStyle.fontFamily ||
  18321. prevStyle.fontWeight !== thisStyle.fontWeight ||
  18322. prevStyle.fontStyle !== thisStyle.fontStyle ||
  18323. prevStyle.stroke !== thisStyle.stroke ||
  18324. prevStyle.strokeWidth !== thisStyle.strokeWidth
  18325. );
  18326. },
  18327. /**
  18328. * @private
  18329. * @param {CanvasRenderingContext2D} ctx Context to render on
  18330. */
  18331. _renderCharDecoration: function(ctx, styleDeclaration, left, top, offset, charWidth, charHeight) {
  18332. var textDecoration = styleDeclaration
  18333. ? (styleDeclaration.textDecoration || this.textDecoration)
  18334. : this.textDecoration;
  18335. if (!textDecoration) {
  18336. return;
  18337. }
  18338. if (textDecoration.indexOf('underline') > -1) {
  18339. ctx.fillRect(
  18340. left,
  18341. top + charHeight / 10,
  18342. charWidth ,
  18343. charHeight / 15
  18344. );
  18345. }
  18346. if (textDecoration.indexOf('line-through') > -1) {
  18347. ctx.fillRect(
  18348. left,
  18349. top - charHeight * (this._fontSizeFraction + this._fontSizeMult - 1) + charHeight / 15,
  18350. charWidth,
  18351. charHeight / 15
  18352. );
  18353. }
  18354. if (textDecoration.indexOf('overline') > -1) {
  18355. ctx.fillRect(
  18356. left,
  18357. top - (this._fontSizeMult - this._fontSizeFraction) * charHeight,
  18358. charWidth,
  18359. charHeight / 15
  18360. );
  18361. }
  18362. },
  18363. /**
  18364. * @private
  18365. * @param {String} method
  18366. * @param {CanvasRenderingContext2D} ctx Context to render on
  18367. * @param {String} line
  18368. */
  18369. _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
  18370. // to "cancel" this.fontSize subtraction in fabric.Text#_renderTextLine
  18371. // the adding 0.03 is just to align text with itext by overlap test
  18372. if (!this.isEmptyStyles()) {
  18373. top += this.fontSize * (this._fontSizeFraction + 0.03);
  18374. }
  18375. this.callSuper('_renderTextLine', method, ctx, line, left, top, lineIndex);
  18376. },
  18377. /**
  18378. * @private
  18379. * @param {CanvasRenderingContext2D} ctx Context to render on
  18380. */
  18381. _renderTextDecoration: function(ctx) {
  18382. if (this.isEmptyStyles()) {
  18383. return this.callSuper('_renderTextDecoration', ctx);
  18384. }
  18385. },
  18386. /**
  18387. * @private
  18388. * @param {CanvasRenderingContext2D} ctx Context to render on
  18389. */
  18390. _renderTextLinesBackground: function(ctx) {
  18391. if (!this.textBackgroundColor && !this.styles) {
  18392. return;
  18393. }
  18394. ctx.save();
  18395. if (this.textBackgroundColor) {
  18396. ctx.fillStyle = this.textBackgroundColor;
  18397. }
  18398. var lineHeights = 0;
  18399. for (var i = 0, len = this._textLines.length; i < len; i++) {
  18400. var heightOfLine = this._getHeightOfLine(ctx, i);
  18401. if (this._textLines[i] === '') {
  18402. lineHeights += heightOfLine;
  18403. continue;
  18404. }
  18405. var lineWidth = this._getLineWidth(ctx, i),
  18406. lineLeftOffset = this._getCachedLineOffset(i);
  18407. if (this.textBackgroundColor) {
  18408. ctx.fillStyle = this.textBackgroundColor;
  18409. ctx.fillRect(
  18410. this._getLeftOffset() + lineLeftOffset,
  18411. this._getTopOffset() + lineHeights,
  18412. lineWidth,
  18413. heightOfLine / this.lineHeight
  18414. );
  18415. }
  18416. if (this.styles[i]) {
  18417. for (var j = 0, jlen = this._textLines[i].length; j < jlen; j++) {
  18418. if (this.styles[i] && this.styles[i][j] && this.styles[i][j].textBackgroundColor) {
  18419. var _char = this._textLines[i][j];
  18420. ctx.fillStyle = this.styles[i][j].textBackgroundColor;
  18421. ctx.fillRect(
  18422. this._getLeftOffset() + lineLeftOffset + this._getWidthOfCharsAt(ctx, i, j),
  18423. this._getTopOffset() + lineHeights,
  18424. this._getWidthOfChar(ctx, _char, i, j) + 1,
  18425. heightOfLine / this.lineHeight
  18426. );
  18427. }
  18428. }
  18429. }
  18430. lineHeights += heightOfLine;
  18431. }
  18432. ctx.restore();
  18433. },
  18434. /**
  18435. * @private
  18436. */
  18437. _getCacheProp: function(_char, styleDeclaration) {
  18438. return _char +
  18439. styleDeclaration.fontFamily +
  18440. styleDeclaration.fontSize +
  18441. styleDeclaration.fontWeight +
  18442. styleDeclaration.fontStyle +
  18443. styleDeclaration.shadow;
  18444. },
  18445. /**
  18446. * @private
  18447. * @param {CanvasRenderingContext2D} ctx Context to render on
  18448. * @param {String} _char
  18449. * @param {Number} lineIndex
  18450. * @param {Number} charIndex
  18451. * @param {Object} [decl]
  18452. */
  18453. _applyCharStylesGetWidth: function(ctx, _char, lineIndex, charIndex, decl) {
  18454. var styleDeclaration = decl ||
  18455. (this.styles[lineIndex] &&
  18456. this.styles[lineIndex][charIndex]);
  18457. if (styleDeclaration) {
  18458. // cloning so that original style object is not polluted with following font declarations
  18459. styleDeclaration = clone(styleDeclaration);
  18460. }
  18461. else {
  18462. styleDeclaration = { };
  18463. }
  18464. this._applyFontStyles(styleDeclaration);
  18465. var cacheProp = this._getCacheProp(_char, styleDeclaration);
  18466. // short-circuit if no styles
  18467. if (this.isEmptyStyles() && this._charWidthsCache[cacheProp] && this.caching) {
  18468. return this._charWidthsCache[cacheProp];
  18469. }
  18470. if (typeof styleDeclaration.shadow === 'string') {
  18471. styleDeclaration.shadow = new fabric.Shadow(styleDeclaration.shadow);
  18472. }
  18473. var fill = styleDeclaration.fill || this.fill;
  18474. ctx.fillStyle = fill.toLive
  18475. ? fill.toLive(ctx, this)
  18476. : fill;
  18477. if (styleDeclaration.stroke) {
  18478. ctx.strokeStyle = (styleDeclaration.stroke && styleDeclaration.stroke.toLive)
  18479. ? styleDeclaration.stroke.toLive(ctx, this)
  18480. : styleDeclaration.stroke;
  18481. }
  18482. ctx.lineWidth = styleDeclaration.strokeWidth || this.strokeWidth;
  18483. ctx.font = this._getFontDeclaration.call(styleDeclaration);
  18484. this._setShadow.call(styleDeclaration, ctx);
  18485. if (!this.caching) {
  18486. return ctx.measureText(_char).width;
  18487. }
  18488. if (!this._charWidthsCache[cacheProp]) {
  18489. this._charWidthsCache[cacheProp] = ctx.measureText(_char).width;
  18490. }
  18491. return this._charWidthsCache[cacheProp];
  18492. },
  18493. /**
  18494. * @private
  18495. * @param {Object} styleDeclaration
  18496. */
  18497. _applyFontStyles: function(styleDeclaration) {
  18498. if (!styleDeclaration.fontFamily) {
  18499. styleDeclaration.fontFamily = this.fontFamily;
  18500. }
  18501. if (!styleDeclaration.fontSize) {
  18502. styleDeclaration.fontSize = this.fontSize;
  18503. }
  18504. if (!styleDeclaration.fontWeight) {
  18505. styleDeclaration.fontWeight = this.fontWeight;
  18506. }
  18507. if (!styleDeclaration.fontStyle) {
  18508. styleDeclaration.fontStyle = this.fontStyle;
  18509. }
  18510. },
  18511. /**
  18512. * @private
  18513. * @param {Number} lineIndex
  18514. * @param {Number} charIndex
  18515. */
  18516. _getStyleDeclaration: function(lineIndex, charIndex) {
  18517. return (this.styles[lineIndex] && this.styles[lineIndex][charIndex])
  18518. ? clone(this.styles[lineIndex][charIndex])
  18519. : { };
  18520. },
  18521. /**
  18522. * @private
  18523. * @param {CanvasRenderingContext2D} ctx Context to render on
  18524. */
  18525. _getWidthOfChar: function(ctx, _char, lineIndex, charIndex) {
  18526. if (this.textAlign === 'justify' && /\s/.test(_char)) {
  18527. return this._getWidthOfSpace(ctx, lineIndex);
  18528. }
  18529. var styleDeclaration = this._getStyleDeclaration(lineIndex, charIndex);
  18530. this._applyFontStyles(styleDeclaration);
  18531. var cacheProp = this._getCacheProp(_char, styleDeclaration);
  18532. if (this._charWidthsCache[cacheProp] && this.caching) {
  18533. return this._charWidthsCache[cacheProp];
  18534. }
  18535. else if (ctx) {
  18536. ctx.save();
  18537. var width = this._applyCharStylesGetWidth(ctx, _char, lineIndex, charIndex);
  18538. ctx.restore();
  18539. return width;
  18540. }
  18541. },
  18542. /**
  18543. * @private
  18544. * @param {CanvasRenderingContext2D} ctx Context to render on
  18545. */
  18546. _getHeightOfChar: function(ctx, _char, lineIndex, charIndex) {
  18547. if (this.styles[lineIndex] && this.styles[lineIndex][charIndex]) {
  18548. return this.styles[lineIndex][charIndex].fontSize || this.fontSize;
  18549. }
  18550. return this.fontSize;
  18551. },
  18552. /**
  18553. * @private
  18554. * @param {CanvasRenderingContext2D} ctx Context to render on
  18555. */
  18556. _getHeightOfCharAt: function(ctx, lineIndex, charIndex) {
  18557. var _char = this._textLines[lineIndex][charIndex];
  18558. return this._getHeightOfChar(ctx, _char, lineIndex, charIndex);
  18559. },
  18560. /**
  18561. * @private
  18562. * @param {CanvasRenderingContext2D} ctx Context to render on
  18563. */
  18564. _getWidthOfCharsAt: function(ctx, lineIndex, charIndex) {
  18565. var width = 0, i, _char;
  18566. for (i = 0; i < charIndex; i++) {
  18567. _char = this._textLines[lineIndex][i];
  18568. width += this._getWidthOfChar(ctx, _char, lineIndex, i);
  18569. }
  18570. return width;
  18571. },
  18572. /**
  18573. * @private
  18574. * @param {CanvasRenderingContext2D} ctx Context to render on
  18575. */
  18576. _getLineWidth: function(ctx, lineIndex) {
  18577. if (this.__lineWidths[lineIndex]) {
  18578. return this.__lineWidths[lineIndex];
  18579. }
  18580. this.__lineWidths[lineIndex] = this._getWidthOfCharsAt(ctx, lineIndex, this._textLines[lineIndex].length);
  18581. return this.__lineWidths[lineIndex];
  18582. },
  18583. /**
  18584. * @private
  18585. * @param {CanvasRenderingContext2D} ctx Context to render on
  18586. * @param {Number} lineIndex
  18587. */
  18588. _getWidthOfSpace: function (ctx, lineIndex) {
  18589. if (this.__widthOfSpace[lineIndex]) {
  18590. return this.__widthOfSpace[lineIndex];
  18591. }
  18592. var line = this._textLines[lineIndex],
  18593. wordsWidth = this._getWidthOfWords(ctx, line, lineIndex),
  18594. widthDiff = this.width - wordsWidth,
  18595. numSpaces = line.length - line.replace(/\s+/g, '').length,
  18596. width = widthDiff / numSpaces;
  18597. this.__widthOfSpace[lineIndex] = width;
  18598. return width;
  18599. },
  18600. /**
  18601. * @private
  18602. * @param {CanvasRenderingContext2D} ctx Context to render on
  18603. * @param {Number} line
  18604. * @param {Number} lineIndex
  18605. */
  18606. _getWidthOfWords: function (ctx, line, lineIndex) {
  18607. var width = 0;
  18608. for (var charIndex = 0; charIndex < line.length; charIndex++) {
  18609. var _char = line[charIndex];
  18610. if (!_char.match(/\s/)) {
  18611. width += this._getWidthOfChar(ctx, _char, lineIndex, charIndex);
  18612. }
  18613. }
  18614. return width;
  18615. },
  18616. /**
  18617. * @private
  18618. * @param {CanvasRenderingContext2D} ctx Context to render on
  18619. */
  18620. _getHeightOfLine: function(ctx, lineIndex) {
  18621. if (this.__lineHeights[lineIndex]) {
  18622. return this.__lineHeights[lineIndex];
  18623. }
  18624. var line = this._textLines[lineIndex],
  18625. maxHeight = this._getHeightOfChar(ctx, line[0], lineIndex, 0);
  18626. for (var i = 1, len = line.length; i < len; i++) {
  18627. var currentCharHeight = this._getHeightOfChar(ctx, line[i], lineIndex, i);
  18628. if (currentCharHeight > maxHeight) {
  18629. maxHeight = currentCharHeight;
  18630. }
  18631. }
  18632. this.__maxFontHeights[lineIndex] = maxHeight;
  18633. this.__lineHeights[lineIndex] = maxHeight * this.lineHeight * this._fontSizeMult;
  18634. return this.__lineHeights[lineIndex];
  18635. },
  18636. /**
  18637. * @private
  18638. * @param {CanvasRenderingContext2D} ctx Context to render on
  18639. */
  18640. _getTextHeight: function(ctx) {
  18641. var height = 0;
  18642. for (var i = 0, len = this._textLines.length; i < len; i++) {
  18643. height += this._getHeightOfLine(ctx, i);
  18644. }
  18645. return height;
  18646. },
  18647. /**
  18648. * This method is overwritten to account for different top offset
  18649. * @private
  18650. */
  18651. _renderTextBoxBackground: function(ctx) {
  18652. if (!this.backgroundColor) {
  18653. return;
  18654. }
  18655. ctx.save();
  18656. ctx.fillStyle = this.backgroundColor;
  18657. ctx.fillRect(
  18658. this._getLeftOffset(),
  18659. this._getTopOffset(),
  18660. this.width,
  18661. this.height
  18662. );
  18663. ctx.restore();
  18664. },
  18665. /**
  18666. * Returns object representation of an instance
  18667. * @method toObject
  18668. * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
  18669. * @return {Object} object representation of an instance
  18670. */
  18671. toObject: function(propertiesToInclude) {
  18672. return fabric.util.object.extend(this.callSuper('toObject', propertiesToInclude), {
  18673. styles: clone(this.styles)
  18674. });
  18675. }
  18676. });
  18677. /**
  18678. * Returns fabric.IText instance from an object representation
  18679. * @static
  18680. * @memberOf fabric.IText
  18681. * @param {Object} object Object to create an instance from
  18682. * @return {fabric.IText} instance of fabric.IText
  18683. */
  18684. fabric.IText.fromObject = function(object) {
  18685. return new fabric.IText(object.text, clone(object));
  18686. };
  18687. })();
  18688. (function() {
  18689. var clone = fabric.util.object.clone;
  18690. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  18691. /**
  18692. * Initializes all the interactive behavior of IText
  18693. */
  18694. initBehavior: function() {
  18695. this.initAddedHandler();
  18696. this.initRemovedHandler();
  18697. this.initCursorSelectionHandlers();
  18698. this.initDoubleClickSimulation();
  18699. },
  18700. /**
  18701. * Initializes "selected" event handler
  18702. */
  18703. initSelectedHandler: function() {
  18704. this.on('selected', function() {
  18705. var _this = this;
  18706. setTimeout(function() {
  18707. _this.selected = true;
  18708. }, 100);
  18709. });
  18710. },
  18711. /**
  18712. * Initializes "added" event handler
  18713. */
  18714. initAddedHandler: function() {
  18715. var _this = this;
  18716. this.on('added', function() {
  18717. if (this.canvas && !this.canvas._hasITextHandlers) {
  18718. this.canvas._hasITextHandlers = true;
  18719. this._initCanvasHandlers();
  18720. }
  18721. // Track IText instances per-canvas. Only register in this array once added
  18722. // to a canvas; we don't want to leak a reference to the instance forever
  18723. // simply because it existed at some point.
  18724. //
  18725. // (Might be added to a collection, but not on a canvas.)
  18726. if (_this.canvas) {
  18727. _this.canvas._iTextInstances = _this.canvas._iTextInstances || [];
  18728. _this.canvas._iTextInstances.push(_this);
  18729. }
  18730. });
  18731. },
  18732. initRemovedHandler: function() {
  18733. var _this = this;
  18734. this.on('removed', function() {
  18735. // (Might be removed from a collection, but not on a canvas.)
  18736. if (_this.canvas) {
  18737. _this.canvas._iTextInstances = _this.canvas._iTextInstances || [];
  18738. fabric.util.removeFromArray(_this.canvas._iTextInstances, _this);
  18739. }
  18740. });
  18741. },
  18742. /**
  18743. * @private
  18744. */
  18745. _initCanvasHandlers: function() {
  18746. var _this = this;
  18747. this.canvas.on('selection:cleared', function() {
  18748. fabric.IText.prototype.exitEditingOnOthers(_this.canvas);
  18749. });
  18750. this.canvas.on('mouse:up', function() {
  18751. if (_this.canvas._iTextInstances) {
  18752. _this.canvas._iTextInstances.forEach(function(obj) {
  18753. obj.__isMousedown = false;
  18754. });
  18755. }
  18756. });
  18757. this.canvas.on('object:selected', function() {
  18758. fabric.IText.prototype.exitEditingOnOthers(_this.canvas);
  18759. });
  18760. },
  18761. /**
  18762. * @private
  18763. */
  18764. _tick: function() {
  18765. this._currentTickState = this._animateCursor(this, 1, this.cursorDuration, '_onTickComplete');
  18766. },
  18767. /**
  18768. * @private
  18769. */
  18770. _animateCursor: function(obj, targetOpacity, duration, completeMethod) {
  18771. var tickState;
  18772. tickState = {
  18773. isAborted: false,
  18774. abort: function() {
  18775. this.isAborted = true;
  18776. },
  18777. };
  18778. obj.animate('_currentCursorOpacity', targetOpacity, {
  18779. duration: duration,
  18780. onComplete: function() {
  18781. if (!tickState.isAborted) {
  18782. obj[completeMethod]();
  18783. }
  18784. },
  18785. onChange: function() {
  18786. if (obj.canvas) {
  18787. obj.canvas.clearContext(obj.canvas.contextTop || obj.ctx);
  18788. obj.renderCursorOrSelection();
  18789. }
  18790. },
  18791. abort: function() {
  18792. return tickState.isAborted;
  18793. }
  18794. });
  18795. return tickState;
  18796. },
  18797. /**
  18798. * @private
  18799. */
  18800. _onTickComplete: function() {
  18801. var _this = this;
  18802. if (this._cursorTimeout1) {
  18803. clearTimeout(this._cursorTimeout1);
  18804. }
  18805. this._cursorTimeout1 = setTimeout(function() {
  18806. _this._currentTickCompleteState = _this._animateCursor(_this, 0, this.cursorDuration / 2, '_tick');
  18807. }, 100);
  18808. },
  18809. /**
  18810. * Initializes delayed cursor
  18811. */
  18812. initDelayedCursor: function(restart) {
  18813. var _this = this,
  18814. delay = restart ? 0 : this.cursorDelay;
  18815. this._currentTickState && this._currentTickState.abort();
  18816. this._currentTickCompleteState && this._currentTickCompleteState.abort();
  18817. clearTimeout(this._cursorTimeout1);
  18818. this._currentCursorOpacity = 1;
  18819. if (this.canvas) {
  18820. this.canvas.clearContext(this.canvas.contextTop || this.ctx);
  18821. this.renderCursorOrSelection();
  18822. }
  18823. if (this._cursorTimeout2) {
  18824. clearTimeout(this._cursorTimeout2);
  18825. }
  18826. this._cursorTimeout2 = setTimeout(function() {
  18827. _this._tick();
  18828. }, delay);
  18829. },
  18830. /**
  18831. * Aborts cursor animation and clears all timeouts
  18832. */
  18833. abortCursorAnimation: function() {
  18834. this._currentTickState && this._currentTickState.abort();
  18835. this._currentTickCompleteState && this._currentTickCompleteState.abort();
  18836. clearTimeout(this._cursorTimeout1);
  18837. clearTimeout(this._cursorTimeout2);
  18838. this._currentCursorOpacity = 0;
  18839. this.canvas && this.canvas.clearContext(this.canvas.contextTop || this.ctx);
  18840. },
  18841. /**
  18842. * Selects entire text
  18843. */
  18844. selectAll: function() {
  18845. this.setSelectionStart(0);
  18846. this.setSelectionEnd(this.text.length);
  18847. },
  18848. /**
  18849. * Returns selected text
  18850. * @return {String}
  18851. */
  18852. getSelectedText: function() {
  18853. return this.text.slice(this.selectionStart, this.selectionEnd);
  18854. },
  18855. /**
  18856. * Find new selection index representing start of current word according to current selection index
  18857. * @param {Number} startFrom Surrent selection index
  18858. * @return {Number} New selection index
  18859. */
  18860. findWordBoundaryLeft: function(startFrom) {
  18861. var offset = 0, index = startFrom - 1;
  18862. // remove space before cursor first
  18863. if (this._reSpace.test(this.text.charAt(index))) {
  18864. while (this._reSpace.test(this.text.charAt(index))) {
  18865. offset++;
  18866. index--;
  18867. }
  18868. }
  18869. while (/\S/.test(this.text.charAt(index)) && index > -1) {
  18870. offset++;
  18871. index--;
  18872. }
  18873. return startFrom - offset;
  18874. },
  18875. /**
  18876. * Find new selection index representing end of current word according to current selection index
  18877. * @param {Number} startFrom Current selection index
  18878. * @return {Number} New selection index
  18879. */
  18880. findWordBoundaryRight: function(startFrom) {
  18881. var offset = 0, index = startFrom;
  18882. // remove space after cursor first
  18883. if (this._reSpace.test(this.text.charAt(index))) {
  18884. while (this._reSpace.test(this.text.charAt(index))) {
  18885. offset++;
  18886. index++;
  18887. }
  18888. }
  18889. while (/\S/.test(this.text.charAt(index)) && index < this.text.length) {
  18890. offset++;
  18891. index++;
  18892. }
  18893. return startFrom + offset;
  18894. },
  18895. /**
  18896. * Find new selection index representing start of current line according to current selection index
  18897. * @param {Number} startFrom Current selection index
  18898. * @return {Number} New selection index
  18899. */
  18900. findLineBoundaryLeft: function(startFrom) {
  18901. var offset = 0, index = startFrom - 1;
  18902. while (!/\n/.test(this.text.charAt(index)) && index > -1) {
  18903. offset++;
  18904. index--;
  18905. }
  18906. return startFrom - offset;
  18907. },
  18908. /**
  18909. * Find new selection index representing end of current line according to current selection index
  18910. * @param {Number} startFrom Current selection index
  18911. * @return {Number} New selection index
  18912. */
  18913. findLineBoundaryRight: function(startFrom) {
  18914. var offset = 0, index = startFrom;
  18915. while (!/\n/.test(this.text.charAt(index)) && index < this.text.length) {
  18916. offset++;
  18917. index++;
  18918. }
  18919. return startFrom + offset;
  18920. },
  18921. /**
  18922. * Returns number of newlines in selected text
  18923. * @return {Number} Number of newlines in selected text
  18924. */
  18925. getNumNewLinesInSelectedText: function() {
  18926. var selectedText = this.getSelectedText(),
  18927. numNewLines = 0;
  18928. for (var i = 0, chars = selectedText.split(''), len = chars.length; i < len; i++) {
  18929. if (chars[i] === '\n') {
  18930. numNewLines++;
  18931. }
  18932. }
  18933. return numNewLines;
  18934. },
  18935. /**
  18936. * Finds index corresponding to beginning or end of a word
  18937. * @param {Number} selectionStart Index of a character
  18938. * @param {Number} direction: 1 or -1
  18939. * @return {Number} Index of the beginning or end of a word
  18940. */
  18941. searchWordBoundary: function(selectionStart, direction) {
  18942. var index = this._reSpace.test(this.text.charAt(selectionStart)) ? selectionStart - 1 : selectionStart,
  18943. _char = this.text.charAt(index),
  18944. reNonWord = /[ \n\.,;!\?\-]/;
  18945. while (!reNonWord.test(_char) && index > 0 && index < this.text.length) {
  18946. index += direction;
  18947. _char = this.text.charAt(index);
  18948. }
  18949. if (reNonWord.test(_char) && _char !== '\n') {
  18950. index += direction === 1 ? 0 : 1;
  18951. }
  18952. return index;
  18953. },
  18954. /**
  18955. * Selects a word based on the index
  18956. * @param {Number} selectionStart Index of a character
  18957. */
  18958. selectWord: function(selectionStart) {
  18959. var newSelectionStart = this.searchWordBoundary(selectionStart, -1), /* search backwards */
  18960. newSelectionEnd = this.searchWordBoundary(selectionStart, 1); /* search forward */
  18961. this.setSelectionStart(newSelectionStart);
  18962. this.setSelectionEnd(newSelectionEnd);
  18963. },
  18964. /**
  18965. * Selects a line based on the index
  18966. * @param {Number} selectionStart Index of a character
  18967. */
  18968. selectLine: function(selectionStart) {
  18969. var newSelectionStart = this.findLineBoundaryLeft(selectionStart),
  18970. newSelectionEnd = this.findLineBoundaryRight(selectionStart);
  18971. this.setSelectionStart(newSelectionStart);
  18972. this.setSelectionEnd(newSelectionEnd);
  18973. },
  18974. /**
  18975. * Enters editing state
  18976. * @return {fabric.IText} thisArg
  18977. * @chainable
  18978. */
  18979. enterEditing: function() {
  18980. if (this.isEditing || !this.editable) {
  18981. return;
  18982. }
  18983. if (this.canvas) {
  18984. this.exitEditingOnOthers(this.canvas);
  18985. }
  18986. this.isEditing = true;
  18987. this.initHiddenTextarea();
  18988. this.hiddenTextarea.focus();
  18989. this._updateTextarea();
  18990. this._saveEditingProps();
  18991. this._setEditingProps();
  18992. this._tick();
  18993. this.fire('editing:entered');
  18994. if (!this.canvas) {
  18995. return this;
  18996. }
  18997. this.canvas.renderAll();
  18998. this.canvas.fire('text:editing:entered', { target: this });
  18999. this.initMouseMoveHandler();
  19000. return this;
  19001. },
  19002. exitEditingOnOthers: function(canvas) {
  19003. if (canvas._iTextInstances) {
  19004. canvas._iTextInstances.forEach(function(obj) {
  19005. obj.selected = false;
  19006. if (obj.isEditing) {
  19007. obj.exitEditing();
  19008. }
  19009. });
  19010. }
  19011. },
  19012. /**
  19013. * Initializes "mousemove" event handler
  19014. */
  19015. initMouseMoveHandler: function() {
  19016. var _this = this;
  19017. this.canvas.on('mouse:move', function(options) {
  19018. if (!_this.__isMousedown || !_this.isEditing) {
  19019. return;
  19020. }
  19021. var newSelectionStart = _this.getSelectionStartFromPointer(options.e);
  19022. if (newSelectionStart >= _this.__selectionStartOnMouseDown) {
  19023. _this.setSelectionStart(_this.__selectionStartOnMouseDown);
  19024. _this.setSelectionEnd(newSelectionStart);
  19025. }
  19026. else {
  19027. _this.setSelectionStart(newSelectionStart);
  19028. _this.setSelectionEnd(_this.__selectionStartOnMouseDown);
  19029. }
  19030. });
  19031. },
  19032. /**
  19033. * @private
  19034. */
  19035. _setEditingProps: function() {
  19036. this.hoverCursor = 'text';
  19037. if (this.canvas) {
  19038. this.canvas.defaultCursor = this.canvas.moveCursor = 'text';
  19039. }
  19040. this.borderColor = this.editingBorderColor;
  19041. this.hasControls = this.selectable = false;
  19042. this.lockMovementX = this.lockMovementY = true;
  19043. },
  19044. /**
  19045. * @private
  19046. */
  19047. _updateTextarea: function() {
  19048. if (!this.hiddenTextarea) {
  19049. return;
  19050. }
  19051. this.hiddenTextarea.value = this.text;
  19052. this.hiddenTextarea.selectionStart = this.selectionStart;
  19053. this.hiddenTextarea.selectionEnd = this.selectionEnd;
  19054. },
  19055. /**
  19056. * @private
  19057. */
  19058. _saveEditingProps: function() {
  19059. this._savedProps = {
  19060. hasControls: this.hasControls,
  19061. borderColor: this.borderColor,
  19062. lockMovementX: this.lockMovementX,
  19063. lockMovementY: this.lockMovementY,
  19064. hoverCursor: this.hoverCursor,
  19065. defaultCursor: this.canvas && this.canvas.defaultCursor,
  19066. moveCursor: this.canvas && this.canvas.moveCursor
  19067. };
  19068. },
  19069. /**
  19070. * @private
  19071. */
  19072. _restoreEditingProps: function() {
  19073. if (!this._savedProps) {
  19074. return;
  19075. }
  19076. this.hoverCursor = this._savedProps.overCursor;
  19077. this.hasControls = this._savedProps.hasControls;
  19078. this.borderColor = this._savedProps.borderColor;
  19079. this.lockMovementX = this._savedProps.lockMovementX;
  19080. this.lockMovementY = this._savedProps.lockMovementY;
  19081. if (this.canvas) {
  19082. this.canvas.defaultCursor = this._savedProps.defaultCursor;
  19083. this.canvas.moveCursor = this._savedProps.moveCursor;
  19084. }
  19085. },
  19086. /**
  19087. * Exits from editing state
  19088. * @return {fabric.IText} thisArg
  19089. * @chainable
  19090. */
  19091. exitEditing: function() {
  19092. this.selected = false;
  19093. this.isEditing = false;
  19094. this.selectable = true;
  19095. this.selectionEnd = this.selectionStart;
  19096. this.hiddenTextarea && this.canvas && this.hiddenTextarea.parentNode.removeChild(this.hiddenTextarea);
  19097. this.hiddenTextarea = null;
  19098. this.abortCursorAnimation();
  19099. this._restoreEditingProps();
  19100. this._currentCursorOpacity = 0;
  19101. this.fire('editing:exited');
  19102. this.canvas && this.canvas.fire('text:editing:exited', { target: this });
  19103. return this;
  19104. },
  19105. /**
  19106. * @private
  19107. */
  19108. _removeExtraneousStyles: function() {
  19109. for (var prop in this.styles) {
  19110. if (!this._textLines[prop]) {
  19111. delete this.styles[prop];
  19112. }
  19113. }
  19114. },
  19115. /**
  19116. * @private
  19117. */
  19118. _removeCharsFromTo: function(start, end) {
  19119. var i = end;
  19120. while (i !== start) {
  19121. var prevIndex = this.get2DCursorLocation(i).charIndex;
  19122. i--;
  19123. var index = this.get2DCursorLocation(i).charIndex,
  19124. isNewline = index > prevIndex;
  19125. if (isNewline) {
  19126. this.removeStyleObject(isNewline, i + 1);
  19127. }
  19128. else {
  19129. this.removeStyleObject(this.get2DCursorLocation(i).charIndex === 0, i);
  19130. }
  19131. }
  19132. this.text = this.text.slice(0, start) +
  19133. this.text.slice(end);
  19134. this._clearCache();
  19135. },
  19136. /**
  19137. * Inserts a character where cursor is (replacing selection if one exists)
  19138. * @param {String} _chars Characters to insert
  19139. */
  19140. insertChars: function(_chars, useCopiedStyle) {
  19141. var isEndOfLine = this.text.slice(this.selectionStart, this.selectionStart + 1) === '\n';
  19142. this.text = this.text.slice(0, this.selectionStart) +
  19143. _chars +
  19144. this.text.slice(this.selectionEnd);
  19145. if (this.selectionStart === this.selectionEnd) {
  19146. this.insertStyleObjects(_chars, isEndOfLine, useCopiedStyle);
  19147. }
  19148. // else if (this.selectionEnd - this.selectionStart > 1) {
  19149. // TODO: replace styles properly
  19150. // console.log('replacing MORE than 1 char');
  19151. // }
  19152. this.setSelectionStart(this.selectionStart + _chars.length);
  19153. this.setSelectionEnd(this.selectionStart);
  19154. this._clearCache();
  19155. this.canvas && this.canvas.renderAll();
  19156. this.setCoords();
  19157. this.fire('changed');
  19158. this.canvas && this.canvas.fire('text:changed', { target: this });
  19159. },
  19160. /**
  19161. * Inserts new style object
  19162. * @param {Number} lineIndex Index of a line
  19163. * @param {Number} charIndex Index of a char
  19164. * @param {Boolean} isEndOfLine True if it's end of line
  19165. */
  19166. insertNewlineStyleObject: function(lineIndex, charIndex, isEndOfLine) {
  19167. this.shiftLineStyles(lineIndex, +1);
  19168. if (!this.styles[lineIndex + 1]) {
  19169. this.styles[lineIndex + 1] = { };
  19170. }
  19171. var currentCharStyle = this.styles[lineIndex][charIndex - 1],
  19172. newLineStyles = { };
  19173. // if there's nothing after cursor,
  19174. // we clone current char style onto the next (otherwise empty) line
  19175. if (isEndOfLine) {
  19176. newLineStyles[0] = clone(currentCharStyle);
  19177. this.styles[lineIndex + 1] = newLineStyles;
  19178. }
  19179. // otherwise we clone styles of all chars
  19180. // after cursor onto the next line, from the beginning
  19181. else {
  19182. for (var index in this.styles[lineIndex]) {
  19183. if (parseInt(index, 10) >= charIndex) {
  19184. newLineStyles[parseInt(index, 10) - charIndex] = this.styles[lineIndex][index];
  19185. // remove lines from the previous line since they're on a new line now
  19186. delete this.styles[lineIndex][index];
  19187. }
  19188. }
  19189. this.styles[lineIndex + 1] = newLineStyles;
  19190. }
  19191. this._clearCache();
  19192. },
  19193. /**
  19194. * Inserts style object for a given line/char index
  19195. * @param {Number} lineIndex Index of a line
  19196. * @param {Number} charIndex Index of a char
  19197. * @param {Object} [style] Style object to insert, if given
  19198. */
  19199. insertCharStyleObject: function(lineIndex, charIndex, style) {
  19200. var currentLineStyles = this.styles[lineIndex],
  19201. currentLineStylesCloned = clone(currentLineStyles);
  19202. if (charIndex === 0 && !style) {
  19203. charIndex = 1;
  19204. }
  19205. // shift all char styles by 1 forward
  19206. // 0,1,2,3 -> (charIndex=2) -> 0,1,3,4 -> (insert 2) -> 0,1,2,3,4
  19207. for (var index in currentLineStylesCloned) {
  19208. var numericIndex = parseInt(index, 10);
  19209. if (numericIndex >= charIndex) {
  19210. currentLineStyles[numericIndex + 1] = currentLineStylesCloned[numericIndex];
  19211. //delete currentLineStyles[index];
  19212. }
  19213. }
  19214. this.styles[lineIndex][charIndex] =
  19215. style || clone(currentLineStyles[charIndex - 1]);
  19216. this._clearCache();
  19217. },
  19218. /**
  19219. * Inserts style object(s)
  19220. * @param {String} _chars Characters at the location where style is inserted
  19221. * @param {Boolean} isEndOfLine True if it's end of line
  19222. * @param {Boolean} [useCopiedStyle] Style to insert
  19223. */
  19224. insertStyleObjects: function(_chars, isEndOfLine, useCopiedStyle) {
  19225. // removed shortcircuit over isEmptyStyles
  19226. var cursorLocation = this.get2DCursorLocation(),
  19227. lineIndex = cursorLocation.lineIndex,
  19228. charIndex = cursorLocation.charIndex;
  19229. if (!this.styles[lineIndex]) {
  19230. this.styles[lineIndex] = { };
  19231. }
  19232. if (_chars === '\n') {
  19233. this.insertNewlineStyleObject(lineIndex, charIndex, isEndOfLine);
  19234. }
  19235. else {
  19236. if (useCopiedStyle) {
  19237. this._insertStyles(this.copiedStyles);
  19238. }
  19239. else {
  19240. // TODO: support multiple style insertion if _chars.length > 1
  19241. this.insertCharStyleObject(lineIndex, charIndex);
  19242. }
  19243. }
  19244. },
  19245. /**
  19246. * @private
  19247. */
  19248. _insertStyles: function(styles) {
  19249. for (var i = 0, len = styles.length; i < len; i++) {
  19250. var cursorLocation = this.get2DCursorLocation(this.selectionStart + i),
  19251. lineIndex = cursorLocation.lineIndex,
  19252. charIndex = cursorLocation.charIndex;
  19253. this.insertCharStyleObject(lineIndex, charIndex, styles[i]);
  19254. }
  19255. },
  19256. /**
  19257. * Shifts line styles up or down
  19258. * @param {Number} lineIndex Index of a line
  19259. * @param {Number} offset Can be -1 or +1
  19260. */
  19261. shiftLineStyles: function(lineIndex, offset) {
  19262. // shift all line styles by 1 upward
  19263. var clonedStyles = clone(this.styles);
  19264. for (var line in this.styles) {
  19265. var numericLine = parseInt(line, 10);
  19266. if (numericLine > lineIndex) {
  19267. this.styles[numericLine + offset] = clonedStyles[numericLine];
  19268. }
  19269. }
  19270. },
  19271. /**
  19272. * Removes style object
  19273. * @param {Boolean} isBeginningOfLine True if cursor is at the beginning of line
  19274. * @param {Number} [index] Optional index. When not given, current selectionStart is used.
  19275. */
  19276. removeStyleObject: function(isBeginningOfLine, index) {
  19277. var cursorLocation = this.get2DCursorLocation(index),
  19278. lineIndex = cursorLocation.lineIndex,
  19279. charIndex = cursorLocation.charIndex;
  19280. if (isBeginningOfLine) {
  19281. var textOnPreviousLine = this._textLines[lineIndex - 1],
  19282. newCharIndexOnPrevLine = textOnPreviousLine
  19283. ? textOnPreviousLine.length
  19284. : 0;
  19285. if (!this.styles[lineIndex - 1]) {
  19286. this.styles[lineIndex - 1] = { };
  19287. }
  19288. for (charIndex in this.styles[lineIndex]) {
  19289. this.styles[lineIndex - 1][parseInt(charIndex, 10) + newCharIndexOnPrevLine]
  19290. = this.styles[lineIndex][charIndex];
  19291. }
  19292. this.shiftLineStyles(lineIndex, -1);
  19293. }
  19294. else {
  19295. var currentLineStyles = this.styles[lineIndex];
  19296. if (currentLineStyles) {
  19297. var offset = this.selectionStart === this.selectionEnd ? -1 : 0;
  19298. delete currentLineStyles[charIndex + offset];
  19299. // console.log('deleting', lineIndex, charIndex + offset);
  19300. }
  19301. var currentLineStylesCloned = clone(currentLineStyles);
  19302. // shift all styles by 1 backwards
  19303. for (var i in currentLineStylesCloned) {
  19304. var numericIndex = parseInt(i, 10);
  19305. if (numericIndex >= charIndex && numericIndex !== 0) {
  19306. currentLineStyles[numericIndex - 1] = currentLineStylesCloned[numericIndex];
  19307. delete currentLineStyles[numericIndex];
  19308. }
  19309. }
  19310. }
  19311. },
  19312. /**
  19313. * Inserts new line
  19314. */
  19315. insertNewline: function() {
  19316. this.insertChars('\n');
  19317. }
  19318. });
  19319. })();
  19320. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  19321. /**
  19322. * Initializes "dbclick" event handler
  19323. */
  19324. initDoubleClickSimulation: function() {
  19325. // for double click
  19326. this.__lastClickTime = +new Date();
  19327. // for triple click
  19328. this.__lastLastClickTime = +new Date();
  19329. this.__lastPointer = { };
  19330. this.on('mousedown', this.onMouseDown.bind(this));
  19331. },
  19332. onMouseDown: function(options) {
  19333. this.__newClickTime = +new Date();
  19334. var newPointer = this.canvas.getPointer(options.e);
  19335. if (this.isTripleClick(newPointer)) {
  19336. this.fire('tripleclick', options);
  19337. this._stopEvent(options.e);
  19338. }
  19339. else if (this.isDoubleClick(newPointer)) {
  19340. this.fire('dblclick', options);
  19341. this._stopEvent(options.e);
  19342. }
  19343. this.__lastLastClickTime = this.__lastClickTime;
  19344. this.__lastClickTime = this.__newClickTime;
  19345. this.__lastPointer = newPointer;
  19346. this.__lastIsEditing = this.isEditing;
  19347. this.__lastSelected = this.selected;
  19348. },
  19349. isDoubleClick: function(newPointer) {
  19350. return this.__newClickTime - this.__lastClickTime < 500 &&
  19351. this.__lastPointer.x === newPointer.x &&
  19352. this.__lastPointer.y === newPointer.y && this.__lastIsEditing;
  19353. },
  19354. isTripleClick: function(newPointer) {
  19355. return this.__newClickTime - this.__lastClickTime < 500 &&
  19356. this.__lastClickTime - this.__lastLastClickTime < 500 &&
  19357. this.__lastPointer.x === newPointer.x &&
  19358. this.__lastPointer.y === newPointer.y;
  19359. },
  19360. /**
  19361. * @private
  19362. */
  19363. _stopEvent: function(e) {
  19364. e.preventDefault && e.preventDefault();
  19365. e.stopPropagation && e.stopPropagation();
  19366. },
  19367. /**
  19368. * Initializes event handlers related to cursor or selection
  19369. */
  19370. initCursorSelectionHandlers: function() {
  19371. this.initSelectedHandler();
  19372. this.initMousedownHandler();
  19373. this.initMouseupHandler();
  19374. this.initClicks();
  19375. },
  19376. /**
  19377. * Initializes double and triple click event handlers
  19378. */
  19379. initClicks: function() {
  19380. this.on('dblclick', function(options) {
  19381. this.selectWord(this.getSelectionStartFromPointer(options.e));
  19382. });
  19383. this.on('tripleclick', function(options) {
  19384. this.selectLine(this.getSelectionStartFromPointer(options.e));
  19385. });
  19386. },
  19387. /**
  19388. * Initializes "mousedown" event handler
  19389. */
  19390. initMousedownHandler: function() {
  19391. this.on('mousedown', function(options) {
  19392. var pointer = this.canvas.getPointer(options.e);
  19393. this.__mousedownX = pointer.x;
  19394. this.__mousedownY = pointer.y;
  19395. this.__isMousedown = true;
  19396. if (this.hiddenTextarea && this.canvas) {
  19397. this.canvas.wrapperEl.appendChild(this.hiddenTextarea);
  19398. }
  19399. if (this.selected) {
  19400. this.setCursorByClick(options.e);
  19401. }
  19402. if (this.isEditing) {
  19403. this.__selectionStartOnMouseDown = this.selectionStart;
  19404. this.initDelayedCursor(true);
  19405. }
  19406. });
  19407. },
  19408. /**
  19409. * @private
  19410. */
  19411. _isObjectMoved: function(e) {
  19412. var pointer = this.canvas.getPointer(e);
  19413. return this.__mousedownX !== pointer.x ||
  19414. this.__mousedownY !== pointer.y;
  19415. },
  19416. /**
  19417. * Initializes "mouseup" event handler
  19418. */
  19419. initMouseupHandler: function() {
  19420. this.on('mouseup', function(options) {
  19421. this.__isMousedown = false;
  19422. if (this._isObjectMoved(options.e)) {
  19423. return;
  19424. }
  19425. if (this.__lastSelected) {
  19426. this.enterEditing();
  19427. this.initDelayedCursor(true);
  19428. }
  19429. this.selected = true;
  19430. });
  19431. },
  19432. /**
  19433. * Changes cursor location in a text depending on passed pointer (x/y) object
  19434. * @param {Event} e Event object
  19435. */
  19436. setCursorByClick: function(e) {
  19437. var newSelectionStart = this.getSelectionStartFromPointer(e);
  19438. if (e.shiftKey) {
  19439. if (newSelectionStart < this.selectionStart) {
  19440. this.setSelectionEnd(this.selectionStart);
  19441. this.setSelectionStart(newSelectionStart);
  19442. }
  19443. else {
  19444. this.setSelectionEnd(newSelectionStart);
  19445. }
  19446. }
  19447. else {
  19448. this.setSelectionStart(newSelectionStart);
  19449. this.setSelectionEnd(newSelectionStart);
  19450. }
  19451. },
  19452. /**
  19453. * @private
  19454. * @param {Event} e Event object
  19455. * @return {Object} Coordinates of a pointer (x, y)
  19456. */
  19457. _getLocalRotatedPointer: function(e) {
  19458. var pointer = this.canvas.getPointer(e),
  19459. pClicked = new fabric.Point(pointer.x, pointer.y),
  19460. pLeftTop = new fabric.Point(this.left, this.top),
  19461. rotated = fabric.util.rotatePoint(
  19462. pClicked, pLeftTop, fabric.util.degreesToRadians(-this.angle));
  19463. return this.getLocalPointer(e, rotated);
  19464. },
  19465. /**
  19466. * Returns index of a character corresponding to where an object was clicked
  19467. * @param {Event} e Event object
  19468. * @return {Number} Index of a character
  19469. */
  19470. getSelectionStartFromPointer: function(e) {
  19471. var mouseOffset = this._getLocalRotatedPointer(e),
  19472. prevWidth = 0,
  19473. width = 0,
  19474. height = 0,
  19475. charIndex = 0,
  19476. newSelectionStart,
  19477. line;
  19478. for (var i = 0, len = this._textLines.length; i < len; i++) {
  19479. line = this._textLines[i].split('');
  19480. height += this._getHeightOfLine(this.ctx, i) * this.scaleY;
  19481. var widthOfLine = this._getLineWidth(this.ctx, i),
  19482. lineLeftOffset = this._getLineLeftOffset(widthOfLine);
  19483. width = lineLeftOffset * this.scaleX;
  19484. if (this.flipX) {
  19485. // when oject is horizontally flipped we reverse chars
  19486. this._textLines[i] = line.reverse().join('');
  19487. }
  19488. for (var j = 0, jlen = line.length; j < jlen; j++) {
  19489. var _char = line[j];
  19490. prevWidth = width;
  19491. width += this._getWidthOfChar(this.ctx, _char, i, this.flipX ? jlen - j : j) *
  19492. this.scaleX;
  19493. if (height <= mouseOffset.y || width <= mouseOffset.x) {
  19494. charIndex++;
  19495. continue;
  19496. }
  19497. return this._getNewSelectionStartFromOffset(
  19498. mouseOffset, prevWidth, width, charIndex + i, jlen);
  19499. }
  19500. if (mouseOffset.y < height) {
  19501. return this._getNewSelectionStartFromOffset(
  19502. mouseOffset, prevWidth, width, charIndex + i, jlen);
  19503. }
  19504. }
  19505. // clicked somewhere after all chars, so set at the end
  19506. if (typeof newSelectionStart === 'undefined') {
  19507. return this.text.length;
  19508. }
  19509. },
  19510. /**
  19511. * @private
  19512. */
  19513. _getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index, jlen) {
  19514. var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth,
  19515. distanceBtwNextCharAndCursor = width - mouseOffset.x,
  19516. offset = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor ? 0 : 1,
  19517. newSelectionStart = index + offset;
  19518. // if object is horizontally flipped, mirror cursor location from the end
  19519. if (this.flipX) {
  19520. newSelectionStart = jlen - newSelectionStart;
  19521. }
  19522. if (newSelectionStart > this.text.length) {
  19523. newSelectionStart = this.text.length;
  19524. }
  19525. return newSelectionStart;
  19526. }
  19527. });
  19528. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  19529. /**
  19530. * Initializes hidden textarea (needed to bring up keyboard in iOS)
  19531. */
  19532. initHiddenTextarea: function() {
  19533. this.hiddenTextarea = fabric.document.createElement('textarea');
  19534. this.hiddenTextarea.setAttribute('autocapitalize', 'off');
  19535. this.hiddenTextarea.style.cssText = 'position: fixed; bottom: 20px; left: 0px; opacity: 0;'
  19536. + ' width: 0px; height: 0px; z-index: -999;';
  19537. fabric.document.body.appendChild(this.hiddenTextarea);
  19538. fabric.util.addListener(this.hiddenTextarea, 'keydown', this.onKeyDown.bind(this));
  19539. fabric.util.addListener(this.hiddenTextarea, 'keypress', this.onKeyPress.bind(this));
  19540. fabric.util.addListener(this.hiddenTextarea, 'copy', this.copy.bind(this));
  19541. fabric.util.addListener(this.hiddenTextarea, 'paste', this.paste.bind(this));
  19542. if (!this._clickHandlerInitialized && this.canvas) {
  19543. fabric.util.addListener(this.canvas.upperCanvasEl, 'click', this.onClick.bind(this));
  19544. this._clickHandlerInitialized = true;
  19545. }
  19546. },
  19547. /**
  19548. * @private
  19549. */
  19550. _keysMap: {
  19551. 8: 'removeChars',
  19552. 9: 'exitEditing',
  19553. 27: 'exitEditing',
  19554. 13: 'insertNewline',
  19555. 33: 'moveCursorUp',
  19556. 34: 'moveCursorDown',
  19557. 35: 'moveCursorRight',
  19558. 36: 'moveCursorLeft',
  19559. 37: 'moveCursorLeft',
  19560. 38: 'moveCursorUp',
  19561. 39: 'moveCursorRight',
  19562. 40: 'moveCursorDown',
  19563. 46: 'forwardDelete'
  19564. },
  19565. /**
  19566. * @private
  19567. */
  19568. _ctrlKeysMap: {
  19569. 65: 'selectAll',
  19570. 88: 'cut'
  19571. },
  19572. onClick: function() {
  19573. // No need to trigger click event here, focus is enough to have the keyboard appear on Android
  19574. this.hiddenTextarea && this.hiddenTextarea.focus();
  19575. },
  19576. /**
  19577. * Handles keyup event
  19578. * @param {Event} e Event object
  19579. */
  19580. onKeyDown: function(e) {
  19581. if (!this.isEditing) {
  19582. return;
  19583. }
  19584. if (e.keyCode in this._keysMap) {
  19585. this[this._keysMap[e.keyCode]](e);
  19586. }
  19587. else if ((e.keyCode in this._ctrlKeysMap) && (e.ctrlKey || e.metaKey)) {
  19588. this[this._ctrlKeysMap[e.keyCode]](e);
  19589. }
  19590. else {
  19591. return;
  19592. }
  19593. e.stopImmediatePropagation();
  19594. e.preventDefault();
  19595. this.canvas && this.canvas.renderAll();
  19596. },
  19597. /**
  19598. * Forward delete
  19599. */
  19600. forwardDelete: function(e) {
  19601. if (this.selectionStart === this.selectionEnd) {
  19602. this.moveCursorRight(e);
  19603. }
  19604. this.removeChars(e);
  19605. },
  19606. /**
  19607. * Copies selected text
  19608. * @param {Event} e Event object
  19609. */
  19610. copy: function(e) {
  19611. var selectedText = this.getSelectedText(),
  19612. clipboardData = this._getClipboardData(e);
  19613. // Check for backward compatibility with old browsers
  19614. if (clipboardData) {
  19615. clipboardData.setData('text', selectedText);
  19616. }
  19617. this.copiedText = selectedText;
  19618. this.copiedStyles = this.getSelectionStyles(
  19619. this.selectionStart,
  19620. this.selectionEnd);
  19621. },
  19622. /**
  19623. * Pastes text
  19624. * @param {Event} e Event object
  19625. */
  19626. paste: function(e) {
  19627. var copiedText = null,
  19628. clipboardData = this._getClipboardData(e);
  19629. // Check for backward compatibility with old browsers
  19630. if (clipboardData) {
  19631. copiedText = clipboardData.getData('text');
  19632. }
  19633. else {
  19634. copiedText = this.copiedText;
  19635. }
  19636. if (copiedText) {
  19637. this.insertChars(copiedText, true);
  19638. }
  19639. },
  19640. /**
  19641. * Cuts text
  19642. * @param {Event} e Event object
  19643. */
  19644. cut: function(e) {
  19645. if (this.selectionStart === this.selectionEnd) {
  19646. return;
  19647. }
  19648. this.copy();
  19649. this.removeChars(e);
  19650. },
  19651. /**
  19652. * @private
  19653. * @param {Event} e Event object
  19654. * @return {Object} Clipboard data object
  19655. */
  19656. _getClipboardData: function(e) {
  19657. return e && (e.clipboardData || fabric.window.clipboardData);
  19658. },
  19659. /**
  19660. * Handles keypress event
  19661. * @param {Event} e Event object
  19662. */
  19663. onKeyPress: function(e) {
  19664. if (!this.isEditing || e.metaKey || e.ctrlKey) {
  19665. return;
  19666. }
  19667. if (e.which !== 0) {
  19668. this.insertChars(String.fromCharCode(e.which));
  19669. }
  19670. e.stopPropagation();
  19671. },
  19672. /**
  19673. * Gets start offset of a selection
  19674. * @param {Event} e Event object
  19675. * @param {Boolean} isRight
  19676. * @return {Number}
  19677. */
  19678. getDownCursorOffset: function(e, isRight) {
  19679. var selectionProp = isRight ? this.selectionEnd : this.selectionStart,
  19680. _char, lineLeftOffset,
  19681. textBeforeCursor = this.text.slice(0, selectionProp),
  19682. textAfterCursor = this.text.slice(selectionProp),
  19683. textOnSameLineBeforeCursor = textBeforeCursor.slice(textBeforeCursor.lastIndexOf('\n') + 1),
  19684. textOnSameLineAfterCursor = textAfterCursor.match(/(.*)\n?/)[1],
  19685. textOnNextLine = (textAfterCursor.match(/.*\n(.*)\n?/) || { })[1] || '',
  19686. cursorLocation = this.get2DCursorLocation(selectionProp);
  19687. // if on last line, down cursor goes to end of line
  19688. if (cursorLocation.lineIndex === this._textLines.length - 1 || e.metaKey || e.keyCode === 34) {
  19689. // move to the end of a text
  19690. return this.text.length - selectionProp;
  19691. }
  19692. var widthOfSameLineBeforeCursor = this._getLineWidth(this.ctx, cursorLocation.lineIndex);
  19693. lineLeftOffset = this._getLineLeftOffset(widthOfSameLineBeforeCursor);
  19694. var widthOfCharsOnSameLineBeforeCursor = lineLeftOffset,
  19695. lineIndex = cursorLocation.lineIndex;
  19696. for (var i = 0, len = textOnSameLineBeforeCursor.length; i < len; i++) {
  19697. _char = textOnSameLineBeforeCursor[i];
  19698. widthOfCharsOnSameLineBeforeCursor += this._getWidthOfChar(this.ctx, _char, lineIndex, i);
  19699. }
  19700. var indexOnNextLine = this._getIndexOnNextLine(
  19701. cursorLocation, textOnNextLine, widthOfCharsOnSameLineBeforeCursor);
  19702. return textOnSameLineAfterCursor.length + 1 + indexOnNextLine;
  19703. },
  19704. /**
  19705. * @private
  19706. */
  19707. _getIndexOnNextLine: function(cursorLocation, textOnNextLine, widthOfCharsOnSameLineBeforeCursor) {
  19708. var lineIndex = cursorLocation.lineIndex + 1,
  19709. widthOfNextLine = this._getLineWidth(this.ctx, lineIndex),
  19710. lineLeftOffset = this._getLineLeftOffset(widthOfNextLine),
  19711. widthOfCharsOnNextLine = lineLeftOffset,
  19712. indexOnNextLine = 0,
  19713. foundMatch;
  19714. for (var j = 0, jlen = textOnNextLine.length; j < jlen; j++) {
  19715. var _char = textOnNextLine[j],
  19716. widthOfChar = this._getWidthOfChar(this.ctx, _char, lineIndex, j);
  19717. widthOfCharsOnNextLine += widthOfChar;
  19718. if (widthOfCharsOnNextLine > widthOfCharsOnSameLineBeforeCursor) {
  19719. foundMatch = true;
  19720. var leftEdge = widthOfCharsOnNextLine - widthOfChar,
  19721. rightEdge = widthOfCharsOnNextLine,
  19722. offsetFromLeftEdge = Math.abs(leftEdge - widthOfCharsOnSameLineBeforeCursor),
  19723. offsetFromRightEdge = Math.abs(rightEdge - widthOfCharsOnSameLineBeforeCursor);
  19724. indexOnNextLine = offsetFromRightEdge < offsetFromLeftEdge ? j + 1 : j;
  19725. break;
  19726. }
  19727. }
  19728. // reached end
  19729. if (!foundMatch) {
  19730. indexOnNextLine = textOnNextLine.length;
  19731. }
  19732. return indexOnNextLine;
  19733. },
  19734. /**
  19735. * Moves cursor down
  19736. * @param {Event} e Event object
  19737. */
  19738. moveCursorDown: function(e) {
  19739. this.abortCursorAnimation();
  19740. this._currentCursorOpacity = 1;
  19741. var offset = this.getDownCursorOffset(e, this._selectionDirection === 'right');
  19742. if (e.shiftKey) {
  19743. this.moveCursorDownWithShift(offset);
  19744. }
  19745. else {
  19746. this.moveCursorDownWithoutShift(offset);
  19747. }
  19748. this.initDelayedCursor();
  19749. },
  19750. /**
  19751. * Moves cursor down without keeping selection
  19752. * @param {Number} offset
  19753. */
  19754. moveCursorDownWithoutShift: function(offset) {
  19755. this._selectionDirection = 'right';
  19756. this.setSelectionStart(this.selectionStart + offset);
  19757. this.setSelectionEnd(this.selectionStart);
  19758. },
  19759. /**
  19760. * private
  19761. */
  19762. swapSelectionPoints: function() {
  19763. var swapSel = this.selectionEnd;
  19764. this.setSelectionEnd(this.selectionStart);
  19765. this.setSelectionStart(swapSel);
  19766. },
  19767. /**
  19768. * Moves cursor down while keeping selection
  19769. * @param {Number} offset
  19770. */
  19771. moveCursorDownWithShift: function(offset) {
  19772. if (this.selectionEnd === this.selectionStart) {
  19773. this._selectionDirection = 'right';
  19774. }
  19775. if (this._selectionDirection === 'right') {
  19776. this.setSelectionEnd(this.selectionEnd + offset);
  19777. }
  19778. else {
  19779. this.setSelectionStart(this.selectionStart + offset);
  19780. }
  19781. if (this.selectionEnd < this.selectionStart && this._selectionDirection === 'left') {
  19782. this.swapSelectionPoints();
  19783. this._selectionDirection = 'right';
  19784. }
  19785. if (this.selectionEnd > this.text.length) {
  19786. this.setSelectionEnd(this.text.length);
  19787. }
  19788. },
  19789. /**
  19790. * @param {Event} e Event object
  19791. * @param {Boolean} isRight
  19792. * @return {Number}
  19793. */
  19794. getUpCursorOffset: function(e, isRight) {
  19795. var selectionProp = isRight ? this.selectionEnd : this.selectionStart,
  19796. cursorLocation = this.get2DCursorLocation(selectionProp);
  19797. // if on first line, up cursor goes to start of line
  19798. if (cursorLocation.lineIndex === 0 || e.metaKey || e.keyCode === 33) {
  19799. return selectionProp;
  19800. }
  19801. var textBeforeCursor = this.text.slice(0, selectionProp),
  19802. textOnSameLineBeforeCursor = textBeforeCursor.slice(textBeforeCursor.lastIndexOf('\n') + 1),
  19803. textOnPreviousLine = (textBeforeCursor.match(/\n?(.*)\n.*$/) || {})[1] || '',
  19804. _char,
  19805. widthOfSameLineBeforeCursor = this._getLineWidth(this.ctx, cursorLocation.lineIndex),
  19806. lineLeftOffset = this._getLineLeftOffset(widthOfSameLineBeforeCursor),
  19807. widthOfCharsOnSameLineBeforeCursor = lineLeftOffset,
  19808. lineIndex = cursorLocation.lineIndex;
  19809. for (var i = 0, len = textOnSameLineBeforeCursor.length; i < len; i++) {
  19810. _char = textOnSameLineBeforeCursor[i];
  19811. widthOfCharsOnSameLineBeforeCursor += this._getWidthOfChar(this.ctx, _char, lineIndex, i);
  19812. }
  19813. var indexOnPrevLine = this._getIndexOnPrevLine(
  19814. cursorLocation, textOnPreviousLine, widthOfCharsOnSameLineBeforeCursor);
  19815. return textOnPreviousLine.length - indexOnPrevLine + textOnSameLineBeforeCursor.length;
  19816. },
  19817. /**
  19818. * @private
  19819. */
  19820. _getIndexOnPrevLine: function(cursorLocation, textOnPreviousLine, widthOfCharsOnSameLineBeforeCursor) {
  19821. var lineIndex = cursorLocation.lineIndex - 1,
  19822. widthOfPreviousLine = this._getLineWidth(this.ctx, lineIndex),
  19823. lineLeftOffset = this._getLineLeftOffset(widthOfPreviousLine),
  19824. widthOfCharsOnPreviousLine = lineLeftOffset,
  19825. indexOnPrevLine = 0,
  19826. foundMatch;
  19827. for (var j = 0, jlen = textOnPreviousLine.length; j < jlen; j++) {
  19828. var _char = textOnPreviousLine[j],
  19829. widthOfChar = this._getWidthOfChar(this.ctx, _char, lineIndex, j);
  19830. widthOfCharsOnPreviousLine += widthOfChar;
  19831. if (widthOfCharsOnPreviousLine > widthOfCharsOnSameLineBeforeCursor) {
  19832. foundMatch = true;
  19833. var leftEdge = widthOfCharsOnPreviousLine - widthOfChar,
  19834. rightEdge = widthOfCharsOnPreviousLine,
  19835. offsetFromLeftEdge = Math.abs(leftEdge - widthOfCharsOnSameLineBeforeCursor),
  19836. offsetFromRightEdge = Math.abs(rightEdge - widthOfCharsOnSameLineBeforeCursor);
  19837. indexOnPrevLine = offsetFromRightEdge < offsetFromLeftEdge ? j : (j - 1);
  19838. break;
  19839. }
  19840. }
  19841. // reached end
  19842. if (!foundMatch) {
  19843. indexOnPrevLine = textOnPreviousLine.length - 1;
  19844. }
  19845. return indexOnPrevLine;
  19846. },
  19847. /**
  19848. * Moves cursor up
  19849. * @param {Event} e Event object
  19850. */
  19851. moveCursorUp: function(e) {
  19852. this.abortCursorAnimation();
  19853. this._currentCursorOpacity = 1;
  19854. var offset = this.getUpCursorOffset(e, this._selectionDirection === 'right');
  19855. if (e.shiftKey) {
  19856. this.moveCursorUpWithShift(offset);
  19857. }
  19858. else {
  19859. this.moveCursorUpWithoutShift(offset);
  19860. }
  19861. this.initDelayedCursor();
  19862. },
  19863. /**
  19864. * Moves cursor up with shift
  19865. * @param {Number} offset
  19866. */
  19867. moveCursorUpWithShift: function(offset) {
  19868. if (this.selectionEnd === this.selectionStart) {
  19869. this._selectionDirection = 'left';
  19870. }
  19871. if (this._selectionDirection === 'right') {
  19872. this.setSelectionEnd(this.selectionEnd - offset);
  19873. }
  19874. else {
  19875. this.setSelectionStart(this.selectionStart - offset);
  19876. }
  19877. if (this.selectionEnd < this.selectionStart && this._selectionDirection === 'right') {
  19878. this.swapSelectionPoints();
  19879. this._selectionDirection = 'left';
  19880. }
  19881. },
  19882. /**
  19883. * Moves cursor up without shift
  19884. * @param {Number} offset
  19885. */
  19886. moveCursorUpWithoutShift: function(offset) {
  19887. if (this.selectionStart === this.selectionEnd) {
  19888. this.setSelectionStart(this.selectionStart - offset);
  19889. }
  19890. this.setSelectionEnd(this.selectionStart);
  19891. this._selectionDirection = 'left';
  19892. },
  19893. /**
  19894. * Moves cursor left
  19895. * @param {Event} e Event object
  19896. */
  19897. moveCursorLeft: function(e) {
  19898. if (this.selectionStart === 0 && this.selectionEnd === 0) {
  19899. return;
  19900. }
  19901. this.abortCursorAnimation();
  19902. this._currentCursorOpacity = 1;
  19903. if (e.shiftKey) {
  19904. this.moveCursorLeftWithShift(e);
  19905. }
  19906. else {
  19907. this.moveCursorLeftWithoutShift(e);
  19908. }
  19909. this.initDelayedCursor();
  19910. },
  19911. /**
  19912. * @private
  19913. */
  19914. _move: function(e, prop, direction) {
  19915. var propMethod = (prop === 'selectionStart' ? 'setSelectionStart' : 'setSelectionEnd');
  19916. if (e.altKey) {
  19917. this[propMethod](this['findWordBoundary' + direction](this[prop]));
  19918. }
  19919. else if (e.metaKey || e.keyCode === 35 || e.keyCode === 36 ) {
  19920. this[propMethod](this['findLineBoundary' + direction](this[prop]));
  19921. }
  19922. else {
  19923. this[propMethod](this[prop] + (direction === 'Left' ? -1 : 1));
  19924. }
  19925. },
  19926. /**
  19927. * @private
  19928. */
  19929. _moveLeft: function(e, prop) {
  19930. this._move(e, prop, 'Left');
  19931. },
  19932. /**
  19933. * @private
  19934. */
  19935. _moveRight: function(e, prop) {
  19936. this._move(e, prop, 'Right');
  19937. },
  19938. /**
  19939. * Moves cursor left without keeping selection
  19940. * @param {Event} e
  19941. */
  19942. moveCursorLeftWithoutShift: function(e) {
  19943. this._selectionDirection = 'left';
  19944. // only move cursor when there is no selection,
  19945. // otherwise we discard it, and leave cursor on same place
  19946. if (this.selectionEnd === this.selectionStart) {
  19947. this._moveLeft(e, 'selectionStart');
  19948. }
  19949. this.setSelectionEnd(this.selectionStart);
  19950. },
  19951. /**
  19952. * Moves cursor left while keeping selection
  19953. * @param {Event} e
  19954. */
  19955. moveCursorLeftWithShift: function(e) {
  19956. if (this._selectionDirection === 'right' && this.selectionStart !== this.selectionEnd) {
  19957. this._moveLeft(e, 'selectionEnd');
  19958. }
  19959. else {
  19960. this._selectionDirection = 'left';
  19961. this._moveLeft(e, 'selectionStart');
  19962. // increase selection by one if it's a newline
  19963. if (this.text.charAt(this.selectionStart) === '\n') {
  19964. this.setSelectionStart(this.selectionStart - 1);
  19965. }
  19966. }
  19967. },
  19968. /**
  19969. * Moves cursor right
  19970. * @param {Event} e Event object
  19971. */
  19972. moveCursorRight: function(e) {
  19973. if (this.selectionStart >= this.text.length && this.selectionEnd >= this.text.length) {
  19974. return;
  19975. }
  19976. this.abortCursorAnimation();
  19977. this._currentCursorOpacity = 1;
  19978. if (e.shiftKey) {
  19979. this.moveCursorRightWithShift(e);
  19980. }
  19981. else {
  19982. this.moveCursorRightWithoutShift(e);
  19983. }
  19984. this.initDelayedCursor();
  19985. },
  19986. /**
  19987. * Moves cursor right while keeping selection
  19988. * @param {Event} e
  19989. */
  19990. moveCursorRightWithShift: function(e) {
  19991. if (this._selectionDirection === 'left' && this.selectionStart !== this.selectionEnd) {
  19992. this._moveRight(e, 'selectionStart');
  19993. }
  19994. else {
  19995. this._selectionDirection = 'right';
  19996. this._moveRight(e, 'selectionEnd');
  19997. // increase selection by one if it's a newline
  19998. if (this.text.charAt(this.selectionEnd - 1) === '\n') {
  19999. this.setSelectionEnd(this.selectionEnd + 1);
  20000. }
  20001. }
  20002. },
  20003. /**
  20004. * Moves cursor right without keeping selection
  20005. * @param {Event} e Event object
  20006. */
  20007. moveCursorRightWithoutShift: function(e) {
  20008. this._selectionDirection = 'right';
  20009. if (this.selectionStart === this.selectionEnd) {
  20010. this._moveRight(e, 'selectionStart');
  20011. this.setSelectionEnd(this.selectionStart);
  20012. }
  20013. else {
  20014. this.setSelectionEnd(this.selectionEnd + this.getNumNewLinesInSelectedText());
  20015. this.setSelectionStart(this.selectionEnd);
  20016. }
  20017. },
  20018. /**
  20019. * Removes characters selected by selection
  20020. * @param {Event} e Event object
  20021. */
  20022. removeChars: function(e) {
  20023. if (this.selectionStart === this.selectionEnd) {
  20024. this._removeCharsNearCursor(e);
  20025. }
  20026. else {
  20027. this._removeCharsFromTo(this.selectionStart, this.selectionEnd);
  20028. }
  20029. this.setSelectionEnd(this.selectionStart);
  20030. this._removeExtraneousStyles();
  20031. this._clearCache();
  20032. this.canvas && this.canvas.renderAll();
  20033. this.setCoords();
  20034. this.fire('changed');
  20035. this.canvas && this.canvas.fire('text:changed', { target: this });
  20036. },
  20037. /**
  20038. * @private
  20039. * @param {Event} e Event object
  20040. */
  20041. _removeCharsNearCursor: function(e) {
  20042. if (this.selectionStart !== 0) {
  20043. if (e.metaKey) {
  20044. // remove all till the start of current line
  20045. var leftLineBoundary = this.findLineBoundaryLeft(this.selectionStart);
  20046. this._removeCharsFromTo(leftLineBoundary, this.selectionStart);
  20047. this.setSelectionStart(leftLineBoundary);
  20048. }
  20049. else if (e.altKey) {
  20050. // remove all till the start of current word
  20051. var leftWordBoundary = this.findWordBoundaryLeft(this.selectionStart);
  20052. this._removeCharsFromTo(leftWordBoundary, this.selectionStart);
  20053. this.setSelectionStart(leftWordBoundary);
  20054. }
  20055. else {
  20056. var isBeginningOfLine = this.text.slice(this.selectionStart - 1, this.selectionStart) === '\n';
  20057. this.removeStyleObject(isBeginningOfLine);
  20058. this.setSelectionStart(this.selectionStart - 1);
  20059. this.text = this.text.slice(0, this.selectionStart) +
  20060. this.text.slice(this.selectionStart + 1);
  20061. }
  20062. }
  20063. }
  20064. });
  20065. /* _TO_SVG_START_ */
  20066. fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
  20067. /**
  20068. * @private
  20069. */
  20070. _setSVGTextLineText: function(lineIndex, textSpans, height, textLeftOffset, textTopOffset, textBgRects) {
  20071. if (!this.styles[lineIndex]) {
  20072. this.callSuper('_setSVGTextLineText',
  20073. lineIndex, textSpans, height, textLeftOffset, textTopOffset);
  20074. }
  20075. else {
  20076. this._setSVGTextLineChars(
  20077. lineIndex, textSpans, height, textLeftOffset, textBgRects);
  20078. }
  20079. },
  20080. /**
  20081. * @private
  20082. */
  20083. _setSVGTextLineChars: function(lineIndex, textSpans, height, textLeftOffset, textBgRects) {
  20084. var chars = this._textLines[lineIndex].split(''),
  20085. charOffset = 0,
  20086. lineLeftOffset = this._getSVGLineLeftOffset(lineIndex) - this.width / 2,
  20087. lineOffset = this._getSVGLineTopOffset(lineIndex),
  20088. heightOfLine = this._getHeightOfLine(this.ctx, lineIndex);
  20089. for (var i = 0, len = chars.length; i < len; i++) {
  20090. var styleDecl = this.styles[lineIndex][i] || { };
  20091. textSpans.push(
  20092. this._createTextCharSpan(
  20093. chars[i], styleDecl, lineLeftOffset, lineOffset.lineTop + lineOffset.offset, charOffset));
  20094. var charWidth = this._getWidthOfChar(this.ctx, chars[i], lineIndex, i);
  20095. if (styleDecl.textBackgroundColor) {
  20096. textBgRects.push(
  20097. this._createTextCharBg(
  20098. styleDecl, lineLeftOffset, lineOffset.lineTop, heightOfLine, charWidth, charOffset));
  20099. }
  20100. charOffset += charWidth;
  20101. }
  20102. },
  20103. /**
  20104. * @private
  20105. */
  20106. _getSVGLineLeftOffset: function(lineIndex) {
  20107. return fabric.util.toFixed(this._getLineLeftOffset(this.__lineWidths[lineIndex]), 2);
  20108. },
  20109. /**
  20110. * @private
  20111. */
  20112. _getSVGLineTopOffset: function(lineIndex) {
  20113. var lineTopOffset = 0, lastHeight = 0;
  20114. for (var j = 0; j < lineIndex; j++) {
  20115. lineTopOffset += this._getHeightOfLine(this.ctx, j);
  20116. }
  20117. lastHeight = this._getHeightOfLine(this.ctx, j);
  20118. return {
  20119. lineTop: lineTopOffset,
  20120. offset: (this._fontSizeMult - this._fontSizeFraction) * lastHeight / (this.lineHeight * this._fontSizeMult)
  20121. };
  20122. },
  20123. /**
  20124. * @private
  20125. */
  20126. _createTextCharBg: function(styleDecl, lineLeftOffset, lineTopOffset, heightOfLine, charWidth, charOffset) {
  20127. return [
  20128. //jscs:disable validateIndentation
  20129. '<rect fill="', styleDecl.textBackgroundColor,
  20130. '" x="', lineLeftOffset + charOffset,
  20131. '" y="', lineTopOffset - this.height/2,
  20132. '" width="', charWidth,
  20133. '" height="', heightOfLine / this.lineHeight,
  20134. '"></rect>'
  20135. //jscs:enable validateIndentation
  20136. ].join('');
  20137. },
  20138. /**
  20139. * @private
  20140. */
  20141. _createTextCharSpan: function(_char, styleDecl, lineLeftOffset, lineTopOffset, charOffset) {
  20142. var fillStyles = this.getSvgStyles.call(fabric.util.object.extend({
  20143. visible: true,
  20144. fill: this.fill,
  20145. stroke: this.stroke,
  20146. type: 'text'
  20147. }, styleDecl));
  20148. return [
  20149. //jscs:disable validateIndentation
  20150. '<tspan x="', lineLeftOffset + charOffset, '" y="',
  20151. lineTopOffset - this.height/2, '" ',
  20152. (styleDecl.fontFamily ? 'font-family="' + styleDecl.fontFamily.replace(/"/g, '\'') + '" ': ''),
  20153. (styleDecl.fontSize ? 'font-size="' + styleDecl.fontSize + '" ': ''),
  20154. (styleDecl.fontStyle ? 'font-style="' + styleDecl.fontStyle + '" ': ''),
  20155. (styleDecl.fontWeight ? 'font-weight="' + styleDecl.fontWeight + '" ': ''),
  20156. (styleDecl.textDecoration ? 'text-decoration="' + styleDecl.textDecoration + '" ': ''),
  20157. 'style="', fillStyles, '">',
  20158. fabric.util.string.escapeXml(_char),
  20159. '</tspan>'
  20160. //jscs:enable validateIndentation
  20161. ].join('');
  20162. }
  20163. });
  20164. /* _TO_SVG_END_ */
  20165. (function() {
  20166. if (typeof document !== 'undefined' && typeof window !== 'undefined') {
  20167. return;
  20168. }
  20169. var DOMParser = require('xmldom').DOMParser,
  20170. URL = require('url'),
  20171. HTTP = require('http'),
  20172. HTTPS = require('https'),
  20173. Canvas = require('canvas'),
  20174. Image = require('canvas').Image;
  20175. /** @private */
  20176. function request(url, encoding, callback) {
  20177. var oURL = URL.parse(url);
  20178. // detect if http or https is used
  20179. if ( !oURL.port ) {
  20180. oURL.port = ( oURL.protocol.indexOf('https:') === 0 ) ? 443 : 80;
  20181. }
  20182. // assign request handler based on protocol
  20183. var reqHandler = (oURL.protocol.indexOf('https:') === 0 ) ? HTTPS : HTTP,
  20184. req = reqHandler.request({
  20185. hostname: oURL.hostname,
  20186. port: oURL.port,
  20187. path: oURL.path,
  20188. method: 'GET'
  20189. }, function(response) {
  20190. var body = '';
  20191. if (encoding) {
  20192. response.setEncoding(encoding);
  20193. }
  20194. response.on('end', function () {
  20195. callback(body);
  20196. });
  20197. response.on('data', function (chunk) {
  20198. if (response.statusCode === 200) {
  20199. body += chunk;
  20200. }
  20201. });
  20202. });
  20203. req.on('error', function(err) {
  20204. if (err.errno === process.ECONNREFUSED) {
  20205. fabric.log('ECONNREFUSED: connection refused to ' + oURL.hostname + ':' + oURL.port);
  20206. }
  20207. else {
  20208. fabric.log(err.message);
  20209. }
  20210. });
  20211. req.end();
  20212. }
  20213. /** @private */
  20214. function requestFs(path, callback) {
  20215. var fs = require('fs');
  20216. fs.readFile(path, function (err, data) {
  20217. if (err) {
  20218. fabric.log(err);
  20219. throw err;
  20220. }
  20221. else {
  20222. callback(data);
  20223. }
  20224. });
  20225. }
  20226. fabric.util.loadImage = function(url, callback, context) {
  20227. function createImageAndCallBack(data) {
  20228. img.src = new Buffer(data, 'binary');
  20229. // preserving original url, which seems to be lost in node-canvas
  20230. img._src = url;
  20231. callback && callback.call(context, img);
  20232. }
  20233. var img = new Image();
  20234. if (url && (url instanceof Buffer || url.indexOf('data') === 0)) {
  20235. img.src = img._src = url;
  20236. callback && callback.call(context, img);
  20237. }
  20238. else if (url && url.indexOf('http') !== 0) {
  20239. requestFs(url, createImageAndCallBack);
  20240. }
  20241. else if (url) {
  20242. request(url, 'binary', createImageAndCallBack);
  20243. }
  20244. else {
  20245. callback && callback.call(context, url);
  20246. }
  20247. };
  20248. fabric.loadSVGFromURL = function(url, callback, reviver) {
  20249. url = url.replace(/^\n\s*/, '').replace(/\?.*$/, '').trim();
  20250. if (url.indexOf('http') !== 0) {
  20251. requestFs(url, function(body) {
  20252. fabric.loadSVGFromString(body.toString(), callback, reviver);
  20253. });
  20254. }
  20255. else {
  20256. request(url, '', function(body) {
  20257. fabric.loadSVGFromString(body, callback, reviver);
  20258. });
  20259. }
  20260. };
  20261. fabric.loadSVGFromString = function(string, callback, reviver) {
  20262. var doc = new DOMParser().parseFromString(string);
  20263. fabric.parseSVGDocument(doc.documentElement, function(results, options) {
  20264. callback && callback(results, options);
  20265. }, reviver);
  20266. };
  20267. fabric.util.getScript = function(url, callback) {
  20268. request(url, '', function(body) {
  20269. eval(body);
  20270. callback && callback();
  20271. });
  20272. };
  20273. fabric.Image.fromObject = function(object, callback) {
  20274. fabric.util.loadImage(object.src, function(img) {
  20275. var oImg = new fabric.Image(img);
  20276. oImg._initConfig(object);
  20277. oImg._initFilters(object, function(filters) {
  20278. oImg.filters = filters || [ ];
  20279. callback && callback(oImg);
  20280. });
  20281. });
  20282. };
  20283. /**
  20284. * Only available when running fabric on node.js
  20285. * @param {Number} width Canvas width
  20286. * @param {Number} height Canvas height
  20287. * @param {Object} [options] Options to pass to FabricCanvas.
  20288. * @param {Object} [nodeCanvasOptions] Options to pass to NodeCanvas.
  20289. * @return {Object} wrapped canvas instance
  20290. */
  20291. fabric.createCanvasForNode = function(width, height, options, nodeCanvasOptions) {
  20292. nodeCanvasOptions = nodeCanvasOptions || options;
  20293. var canvasEl = fabric.document.createElement('canvas'),
  20294. nodeCanvas = new Canvas(width || 600, height || 600, nodeCanvasOptions);
  20295. // jsdom doesn't create style on canvas element, so here be temp. workaround
  20296. canvasEl.style = { };
  20297. canvasEl.width = nodeCanvas.width;
  20298. canvasEl.height = nodeCanvas.height;
  20299. var FabricCanvas = fabric.Canvas || fabric.StaticCanvas,
  20300. fabricCanvas = new FabricCanvas(canvasEl, options);
  20301. fabricCanvas.contextContainer = nodeCanvas.getContext('2d');
  20302. fabricCanvas.nodeCanvas = nodeCanvas;
  20303. fabricCanvas.Font = Canvas.Font;
  20304. return fabricCanvas;
  20305. };
  20306. /** @ignore */
  20307. fabric.StaticCanvas.prototype.createPNGStream = function() {
  20308. return this.nodeCanvas.createPNGStream();
  20309. };
  20310. fabric.StaticCanvas.prototype.createJPEGStream = function(opts) {
  20311. return this.nodeCanvas.createJPEGStream(opts);
  20312. };
  20313. var origSetWidth = fabric.StaticCanvas.prototype.setWidth;
  20314. fabric.StaticCanvas.prototype.setWidth = function(width, options) {
  20315. origSetWidth.call(this, width, options);
  20316. this.nodeCanvas.width = width;
  20317. return this;
  20318. };
  20319. if (fabric.Canvas) {
  20320. fabric.Canvas.prototype.setWidth = fabric.StaticCanvas.prototype.setWidth;
  20321. }
  20322. var origSetHeight = fabric.StaticCanvas.prototype.setHeight;
  20323. fabric.StaticCanvas.prototype.setHeight = function(height, options) {
  20324. origSetHeight.call(this, height, options);
  20325. this.nodeCanvas.height = height;
  20326. return this;
  20327. };
  20328. if (fabric.Canvas) {
  20329. fabric.Canvas.prototype.setHeight = fabric.StaticCanvas.prototype.setHeight;
  20330. }
  20331. })();