hilo-standalone.js 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659
  1. /**
  2. * Hilo 0.1.1
  3. * Copyright 2014 hilojs.com
  4. * Licensed under the MIT License
  5. */
  6. (function(window){
  7. /**
  8. * @namespace Hilo的基础核心方法集合。
  9. * @static
  10. * @module hilo/core/Hilo
  11. */
  12. var Hilo = (function(){
  13. var win = window, doc = document, docElem = doc.documentElement,
  14. uid = 0;
  15. return {
  16. /**
  17. * 获取一个全局唯一的id。如Stage1,Bitmap2等。
  18. * @param {String} prefix 生成id的前缀。
  19. */
  20. getUid: function(prefix){
  21. var id = ++uid;
  22. if(prefix){
  23. var charCode = prefix.charCodeAt(prefix.length - 1);
  24. if (charCode >= 48 && charCode <= 57) prefix += "_"; // 0至9之间添加下划线
  25. return prefix + id;
  26. }
  27. return id;
  28. },
  29. /**
  30. * 为指定的可视对象生成一个包含路径的字符串表示形式。如Stage1.Container2.Bitmap3。
  31. * @param {View} view 指定的可视对象。
  32. */
  33. viewToString: function(view){
  34. var result, obj = view;
  35. while(obj){
  36. result = result ? (obj.id + '.' + result) : obj.id;
  37. obj = obj.parent;
  38. }
  39. return result;
  40. },
  41. /**
  42. * 简单的浅复制对象。
  43. * @param {Object} target 要复制的目标对象。
  44. * @param {Object} source 要复制的源对象。
  45. * @param {Boolean} strict 指定是否覆盖已有属性,默认为false,即不覆盖。
  46. */
  47. copy: function(target, source, strict){
  48. for(var key in source){
  49. if(!strict || target.hasOwnProperty(key) || target[key] !== undefined){
  50. target[key] = source[key];
  51. }
  52. }
  53. return target;
  54. },
  55. /**
  56. * 浏览器特性。
  57. */
  58. browser: (function(){
  59. var ua = navigator.userAgent;
  60. var data = {
  61. iphone: /iphone/i.test(ua),
  62. ipad: /ipad/i.test(ua),
  63. ipod: /ipod/i.test(ua),
  64. android: /android/i.test(ua),
  65. webkit: /webkit/i.test(ua),
  66. chrome: /chrome/i.test(ua),
  67. safari: /safari/i.test(ua),
  68. firefox: /firefox/i.test(ua),
  69. ie: /msie/i.test(ua),
  70. opera: /opera/i.test(ua),
  71. supportTouch: 'ontouchstart' in win,
  72. supportCanvas: doc.createElement('canvas').getContext != null,
  73. supportStorage: false,
  74. supportOrientation: 'orientation' in win,
  75. supportDeviceMotion: 'ondevicemotion' in win
  76. };
  77. //`localStorage` is null or `localStorage.setItem` throws error in some cases (e.g. localStorage is disabled)
  78. try{
  79. var value = 'hilo';
  80. localStorage.setItem(value, value);
  81. localStorage.removeItem(value);
  82. data.supportStorage = true;
  83. }catch(e){ };
  84. //vendro prefix
  85. var jsVendor = data.jsVendor = data.webkit ? 'webkit' : data.firefox ? 'Moz' : data.opera ? 'O' : data.ie ? 'ms' : '';
  86. var cssVendor = data.cssVendor = '-' + jsVendor + '-';
  87. //css transform/3d feature dectection
  88. var testElem = doc.createElement('div'), style = testElem.style;
  89. var supportTransform = style[jsVendor + 'Transform'] != undefined;
  90. var supportTransform3D = style[jsVendor + 'Perspective'] != undefined;
  91. if(supportTransform3D){
  92. testElem.id = 'test3d';
  93. style = doc.createElement('style');
  94. style.textContent = '@media ('+ cssVendor +'transform-3d){#test3d{height:3px}}';
  95. doc.head.appendChild(style);
  96. docElem.appendChild(testElem);
  97. supportTransform3D = testElem.offsetHeight == 3;
  98. doc.head.removeChild(style);
  99. docElem.removeChild(testElem);
  100. };
  101. data.supportTransform = supportTransform;
  102. data.supportTransform3D = supportTransform3D;
  103. return data;
  104. })(),
  105. /**
  106. * 事件类型枚举对象。
  107. */
  108. event: (function(){
  109. var supportTouch = 'ontouchstart' in win;
  110. return {
  111. POINTER_START: supportTouch ? 'touchstart' : 'mousedown',
  112. POINTER_MOVE: supportTouch ? 'touchmove' : 'mousemove',
  113. POINTER_END: supportTouch ? 'touchend' : 'mouseup'
  114. };
  115. })(),
  116. /**
  117. * 获取DOM元素在页面中的内容显示区域。
  118. * @param {HTMLElement} elem DOM元素。
  119. * @returns {Object} DOM元素的现实区域。格式为:{left:0, top:0, width:100, height:100}。
  120. */
  121. getElementRect: function(elem){
  122. try{
  123. //this fails if it's a disconnected DOM node
  124. var bounds = elem.getBoundingClientRect();
  125. }catch(e){
  126. bounds = {top: elem.offsetTop, left: elem.offsetLeft, width:elem.offsetWidth, height:elem.offsetHeight};
  127. }
  128. var offsetX = (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0);
  129. var offsetY = (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0);
  130. var styles = win.getComputedStyle ? getComputedStyle(elem) : elem.currentStyle;
  131. var parseIntFn = parseInt;
  132. var padLeft = parseIntFn(styles.paddingLeft) + parseIntFn(styles.borderLeftWidth);
  133. var padTop = parseIntFn(styles.paddingTop) + parseIntFn(styles.borderTopWidth);
  134. var padRight = parseIntFn(styles.paddingRight) + parseIntFn(styles.borderRightWidth);
  135. var padBottom = parseIntFn(styles.paddingBottom) + parseIntFn(styles.borderBottomWidth);
  136. return {
  137. left: bounds.left + offsetX + padLeft,
  138. top: bounds.top + offsetY + padTop,
  139. width: bounds.right - padRight - bounds.left - padLeft,
  140. height: bounds.bottom - padBottom - bounds.top - padTop
  141. };
  142. },
  143. /**
  144. * 创建一个DOM元素。可指定属性和样式。
  145. * @param {String} type 要创建的DOM元素的类型。比如:'div'。
  146. * @param {Object} properties 指定DOM元素的属性和样式。
  147. * @returns {HTMLElement} 一个DOM元素。
  148. */
  149. createElement: function(type, properties){
  150. var elem = doc.createElement(type), p, val, s;
  151. for(p in properties){
  152. val = properties[p];
  153. if(p === 'style'){
  154. for(s in val) elem.style[s] = val[s];
  155. }else{
  156. elem[p] = val;
  157. }
  158. }
  159. return elem;
  160. },
  161. /**
  162. * 根据参数id获取一个DOM元素。此方法等价于document.getElementById(id)。
  163. * @param {String} 要获取的DOM元素的id。
  164. * @returns {HTMLElement} 一个DOM元素。
  165. */
  166. getElement: function(id){
  167. return doc.getElementById(id);
  168. },
  169. /**
  170. * 设置可视对象DOM元素的CSS样式。
  171. * @param {View} obj 指定要设置CSS样式的可视对象。
  172. */
  173. setElementStyleByView: function(obj){
  174. var drawable = obj.drawable,
  175. image = drawable.image,
  176. rect = drawable.rect,
  177. style = drawable.domElement.style,
  178. prefix = Hilo.browser.jsVendor, px = 'px';
  179. style.pointerEvents = 'none';
  180. style.display = (!obj.visible || obj.alpha <= 0) ? 'none' : '';
  181. style.width = obj.width + px;
  182. style.height = obj.height + px;
  183. style.opacity = obj.alpha;
  184. style.zIndex = obj.depth;
  185. style[prefix + 'TransformOrigin'] = obj.pivotX + px + ' ' + obj.pivotY + px;
  186. style[prefix + 'Transform'] = this.getTransformCSS(obj);
  187. if(obj.bgFill) style.backgroundColor = obj.bgFill.style;
  188. if(image){
  189. if(style.backgroundImage.indexOf(image.src) != 4){
  190. style.backgroundImage = 'url(' + image.src + ')';
  191. }
  192. if(rect){
  193. style.backgroundPosition = -rect[0] + px + ' ' + -rect[1] + px;
  194. }
  195. }
  196. if(obj.mask){
  197. style[prefix + 'MaskImage'] = obj.mask.drawable.domElement.style.backgroundImage;
  198. style[prefix + 'MaskRepeat'] = 'no-repeat';
  199. style[prefix + 'MaskPosition'] = obj.mask.x + px + ' ' + obj.mask.y + px;
  200. }
  201. },
  202. /**
  203. * 生成可视对象的CSS变换样式。
  204. * @param {View} obj 指定生成CSS变换样式的可视对象。
  205. * @returns {String} 生成的CSS样式字符串。
  206. */
  207. getTransformCSS: function(obj){
  208. var use3d = this.browser.supportTransform3D,
  209. str3d = use3d ? '3d' : '';
  210. return 'translate' + str3d + '(' + (obj.x - obj.pivotX) + 'px, ' + (obj.y - obj.pivotY) + (use3d ? 'px, 0px)' : 'px)')
  211. + 'rotate' + str3d + (use3d ? '(0, 0, 1, ' : '(') + obj.rotation + 'deg)'
  212. + 'scale' + str3d + '(' + obj.scaleX + ', ' + obj.scaleY + (use3d ? ', 1)' : ')');
  213. }
  214. };
  215. })();
  216. /**
  217. * @namespace Class是提供类的创建的辅助工具。
  218. * @static
  219. * @module hilo/core/Class
  220. */
  221. var Class = (function(){
  222. /**
  223. * 此方法是在Hilo中创建类的主要方法。
  224. * @param {Object} properties 要创建的类的相关属性和方法。主要有:
  225. * <ul>
  226. * <li><b>Extends</b> - 指定要继承的父类。</li>
  227. * <li><b>Mixes</b> - 指定要混入的成员集合对象。</li>
  228. * <li><b>Statics</b> - 指定类的静态属性或方法。</li>
  229. * </ul>
  230. * @returns {Object} 创建好的类。
  231. */
  232. var create = function(properties){
  233. properties = properties || {};
  234. var clazz = properties.hasOwnProperty('constructor') ? properties.constructor : function(){};
  235. implement.call(clazz, properties);
  236. return clazz;
  237. }
  238. /**
  239. * @private
  240. */
  241. var implement = function(properties){
  242. var proto = {}, key, value;
  243. for(key in properties){
  244. value = properties[key];
  245. if(classMutators.hasOwnProperty(key)){
  246. classMutators[key].call(this, value);
  247. }else{
  248. proto[key] = value;
  249. }
  250. }
  251. mix(this.prototype, proto);
  252. };
  253. var classMutators = /** @ignore */{
  254. Extends: function(parent){
  255. var existed = this.prototype, proto = createProto(parent.prototype);
  256. //inherit static properites
  257. mix(this, parent);
  258. //keep existed properties
  259. mix(proto, existed);
  260. //correct constructor
  261. proto.constructor = this;
  262. //prototype chaining
  263. this.prototype = proto;
  264. //shortcut to parent's prototype
  265. this.superclass = parent.prototype;
  266. },
  267. Mixes: function(items){
  268. items instanceof Array || (items = [items]);
  269. var proto = this.prototype, item;
  270. while(item = items.shift()){
  271. mix(proto, item.prototype || item);
  272. }
  273. },
  274. Statics: function(properties){
  275. mix(this, properties);
  276. }
  277. };
  278. /**
  279. * @private
  280. */
  281. var createProto = (function(){
  282. if(Object.__proto__){
  283. return function(proto){
  284. return {__proto__: proto};
  285. }
  286. }else{
  287. var Ctor = function(){};
  288. return function(proto){
  289. Ctor.prototype = proto;
  290. return new Ctor();
  291. }
  292. }
  293. })();
  294. /**
  295. * 混入属性或方法。
  296. * @param {Object} target 混入目标对象。
  297. * @returns {Object} 混入目标对象。
  298. */
  299. var mix = function(target){
  300. for(var i = 1, len = arguments.length; i < len; i++){
  301. var source = arguments[i], defineProps;
  302. for(var key in source){
  303. var prop = source[key];
  304. if(prop && typeof prop === 'object'){
  305. if(prop.value !== undefined || typeof prop.get === 'function' || typeof prop.set === 'function'){
  306. defineProps = defineProps || {};
  307. defineProps[key] = prop;
  308. continue;
  309. }
  310. }
  311. target[key] = prop;
  312. }
  313. if(defineProps) defineProperties(target, defineProps);
  314. }
  315. return target;
  316. };
  317. try{
  318. var defineProperty = Object.defineProperty,
  319. defineProperties = Object.defineProperties;
  320. defineProperty({}, '$', {value:0});
  321. }catch(e){
  322. if('__defineGetter__' in Object){
  323. defineProperty = function(obj, prop, desc){
  324. if('value' in desc) obj[prop] = desc.value;
  325. if('get' in desc) obj.__defineGetter__(prop, desc.get);
  326. if('set' in desc) obj.__defineSetter__(prop, desc.set);
  327. return obj;
  328. };
  329. defineProperties = function(obj, props){
  330. for(var prop in props){
  331. if(props.hasOwnProperty(prop)){
  332. defineProperty(obj, prop, props[prop]);
  333. }
  334. }
  335. return obj;
  336. };
  337. }
  338. }
  339. return {create:create, mix:mix};
  340. })();
  341. /**
  342. * @class EventMixin是一个包含事件相关功能的mixin。可以通过 Class.mix(target, EventMixin) 来为target增加事件功能。
  343. * @mixin
  344. * @static
  345. * @module hilo/event/EventMixin
  346. * @requires hilo/core/Class
  347. */
  348. var EventMixin = {
  349. _listeners: null,
  350. /**
  351. * 增加一个事件监听。
  352. * @param {String} type 要监听的事件类型。
  353. * @param {Function} listener 事件监听回调函数。
  354. * @param {Boolean} once 是否是一次性监听,即回调函数响应一次后即删除,不再响应。
  355. */
  356. on: function(type, listener, once){
  357. var listeners = (this._listeners = this._listeners || {});
  358. var eventListeners = (listeners[type] = listeners[type] || []);
  359. for(var i = 0, len = eventListeners.length; i < len; i++){
  360. var el = eventListeners[i];
  361. if(el.listener === listener) return;
  362. }
  363. eventListeners.push({listener:listener, once:once});
  364. return this;
  365. },
  366. /**
  367. * 删除一个事件监听。如果不传入任何参数,则删除所有的事件监听;如果不传入第二个参数,则删除指定类型的所有事件监听。
  368. * @param {String} type 要删除监听的事件类型。
  369. * @param {Function} listener 要删除监听的回调函数。
  370. */
  371. off: function(type, listener){
  372. //remove all event listeners
  373. if(arguments.length == 0){
  374. this._listeners = null;
  375. return this;
  376. }
  377. var eventListeners = this._listeners && this._listeners[type];
  378. if(eventListeners){
  379. //remove event listeners by specified type
  380. if(arguments.length == 1){
  381. delete this._listeners[type];
  382. return this;
  383. }
  384. for(var i = 0, len = eventListeners.length; i < len; i++){
  385. var el = eventListeners[i];
  386. if(el.listener === listener){
  387. eventListeners.splice(i, 1);
  388. if(eventListeners.length === 0) delete this._listeners[type];
  389. break;
  390. }
  391. }
  392. }
  393. return this;
  394. },
  395. /**
  396. * 发送事件。当第一个参数类型为Object时,则把它作为一个整体事件对象。
  397. * @param {String} type 要发送的事件类型。
  398. * @param {Object} detail 要发送的事件的具体信息,即事件随带参数。
  399. */
  400. fire: function(type, detail){
  401. var event, eventType;
  402. if(typeof type === 'string'){
  403. eventType = type;
  404. }else{
  405. event = type;
  406. eventType = type.type;
  407. }
  408. var listeners = this._listeners;
  409. if(!listeners) return false;
  410. var eventListeners = listeners[eventType];
  411. if(eventListeners){
  412. eventListeners = eventListeners.slice(0);
  413. event = event || new EventObject(eventType, this, detail);
  414. for(var i = 0; i < eventListeners.length && !event._stopped; i++){
  415. var el = eventListeners[i];
  416. el.listener.call(this, event);
  417. if(el.once) eventListeners.splice(i--, 1);
  418. }
  419. if(eventListeners.length == 0) delete listeners[eventType];
  420. return true;
  421. }
  422. return false;
  423. }
  424. };
  425. /**
  426. * 事件对象类。当前仅为内部类,以后有需求的话可能会考虑独立为公开类。
  427. */
  428. var EventObject = Class.create({
  429. constructor: function EventObject(type, target, detail){
  430. this.type = type;
  431. this.target = target;
  432. this.detail = detail;
  433. this.timeStamp = +new Date();
  434. },
  435. type: null,
  436. target: null,
  437. detail: null,
  438. timeStamp: 0,
  439. stopImmediatePropagation: function(){
  440. this._stopped = true;
  441. }
  442. });
  443. /**
  444. * @class 渲染器抽象基类。
  445. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  446. * @module hilo/renderer/Renderer
  447. * @requires hilo/core/Hilo
  448. * @requires hilo/core/Class
  449. * @property {Object} canvas 渲染器对应的画布。它可能是一个普通的DOM元素,比如div,也可以是一个canvas画布元素。只读属性。
  450. * @property {Object} stage 渲染器对应的舞台。只读属性。
  451. */
  452. var Renderer = Class.create(/** @lends Renderer.prototype */{
  453. constructor: function Renderer(properties){
  454. properties = properties || {};
  455. Hilo.copy(this, properties, true);
  456. },
  457. canvas: null,
  458. stage: null,
  459. /**
  460. * 为开始绘制可视对象做准备。需要子类来实现。
  461. * @param {View} target 要绘制的可视对象。
  462. */
  463. startDraw: function(target){ },
  464. /**
  465. * 绘制可视对象。需要子类来实现。
  466. * @param {View} target 要绘制的可视对象。
  467. */
  468. draw: function(target){ },
  469. /**
  470. * 结束绘制可视对象后的后续处理方法。需要子类来实现。
  471. * @param {View} target 要绘制的可视对象。
  472. */
  473. endDraw: function(target){ },
  474. /**
  475. * 对可视对象进行变换。需要子类来实现。
  476. */
  477. transform: function(){ },
  478. /**
  479. * 隐藏可视对象。需要子类来实现。
  480. */
  481. hide: function(){ },
  482. /**
  483. * 从画布中删除可视对象。注意:不是从stage中删除对象。需要子类来实现。
  484. * @param {View} target 要删除的可视对象。
  485. */
  486. remove: function(target){ },
  487. /**
  488. * 清除画布指定区域。需要子类来实现。
  489. * @param {Number} x 指定区域的x轴坐标。
  490. * @param {Number} y 指定区域的y轴坐标。
  491. * @param {Number} width 指定区域的宽度。
  492. * @param {Number} height 指定区域的高度。
  493. */
  494. clear: function(x, y, width, height){ }
  495. });
  496. /**
  497. * @class canvas画布渲染器。所有可视对象将渲染在canvas画布上。
  498. * @augments Renderer
  499. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  500. * @module hilo/renderer/CanvasRenderer
  501. * @requires hilo/core/Class
  502. * @requires hilo/renderer/Renderer
  503. * @property {CanvasRenderingContext2D} context canvas画布的上下文。只读属性。
  504. */
  505. var CanvasRenderer = Class.create(/** @lends CanvasRenderer.prototype */{
  506. Extends: Renderer,
  507. constructor: function CanvasRenderer(properties){
  508. CanvasRenderer.superclass.constructor.call(this, properties);
  509. this.context = this.canvas.getContext("2d");
  510. },
  511. context: null,
  512. /**
  513. * @private
  514. * @see Renderer#startDraw
  515. */
  516. startDraw: function(target){
  517. if(target.visible && target.alpha > 0){
  518. if(target === this.stage){
  519. this.context.clearRect(0, 0, target.width, target.height);
  520. }
  521. this.context.save();
  522. return true;
  523. }
  524. return false;
  525. },
  526. /**
  527. * @private
  528. * @see Renderer#draw
  529. */
  530. draw: function(target){
  531. var ctx = this.context, w = target.width, h = target.height;
  532. //draw background fill
  533. var bgFill = target.bgFill;
  534. if(bgFill){
  535. ctx.fillStyle = bgFill.style;
  536. ctx.fillRect(bgFill.x, bgFill.y, bgFill.width || w, bgFill.height || h);
  537. }
  538. //draw image
  539. var drawable = target.drawable;
  540. if(drawable && drawable.image){
  541. var rect = drawable.rect, sw = rect[2], sh = rect[3];
  542. if(!w && !h){
  543. //fix width/height TODO: how to get rid of this?
  544. target.width = rect[2];
  545. target.height = rect[3];
  546. }
  547. ctx.drawImage(drawable.image, rect[0], rect[1], sw, sh, 0, 0, w, h);
  548. }
  549. },
  550. /**
  551. * @private
  552. * @see Renderer#endDraw
  553. */
  554. endDraw: function(target){
  555. this.context.restore();
  556. },
  557. /**
  558. * @private
  559. * @see Renderer#transform
  560. */
  561. transform: function(target){
  562. var ctx = this.context,
  563. scaleX = target.scaleX,
  564. scaleY = target.scaleY;
  565. if(target === this.stage){
  566. var style = this.canvas.style,
  567. oldScaleX = target._scaleX,
  568. oldScaleY = target._scaleY;
  569. if((!oldScaleX && scaleX != 1) || (oldScaleX && oldScaleX != scaleX)){
  570. target._scaleX = scaleX;
  571. style.width = scaleX * target.width + "px";
  572. }
  573. if((!oldScaleY && scaleY != 1) || (oldScaleY && oldScaleY != scaleY)){
  574. target._scaleY = scaleY;
  575. style.height = scaleY * target.height + "px";
  576. }
  577. }else{
  578. var x = target.x,
  579. y = target.y,
  580. pivotX = target.pivotX,
  581. pivotY = target.pivotY,
  582. rotation = target.rotation % 360;
  583. if(x != 0 || y != 0) ctx.translate(x, y);
  584. if(rotation != 0) ctx.rotate(rotation * Math.PI / 180);
  585. if(scaleX != 1 || scaleY != 1) ctx.scale(scaleX, scaleY);
  586. if(pivotX != 0 || pivotY != 0) ctx.translate(-pivotX, -pivotY);
  587. }
  588. if(target.alpha > 0) ctx.globalAlpha *= target.alpha;
  589. },
  590. /**
  591. * @private
  592. * @see Renderer#remove
  593. */
  594. remove: function(target){
  595. if(target instanceof DOMElement){
  596. var elem = target.drawable.domElement,
  597. parentElem = elem && elem.parentNode;
  598. if(parentElem){
  599. parentElem.removeChild(elem);
  600. }
  601. }
  602. },
  603. /**
  604. * @private
  605. * @see Renderer#clear
  606. */
  607. clear: function(x, y, width, height){
  608. this.context.clearRect(x, y, width, height);
  609. }
  610. });
  611. /**
  612. * @class DOM+CSS3渲染器。将可视对象以DOM元素方式渲染出来。
  613. * @augments Renderer
  614. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  615. * @module hilo/renderer/DOMRenderer
  616. * @requires hilo/core/Class
  617. * @requires hilo/core/Hilo
  618. * @requires hilo/renderer/Renderer
  619. */
  620. var DOMRenderer = (function(){
  621. return Class.create({
  622. Extends: Renderer,
  623. constructor: function DOMRenderer(properties){
  624. DOMRenderer.superclass.constructor.call(this, properties);
  625. },
  626. /**
  627. * @private
  628. * @see Renderer#startDraw
  629. */
  630. startDraw: function(target){
  631. if(target.visible && target.alpha > 0){
  632. //prepare drawable
  633. var drawable = (target.drawable = target.drawable || new Drawable());
  634. drawable.domElement = drawable.domElement || createDOMDrawable(target, drawable);
  635. return true;
  636. }
  637. return false;
  638. },
  639. /**
  640. * @private
  641. * @see Renderer#draw
  642. */
  643. draw: function(target){
  644. var parent = target.parent,
  645. targetElem = target.drawable.domElement,
  646. currentParent = targetElem.parentNode;
  647. if(parent){
  648. var parentElem = parent.drawable.domElement;
  649. if(parentElem != currentParent){
  650. parentElem.appendChild(targetElem);
  651. }
  652. }else if(target === stage && !currentParent){
  653. this.canvas.appendChild(targetElem);
  654. }
  655. },
  656. /**
  657. * @private
  658. * @see Renderer#transform
  659. */
  660. transform: function(target){
  661. Hilo.setElementStyleByView(target);
  662. },
  663. /**
  664. * @private
  665. * @see Renderer#remove
  666. */
  667. remove: function(target){
  668. var targetElem = target.drawable.domElement,
  669. parentElem = targetElem.parentNode;
  670. if(parentElem) parentElem.removeChild(targetElem);
  671. },
  672. /**
  673. * @private
  674. * @see Renderer#hide
  675. */
  676. hide: function(target){
  677. var elem = target.drawable && target.drawable.domElement;
  678. if(elem) elem.style.display = "none";
  679. }
  680. });
  681. /**
  682. * 创建一个可渲染的DOM,可指定tagName,如canvas或div。
  683. * @param {Object} view 一个可视对象或类似的对象。
  684. * @param {Object} imageObj 指定渲染的image及相关设置,如绘制区域rect。
  685. * @return {HTMLElement} 新创建的DOM对象。
  686. * @private
  687. */
  688. function createDOMDrawable(view, imageObj){
  689. var tag = view.tagName || "div",
  690. img = imageObj.image,
  691. w = view.width || (img && img.width),
  692. h = view.height || (img && img.height),
  693. elem = Hilo.createElement(tag), style = elem.style;
  694. if(view.id) elem.id = view.id;
  695. style.position = "absolute";
  696. style.left = (view.left || 0) + "px";
  697. style.top = (view.top || 0) + "px";
  698. style.width = w + "px";
  699. style.height = h + "px";
  700. if(tag == "canvas"){
  701. elem.width = w;
  702. elem.height = h;
  703. if(img){
  704. var ctx = elem.getContext("2d");
  705. var rect = imageObj.rect || [0, 0, w, h];
  706. ctx.drawImage(img, rect[0], rect[1], rect[2], rect[3],
  707. (view.x || 0), (view.y || 0),
  708. (view.width || rect[2]),
  709. (view.height || rect[3]));
  710. }
  711. }else{
  712. style.opacity = view.alpha != undefined ? view.alpha : 1;
  713. if(view === stage || view.clipChildren) style.overflow = "hidden";
  714. if(img && img.src){
  715. style.backgroundImage = "url(" + img.src + ")";
  716. var bgX = view.rectX || 0, bgY = view.rectY || 0;
  717. style.backgroundPosition = (-bgX) + "px " + (-bgY) + "px";
  718. }
  719. }
  720. return elem;
  721. }
  722. })();
  723. /**
  724. * @class Matrix类表示一个转换矩阵,它确定如何将点从一个坐标空间映射到另一个坐标空间。
  725. * @param {Number} a 缩放或旋转图像时影响像素沿 x 轴定位的值。
  726. * @param {Number} b 旋转或倾斜图像时影响像素沿 y 轴定位的值。
  727. * @param {Number} c 旋转或倾斜图像时影响像素沿 x 轴定位的值。
  728. * @param {Number} d 缩放或旋转图像时影响像素沿 y 轴定位的值。
  729. * @param {Number} tx 沿 x 轴平移每个点的距离。
  730. * @param {Number} ty 沿 y 轴平移每个点的距离。
  731. * @module hilo/geom/Matrix
  732. * @requires hilo/core/Class
  733. */
  734. var Matrix = Class.create(/** @lends Matrix.prototype */{
  735. constructor: function Matrix(a, b, c, d, tx, ty){
  736. this.a = a;
  737. this.b = b;
  738. this.c = c;
  739. this.d = d;
  740. this.tx = tx;
  741. this.ty = ty;
  742. },
  743. /**
  744. * 将某个矩阵与当前矩阵连接,从而将这两个矩阵的几何效果有效地结合在一起。
  745. * @param {Matrix} mtx 要连接到源矩阵的矩阵。
  746. * @returns {Matrix} 一个Matrix对象。
  747. */
  748. concat: function(mtx){
  749. var args = arguments,
  750. a = this.a, b = this.b, c = this.c, d = this.d,
  751. tx = this.tx, ty = this.ty;
  752. if(args.length >= 6){
  753. var ma = args[0], mb = args[1], mc = args[2],
  754. md = args[3], mx = args[4], my = args[5];
  755. }else{
  756. ma = mtx.a;
  757. mb = mtx.b;
  758. mc = mtx.c;
  759. md = mtx.d;
  760. mx = mtx.tx;
  761. my = mtx.ty;
  762. }
  763. this.a = a * ma + b * mc;
  764. this.b = a * mb + b * md;
  765. this.c = c * ma + d * mc;
  766. this.d = c * mb + d * md;
  767. this.tx = tx * ma + ty * mc + mx;
  768. this.ty = tx * mb + ty * md + my;
  769. return this;
  770. },
  771. /**
  772. * 对 Matrix 对象应用旋转转换。
  773. * @param {Number} angle 旋转的角度。
  774. * @returns {Matrix} 一个Matrix对象。
  775. */
  776. rotate: function(angle){
  777. var sin = Math.sin(angle), cos = Math.cos(angle),
  778. a = this.a, b = this.b, c = this.c, d = this.d,
  779. tx = this.tx, ty = this.ty;
  780. this.a = a * cos - b * sin;
  781. this.b = a * sin + b * cos;
  782. this.c = c * cos - d * sin;
  783. this.d = c * sin + d * cos;
  784. this.tx = tx * cos - ty * sin;
  785. this.ty = tx * sin + ty * cos;
  786. return this;
  787. },
  788. /**
  789. * 对矩阵应用缩放转换。
  790. * @param {Number} sx 用于沿 x 轴缩放对象的乘数。
  791. * @param {Number} sy 用于沿 y 轴缩放对象的乘数。
  792. * @returns {Matrix} 一个Matrix对象。
  793. */
  794. scale: function(sx, sy){
  795. this.a *= sx;
  796. this.d *= sy;
  797. this.tx *= sx;
  798. this.ty *= sy;
  799. return this;
  800. },
  801. /**
  802. * 沿 x 和 y 轴平移矩阵,由 dx 和 dy 参数指定。
  803. * @param {Number} dx 沿 x 轴向右移动的量(以像素为单位)。
  804. * @param {Number} dy 沿 y 轴向右移动的量(以像素为单位)。
  805. * @returns {Matrix} 一个Matrix对象。
  806. */
  807. translate: function(dx, dy){
  808. this.tx += dx;
  809. this.ty += dy;
  810. return this;
  811. },
  812. /**
  813. * 为每个矩阵属性设置一个值,该值将导致 null 转换。通过应用恒等矩阵转换的对象将与原始对象完全相同。
  814. * @returns {Matrix} 一个Matrix对象。
  815. */
  816. identity: function(){
  817. this.a = this.d = 1;
  818. this.b = this.c = this.tx = this.ty = 0;
  819. return this;
  820. },
  821. /**
  822. * 执行原始矩阵的逆转换。您可以将一个逆矩阵应用于对象来撤消在应用原始矩阵时执行的转换。
  823. * @returns {Matrix} 一个Matrix对象。
  824. */
  825. invert: function(){
  826. var a = this.a;
  827. var b = this.b;
  828. var c = this.c;
  829. var d = this.d;
  830. var tx = this.tx;
  831. var i = a * d - b * c;
  832. this.a = d / i;
  833. this.b = -b / i;
  834. this.c = -c / i;
  835. this.d = a / i;
  836. this.tx = (c * this.ty - d * tx) / i;
  837. this.ty = -(a * this.ty - b * tx) / i;
  838. return this;
  839. },
  840. /**
  841. * 返回将 Matrix 对象表示的几何转换应用于指定点所产生的结果。
  842. * @param {Object} point 想要获得其矩阵转换结果的点。
  843. * @param {Boolean} round 是否对点的坐标进行向上取整。
  844. * @param {Boolean} returnNew 是否返回一个新的点。
  845. * @returns {Object} 由应用矩阵转换所产生的点。
  846. */
  847. transformPoint: function(point, round, returnNew){
  848. var x = point.x * this.a + point.y * this.c + this.tx,
  849. y = point.x * this.b + point.y * this.d + this.ty;
  850. if(round){
  851. x = x + 0.5 >> 0;
  852. y = y + 0.5 >> 0;
  853. }
  854. if(returnNew) return {x:x, y:y};
  855. point.x = x;
  856. point.y = y;
  857. return point;
  858. }
  859. });
  860. /**
  861. * @class Drawable是可绘制图像的包装。
  862. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  863. * @module hilo/view/Drawable
  864. * @requires hilo/core/Hilo
  865. * @requires hilo/core/Class
  866. * @property {Object} image 要绘制的图像。即可被CanvasRenderingContext2D.drawImage使用的对象类型,可以是HTMLImageElement、HTMLCanvasElement、HTMLVideoElement等对象。
  867. * @property {array} rect 要绘制的图像的矩形区域。
  868. */
  869. var Drawable = Class.create(/** @lends Drawable.prototype */{
  870. constructor: function Drawable(properties){
  871. this.init(properties);
  872. },
  873. image: null,
  874. rect: null,
  875. /**
  876. * 初始化可绘制对象。
  877. * @param {Object} properties 要初始化的属性。
  878. */
  879. init: function(properties){
  880. var me = this, oldImage = me.image;
  881. if(Drawable.isDrawable(properties)){
  882. me.image = properties;
  883. }else{
  884. Hilo.copy(me, properties, true);
  885. }
  886. var image = me.image;
  887. if(typeof image === 'string'){
  888. if(oldImage && image === oldImage.getAttribute('src')){
  889. image = me.image = oldImage;
  890. }else{
  891. me.image = null;
  892. //load image dynamically
  893. var img = new Image();
  894. img.onload = function(){
  895. img.onload = null;
  896. me.init(img);
  897. };
  898. img.src = image;
  899. return;
  900. }
  901. }
  902. if(image && !me.rect) me.rect = [0, 0, image.width, image.height];
  903. },
  904. Statics: /** @lends Drawable */{
  905. /**
  906. * 判断参数elem指定的元素是否可包装成Drawable对象。
  907. * @param {Object} elem 要测试的对象。
  908. * @return {Boolean} 如果是可包装成Drawable对象则返回true,否则为false。
  909. */
  910. isDrawable: function(elem){
  911. return (elem instanceof HTMLImageElement) ||
  912. (elem instanceof HTMLCanvasElement) ||
  913. (elem instanceof HTMLVideoElement);
  914. }
  915. }
  916. });
  917. /**
  918. * @class View类是所有可视对象或组件的基类。
  919. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  920. * @module hilo/view/View
  921. * @requires hilo/core/Hilo
  922. * @requires hilo/core/Class
  923. * @requires hilo/event/EventMixin
  924. * @property {String} id 可视对象的唯一标识符。
  925. * @property {Number} x 可视对象的x轴坐标。默认值为0。
  926. * @property {Number} y 可视对象的y轴坐标。默认值为0。
  927. * @property {Number} width 可视对象的宽度。默认值为0。
  928. * @property {Number} height 可视对象的高度。默认值为0。
  929. * @property {Number} alpha 可视对象的透明度。默认值为1。
  930. * @property {Number} rotation 可视对象的旋转角度。默认值为0。
  931. * @property {Boolean} visible 可视对象是否可见。默认为可见,即true。
  932. * @property {Number} pivotX 可视对象的中心点的x轴坐标。默认值为0。
  933. * @property {Number} pivotY 可视对象的中心点的y轴坐标。默认值为0。
  934. * @property {Number} scaleX 可视对象在x轴上的缩放比例。默认为不缩放,即1。
  935. * @property {Number} scaleY 可视对象在y轴上的缩放比例。默认为不缩放,即1。
  936. * @property {Boolean} pointerEnabled 可视对象是否接受交互事件。默认为接受交互事件,即true。
  937. * @property {Container} parent 可视对象的父容器。只读属性。
  938. * @property {Stage} stage 可视对象的舞台实例。只读属性。
  939. * @property {Number} depth 可视对象的深度,也即z轴的序号。只读属性。
  940. * @property {Number} measuredWidth 可视对象的测量宽度。只读属性。
  941. * @property {Number} measuredHeight 可视对象的测量高度。只读属性。
  942. * @property {Drawable} drawable 可视对象的可绘制对象。
  943. * @property {Array} boundsArea 可视对象的区域顶点数组。格式为:[{x:10, y:10}, {x:20, y:20}]。
  944. */
  945. var View = (function(){
  946. return Class.create(/** @lends View.prototype */{
  947. Mixes: EventMixin,
  948. constructor: function View(properties){
  949. properties = properties || {};
  950. this.id = this.id || properties.id || Hilo.getUid("View");
  951. Hilo.copy(this, properties, true);
  952. },
  953. id: null,
  954. x: 0,
  955. y: 0,
  956. width: 0,
  957. height: 0,
  958. alpha: 1,
  959. rotation: 0,
  960. visible: true,
  961. pivotX: 0,
  962. pivotY: 0,
  963. scaleX: 1,
  964. scaleY: 1,
  965. pointerEnabled: true,
  966. drawable: null,
  967. boundsArea: null,
  968. parent: null,
  969. depth: -1,
  970. stage: {
  971. get: function(){
  972. var obj = this, parent;
  973. while(parent = obj.parent) obj = parent;
  974. //NOTE: don't use `instanceof` to prevent circular module requirement.
  975. //But it's not a very reliable way to check it's a stage instance.
  976. if(obj.canvas) return obj;
  977. return null;
  978. }
  979. },
  980. measuredWidth: {
  981. get: function(){
  982. return this.width * this.scaleX;
  983. }
  984. },
  985. measuredHeight: {
  986. get: function(){
  987. return this.height * this.scaleY;
  988. }
  989. },
  990. /**
  991. * 添加此对象到父容器。
  992. * @param {Container} container 一个容器。
  993. * @param {Uint} index 要添加到索引位置。
  994. * @returns 可视对象本身。
  995. */
  996. addTo: function(container, index){
  997. if(typeof index === 'number') container.addChildAt(this, index);
  998. else container.addChild(this);
  999. return this;
  1000. },
  1001. /**
  1002. * 从父容器里删除此对象。
  1003. * @returns 可视对象本身。
  1004. */
  1005. removeFromParent: function(){
  1006. var parent = this.parent;
  1007. if(parent) parent.removeChild(this);
  1008. return this;
  1009. },
  1010. /**
  1011. * 设置背景填充样式。限制:DOMRenderer仅支持CSS颜色填充样式。
  1012. * @param {Object} fillStyle 填充样式。可以是CSS颜色值、canvas的gradient或pattern填充。
  1013. * @param {Number} x 背景填充的起始点的x轴坐标。
  1014. * @param {Number} y 背景填充的起始点的y轴坐标。
  1015. * @param {Number} width 背景填充的区域宽度。
  1016. * @param {Number} height 背景填充的区域高度。
  1017. * @returns 可视对象本身。
  1018. */
  1019. setBgFill: function(fillStyle, x, y, width, height){
  1020. if(fillStyle){
  1021. var bgFill = this.bgFill || (this.bgFill = {});
  1022. bgFill.style = fillStyle;
  1023. bgFill.x = x || 0;
  1024. bgFill.y = y || 0;
  1025. if(width) bgFill.width = width;
  1026. if(height) bgFill.height = height;
  1027. }else{
  1028. this.bgFill = null;
  1029. }
  1030. return this;
  1031. },
  1032. /**
  1033. * 获取可视对象在舞台全局坐标系内的外接矩形以及所有顶点坐标。
  1034. * @returns {Array} 可视对象的顶点坐标数组vertexs。另vertexs还包含属性:
  1035. * <ul>
  1036. * <li><b>x</b> - 可视对象的外接矩形x轴坐标。</li>
  1037. * <li><b>y</b> - 可视对象的外接矩形y轴坐标。</li>
  1038. * <li><b>width</b> - 可视对象的外接矩形的宽度。</li>
  1039. * <li><b>height</b> - 可视对象的外接矩形的高度。</li>
  1040. * </ul>
  1041. */
  1042. getBounds: function(){
  1043. var w = this.width, h = this.height,
  1044. mtx = this.getConcatenatedMatrix(),
  1045. poly = this.boundsArea || [{x:0, y:0}, {x:w, y:0}, {x:w, y:h}, {x:0, y:h}],
  1046. vertexs = [], point, x, y, minX, maxX, minY, maxY;
  1047. for(var i = 0, len = poly.length; i < len; i++){
  1048. point = mtx.transformPoint(poly[i], true, true);
  1049. x = point.x;
  1050. y = point.y;
  1051. if(i == 0){
  1052. minX = maxX = x;
  1053. minY = maxY = y;
  1054. }else{
  1055. if(minX > x) minX = x;
  1056. else if(maxX < x) maxX = x;
  1057. if(minY > y) minY = y;
  1058. else if(maxY < y) maxY = y;
  1059. }
  1060. vertexs[i] = point;
  1061. }
  1062. vertexs.x = minX;
  1063. vertexs.y = minY;
  1064. vertexs.width = maxX - minX;
  1065. vertexs.height = maxY - minY;
  1066. return vertexs;
  1067. },
  1068. /**
  1069. * 获取可视对象相对于其某个祖先(默认为舞台Stage)的连接矩阵。
  1070. * @param {View} ancestor 可视对象的相对的祖先容器。
  1071. * @private
  1072. */
  1073. getConcatenatedMatrix: function(ancestor){
  1074. var mtx = new Matrix(1, 0, 0, 1, 0, 0);
  1075. if(ancestor !== this){
  1076. for(var o = this; o.parent && o.parent != ancestor; o = o.parent){
  1077. var cos = 1, sin = 0,
  1078. rotation = o.rotation % 360,
  1079. pivotX = o.pivotX, pivotY = o.pivotY,
  1080. scaleX = o.scaleX, scaleY = o.scaleY;
  1081. if(rotation){
  1082. var r = rotation * Math.PI / 180;
  1083. cos = Math.cos(r);
  1084. sin = Math.sin(r);
  1085. }
  1086. if(pivotX != 0) mtx.tx -= pivotX;
  1087. if(pivotY != 0) mtx.ty -= pivotY;
  1088. mtx.concat(cos*scaleX, sin*scaleX, -sin*scaleY, cos*scaleY, o.x, o.y);
  1089. }
  1090. }
  1091. return mtx;
  1092. },
  1093. /**
  1094. * 检测由x和y参数指定的点是否在其外接矩形之内。
  1095. * @param {Number} x 要检测的点的x轴坐标。
  1096. * @param {Number} y 要检测的点的y轴坐标。
  1097. * @param {Boolean} usePolyCollision 是否使用多边形碰撞检测。默认为false。
  1098. * @returns {Boolean} 点是否在可视对象之内。
  1099. */
  1100. hitTestPoint: function(x, y, usePolyCollision){
  1101. var bound = this.getBounds(),
  1102. hit = x >= bound.x && x <= bound.x + bound.width &&
  1103. y >= bound.y && y <= bound.y + bound.height;
  1104. if(hit && usePolyCollision){
  1105. hit = pointInPolygon(x, y, bound);
  1106. }
  1107. return hit;
  1108. },
  1109. /**
  1110. * 检测object参数指定的对象是否与其相交。
  1111. * @param {View} object 要检测的可视对象。
  1112. * @param {Boolean} usePolyCollision 是否使用多边形碰撞检测。默认为false。
  1113. */
  1114. hitTestObject: function(object, usePolyCollision){
  1115. var b1 = this.getBounds(),
  1116. b2 = object.getBounds(),
  1117. hit = b1.x <= b2.x + b2.width && b2.x <= b1.x + b1.width &&
  1118. b1.y <= b2.y + b2.height && b2.y <= b1.y + b1.height;
  1119. if(hit && usePolyCollision){
  1120. hit = polygonCollision(b1, b2);
  1121. }
  1122. return !!hit;
  1123. },
  1124. /**
  1125. * 可视对象的基本渲染实现,用于框架内部或高级开发使用。通常应该重写render方法。
  1126. * @param {Renderer} renderer 渲染器。
  1127. * @param {Number} delta 渲染时时间偏移量。
  1128. * @protected
  1129. */
  1130. _render: function(renderer, delta){
  1131. if((!this.onUpdate || this.onUpdate(delta) !== false) && renderer.startDraw(this)){
  1132. renderer.transform(this);
  1133. this.render(renderer, delta);
  1134. renderer.endDraw(this);
  1135. }
  1136. },
  1137. /**
  1138. * 更新可视对象,此方法会在可视对象渲染之前调用。此函数可以返回一个Boolean值。若返回false,则此对象不会渲染。默认值为null。
  1139. * 限制:如果在此函数中改变了可视对象在其父容器中的层级,当前渲染帧并不会正确渲染,而是在下一渲染帧。可在其父容器的onUpdate方法中来实现。
  1140. * @type Function
  1141. * @default null
  1142. */
  1143. onUpdate: null,
  1144. /**
  1145. * 可视对象的具体渲染逻辑。子类可通过覆盖此方法实现自己的渲染。
  1146. * @param {Renderer} renderer 渲染器。
  1147. * @param {Number} delta 渲染时时间偏移量。
  1148. */
  1149. render: function(renderer, delta){
  1150. renderer.draw(this);
  1151. },
  1152. /**
  1153. * 返回可视对象的字符串表示。
  1154. * @returns {String} 可视对象的字符串表示。
  1155. */
  1156. toString: function(){
  1157. return Hilo.viewToString(this);
  1158. }
  1159. });
  1160. /**
  1161. * @private
  1162. */
  1163. function pointInPolygon(x, y, poly){
  1164. var cross = 0, onBorder = false, minX, maxX, minY, maxY;
  1165. for(var i = 0, len = poly.length; i < len; i++){
  1166. var p1 = poly[i], p2 = poly[(i+1)%len];
  1167. if(p1.y == p2.y && y == p1.y){
  1168. p1.x > p2.x ? (minX = p2.x, maxX = p1.x) : (minX = p1.x, maxX = p2.x);
  1169. if(x >= minX && x <= maxX){
  1170. onBorder = true;
  1171. continue;
  1172. }
  1173. }
  1174. p1.y > p2.y ? (minY = p2.y, maxY = p1.y) : (minY = p1.y, maxY = p2.y);
  1175. if(y < minY || y > maxY) continue;
  1176. var nx = (y - p1.y)*(p2.x - p1.x) / (p2.y - p1.y) + p1.x;
  1177. if(nx > x) cross++;
  1178. else if(nx == x) onBorder = true;
  1179. }
  1180. return onBorder || (cross % 2 == 1);
  1181. }
  1182. /**
  1183. * @private
  1184. */
  1185. function polygonCollision(poly1, poly2){
  1186. var result = doSATCheck(poly1, poly2, {overlap:-Infinity, normal:{x:0, y:0}});
  1187. if(result) return doSATCheck(poly2, poly1, result);
  1188. return false;
  1189. }
  1190. /**
  1191. * @private
  1192. */
  1193. function doSATCheck(poly1, poly2, result){
  1194. var len1 = poly1.length, len2 = poly2.length,
  1195. currentPoint, nextPoint, distance,
  1196. min1, max1, min2, max2, dot, overlap, normal = {x:0, y:0};
  1197. for(var i = 0; i < len1; i++){
  1198. currentPoint = poly1[i];
  1199. nextPoint = poly1[(i < len1-1 ? i+1 : 0)];
  1200. normal.x = currentPoint.y - nextPoint.y;
  1201. normal.y = nextPoint.x - currentPoint.x;
  1202. distance = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
  1203. normal.x /= distance;
  1204. normal.y /= distance;
  1205. min1 = max1 = poly1[0].x * normal.x + poly1[0].y * normal.y;
  1206. for(var j = 1; j < len1; j++){
  1207. dot = poly1[j].x * normal.x + poly1[j].y * normal.y;
  1208. if(dot > max1) max1 = dot;
  1209. else if(dot < min1) min1 = dot;
  1210. }
  1211. min2 = max2 = poly2[0].x * normal.x + poly2[0].y * normal.y;
  1212. for(j = 1; j < len2; j++){
  1213. dot = poly2[j].x * normal.x + poly2[j].y * normal.y;
  1214. if(dot > max2) max2 = dot;
  1215. else if(dot < min2) min2 = dot;
  1216. }
  1217. if(min1 < min2){
  1218. overlap = min2 - max1;
  1219. normal.x = -normal.x;
  1220. normal.y = -normal.y;
  1221. }else{
  1222. overlap = min1 - max2;
  1223. }
  1224. if(overlap >= 0){
  1225. return false;
  1226. }else if(overlap > result.overlap){
  1227. result.overlap = overlap;
  1228. result.normal.x = normal.x;
  1229. result.normal.y = normal.y;
  1230. }
  1231. }
  1232. return result;
  1233. }
  1234. })();
  1235. /**
  1236. * @class Container是所有容器类的基类。每个Container都可以添加其他可视对象为子级。
  1237. * @augments View
  1238. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  1239. * @module hilo/view/Container
  1240. * @requires hilo/core/Hilo
  1241. * @requires hilo/core/Class
  1242. * @requires hilo/view/View
  1243. * @property {Array} children 容器的子元素列表。只读。
  1244. * @property {Number} numChildren 容器的子元素数量。只读。
  1245. * @property {Boolean} pointerChildren 指示容器的子元素是否能响应用户交互事件。默认为true。
  1246. * @property {Boolean} clipChildren 指示是否裁剪超出容器范围的子元素。默认为false。
  1247. */
  1248. var Container = Class.create(/** @lends Container.prototype */{
  1249. Extends: View,
  1250. constructor: function Container(properties){
  1251. properties = properties || {};
  1252. this.id = this.id || properties.id || Hilo.getUid("Container");
  1253. Container.superclass.constructor.call(this, properties);
  1254. if(this.children) this._updateChildren();
  1255. else this.children = [];
  1256. },
  1257. children: null,
  1258. pointerChildren: true,
  1259. clipChildren: false,
  1260. numChildren: {
  1261. get: function(){
  1262. return this.children.length;
  1263. }
  1264. },
  1265. /**
  1266. * 在指定索引位置添加子元素。
  1267. * @param {View} child 要添加的子元素。
  1268. * @param {Number} index 指定的索引位置,从0开始。
  1269. */
  1270. addChildAt: function(child, index){
  1271. var children = this.children,
  1272. len = children.length,
  1273. parent = child.parent;
  1274. index = index < 0 ? 0 : index > len ? len : index;
  1275. var childIndex = this.getChildIndex(child);
  1276. if(childIndex == index){
  1277. return this;
  1278. }else if(childIndex >= 0){
  1279. children.splice(childIndex, 1);
  1280. }else if(parent){
  1281. parent.removeChild(child);
  1282. }
  1283. children.splice(index, 0, child);
  1284. this._updateChildren(index);
  1285. return this;
  1286. },
  1287. /**
  1288. * 在最上面添加子元素。
  1289. * @param {View} child 要添加的子元素。
  1290. */
  1291. addChild: function(child){
  1292. var total = this.children.length,
  1293. args = arguments;
  1294. for(var i = 0, len = args.length; i < len; i++){
  1295. this.addChildAt(args[i], total + i);
  1296. }
  1297. return this;
  1298. },
  1299. /**
  1300. * 在指定索引位置删除子元素。
  1301. * @param {Int} index 指定删除元素的索引位置,从0开始。
  1302. * @returns 被删除的对象。
  1303. */
  1304. removeChildAt: function(index){
  1305. var children = this.children;
  1306. if(index < 0 || index >= children.length) return null;
  1307. var child = children[index];
  1308. if(child){
  1309. var stage = this.stage;
  1310. if(stage) stage.renderer.remove(child);
  1311. child.parent = null;
  1312. child.depth = -1;
  1313. }
  1314. children.splice(index, 1);
  1315. this._updateChildren(index);
  1316. return child;
  1317. },
  1318. /**
  1319. * 删除指定的子元素。
  1320. * @param {View} child 指定要删除的子元素。
  1321. * @returns 被删除的对象。
  1322. */
  1323. removeChild: function(child){
  1324. return this.removeChildAt(this.getChildIndex(child));
  1325. },
  1326. /**
  1327. * 删除指定id的子元素。
  1328. * @param {String} id 指定要删除的子元素的id。
  1329. * @returns 被删除的对象。
  1330. */
  1331. removeChildById: function(id){
  1332. var children = this.children, child;
  1333. for(var i = 0, len = children.length; i < len; i++){
  1334. child = children[i];
  1335. if(child.id === id){
  1336. this.removeChildAt(i);
  1337. return child;
  1338. }
  1339. }
  1340. return null;
  1341. },
  1342. /**
  1343. * 删除所有的子元素。
  1344. */
  1345. removeAllChildren: function(){
  1346. while(this.children.length) this.removeChildAt(0);
  1347. return this;
  1348. },
  1349. /**
  1350. * 返回指定索引位置的子元素。
  1351. * @param {Number} index 指定要返回的子元素的索引值,从0开始。
  1352. */
  1353. getChildAt: function(index){
  1354. var children = this.children;
  1355. if(index < 0 || index >= children.length) return null;
  1356. return children[index];
  1357. },
  1358. /**
  1359. * 返回指定id的子元素。
  1360. * @param {String} id 指定要返回的子元素的id。
  1361. */
  1362. getChildById: function(id){
  1363. var children = this.children, child;
  1364. for(var i = 0, len = children.length; i < len; i++){
  1365. child = children[i];
  1366. if(child.id === id) return child;
  1367. }
  1368. return null;
  1369. },
  1370. /**
  1371. * 返回指定子元素的索引值。
  1372. * @param {View} child 指定要返回索引值的子元素。
  1373. */
  1374. getChildIndex: function(child){
  1375. return this.children.indexOf(child);
  1376. },
  1377. /**
  1378. * 设置子元素的索引位置。
  1379. * @param {View} child 指定要设置的子元素。
  1380. * @param {Number} index 指定要设置的索引值。
  1381. */
  1382. setChildIndex: function(child, index){
  1383. var children = this.children,
  1384. oldIndex = children.indexOf(child);
  1385. if(oldIndex >= 0 && oldIndex != index){
  1386. var len = children.length;
  1387. index = index < 0 ? 0 : index >= len ? len - 1 : index;
  1388. children.splice(oldIndex, 1);
  1389. children.splice(index, 0, child);
  1390. this._updateChildren();
  1391. }
  1392. return this;
  1393. },
  1394. /**
  1395. * 交换两个子元素的索引位置。
  1396. * @param {View} child1 指定要交换的子元素A。
  1397. * @param {View} child2 指定要交换的子元素B。
  1398. */
  1399. swapChildren: function(child1, child2){
  1400. var children = this.children,
  1401. index1 = this.getChildIndex(child1),
  1402. index2 = this.getChildIndex(child2);
  1403. child1.depth = index2;
  1404. children[index2] = child1;
  1405. child2.depth = index1;
  1406. children[index1] = child2;
  1407. },
  1408. /**
  1409. * 交换两个指定索引位置的子元素。
  1410. * @param {Number} index1 指定要交换的索引位置A。
  1411. * @param {Number} index2 指定要交换的索引位置B。
  1412. */
  1413. swapChildrenAt: function(index1, index2){
  1414. var children = this.children,
  1415. child1 = this.getChildAt(index1),
  1416. child2 = this.getChildAt(index2);
  1417. child1.depth = index2;
  1418. children[index2] = child1;
  1419. child2.depth = index1;
  1420. children[index1] = child2;
  1421. },
  1422. /**
  1423. * 根据指定键值或函数对子元素进行排序。
  1424. * @param {Object} keyOrFunction 如果此参数为String时,则根据子元素的某个属性值进行排序;如果此参数为Function时,则根据此函数进行排序。
  1425. */
  1426. sortChildren: function(keyOrFunction){
  1427. var fn = keyOrFunction,
  1428. children = this.children;
  1429. if(typeof fn == "string"){
  1430. var key = fn;
  1431. fn = function(a, b){
  1432. return b[key] - a[key];
  1433. };
  1434. }
  1435. children.sort(fn);
  1436. this._updateChildren();
  1437. },
  1438. /**
  1439. * 更新子元素。
  1440. * @private
  1441. */
  1442. _updateChildren: function(start, end){
  1443. var children = this.children, child,
  1444. start = start || 0,
  1445. end = end || children.length;
  1446. for(var i = start; i < end; i++){
  1447. child = children[i];
  1448. child.depth = i + 1;
  1449. child.parent = this;
  1450. }
  1451. },
  1452. /**
  1453. * 返回是否包含参数指定的子元素。
  1454. * @param {View} child 指定要测试的子元素。
  1455. */
  1456. contains: function(child){
  1457. return this.getChildIndex(child) >= 0;
  1458. },
  1459. /**
  1460. * 返回由x和y指定的点下的对象。
  1461. * @param {Number} x 指定点的x轴坐标。
  1462. * @param {Number} y 指定点的y轴坐标。
  1463. * @param {Boolean} usePolyCollision 指定是否使用多边形碰撞检测。默认为false。
  1464. * @param {Boolean} global 使用此标志表明将查找所有符合的对象,而不仅仅是第一个,即全局匹配。默认为false。
  1465. * @param {Boolean} eventMode 使用此标志表明将在事件模式下查找对象。默认为false。
  1466. */
  1467. getViewAtPoint: function(x, y, usePolyCollision, global, eventMode){
  1468. var result = global ? [] : null,
  1469. children = this.children, child, obj;
  1470. for(var i = children.length - 1; i >= 0; i--){
  1471. child = children[i];
  1472. //skip child which is not shown or pointer enabled
  1473. if(!child || !child.visible || child.alpha <= 0 || (eventMode && !child.pointerEnabled)) continue;
  1474. //find child recursively
  1475. if(child.children && child.numChildren && !(eventMode && !child.pointerChildren)){
  1476. obj = child.getViewAtPoint(x, y, usePolyCollision, global, eventMode);
  1477. }
  1478. if(obj){
  1479. if(!global) return obj;
  1480. else if(obj.length) result = result.concat(obj);
  1481. }else if(child.hitTestPoint(x, y, usePolyCollision)){
  1482. if(!global) return child;
  1483. else result.push(child);
  1484. }
  1485. }
  1486. return global && result.length ? result : null;
  1487. },
  1488. /**
  1489. * 覆盖渲染方法。
  1490. * @private
  1491. */
  1492. render: function(renderer, delta){
  1493. Container.superclass.render.call(this, renderer, delta);
  1494. var children = this.children.slice(0), i, len, child;
  1495. for(i = 0, len = children.length; i < len; i++){
  1496. child = children[i];
  1497. //NOTE: the child could remove or change it's parent
  1498. if(child.parent === this) child._render(renderer, delta);
  1499. }
  1500. }
  1501. });
  1502. /**
  1503. * @class 舞台是可视对象树的根,可视对象只有添加到舞台或其子对象后才会被渲染出来。
  1504. * @augments Container
  1505. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  1506. * @module hilo/view/Stage
  1507. * @requires hilo/core/Hilo
  1508. * @requires hilo/core/Class
  1509. * @requires hilo/view/Container
  1510. * @requires hilo/renderer/CanvasRenderer
  1511. * @property {HTMLElement} canvas 舞台所对应的画布。它可以是一个canvas或一个普通的div。只读属性。
  1512. * @property {Renderer} renderer 舞台渲染器。只读属性。
  1513. * @property {Boolean} paused 指示舞台是否暂停刷新渲染。
  1514. * @property {Object} viewport 舞台内容在页面中的渲染区域。包含的属性有:left、top、width、height。只读属性。
  1515. */
  1516. var Stage = Class.create(/** @lends Stage.prototype */{
  1517. Extends: Container,
  1518. constructor: function Stage(properties){
  1519. properties = properties || {};
  1520. this.id = this.id || properties.id || Hilo.getUid('Stage');
  1521. Stage.superclass.constructor.call(this, properties);
  1522. //init canvas
  1523. var canvas = this.canvas;
  1524. if(typeof canvas === 'string') canvas = Hilo.getElement(canvas);
  1525. if(!canvas){
  1526. canvas = Hilo.createElement('canvas', {
  1527. style: {
  1528. position: 'absolute'
  1529. }
  1530. });
  1531. }
  1532. this.canvas = canvas;
  1533. if(canvas.parentNode) this.updateViewport();
  1534. if(!properties.width) this.width = this.viewport.width || 320;
  1535. if(!properties.height) this.height = this.viewport.height || 480;
  1536. var isCanvas = canvas.getContext;
  1537. if(isCanvas){
  1538. canvas.width = this.width;
  1539. canvas.height = this.height;
  1540. }
  1541. //init renderer
  1542. var props = {canvas:canvas, stage:this};
  1543. this.renderer = isCanvas ? new CanvasRenderer(props) : new DOMRenderer(props);
  1544. },
  1545. canvas: null,
  1546. renderer: null,
  1547. paused: false,
  1548. viewport: null,
  1549. /**
  1550. * 调用tick会触发舞台的更新和渲染。
  1551. */
  1552. tick: function(delta){
  1553. if(!this.paused){
  1554. this._render(this.renderer, delta);
  1555. }
  1556. },
  1557. /**
  1558. * 开启/关闭DOM事件功能。
  1559. */
  1560. enableDOMEvent: function(type, enable){
  1561. var me = this,
  1562. canvas = me.canvas,
  1563. types = typeof type === 'string' ? [type] : type,
  1564. handler = me._domListener || (me._domListener = function(e){me._onDOMEvent(e)});
  1565. for(var i = 0; i < types.length; i++){
  1566. var type = types[i];
  1567. if(enable === false){
  1568. canvas.removeEventListener(type, handler);
  1569. }else{
  1570. canvas.addEventListener(type, handler, false);
  1571. }
  1572. }
  1573. },
  1574. /**
  1575. * DOM事件处理函数。此方法会把事件调度到事件的坐标点所对应的可视对象。
  1576. * @private
  1577. */
  1578. _onDOMEvent: function(e){
  1579. var type = e.type, event = e, isTouch = type.indexOf('touch') == 0;
  1580. //calculate stageX/stageY
  1581. var posObj = e;
  1582. if(isTouch){
  1583. var touches = e.touches, changedTouches = e.changedTouches;
  1584. posObj = (touches && touches.length) ? touches[0] :
  1585. (changedTouches && changedTouches.length) ? changedTouches[0] : null;
  1586. }
  1587. var x = posObj.pageX || posObj.clientX, y = posObj.pageY || posObj.clientY,
  1588. viewport = this.viewport || this.updateViewport();
  1589. event.stageX = x = (x - viewport.left) / this.scaleX;
  1590. event.stageY = y = (y - viewport.top) / this.scaleY;
  1591. var obj = this.getViewAtPoint(x, y, true, false, true),
  1592. canvas = this.canvas, target = this._eventTarget;
  1593. //fire mouseout/touchout event for last event target
  1594. var leave = type === 'mouseout' && !canvas.contains(e.relatedTarget);
  1595. if(target && (target != obj || leave)){
  1596. var out = (type === 'touchmove') ? 'touchout' :
  1597. (type === 'mousemove' || leave || !obj) ? 'mouseout' : null;
  1598. if(out) target.fire(out);
  1599. event.lastEventTarget = target;
  1600. this._eventTarget = null;
  1601. }
  1602. //fire event for current view
  1603. if(obj && obj.pointerEnabled && type !== 'mouseout'){
  1604. event.eventTarget = this._eventTarget = obj;
  1605. obj.fire(event);
  1606. }
  1607. //set cursor for current view
  1608. if(!isTouch){
  1609. var cursor = (obj && obj.pointerEnabled && obj.useHandCursor) ? 'pointer' : '';
  1610. canvas.style.cursor = cursor;
  1611. }
  1612. //fire event for stage
  1613. if(leave || type !== "mouseout") this.fire(event);
  1614. //fix android: `touchmove` fires only once
  1615. if(Hilo.browser.android && type === 'touchmove'){
  1616. e.preventDefault();
  1617. }
  1618. },
  1619. /**
  1620. * 更新舞台在页面中的渲染区域。当舞台canvas的样式border、margin、padding等属性更改后,需要调用此方法更新舞台渲染区域。
  1621. */
  1622. updateViewport: function(){
  1623. return this.viewport = Hilo.getElementRect(this.canvas);
  1624. }
  1625. });
  1626. /**
  1627. * 示例:
  1628. * <pre>
  1629. * var bmp = new Hilo.Bitmap({image:imgElem, rect:[0, 0, 100, 100]});
  1630. * stage.addChild(bmp);
  1631. * </pre>
  1632. * @class Bitmap类表示位图图像类。
  1633. * @augments View
  1634. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。此外还包括:
  1635. * <ul>
  1636. * <li><b>image</b> - 位图所在的图像image。必需。</li>
  1637. * <li><b>rect</b> - 位图在图像image中矩形区域。</li>
  1638. * </ul>
  1639. * @module hilo/view/Bitmap
  1640. * @requires hilo/core/Hilo
  1641. * @requires hilo/core/Class
  1642. * @requires hilo/view/View
  1643. * @requires hilo/view/Drawable
  1644. */
  1645. var Bitmap = Class.create(/** @lends Bitmap.prototype */{
  1646. Extends: View,
  1647. constructor: function Bitmap(properties){
  1648. properties = properties || {};
  1649. this.id = this.id || properties.id || Hilo.getUid("Bitmap");
  1650. Bitmap.superclass.constructor.call(this, properties);
  1651. this.drawable = new Drawable(properties);
  1652. //init width and height
  1653. if(!this.width || !this.height){
  1654. var rect = this.drawable.rect;
  1655. if(rect){
  1656. this.width = rect[2];
  1657. this.height = rect[3];
  1658. }
  1659. }
  1660. }
  1661. });
  1662. /**
  1663. * @class 动画精灵类。
  1664. * @augments View
  1665. * @module hilo/view/Sprite
  1666. * @requires hilo/core/Hilo
  1667. * @requires hilo/core/Class
  1668. * @requires hilo/view/View
  1669. * @requires hilo/view/Drawable
  1670. * @param properties 创建对象的属性参数。可包含此类所有可写属性。此外还包括:
  1671. * <ul>
  1672. * <li><b>frames</b> - 精灵动画的帧数据对象。</li>
  1673. * </ul>
  1674. * @property {number} currentFrame 当前播放帧的索引。从0开始。
  1675. * @property {number} numFrames 精灵动画的总帧数。
  1676. * @property {boolean} paused 判断精灵是否暂停。默认为false。
  1677. * @property {boolean} loop 判断精灵是否可以循环播放。默认为true。
  1678. * @property {boolean} timeBased 指定精灵动画是否是以时间为基准。默认为false,即以帧为基准。
  1679. * @property {number} interval 精灵动画的帧间隔。如果timeBased为true,则单位为毫秒,否则为帧数。
  1680. */
  1681. var Sprite = Class.create(/** @lends Sprite.prototype */{
  1682. Extends: View,
  1683. constructor: function Sprite(properties){
  1684. properties = properties || {};
  1685. this.id = this.id || properties.id || Hilo.getUid("Sprite");
  1686. Sprite.superclass.constructor.call(this, properties);
  1687. this._frames = [];
  1688. this._frameNames = {};
  1689. this.drawable = new Drawable();
  1690. if(properties.frames) this.addFrame(properties.frames);
  1691. },
  1692. _frames: null, //所有帧的集合
  1693. _frameNames: null, //带名字name的帧的集合
  1694. _frameElapsed: 0, //当前帧持续的时间或帧数
  1695. _currentFrame: 0, //当前帧的索引
  1696. paused: false,
  1697. loop: true,
  1698. timeBased: false,
  1699. interval: 1,
  1700. currentFrame: {
  1701. get: function(){
  1702. return this._currentFrame;
  1703. }
  1704. },
  1705. numFrames: {
  1706. get: function(){
  1707. return this._frames ? this._frames.length : 0;
  1708. }
  1709. },
  1710. /**
  1711. * 往精灵动画序列中增加帧。
  1712. * @param {Object} frame 要增加的精灵动画帧数据。
  1713. * @returns {Sprite} Sprite对象本身。
  1714. */
  1715. addFrame: function(frame){
  1716. var total = this._frames.length;
  1717. if(frame instanceof Array){
  1718. for(var i = 0, len = frame.length; i < len; i++){
  1719. this.setFrame(frame[i], total + i);
  1720. }
  1721. }else{
  1722. this.setFrame(frame, total);
  1723. }
  1724. return this;
  1725. },
  1726. /**
  1727. * 设置精灵动画序列指定索引位置的帧。
  1728. * @param {Object} frame 要设置的精灵动画帧数据。
  1729. * @param {Int} index 要设置的索引位置。
  1730. * @returns {Sprite} Sprite对象本身。
  1731. */
  1732. setFrame: function(frame, index){
  1733. var frames = this._frames,
  1734. total = frames.length;
  1735. index = index < 0 ? 0 : index > total ? total : index;
  1736. frames[index] = frame;
  1737. if(frame.name) this._frameNames[frame.name] = frame;
  1738. if(index == 0 && !this.width || !this.height){
  1739. this.width = frame.rect[2];
  1740. this.height = frame.rect[3];
  1741. }
  1742. return this;
  1743. },
  1744. /**
  1745. * 获取精灵动画序列中指定的帧。
  1746. * @param {Object} indexOrName 要获取的帧的索引位置或别名。
  1747. * @returns {Object} 精灵帧对象。
  1748. */
  1749. getFrame: function(indexOrName){
  1750. if(typeof indexOrName === 'number'){
  1751. var frames = this._frames;
  1752. if(indexOrName < 0 || indexOrName >= frames.length) return null;
  1753. return frames[indexOrName];
  1754. }
  1755. return this._frameNames[indexOrName];
  1756. },
  1757. /**
  1758. * 获取精灵动画序列中指定帧的索引位置。
  1759. * @param {Object} frameValue 要获取的帧的索引位置或别名。
  1760. * @returns {Object} 精灵帧对象。
  1761. */
  1762. getFrameIndex: function(frameValue){
  1763. var frames = this._frames,
  1764. total = frames.length,
  1765. index = -1;
  1766. if(typeof frameValue === 'number'){
  1767. index = frameValue;
  1768. }else{
  1769. var frame = typeof frameValue === 'string' ? this._frameNames[frameValue] : frameValue;
  1770. if(frame){
  1771. for(var i = 0; i < total; i++){
  1772. if(frame === frames[i]){
  1773. index = i;
  1774. break;
  1775. }
  1776. }
  1777. }
  1778. }
  1779. return index;
  1780. },
  1781. /**
  1782. * 播放精灵动画。
  1783. * @returns {Sprite} Sprite对象本身。
  1784. */
  1785. play: function(){
  1786. this.paused = false;
  1787. return this;
  1788. },
  1789. /**
  1790. * 暂停播放精灵动画。
  1791. * @returns {Sprite} Sprite对象本身。
  1792. */
  1793. stop: function(){
  1794. this.paused = true;
  1795. return this;
  1796. },
  1797. /**
  1798. * 跳转精灵动画到指定的帧。
  1799. * @param {Object} indexOrName 要跳转的帧的索引位置或别名。
  1800. * @param {Boolean} pause 指示跳转后是否暂停播放。
  1801. * @returns {Sprite} Sprite对象本身。
  1802. */
  1803. goto: function(indexOrName, pause){
  1804. var total = this._frames.length,
  1805. index = this.getFrameIndex(indexOrName);
  1806. this._currentFrame = index < 0 ? 0 : index >= total ? total - 1 : index;
  1807. this.paused = pause;
  1808. return this;
  1809. },
  1810. /**
  1811. * 渲染方法。
  1812. * @private
  1813. */
  1814. _render: function(renderer, delta){
  1815. var frameIndex = this._nextFrame(delta),
  1816. frame = this._frames[frameIndex];
  1817. this.drawable.init(frame);
  1818. Sprite.superclass._render.call(this, renderer, delta);
  1819. },
  1820. /**
  1821. * @private
  1822. */
  1823. _nextFrame: function(delta){
  1824. var frames = this._frames,
  1825. total = frames.length,
  1826. frameIndex = this._currentFrame,
  1827. frame = frames[frameIndex],
  1828. duration = frame.duration || this.interval,
  1829. elapsed = this._frameElapsed;
  1830. //calculate the current frame elapsed frames/time
  1831. var value = (frameIndex == 0 && !this.drawable) ? 0 : elapsed + (this.timeBased ? delta : 1);
  1832. elapsed = this._frameElapsed = value < duration ? value : 0;
  1833. if(frame.stop || !this.loop && frameIndex >= total - 1){
  1834. this.stop();
  1835. }
  1836. if(!this.paused && elapsed == 0){
  1837. if(frame.next != null){
  1838. //jump to the specified frame
  1839. frameIndex = this.getFrameIndex(frame.next);
  1840. }else if(frameIndex >= total - 1){
  1841. //at the end of the frames, go back to first frame
  1842. frameIndex = 0;
  1843. }else if(this.drawable){
  1844. //normal go forward to next frame
  1845. frameIndex++;
  1846. }
  1847. this._currentFrame = frameIndex;
  1848. }
  1849. if(this.onEnterFrame) this.onEnterFrame(frameIndex);
  1850. return frameIndex;
  1851. },
  1852. /**
  1853. * 精灵动画的播放头进入新帧时的回调方法。默认值为null。
  1854. * @type Function
  1855. */
  1856. onEnterFrame: null
  1857. });
  1858. /**
  1859. * @name DOMElement
  1860. * @class DOMElement是dom元素的包装。
  1861. * @augments View
  1862. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。特殊属性有:
  1863. * <ul>
  1864. * <li><b>element</b> - 要包装的dom元素。必需。</li>
  1865. * </ul>
  1866. * @module hilo/view/DOMElement
  1867. * @requires hilo/core/Hilo
  1868. * @requires hilo/core/Class
  1869. * @requires hilo/view/View
  1870. * @requires hilo/view/Drawable
  1871. */
  1872. var DOMElement = Class.create(/** @lends DOMElement.prototype */{
  1873. Extends: View,
  1874. constructor: function DOMElement(properties){
  1875. properties = properties || {};
  1876. this.id = this.id || properties.id || Hilo.getUid("DOMElement");
  1877. DOMElement.superclass.constructor.call(this, properties);
  1878. this.drawable = new Drawable();
  1879. var elem = this.drawable.domElement = properties.element || Hilo.createElement('div');
  1880. elem.id = this.id;
  1881. },
  1882. /**
  1883. * 覆盖渲染方法。
  1884. * @private
  1885. */
  1886. _render: function(renderer, delta){
  1887. if(!this.onRender || this.onRender(delta) !== false){
  1888. var elem = this.drawable.domElement, style = elem.style;
  1889. if(!this.visible || this.alpha <= 0){
  1890. style.display = 'none';
  1891. return;
  1892. }
  1893. style.display = '';
  1894. Hilo.setElementStyleByView(this);
  1895. this.render(renderer, delta);
  1896. }
  1897. },
  1898. /**
  1899. * 覆盖渲染方法。
  1900. * @private
  1901. */
  1902. render: function(renderer, delta){
  1903. var canvas = renderer.canvas;
  1904. if(canvas.getContext){
  1905. var elem = this.drawable.domElement, depth = this.depth,
  1906. nextElement = canvas.nextSibling, nextDepth;
  1907. if(elem.parentNode) return;
  1908. //draw dom element just after stage canvas
  1909. while(nextElement && nextElement.nodeType != 3){
  1910. nextDepth = parseInt(nextElement.style.zIndex) || 0;
  1911. if(nextDepth <= 0 || nextDepth > depth){
  1912. break;
  1913. }
  1914. nextElement = nextElement.nextSibling;
  1915. }
  1916. canvas.parentNode.insertBefore(this.drawable.domElement, nextElement);
  1917. }else{
  1918. renderer.draw(this);
  1919. }
  1920. }
  1921. });
  1922. /**
  1923. * @class Graphics类包含一组创建矢量图形的方法。
  1924. * @augments View
  1925. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  1926. * @module hilo/view/Graphics
  1927. * @requires hilo/core/Hilo
  1928. * @requires hilo/core/Class
  1929. * @property {Number} lineWidth 笔画的线条宽度。默认为1。只读属性。
  1930. * @property {Number} lineAlpha 笔画的线条透明度。默认为1。只读属性。
  1931. * @property {String} lineCap 笔画的线条端部样式。可选值有:butt、round、square等,默认为null。只读属性。
  1932. * @property {String} lineJoin 笔画的线条连接样式。可选值有:miter、round、bevel等,默认为null。只读属性。
  1933. * @property {Number} miterLimit 斜连线长度和线条宽度的最大比率。此属性仅当lineJoin为miter时有效。默认值为10。只读属性。
  1934. * @property {String} strokeStyle 笔画边框的样式。默认值为'0',即黑色。只读属性。
  1935. * @property {String} fillStyle 内容填充的样式。默认值为'0',即黑色。只读属性。
  1936. * @property {Number} fillAlpha 内容填充的透明度。默认值为0。只读属性。
  1937. */
  1938. var Graphics = (function(){
  1939. var helpContext = document.createElement('canvas').getContext('2d');
  1940. return Class.create(/** @lends Graphics.prototype */{
  1941. Extends: View,
  1942. constructor: function Graphics(properties){
  1943. properties = properties || {};
  1944. this.id = this.id || properties.id || Hilo.getUid('Graphics');
  1945. Graphics.superclass.constructor.call(this, properties);
  1946. this._actions = [];
  1947. this._cache = null;
  1948. },
  1949. lineWidth: 1,
  1950. lineAlpha: 1,
  1951. lineCap: null, //'butt', 'round', 'square'
  1952. lineJoin: null, //'miter', 'round', 'bevel'
  1953. miterLimit: 10,
  1954. hasStroke: false,
  1955. strokeStyle: '0',
  1956. hasFill: false,
  1957. fillStyle: '0',
  1958. fillAlpha: 0,
  1959. /**
  1960. * 指定绘制图形的线条样式。
  1961. * @param {Number} thickness 线条的粗细值。默认为1。
  1962. * @param {String} lineColor 线条的CSS颜色值。默认为黑色,即'0'。
  1963. * @param {Number} lineAlpha 线条的透明度值。默认为不透明,即1。
  1964. * @param {String} lineCap 线条的端部样式。可选值有:butt、round、square等,默认值为null。
  1965. * @param {String} lineJoin 线条的连接样式。可选值有:miter、round、bevel等,默认值为null。
  1966. * @param {Number} miterLimit 斜连线长度和线条宽度的最大比率。此属性仅当lineJoin为miter时有效。默认值为10。
  1967. */
  1968. lineStyle: function(thickness, lineColor, lineAlpha, lineCap, lineJoin, miterLimit){
  1969. var me = this, addAction = me._addAction;
  1970. addAction.call(me, ['lineWidth', (me.lineWidth = thickness || 1)]);
  1971. addAction.call(me, ['strokeStyle', (me.strokeStyle = lineColor || '0')]);
  1972. addAction.call(me, ['lineAlpha', (me.lineAlpha = lineAlpha || 1)]);
  1973. if(lineCap != undefined) addAction.call(me, ['lineCap', (me.lineCap = lineCap)]);
  1974. if(lineJoin != undefined) addAction.call(me, ['lineJoin', (me.lineJoin = lineJoin)]);
  1975. if(miterLimit != undefined) addAction.call(me, ['miterLimit', (me.miterLimit = miterLimit)]);
  1976. me.hasStroke = true;
  1977. return me;
  1978. },
  1979. /**
  1980. * 指定绘制图形的填充样式和透明度。
  1981. * @param {String} fill 填充样式。可以是color、gradient或pattern。
  1982. * @param {Number} alpha 透明度。
  1983. */
  1984. beginFill: function(fill, alpha){
  1985. var me = this, addAction = me._addAction;
  1986. addAction.call(me, ['fillStyle', (me.fillStyle = fill)]);
  1987. addAction.call(me, ['fillAlpha', (me.fillAlpha = alpha || 1)]);
  1988. me.hasFill = true;
  1989. return me;
  1990. },
  1991. /**
  1992. * 应用并结束笔画的绘制和图形样式的填充。
  1993. */
  1994. endFill: function(){
  1995. var me = this, addAction = me._addAction;
  1996. if(me.hasStroke) addAction.call(me, ['stroke']);
  1997. if(me.hasFill) addAction.call(me, ['fill']);
  1998. return me;
  1999. },
  2000. /**
  2001. * 指定绘制图形的线性渐变填充样式。
  2002. * @param {Number} x0 渐变的起始点的x轴坐标。
  2003. * @param {Number} y0 渐变的起始点的y轴坐标。
  2004. * @param {Number} x1 渐变的结束点的x轴坐标。
  2005. * @param {Number} y1 渐变的结束点的y轴坐标。
  2006. * @param {Array} colors 渐变中使用的CSS颜色值数组。
  2007. * @param {Array} ratois 渐变中开始与结束之间的位置数组。需与colors数组里的颜色值一一对应,介于0.0与1.0之间的值。
  2008. */
  2009. beginLinearGradientFill: function(x0, y0, x1, y1, colors, ratios){
  2010. var me = this, gradient = helpContext.createLinearGradient(x0, y0, x1, y1);
  2011. for (var i = 0, len = colors.length; i < len; i++){
  2012. gradient.addColorStop(ratios[i], colors[i]);
  2013. }
  2014. me.hasFill = true;
  2015. return me._addAction(['fillStyle', (me.fillStyle = gradient)]);
  2016. },
  2017. /**
  2018. * 指定绘制图形的放射性渐变填充样式。
  2019. * @param {Number} x0 渐变的起始圆的x轴坐标。
  2020. * @param {Number} y0 渐变的起始圆的y轴坐标。
  2021. * @param {Number} r0 渐变的起始圆的半径。
  2022. * @param {Number} x1 渐变的结束圆的x轴坐标。
  2023. * @param {Number} y1 渐变的结束圆的y轴坐标。
  2024. * @param {Number} r1 渐变的结束圆的半径。
  2025. * @param {Array} colors 渐变中使用的CSS颜色值数组。
  2026. * @param {Array} ratois 渐变中开始与结束之间的位置数组。需与colors数组里的颜色值一一对应,介于0.0与1.0之间的值。
  2027. */
  2028. beginRadialGradientFill: function(x0, y0, r0, x1, y1, r1, colors, ratios){
  2029. var me = this, gradient = helpContext.createRadialGradient(x0, y0, r0, x1, y1, r1);
  2030. for (var i = 0, len = colors.length; i < len; i++)
  2031. {
  2032. gradient.addColorStop(ratios[i], colors[i]);
  2033. }
  2034. me.hasFill = true;
  2035. return me._addAction(['fillStyle', (me.fillStyle = gradient)]);
  2036. },
  2037. /**
  2038. * 开始一个位图填充样式。
  2039. * @param {HTMLImageElement} image 指定填充的Image对象。
  2040. * @param {String} repetition 指定填充的重复设置参数。它可以是以下任意一个值:repeat, repeat-x, repeat-y, no-repeat。默认为''。
  2041. */
  2042. beginBitmapFill: function(image, repetition){
  2043. var me = this, pattern = helpContext.createPattern(image, repetition || '');
  2044. me.hasFill = true;
  2045. return me._addAction(['fillStyle', (me.fillStyle = pattern)]);
  2046. },
  2047. /**
  2048. * 开始一个新的路径。
  2049. */
  2050. beginPath: function(){
  2051. return this._addAction(['beginPath']);
  2052. },
  2053. /**
  2054. * 关闭当前的路径。
  2055. */
  2056. closePath: function(){
  2057. return this._addAction(['closePath']);
  2058. },
  2059. /**
  2060. * 绘制一个矩形。
  2061. * @param {Number} x x轴坐标。
  2062. * @param {Number} y y轴坐标。
  2063. * @param {Number} width 矩形的宽度。
  2064. * @param {Number} height 矩形的高度。
  2065. */
  2066. drawRect: function(x, y, width, height){
  2067. return this._addAction(['rect', x, y, width, height]);
  2068. },
  2069. /**
  2070. * 绘制一个复杂的圆角矩形。
  2071. * @param {Number} x x轴坐标。
  2072. * @param {Number} y y轴坐标。
  2073. * @param {Number} width 圆角矩形的宽度。
  2074. * @param {Number} height 圆角矩形的高度。
  2075. * @param {Number} cornerTL 圆角矩形的左上圆角大小。
  2076. * @param {Number} cornerTR 圆角矩形的右上圆角大小。
  2077. * @param {Number} cornerBR 圆角矩形的右下圆角大小。
  2078. * @param {Number} cornerBL 圆角矩形的左下圆角大小。
  2079. */
  2080. drawRoundRectComplex: function(x, y, width, height, cornerTL, cornerTR, cornerBR, cornerBL){
  2081. var me = this, addAction = me._addAction;
  2082. addAction.call(me, ['moveTo', x + cornerTL, y]);
  2083. addAction.call(me, ['lineTo', x + width - cornerTR, y]);
  2084. addAction.call(me, ['arc', x + width - cornerTR, y + cornerTR, cornerTR, -Math.PI/2, 0, false]);
  2085. addAction.call(me, ['lineTo', x + width, y + height - cornerBR]);
  2086. addAction.call(me, ['arc', x + width - cornerBR, y + height - cornerBR, cornerBR, 0, Math.PI/2, false]);
  2087. addAction.call(me, ['lineTo', x + cornerBL, y + height]);
  2088. addAction.call(me, ['arc', x + cornerBL, y + height - cornerBL, cornerBL, Math.PI/2, Math.PI, false]);
  2089. addAction.call(me, ['lineTo', x, y + cornerTL]);
  2090. addAction.call(me, ['arc', x + cornerTL, y + cornerTL, cornerTL, Math.PI, Math.PI*3/2, false]);
  2091. return me;
  2092. },
  2093. /**
  2094. * 绘制一个圆角矩形。
  2095. * @param {Number} x x轴坐标。
  2096. * @param {Number} y y轴坐标。
  2097. * @param {Number} width 圆角矩形的宽度。
  2098. * @param {Number} height 圆角矩形的高度。
  2099. * @param {Number} cornerSize 圆角矩形的圆角大小。
  2100. */
  2101. drawRoundRect: function(x, y, width, height, cornerSize){
  2102. return this.drawRoundRectComplex(x, y, width, height, cornerSize, cornerSize, cornerSize, cornerSize);
  2103. },
  2104. /**
  2105. * 绘制一个圆。
  2106. * @param {Number} x x轴坐标。
  2107. * @param {Number} y y轴坐标。
  2108. * @param {Number} radius 圆的半径。
  2109. */
  2110. drawCircle: function(x, y, radius){
  2111. return this._addAction(['arc', x + radius, y + radius, radius, 0, Math.PI * 2, 0]);
  2112. },
  2113. /**
  2114. * 绘制一个椭圆。
  2115. * @param {Number} x x轴坐标。
  2116. * @param {Number} y y轴坐标。
  2117. * @param {Number} width 椭圆的宽度。
  2118. * @param {Number} height 椭圆的高度。
  2119. */
  2120. drawEllipse: function(x, y, width, height){
  2121. var me = this;
  2122. if(width == height) return me.drawCircle(x, y, width);
  2123. var addAction = me._addAction;
  2124. var w = width / 2, h = height / 2, C = 0.5522847498307933, cx = C * w, cy = C * h;
  2125. x = x + w;
  2126. y = y + h;
  2127. addAction.call(me, ['moveTo', x + w, y]);
  2128. addAction.call(me, ['bezierCurveTo', x + w, y - cy, x + cx, y - h, x, y - h]);
  2129. addAction.call(me, ['bezierCurveTo', x - cx, y - h, x - w, y - cy, x - w, y]);
  2130. addAction.call(me, ['bezierCurveTo', x - w, y + cy, x - cx, y + h, x, y + h]);
  2131. addAction.call(me, ['bezierCurveTo', x + cx, y + h, x + w, y + cy, x + w, y]);
  2132. return me;
  2133. },
  2134. /**
  2135. * 根据参数指定的SVG数据绘制一条路径。
  2136. * 代码示例:
  2137. * <p>var path = 'M250 150 L150 350 L350 350 Z';</p>
  2138. * <p>var shape = new Hilo.Graphics({width:500, height:500});</p>
  2139. * <p>shape.drawSVGPath(path).beginFill('#0ff').endFill();</p>
  2140. * @param {String} pathData 要绘制的SVG路径数据。
  2141. */
  2142. drawSVGPath: function(pathData){
  2143. var me = this, addAction = me._addAction,
  2144. path = pathData.split(/,| (?=[a-zA-Z])/);
  2145. addAction.call(me, ['beginPath']);
  2146. for(var i = 0, len = path.length; i < len; i++){
  2147. var str = path[i], cmd = str[0].toUpperCase(), p = str.substring(1).split(/,| /);
  2148. if(p[0].length == 0) p.shift();
  2149. switch(cmd){
  2150. case 'M':
  2151. addAction.call(me, ['moveTo', p[0], p[1]]);
  2152. break;
  2153. case 'L':
  2154. addAction.call(me, ['lineTo', p[0], p[1]]);
  2155. break;
  2156. case 'C':
  2157. addAction.call(me, ['bezierCurveTo', p[0], p[1], p[2], p[3], p[4], p[5]]);
  2158. break;
  2159. case 'Z':
  2160. addAction.call(me, ['closePath']);
  2161. break;
  2162. }
  2163. }
  2164. return me;
  2165. },
  2166. /**
  2167. * 执行全部绘制动作。内部私有方法。
  2168. * @private
  2169. */
  2170. _draw: function(context){
  2171. var me = this, actions = me._actions, len = actions.length, i;
  2172. context.beginPath();
  2173. for(i = 0; i < len; i++){
  2174. var action = actions[i],
  2175. f = action[0],
  2176. args = action.length > 1 ? action.slice(1) : null;
  2177. if(typeof(context[f]) == 'function') context[f].apply(context, args);
  2178. else context[f] = action[1];
  2179. }
  2180. },
  2181. /**
  2182. * 重写渲染实现。
  2183. * @private
  2184. */
  2185. render: function(renderer, delta){
  2186. var me = this, canvas = renderer.canvas;
  2187. if(canvas.getContext){
  2188. me._draw(renderer.context);
  2189. }else{
  2190. var drawable = me.drawable;
  2191. if(!drawable.image){
  2192. drawable.image = me.toImage();
  2193. }
  2194. renderer.draw(me);
  2195. }
  2196. },
  2197. /**
  2198. * 缓存graphics到一个canvas或image。可用来提高渲染效率。
  2199. * @param {Boolean} toImage 是否缓存为Image。
  2200. */
  2201. cache: function(toImage){
  2202. var me = this, cached = me._cache;
  2203. if(!cached){
  2204. cached = me._cache = Hilo.createElement('canvas', {width:me.width, height:me.height});
  2205. me._draw(cached.getContext('2d'));
  2206. }
  2207. if(toImage) cached = me._cache = me.toImage();
  2208. return cached;
  2209. },
  2210. /**
  2211. * 清除缓存。
  2212. */
  2213. uncache: function(){
  2214. this._cache = null;
  2215. },
  2216. /**
  2217. * 把Graphics对象转换成dataURL格式的位图。
  2218. * @param {String} type 指定转换为DataURL格式的图片mime类型。默认为'image/png'。
  2219. */
  2220. toImage: function(type){
  2221. var me = this, obj = me._cache, w = me.width, h = me.height;
  2222. if(!obj){
  2223. obj = Hilo.createElement('canvas', {width:w, height:h});
  2224. me._draw(obj.getContext('2d'));
  2225. }
  2226. if(!(obj instanceof HTMLImageElement)){
  2227. var src = obj.toDataURL(type || 'image/png');
  2228. obj = new Image();
  2229. obj.src = src;
  2230. obj.width = w;
  2231. obj.height = h;
  2232. }
  2233. return obj;
  2234. },
  2235. /**
  2236. * 清除所有绘制动作并复原所有初始状态。
  2237. */
  2238. clear: function(){
  2239. var me = this;
  2240. me._actions.length = 0;
  2241. me._cache = null;
  2242. me.lineWidth = 1;
  2243. me.lineAlpha = 1;
  2244. me.lineCap = null;
  2245. me.lineJoin = null;
  2246. me.miterLimit = 10;
  2247. me.hasStroke = false;
  2248. me.strokeStyle = '0';
  2249. me.hasFill = false;
  2250. me.fillStyle = '0';
  2251. me.fillAlpha = 1;
  2252. },
  2253. /**
  2254. * 添加一个绘制动作。内部私有方法。
  2255. * @private
  2256. */
  2257. _addAction: function(action){
  2258. var me = this;
  2259. me._actions.push(action);
  2260. return me;
  2261. }
  2262. });
  2263. })();
  2264. /**
  2265. * @class Text类提供简单的文字显示功能。复杂的文本功能可以使用DOMElement。
  2266. * @augments View
  2267. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  2268. * @module hilo/view/Text
  2269. * @requires hilo/core/Class
  2270. * @requires hilo/core/Hilo
  2271. * @requires hilo/view/View
  2272. * @property {String} text 指定要显示的文本内容。
  2273. * @property {String} color 指定使用的字体颜色。
  2274. * @property {String} textAlign 指定文本的对齐方式。可以是以下任意一个值:'start', 'end', 'left', 'right', and 'center'。
  2275. * @property {Boolean} outline 指定文本是绘制边框还是填充。
  2276. * @property {Number} lineSpacing 指定文本的行距。单位为像素。默认值为0。
  2277. * @property {Number} textWidth 指示文本内容的宽度,只读属性。仅在canvas模式下有效。
  2278. * @property {Number} textHeight 指示文本内容的高度,只读属性。仅在canvas模式下有效。
  2279. * @property {String} font 指定使用的字体样式。
  2280. */
  2281. var Text = Class.create(/** @lends Text.prototype */{
  2282. Extends: View,
  2283. constructor: function Text(properties){
  2284. properties = properties || {};
  2285. this.id = this.id || properties.id || Hilo.getUid('Text');
  2286. Text.superclass.constructor.call(this, properties);
  2287. if(!this.width) this.width = 200; //default width
  2288. if(!this.font) this.font = '12px arial'; //default font style
  2289. },
  2290. text: null,
  2291. color: null,
  2292. textAlign: null,
  2293. outline: false,
  2294. lineSpacing: 0,
  2295. textWidth: 0, //read-only
  2296. textHeight: 0, //read-only
  2297. font: {
  2298. get: function(){
  2299. return this._font || null;
  2300. },
  2301. set: function(value){
  2302. if(this._font === value) return;
  2303. this._font = value;
  2304. this._fontHeight = Text.measureFontHeight(value);
  2305. }
  2306. },
  2307. /**
  2308. * 覆盖渲染方法。
  2309. */
  2310. render: function(renderer, delta){
  2311. var me = this, canvas = renderer.canvas;
  2312. if(canvas.getContext){
  2313. me._draw(renderer.context);
  2314. }else{
  2315. var drawable = me.drawable;
  2316. var domElement = drawable.domElement;
  2317. var style = domElement.style;
  2318. style.font = me.font;
  2319. style.textAlign = me.textAlign;
  2320. style.color = me.color;
  2321. style.width = me.width + 'px';
  2322. style.height = me.height + 'px';
  2323. style.lineHeight = (me._fontHeight + me.lineSpacing) + 'px';
  2324. domElement.innerHTML = me.text;
  2325. renderer.draw(this);
  2326. }
  2327. },
  2328. /**
  2329. * 在指定的渲染上下文上绘制文本。
  2330. * @private
  2331. */
  2332. _draw: function(context){
  2333. var me = this, text = me.text.toString();
  2334. if(!text) return;
  2335. //set drawing style
  2336. context.font = me.font;
  2337. context.textAlign = me.textAlign;
  2338. context.textBaseline = 'top';
  2339. if(me.outline) context.strokeStyle = me.color;
  2340. else context.fillStyle = me.color;
  2341. //find and draw all explicit lines
  2342. var lines = text.split(/\r\n|\r|\n|<br(?:[ \/])*>/);
  2343. var width = 0, height = 0;
  2344. var lineHeight = me._fontHeight + me.lineSpacing;
  2345. var i, line, w;
  2346. for(i = 0, len = lines.length; i < len; i++){
  2347. line = lines[i];
  2348. w = context.measureText(line).width;
  2349. //check if the line need to split
  2350. if(w <= me.width){
  2351. me._drawTextLine(context, line, height);
  2352. if(width < w) width = w;
  2353. height += lineHeight;
  2354. continue;
  2355. }
  2356. var str = '', oldWidth = 0, newWidth, j, word;
  2357. for(j = 0, wlen = line.length; j < wlen; j++){
  2358. word = line[j];
  2359. newWidth = context.measureText(str + word).width;
  2360. if(newWidth > me.width){
  2361. me._drawTextLine(context, str, height);
  2362. if(width < oldWidth) width = oldWidth;
  2363. height += lineHeight;
  2364. str = word;
  2365. }else{
  2366. oldWidth = newWidth;
  2367. str += word;
  2368. }
  2369. if(j == wlen - 1){
  2370. me._drawTextLine(context, str, height);
  2371. if(str !== word && width < newWidth) width = newWidth;
  2372. height += lineHeight;
  2373. }
  2374. }
  2375. }
  2376. me.textWidth = width;
  2377. me.textHeight = height;
  2378. if(!me.height) me.height = height;
  2379. },
  2380. /**
  2381. * 在指定的渲染上下文上绘制一行文本。
  2382. * @private
  2383. */
  2384. _drawTextLine: function(context, text, y){
  2385. var me = this, x = 0, width = me.width;
  2386. switch(me.textAlign){
  2387. case 'center':
  2388. x = width * 0.5 >> 0;
  2389. break;
  2390. case 'right':
  2391. case 'end':
  2392. x = width;
  2393. break;
  2394. };
  2395. if(me.outline) context.strokeText(text, x, y);
  2396. else context.fillText(text, x, y);
  2397. },
  2398. Statics: /** @lends Text */{
  2399. /**
  2400. * 测算指定字体样式的行高。
  2401. * @param {String} font 指定要测算的字体样式。
  2402. * @return {Number} 返回指定字体的行高。
  2403. */
  2404. measureFontHeight: function(font){
  2405. var docElement = document.documentElement, fontHeight;
  2406. var elem = Hilo.createElement('div', {style:{font:font, position:'absolute'}, innerHTML:'M'});
  2407. docElement.appendChild(elem);
  2408. fontHeight = elem.offsetHeight;
  2409. docElement.removeChild(elem);
  2410. return fontHeight;
  2411. }
  2412. }
  2413. });
  2414. /**
  2415. * @class BitmapText类提供使用位图文本的功能。当前仅支持单行文本。
  2416. * @augments Container
  2417. * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。
  2418. * @module hilo/view/BitmapText
  2419. * @requires hilo/core/Class
  2420. * @requires hilo/core/Hilo
  2421. * @requires hilo/view/Container
  2422. * @property {Object} glyphs 位图字体的字形集合。格式为:{letter:{image:img, rect:[0,0,100,100]}}。
  2423. * @property {Number} letterSpacing 字距,即字符间的间隔。默认值为0。
  2424. */
  2425. var BitmapText = Class.create(/** @lends BitmapText.prototype */{
  2426. Extends: Container,
  2427. constructor: function BitmapText(properties){
  2428. properties = properties || {};
  2429. this.id = this.id || properties.id || Hilo.getUid('BitmapText');
  2430. BitmapText.superclass.constructor.call(this, properties);
  2431. this.pointerChildren = false; //disable user events for single letters
  2432. },
  2433. glyphs: null,
  2434. letterSpacing: 0,
  2435. text: {
  2436. get: function(){
  2437. return this._text || '';
  2438. },
  2439. set: function(str){
  2440. var me = this, str = str.toString(), len = str.length;
  2441. if(me._text == str) return;
  2442. me._text = str;
  2443. if(!me.children) me.children = [];
  2444. me.removeAllChildren();
  2445. var i, charStr, charGlyph, charObj, width = 0, height = 0, left = 0;
  2446. for(i = 0; i < len; i++){
  2447. charStr = str.charAt(i);
  2448. charGlyph = me.glyphs[charStr];
  2449. if(charGlyph){
  2450. left = width + (width > 0 ? me.letterSpacing : 0);
  2451. charObj = new Bitmap({
  2452. image: charGlyph.image,
  2453. rect: charGlyph.rect,
  2454. x: left
  2455. });
  2456. width = left + charGlyph.rect[2];
  2457. height = Math.max(height, charGlyph.rect[3]);
  2458. me.addChild(charObj);
  2459. }
  2460. }
  2461. me.width = width;
  2462. me.height = height;
  2463. }
  2464. },
  2465. /**
  2466. * 返回能否使用当前指定的字体显示提供的字符串。
  2467. * @param {String} str 要检测的字符串。
  2468. * @returns {Boolean} 是否能使用指定字体。
  2469. */
  2470. hasGlyphs: function(str){
  2471. var glyphs = this.glyphs;
  2472. if(!glyphs) return false;
  2473. var str = str.toString(), len = str.length, i;
  2474. for(i = 0; i < len; i++){
  2475. if(!glyphs[str.charAt(i)]) return false;
  2476. }
  2477. return true;
  2478. }
  2479. });
  2480. /**
  2481. * @class TextureAtlas纹理集是将许多小的纹理图片整合到一起的一张大图。这个类可根据一个纹理集数据读取纹理小图、精灵动画等。
  2482. * @param {Image} image 纹理集图片。
  2483. * @param {Array} frameData 纹理集帧数据。每帧的数据格式为:[x, y, width, height]。
  2484. * @param {Object} spriteData 纹理集精灵数据。
  2485. * @module hilo/util/TextureAtlas
  2486. * @require hilo/core/Class
  2487. */
  2488. var TextureAtlas = (function(){
  2489. return Class.create(/** @lends TextureAtlas.prototype */{
  2490. constructor: function TextureAtlas(image, frameData, spriteData){
  2491. var result = parseAtlasData(image, frameData, spriteData);
  2492. this._frames = result.frames;
  2493. this._sprites = result.sprites;
  2494. },
  2495. _frames: null,
  2496. _sprites: null,
  2497. /**
  2498. * 获取指定索引位置index的帧数据。
  2499. * @param {Int} index 要获取帧的索引位置。
  2500. * @returns {Object} 帧数据。
  2501. */
  2502. getFrame: function(index){
  2503. var frames = this._frames;
  2504. return frames && frames[index];
  2505. },
  2506. /**
  2507. * 获取指定id的精灵数据。
  2508. * @param {String} id 要获取精灵的id。
  2509. * @returns {Object} 精灵数据。
  2510. */
  2511. getSprite: function(id){
  2512. var sprites = this._sprites;
  2513. return sprites && sprites[id];
  2514. }
  2515. });
  2516. /**
  2517. * 解析纹理集帧和精灵数据。
  2518. * @private
  2519. */
  2520. function parseAtlasData(image, frameData, spriteData){
  2521. if(frameData === undefined){
  2522. var data = image;
  2523. image = data.image;
  2524. frameData = data.frames;
  2525. spriteData = data.sprites;
  2526. }
  2527. //frames
  2528. if(frameData){
  2529. var frames = [], frame, obj;
  2530. for(var i = 0, len = frameData.length; i < len; i++){
  2531. obj = frameData[i];
  2532. frame = {
  2533. image: image,
  2534. rect: [obj[0], obj[1], obj[2], obj[3]],
  2535. pivotX: obj[4] || 0,
  2536. pivotY: obj[5] || 0
  2537. };
  2538. frames[i] = frame;
  2539. }
  2540. }
  2541. //sprite frames
  2542. if(spriteData){
  2543. var sprites = {}, sprite, spriteFrames, spriteFrame;
  2544. for(var s in spriteData){
  2545. sprite = spriteData[s];
  2546. if(isNumber(sprite)){
  2547. spriteFrames = translateSpriteFrame(frames[sprite]);
  2548. }else if(sprite instanceof Array){
  2549. spriteFrames = [];
  2550. for(var i = 0, len = sprite.length; i < len; i++){
  2551. var spriteObj = sprite[i], frameObj;
  2552. if(isNumber(spriteObj)){
  2553. spriteFrame = translateSpriteFrame(frames[spriteObj]);
  2554. }else{
  2555. frameObj = spriteObj.rect;
  2556. if(isNumber(frameObj)) frameObj = frames[spriteObj.rect];
  2557. spriteFrame = translateSpriteFrame(frameObj, spriteObj);
  2558. }
  2559. spriteFrames[i] = spriteFrame;
  2560. }
  2561. }
  2562. sprites[s] = spriteFrames;
  2563. }
  2564. }
  2565. return {frames:frames, sprites:sprites};
  2566. }
  2567. function isNumber(value){
  2568. return typeof value === 'number';
  2569. }
  2570. function translateSpriteFrame(frameObj, spriteObj){
  2571. var spriteFrame = {
  2572. image: frameObj.image,
  2573. rect: frameObj.rect,
  2574. pivotX: frameObj.pivotX || 0,
  2575. pivotY: frameObj.pivotY || 0
  2576. };
  2577. if(spriteObj){
  2578. spriteFrame.name = spriteObj.name || null;
  2579. spriteFrame.duration = spriteObj.duration || 0;
  2580. spriteFrame.stop = !!spriteObj.stop;
  2581. spriteFrame.next = spriteObj.next || null;
  2582. }
  2583. return spriteFrame;
  2584. }
  2585. })();
  2586. /**
  2587. * @class Ticker是一个定时器类。它可以按指定帧率重复运行,从而按计划执行代码。
  2588. * @param {Number} fps 指定定时器的运行帧率。
  2589. * @module hilo/util/Ticker
  2590. * @requires hilo/core/Class
  2591. * @requires hilo/core/Hilo
  2592. */
  2593. var Ticker = Class.create(/** @lends Ticker.prototype */{
  2594. constructor: function Ticker(fps){
  2595. this._targetFPS = fps || 30;
  2596. this._interval = 1000 / this._targetFPS;
  2597. this._tickers = [];
  2598. },
  2599. _paused: false,
  2600. _targetFPS: 0,
  2601. _interval: 0,
  2602. _intervalId: null,
  2603. _tickers: null,
  2604. _lastTime: 0,
  2605. _tickCount: 0,
  2606. _tickTime: 0,
  2607. _measuredFPS: 0,
  2608. /**
  2609. * 启动定时器。
  2610. * @param {Boolean} userRAF 是否使用requestAnimationFrame,默认为false。
  2611. */
  2612. start: function(useRAF){
  2613. if(this._intervalId) return;
  2614. this._lastTime = +new Date();
  2615. var self = this, interval = this._interval,
  2616. raf = window.requestAnimationFrame ||
  2617. window[Hilo.browser.jsVendor + 'RequestAnimationFrame'];
  2618. if(useRAF && raf){
  2619. var tick = function(){
  2620. self._tick();
  2621. }
  2622. var runLoop = function(){
  2623. self._intervalId = setTimeout(runLoop, interval);
  2624. raf(tick);
  2625. };
  2626. }else{
  2627. runLoop = function(){
  2628. self._intervalId = setTimeout(runLoop, interval);
  2629. self._tick();
  2630. };
  2631. }
  2632. runLoop();
  2633. },
  2634. /**
  2635. * 停止定时器。
  2636. */
  2637. stop: function(){
  2638. clearTimeout(this._intervalId);
  2639. this._intervalId = null;
  2640. this._lastTime = 0;
  2641. },
  2642. /**
  2643. * 暂停定时器。
  2644. */
  2645. pause: function(){
  2646. this._paused = true;
  2647. },
  2648. /**
  2649. * 恢复定时器。
  2650. */
  2651. resume: function(){
  2652. this._paused = false;
  2653. },
  2654. /**
  2655. * @private
  2656. */
  2657. _tick: function(){
  2658. if(this._paused) return;
  2659. var startTime = +new Date(),
  2660. deltaTime = startTime - this._lastTime,
  2661. tickers = this._tickers;
  2662. for(var i = 0, len = tickers.length; i < len; i++){
  2663. tickers[i].tick(deltaTime);
  2664. }
  2665. //calculates the real fps
  2666. var endTime = +new Date();
  2667. if(++this._tickCount >= this._targetFPS){
  2668. this._measuredFPS = 1000 / (this._tickTime / this._tickCount) + 0.5 >> 0;
  2669. this._tickCount = 0;
  2670. this._tickTime = 0;
  2671. }else{
  2672. this._tickTime += endTime - this._lastTime;
  2673. }
  2674. this._lastTime = endTime;
  2675. },
  2676. /**
  2677. * 获得测定的运行时帧率。
  2678. */
  2679. getMeasuredFPS: function(){
  2680. return this._measuredFPS;
  2681. },
  2682. /**
  2683. * 添加定时器对象。定时器对象必须实现 tick 方法。
  2684. * @param {Object} tickObject 要添加的定时器对象。此对象必须包含 tick 方法。
  2685. */
  2686. addTick: function(tickObject){
  2687. if(!tickObject || typeof(tickObject.tick) != 'function'){
  2688. throw new Error('Ticker: The tick object must implement the tick method.');
  2689. }
  2690. this._tickers.push(tickObject);
  2691. },
  2692. /**
  2693. * 删除定时器对象。
  2694. * @param {Object} tickObject 要删除的定时器对象。
  2695. */
  2696. removeTick: function(tickObject){
  2697. var tickers = this._tickers,
  2698. index = tickers.indexOf(tickObject);
  2699. if(index >= 0){
  2700. tickers.splice(index, 1);
  2701. }
  2702. }
  2703. });
  2704. var arrayProto = Array.prototype,
  2705. slice = arrayProto.slice;
  2706. //polyfiil for Array.prototype.indexOf
  2707. arrayProto.indexOf = arrayProto.indexOf || function(elem, fromIndex){
  2708. fromIndex = fromIndex || 0;
  2709. var len = this.length, i;
  2710. if(len == 0 || fromIndex >= len) return -1;
  2711. if(fromIndex < 0) fromIndex = len + fromIndex;
  2712. for(i = fromIndex; i < len; i++){
  2713. if(this[i] === elem) return i;
  2714. }
  2715. return -1;
  2716. };
  2717. var fnProto = Function.prototype;
  2718. //polyfill for Function.prototype.bind
  2719. fnProto.bind = fnProto.bind || function(thisArg){
  2720. var target = this,
  2721. boundArgs = slice.call(arguments, 1),
  2722. F = function(){};
  2723. function bound(){
  2724. var args = boundArgs.concat(slice.call(arguments));
  2725. return target.apply(this instanceof bound ? this : thisArg, args);
  2726. }
  2727. F.prototype = target.prototype;
  2728. bound.prototype = new F();
  2729. return bound;
  2730. };
  2731. /**
  2732. * @class Tween类提供缓动功能。
  2733. * @param {Object} target 缓动对象。
  2734. * @param {Object} newProps 对象缓动的目标属性集合。
  2735. * @param {Object} params 缓动参数。可包含Tween类所有可写属性。
  2736. * @module hilo/util/Tween
  2737. * @requires hilo/core/Class
  2738. * @property {Object} target 缓动目标。只读属性。
  2739. * @property {Number} time 缓动总时长。单位毫秒。
  2740. * @property {Number} delay 缓动延迟时间。单位毫秒。
  2741. * @property {Boolean} paused 缓动是否暂停。默认为false。
  2742. * @property {Boolean} loop 缓动是否循环。默认为false。
  2743. * @property {Boolean} reverse 缓动是否反转播放。默认为false。
  2744. * @property {Number} interval 缓动间隔。默认为0。
  2745. * @property {Function} ease 缓动变化函数。默认为null。
  2746. * @property {Tween} next 下一个缓动变化对象。默认为null。
  2747. * @property {Function} onUpdate 缓动更新回调函数。默认为null。
  2748. * @property {Function} onComplete 缓动结束回调函数。默认为null。
  2749. */
  2750. var Tween = (function(){
  2751. return Class.create(/** @lends Tween.prototype */{
  2752. constructor: function Tween(target, newProps, params){
  2753. var me = this;
  2754. me.target = target;
  2755. me._oldProps = {};
  2756. me._newProps = {};
  2757. me._deltaProps = {};
  2758. me._startTime = 0;
  2759. me._lastTime = 0;
  2760. me._pausedTime = 0;
  2761. me._pausedStartTime = 0;
  2762. me._reverseFlag = 1;
  2763. me._frameTotal = 0;
  2764. me._frameCount = 0;
  2765. for(var p in newProps){
  2766. var oldVal = target[p], newVal = newProps[p];
  2767. if(oldVal !== undefined){
  2768. if(typeof oldVal == 'number' && typeof newVal == 'number'){
  2769. me._oldProps[p] = oldVal;
  2770. me._newProps[p] = newVal;
  2771. me._deltaProps[p] = newVal - oldVal;
  2772. }
  2773. }
  2774. }
  2775. for(var p in params){
  2776. me[p] = params[p];
  2777. }
  2778. },
  2779. target: null,
  2780. time: 0,
  2781. delay: 0,
  2782. paused: false,
  2783. loop: false,
  2784. reverse: false,
  2785. interval: 0,
  2786. ease: null,
  2787. next: null,
  2788. onUpdate: null,
  2789. onComplete: null,
  2790. /**
  2791. * 设置缓动对象的初始和目标属性。
  2792. * @param oldProps 缓动对象的初始属性。
  2793. * @param newProps 缓动对象的目标属性。
  2794. */
  2795. setProps: function(oldProps, newProps){
  2796. for(var p in oldProps){
  2797. this.target[p] = this._oldProps[p] = oldProps[p];
  2798. }
  2799. for(var p in newProps){
  2800. this._newProps[p] = newProps[p];
  2801. this._deltaProps[p] = newProps[p] - this.target[p];
  2802. }
  2803. },
  2804. /**
  2805. * 初始化Tween类。
  2806. * @private
  2807. */
  2808. _init: function(){
  2809. this._startTime = Date.now() + this.delay;
  2810. this._pausedTime = 0;
  2811. if(this.interval > 0) this._frameTotal = Math.round(this.time / this.interval);
  2812. Tween.add(this);
  2813. },
  2814. /**
  2815. * 启动缓动动画的播放。
  2816. */
  2817. start: function(){
  2818. this._init();
  2819. this.paused = false;
  2820. },
  2821. /**
  2822. * 停止缓动动画的播放。
  2823. */
  2824. stop: function(){
  2825. Tween.remove(this);
  2826. },
  2827. /**
  2828. * 暂停缓动动画的播放。
  2829. */
  2830. pause: function(){
  2831. this.paused = true;
  2832. this._pausedStartTime = Date.now();
  2833. },
  2834. /**
  2835. * 恢复缓动动画的播放。
  2836. */
  2837. resume: function(){
  2838. this.paused = false;
  2839. this._pausedTime += Date.now() - this._pausedStartTime;
  2840. },
  2841. /**
  2842. * Tween类的内部更新方法。
  2843. * @private
  2844. */
  2845. _update: function(){
  2846. if(this.paused) return;
  2847. var now = Date.now();
  2848. var elapsed = now - this._startTime - this._pausedTime;
  2849. if(elapsed < 0) return;
  2850. this._lastTime = now;
  2851. var ratio = this._frameTotal > 0 ? (++this._frameCount / this._frameTotal) : (elapsed / this.time);
  2852. if(ratio > 1) ratio = 1;
  2853. var value = this.ease ? this.ease(ratio) : ratio;
  2854. for(var p in this._oldProps){
  2855. this.target[p] = this._oldProps[p] + this._deltaProps[p] * this._reverseFlag * value;
  2856. }
  2857. if(this.onUpdate) this.onUpdate(value);
  2858. if(ratio >= 1){
  2859. if(this.reverse){
  2860. var tmp = this._oldProps;
  2861. this._oldProps = this._newProps;
  2862. this._newProps = tmp;
  2863. this._startTime = Date.now();
  2864. this._frameCount = 0;
  2865. this._reverseFlag *= -1;
  2866. }else if(this.loop){
  2867. for(var p in this._oldProps) this.target[p] = this._oldProps[p];
  2868. this._startTime = Date.now();
  2869. this._frameCount = 0;
  2870. }else{
  2871. Tween.remove(this);
  2872. var next = this.next, nextTween;
  2873. if(next){
  2874. if(next instanceof Tween){
  2875. nextTween = next;
  2876. next = null;
  2877. }else{
  2878. nextTween = next.shift();
  2879. }
  2880. if(nextTween){
  2881. nextTween.next = next;
  2882. nextTween.start();
  2883. }
  2884. }
  2885. }
  2886. if(this.onComplete) this.onComplete(this);
  2887. if(this.reverse && !this.loop) this.reverse = false;
  2888. }
  2889. },
  2890. Statics: /** @lends Tween */ {
  2891. /**
  2892. * @private
  2893. */
  2894. _tweens: [],
  2895. /**
  2896. * 更新所有Tween实例。
  2897. * @returns {Object} Tween。
  2898. */
  2899. tick: function(){
  2900. var tweens = this._tweens, i = tweens.length;
  2901. while(--i >= 0) tweens[i]._update();
  2902. return this;
  2903. },
  2904. /**
  2905. * 添加Tween实例。
  2906. * @param {Tween} tween 要添加的Tween对象。
  2907. * @returns {Object} Tween。
  2908. */
  2909. add: function(tween){
  2910. if(this._tweens.indexOf(tween) == -1) this._tweens.push(tween);
  2911. return this;
  2912. },
  2913. /**
  2914. * 删除Tween实例。
  2915. * @param {Tween} tween 要删除的Tween对象。
  2916. * @returns {Object} Tween。
  2917. */
  2918. remove: function(tween){
  2919. if(tween){
  2920. var tweens = this._tweens;
  2921. var index = tweens.indexOf(tween);
  2922. if(index > -1) tweens.splice(index, 1);
  2923. }
  2924. return this;
  2925. },
  2926. /**
  2927. * 删除所有Tween实例。
  2928. * @returns {Object} Tween。
  2929. */
  2930. removeAll: function(){
  2931. this._tweens.length = 0;
  2932. return this;
  2933. },
  2934. /**
  2935. * 创建一个缓动动画,让目标对象从当前属性变换到目标属性。
  2936. * @param target 缓动目标对象。
  2937. * @param toProps 缓动目标对象的目标属性。
  2938. * @param params 缓动动画的参数。
  2939. * @returns {Tween} 一个Tween实例对象。
  2940. */
  2941. to: function(target, toProps, params){
  2942. var tween = new Tween(target, toProps, params);
  2943. tween._init();
  2944. return tween;
  2945. },
  2946. /**
  2947. * 创建一个缓动动画,让目标对象从指定的起始属性变换到当前属性。
  2948. * @param target 缓动目标对象。
  2949. * @param toProps 缓动目标对象的起始属性。
  2950. * @param params 缓动动画的参数。
  2951. * @returns {Tween} 一个Tween实例对象。
  2952. */
  2953. from: function(target, fromProps, params){
  2954. var tween = new Tween(target, fromProps, params);
  2955. var tmp = tween._oldProps;
  2956. tween._oldProps = tween._newProps;
  2957. tween._newProps = tmp;
  2958. tween._reverseFlag = -1;
  2959. for(var p in tween._oldProps) target[p] = tween._oldProps[p];
  2960. tween._init();
  2961. return tween;
  2962. }
  2963. }
  2964. });
  2965. })();
  2966. //TODO: 超时timeout,失败重连次数maxTries,更多的下载器Loader,队列暂停恢复等。
  2967. /**
  2968. * @class LoadQueue是一个队列下载工具。
  2969. * @param {Object} source 要下载的资源。可以是单个资源对象或多个资源的数组。
  2970. * @module hilo/loader/LoadQueue
  2971. * @requires hilo/core/Class
  2972. * @requires hilo/event/EventMixin
  2973. * @property {Int} maxConnections 同时下载的最大连接数。默认为2。
  2974. */
  2975. var LoadQueue = Class.create(/** @lends LoadQueue.prototype */{
  2976. Mixes: EventMixin,
  2977. constructor: function LoadQueue(source){
  2978. this._source = [];
  2979. this.add(source);
  2980. },
  2981. maxConnections: 2, //TODO: 应该是每个host的最大连接数。
  2982. _source: null,
  2983. _loaded: 0,
  2984. _connections: 0,
  2985. _currentIndex: -1,
  2986. /**
  2987. * 增加要下载的资源。可以是单个资源对象或多个资源的数组。
  2988. * @returns {LoadQueue} 下载队列实例本身。
  2989. */
  2990. add: function(source){
  2991. var me = this;
  2992. if(source){
  2993. source = source instanceof Array ? source : [source];
  2994. me._source = me._source.concat(source);
  2995. }
  2996. return me;
  2997. },
  2998. /**
  2999. * 根据id或src地址获取资源对象。
  3000. * @returns {Object} 资源对象。
  3001. */
  3002. get: function(id){
  3003. if(id){
  3004. var source = this._source;
  3005. for(var i = 0; i < source.length; i++){
  3006. var item = source[i];
  3007. if(item.id === id || item.src === id){
  3008. return item;
  3009. }
  3010. }
  3011. }
  3012. return null;
  3013. },
  3014. /**
  3015. * 开始下载队列。
  3016. * @returns {LoadQueue} 下载队列实例本身。
  3017. */
  3018. start: function(){
  3019. var me = this;
  3020. me._loadNext();
  3021. return me;
  3022. },
  3023. /**
  3024. * @private
  3025. */
  3026. _loadNext: function(){
  3027. var me = this, source = me._source, len = source.length;
  3028. //all items loaded
  3029. if(me._loaded >= len){
  3030. me.fire('complete');
  3031. return;
  3032. }
  3033. if(me._currentIndex < len - 1 && me._connections < me.maxConnections){
  3034. var index = ++me._currentIndex;
  3035. var item = source[index];
  3036. var loader = me._getLoader(item);
  3037. if(loader){
  3038. var onLoad = loader.onLoad, onError = loader.onError;
  3039. loader.onLoad = function(e){
  3040. loader.onLoad = onLoad;
  3041. loader.onError = onError;
  3042. var content = onLoad && onLoad.call(loader, e) || e.target;
  3043. me._onItemLoad(index, content);
  3044. };
  3045. loader.onError = function(e){
  3046. loader.onLoad = onLoad;
  3047. loader.onError = onError;
  3048. onError && onError.call(loader, e);
  3049. me._onItemError(index, e);
  3050. };
  3051. loader.load(item);
  3052. me._connections++;
  3053. }
  3054. me._loadNext();
  3055. }
  3056. },
  3057. /**
  3058. * @private
  3059. */
  3060. _getLoader: function(item){
  3061. var me = this, loader = item.loader;
  3062. if(loader) return loader;
  3063. var type = item.type || getExtension(item.src);
  3064. switch(type){
  3065. case 'png':
  3066. case 'jpg':
  3067. case 'jpeg':
  3068. case 'gif':
  3069. loader = new ImageLoader();
  3070. break;
  3071. case 'js':
  3072. case 'jsonp':
  3073. loader = new ScriptLoader();
  3074. break;
  3075. }
  3076. return loader;
  3077. },
  3078. /**
  3079. * @private
  3080. */
  3081. _onItemLoad: function(index, content){
  3082. var me = this, item = me._source[index];
  3083. item.loaded = true;
  3084. item.content = content;
  3085. me._connections--;
  3086. me._loaded++;
  3087. me.fire('load', item);
  3088. me._loadNext();
  3089. },
  3090. /**
  3091. * @private
  3092. */
  3093. _onItemError: function(index, e){
  3094. var me = this, item = me._source[index];
  3095. item.error = e;
  3096. me._connections--;
  3097. me._loaded++;
  3098. me.fire('error', item);
  3099. me._loadNext();
  3100. },
  3101. /**
  3102. * 获取全部或已下载的资源的字节大小。
  3103. * @param {Boolean} loaded 指示是已下载的资源还是全部资源。默认为全部。
  3104. * @returns {Number} 指定资源的字节大小。
  3105. */
  3106. getSize: function(loaded){
  3107. var size = 0, source = this._source;
  3108. for(var i = 0; i < source.length; i++){
  3109. var item = source[i];
  3110. size += (loaded ? item.loaded && item.size : item.size) || 0;
  3111. }
  3112. return size;
  3113. },
  3114. /**
  3115. * 获取已下载的资源数量。
  3116. * @returns {Uint} 已下载的资源数量。
  3117. */
  3118. getLoaded: function(){
  3119. return this._loaded;
  3120. },
  3121. /**
  3122. * 获取所有资源的数量。
  3123. * @returns {Uint} 所有资源的数量。
  3124. */
  3125. getTotal: function(){
  3126. return this._source.length;
  3127. }
  3128. });
  3129. /**
  3130. * @private
  3131. */
  3132. function getExtension(src){
  3133. var extRegExp = /\/?[^/]+\.(\w+)/i, match, extension;
  3134. if(match = src.match(extRegExp)){
  3135. extension = match[1].toLowerCase();
  3136. }
  3137. return extension || null;
  3138. }
  3139. /**
  3140. * @private
  3141. * @class 图片资源加载器。
  3142. * @module hilo/loader/ImageLoader
  3143. * @requires hilo/core/Class
  3144. */
  3145. var ImageLoader = Class.create({
  3146. load: function(data){
  3147. var me = this;
  3148. var image = new Image();
  3149. image.onload = me.onLoad.bind(me);
  3150. image.onerror = image.onabort = me.onError.bind(me);
  3151. image.src = data.src + (data.noCache ? (data.src.indexOf('?') == -1 ? '?' : '&') + 't=' + (+new Date) : '');
  3152. },
  3153. onLoad: function(e){
  3154. var image = e.target;
  3155. image.onload = image.onerror = image.onabort = null;
  3156. return image;
  3157. },
  3158. onError: function(e){
  3159. var image = e.target;
  3160. image.onload = image.onerror = image.onabort = null;
  3161. return e;
  3162. }
  3163. });
  3164. /**
  3165. * @private
  3166. * @class javascript或JSONP加载器。
  3167. * @module hilo/loader/ScriptLoader
  3168. * @requires hilo/core/Class
  3169. */
  3170. var ScriptLoader = Class.create({
  3171. load: function(data){
  3172. var me = this, src = data.src, isJSONP = data.type == 'jsonp';
  3173. if(isJSONP){
  3174. var callbackName = data.callbackName || 'callback';
  3175. var callback = data.callback || 'jsonp' + (++ScriptLoader._count);
  3176. var win = window;
  3177. if(!win[callback]){
  3178. win[callback] = function(result){
  3179. delete win[callback];
  3180. }
  3181. }
  3182. }
  3183. if(isJSONP) src += (src.indexOf('?') == -1 ? '?' : '&') + callbackName + '=' + callback;
  3184. if(data.noCache) src += (src.indexOf('?') == -1 ? '?' : '&') + 't=' + (+new Date());
  3185. var script = document.createElement('script');
  3186. script.type = 'text/javascript';
  3187. script.async = true;
  3188. script.onload = me.onLoad.bind(me);
  3189. script.onerror = me.onError.bind(me);
  3190. script.src = src;
  3191. if(data.id) script.id = data.id;
  3192. document.getElementsByTagName('head')[0].appendChild(script);
  3193. },
  3194. onLoad: function(e){
  3195. var script = e.target;
  3196. script.onload = script.onerror = null;
  3197. return script;
  3198. },
  3199. onError: function(e){
  3200. var script = e.target;
  3201. script.onload = script.onerror = null;
  3202. return e;
  3203. },
  3204. Statics: {
  3205. _count: 0
  3206. }
  3207. });
  3208. Hilo.Class = Class;
  3209. Hilo.EventMixin = EventMixin;
  3210. Hilo.Renderer = Renderer;
  3211. Hilo.CanvasRenderer = CanvasRenderer;
  3212. Hilo.DOMRenderer = DOMRenderer;
  3213. Hilo.Matrix = Matrix;
  3214. Hilo.Drawable = Drawable;
  3215. Hilo.View = View;
  3216. Hilo.Container = Container;
  3217. Hilo.Stage = Stage;
  3218. Hilo.Bitmap = Bitmap;
  3219. Hilo.Sprite = Sprite;
  3220. Hilo.DOMElement = DOMElement;
  3221. Hilo.Graphics = Graphics;
  3222. Hilo.Text = Text;
  3223. Hilo.BitmapText = BitmapText;
  3224. Hilo.TextureAtlas = TextureAtlas;
  3225. Hilo.Ticker = Ticker;
  3226. Hilo.Tween = Tween;
  3227. Hilo.LoadQueue = LoadQueue;
  3228. Hilo.ImageLoader = ImageLoader;
  3229. Hilo.ScriptLoader = ScriptLoader;
  3230. window.Hilo = Hilo;
  3231. if(!window.H) window.H = Hilo;
  3232. })(window);