### Dynamic Hilo Example Loading and Navigation Logic Source: https://github.com/hiloteam/hilo/blob/dev/examples/index.html This JavaScript code manages the dynamic loading and navigation of Hilo examples. It populates a list of examples, handles user clicks to load demos into an iframe, and implements keyboard shortcuts (Up/Down arrows, W/S keys) for seamless example switching. It also supports initial loading based on URL hash. ```javascript var listElem = document.getElementById('exampleList'); var iframeElem = document.getElementById('exampleFrame'); var examples = [ 'Bitmap', 'Sprite', 'Sprite2', 'Graphics', 'MouseEvent', 'Button', 'BitmapText', 'LoadQueue', 'Text', 'Tween', 'TweenLink', 'Ease', 'WebSound', 'drag', 'Camera', 'Camera3d', 'Background', 'align', 'DOMElement', 'ParticleSystem', 'Resize', ['physics','../src/extensions/physics/demo/index'], ['dragonbones','../src/extensions/dragonbones/demo/index'] ]; function getExampleName(name){ if(Object.prototype.toString.call(name) === '[object Array]'){ return name[0]; } else{ return name; } } function getExamplePath(name){ if(Object.prototype.toString.call(name) === '[object Array]'){ return name[1] + '.html'; } else{ return name + '.html'; } } var examplesDict = {}; for(var i = 0;i < examples.length;i ++){ (function(originName, i){ var name = getExampleName(originName); var elem = document.createElement('li'); examplesDict[name] = { elem:elem, originName:originName }; elem.innerHTML = name; listElem.appendChild(elem); elem.onclick = function(){ setDemo(originName); }; })(examples[i], i); } var winWidth = window.innerWidth || document.documentElement.clientWidth; var winHeight = window.innerHeight || document.documentElement.clientHeight; iframeElem.width = winWidth - 220; iframeElem.height = winHeight - 20; var iframeWindow = iframeElem.contentWindow; var hashName = location.hash.slice(1); var currentName = ''; function setDemo(originName, first){ var name = getExampleName(originName); var path = getExamplePath(originName); if(name !== currentName){ location.hash = name; iframeElem.src = path + (first?location.search:iframeWindow.location.search); if(examplesDict[currentName]){ examplesDict[currentName].elem.className = ''; } examplesDict[name].elem.className = 'active'; currentName = name; } } setDemo(examplesDict[hashName]?examplesDict[hashName].originName:examples[0], true); window.onkeydown = function(e){ var index = examples.indexOf(examplesDict[currentName].originName); switch(e.keyCode){ case 38://up case 87://w index --; break; case 40://down case 83://s index ++; break; } if(index < 0){ index = examples.length - 1; } else if(index > examples.length - 1){ index = 0; } setDemo(examples[index]); }; ``` -------------------------------- ### Get and Play Audio with WebSound Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/WebSound.html Demonstrates how to get an audio instance using WebSound.getAudio, configure its source, loop, and volume, and attach event listeners for 'load' and 'end' before playing it. This example showcases basic audio playback management within the Hilo framework. ```JavaScript var audio = WebSound.getAudio({ src: 'test.mp3', loop: false, volume: 1 }).on('load', function(e){ console.log('load'); }).on('end', function(e){ console.log('end'); }).play(); ``` -------------------------------- ### Generate New Hilo Game Project with Yeoman Source: https://github.com/hiloteam/hilo/blob/dev/README.md Steps to install Yeoman and the Hilo generator globally, then use them to scaffold a new Hilo game project, enabling quick setup for game development. ```bash npm install -g yo npm install -g generator-hilo yo hilo ``` -------------------------------- ### start() Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/LoadQueue.html start loading ```APIDOC Method: start Signature: start():LoadQueue Description: start loading Returns: LoadQueue - the loading instance ``` -------------------------------- ### Example: Creating a Class with Hilo.Class.create Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_core_Class.js.html This example demonstrates how to define a new class 'Bird' using `Hilo.Class.create`. It showcases inheritance from 'Animal', mixing in 'EventMixin', defining a constructor, instance methods, and static methods. It also shows how to instantiate and use the class. ```JavaScript var Bird = Hilo.Class.create({ Extends: Animal, Mixes: EventMixin, constructor: function(name){ this.name = name; }, fly: function(){ console.log('I am flying'); }, Statics: { isBird: function(bird){ return bird instanceof Bird; } } }); var swallow = new Bird('swallow'); swallow.fly(); Bird.isBird(swallow); ``` -------------------------------- ### Hilo.js Camera: Following and Switching Targets Source: https://github.com/hiloteam/hilo/blob/dev/examples/Camera.html This JavaScript code initializes a Hilo.js game stage with a camera. It sets up the camera's dimensions, bounds, and a deadzone. The example demonstrates how the camera can follow moving 'fish' objects and how to dynamically switch the camera's target between two fish instances with a smooth tween animation upon a mouse click. It also visualizes the camera's deadzone. ```JavaScript stageWidth = 800; stageHeight = 600; function init(){ var Tween = Hilo.Tween; var Camera = Hilo.Camera; gameContainer.style.height = stageHeight + 'px'; var mapScale = 1.5; var mapWidth = 1440 * mapScale; var mapHeight = 900 * mapScale; //init stage var stage = new Hilo.Stage({ renderType:renderType, container: gameContainer, width: stageWidth, height: stageHeight }); //设置deadzone区域 var dw = 250, dh = 150; var deadzone = [dw, dh, stageWidth - dw * 2, stageHeight - dh * 2]; //新建摄像机,设置边界,deadzone var camera = new Camera({ width:stageWidth, height:stageHeight, bounds:[0, 0, mapWidth - stageWidth, mapHeight - stageHeight], deadzone:deadzone }); //创建地图 var map = new Hilo.Container().addTo(stage); var bg = window.bg = new Hilo.Bitmap({ image: 'images/map.jpg', scaleX:mapScale, scaleY:mapScale }).addTo(map); //创建一只鱼 var fishSpeed = 2; var fish0 = new Hilo.Bitmap({ image: 'images/fish.png', rect: [0, 0, 174, 126], x: 0, y: 300, scaleX:.7, scaleY:.7, pivotX:87, pivotY:63, onUpdate:function(){ this.x +=this.speed; if(this.x > mapWidth || this.x < 0){ this.speed *= -1; this.scaleX *= -1; } } }).addTo(map); fish0.speed = fishSpeed; //摄像机跟谁鱼 camera.follow(fish0); var ticker = new Hilo.Ticker(60); ticker.addTick(stage); ticker.addTick(camera); ticker.addTick(Tween); //map跟随摄像机滚动 ticker.addTick({ tick:function(){ map.x = - camera.scroll.x; map.y = - camera.scroll.y; } }); //start stage ticker ticker.start(); var fish1 = new Hilo.Bitmap({ image: 'images/fish.png', rect: [0, 0, 174, 126], x: 400, y: 300, scaleX:.7, scaleY:.7, pivotX:87, pivotY:63, rotation:90, onUpdate:function(){ this.y +=this.speed; if(this.y > mapHeight || this.y < 0){ this.speed *= -1; this.scaleX *= -1; } } }).addTo(map); fish1.speed = fishSpeed; //显示deadzone区域 stage.addChild(new Hilo.View({ x:camera.deadzone[0], y:camera.deadzone[1], width:camera.deadzone[2], height:camera.deadzone[3], background:"rgba(255, 0, 0, .3)" })); //切换摄像机跟随对象 var tween; document.body.onclick = function(){ var target = camera.target == fish1?fish0:fish1; var pos = { x:camera.target.x, y:camera.target.y }; Tween.remove(tween); tween = Tween.to(pos,{ x:target.x, y:target.y },{ duration:1000, onComplete:function(){ camera.follow(target, deadzone); } }) camera.follow(pos, null); } } ``` -------------------------------- ### Hilo.Tween.prototype.start Method Implementation Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_tween_Tween.js.html The JavaScript implementation of the `start` method, which initializes the tween's internal state, including start time, seek time, and flags, then adds the tween to the global Tween manager for active processing. ```JavaScript start: function(){ var me = this; me._startTime = now() + me.delay; me._seekTime = 0; me._pausedTime = 0; me._pausedStartTime = 0; me._reverseFlag = 1; me._repeatCount = 0; me.paused = false; me.isStart = false; me.isComplete = false; Tween.add(me); return me; }, ``` -------------------------------- ### Styling for Hilo Example List and Frame Source: https://github.com/hiloteam/hilo/blob/dev/examples/index.html This CSS defines the visual layout and appearance of the example list (#exampleList) and the iframe (#exampleFrame). It includes styles for list items, active states, and general positioning to create a responsive and organized demo interface. ```css body,ul,li{ margin:0px; padding:0px; } #exampleList{ list-style: none; background: #aaa; width:150px; margin: 10px; } #exampleList li{ font-size: 16px; line-height: 30px; height: 30px; margin: 1px 1px; background: #999; cursor: pointer; text-align: center; color: #fff; } #exampleList .active{ background: #3a383e; } #exampleFrame{ position: absolute; right:10px; top:10px; border:2px solid #333; overflow: hidden; } ``` -------------------------------- ### JavaScript Class Creation Example with Hilo.Class.create Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_core_Class.js.html This example demonstrates how to create a new class `Bird` using `Hilo.Class.create`. It shows how to extend an `Animal` class, mix in `EventMixin`, define a constructor, instance methods like `fly`, and static methods like `isBird`. It also illustrates how to instantiate and use the created class. ```javascript var Bird = Hilo.Class.create({ Extends: Animal, Mixes: EventMixin, constructor: function(name){ this.name = name; }, fly: function(){ console.log('I am flying'); }, Statics: { isBird: function(bird){ return bird instanceof Bird; } } }); var swallow = new Bird('swallow'); swallow.fly(); Bird.isBird(swallow); ``` -------------------------------- ### Initialize Hilo.Stage with Canvas Renderer Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_view_Stage.js.html This example demonstrates how to create a new Hilo.Stage instance, specifying its rendering type as 'canvas', providing a container element, and setting its initial width and height. A Hilo application typically starts by creating a Stage. ```JavaScript var stage = new Hilo.Stage({ renderType:'canvas', container: containerElement, width: 320, height: 480 }); ``` -------------------------------- ### LoadQueue.start: Initiate Download Queue Processing Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_loader_LoadQueue.js.html Starts the download process for all resources in the queue. It returns the `LoadQueue` instance for chaining. ```APIDOC /** * 开始下载队列。 * @returns {LoadQueue} 下载队列实例本身。 */ start: function(){ var me = this; me._loadNext(); return me; } ``` -------------------------------- ### Instantiate Hilo.Button with States Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_view_Button.js.html Demonstrates how to create a new Hilo.Button instance, specifying different visual states (up, over, down, disabled) using image rects. This example shows the basic setup for a clickable button. ```JavaScript var btn = new Hilo.Button({ image: buttonImage, upState: {rect:[0, 0, 64, 64]}, overState: {rect:[64, 0, 64, 64]}, downState: {rect:[128, 0, 64, 64]}, disabledState: {rect:[192, 0, 64, 64]} }); ``` -------------------------------- ### Initialize and Play Audio with WebSound Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_media_WebSound.js.html Demonstrates how to get an audio instance using `WebSound.getAudio`, configure its source, loop, and volume, and attach 'load' and 'end' event listeners before playing the audio. ```JavaScript var audio = WebSound.getAudio({ src: 'test.mp3', loop: false, volume: 1 }).on('load', function(e){ console.log('load'); }).on('end', function(e){ console.log('end'); }).play(); ``` -------------------------------- ### Animate Hilo.js Camera3d Z-Axis Rotation to Target Source: https://github.com/hiloteam/hilo/blob/dev/examples/Camera3d.html Handles the 'start' button click event to animate the Camera3d's Z-axis rotation. It uses Hilo.Tween to smoothly rotate the camera to a random target angle, simulating a spin or selection effect, and also animates X-axis rotation. ```JavaScript document.getElementById('start').onclick = function(){ var me = this, index = Math.floor(Math.random(8)), rotationZ_start = camera.rotationZ, rotationZ_end = index * angle - 180 + 360 * ( Math.floor(rotationZ_start / 360) - 1), decrease_time = (rotationZ_end - rotationZ_start) * 2 / rotateZ_velocity, accelaretion_angle = rotateZ_velocity / decrease_time, animation = { x : camera.rotationX, z : rotationZ_start }; Tween.to(animation, { z : rotationZ_end }, { duration:5000, ease:Ease.Quad.EaseOut, onUpdate: function(){ camera.rotateZ(animation.z); }, onComplete: function(){ // ticker.stop(); } }); Tween.to(animation, { // y : 20, x : 105 }, { duration:1000, onUpdate: function(){ camera.rotateX(animation.x); } }); // ticker.start(); } ``` -------------------------------- ### Hilo.Bitmap: Basic Instantiation and Usage Example Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_view_Bitmap.js.html Demonstrates how to create a new Hilo.Bitmap instance with an image element and a specified rectangle, then add it to a stage for display. ```javascript var bmp = new Hilo.Bitmap({image:imgElem, rect:[0, 0, 100, 100]}); stage.addChild(bmp); ``` -------------------------------- ### Initialize and Start Dragging a Bitmap in Hilo Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/drag.html Demonstrates how to mix the `drag` functionality into a `Bitmap` object and initiate dragging within specified bounds using `Hilo.util.copy`. ```JavaScript var bmp = new Bitmap({image:img}); Hilo.util.copy(bmp, Hilo.drag); bmp.startDrag([0, 0, 550, 400]); ``` -------------------------------- ### LoadQueue: Start Resource Loading Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_loader_LoadQueue.js.html Initiates the loading process for all resources in the queue. It returns the `LoadQueue` instance for chaining. ```APIDOC start(): LoadQueue description: Start loading. returns: type: LoadQueue description: The loading instance. ``` ```JavaScript start: function(){ var me = this; me._loadNext(); return me; }, ``` -------------------------------- ### ParticleSystem Class Methods Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/ParticleSystem.html Documentation for methods of the ParticleSystem class, including update, reset, start, and stop functionalities for particle emission and management. ```APIDOC ParticleSystem Methods: onUpdate(dt: Number) description: 更新 parameters: dt: Number description: delta time(in milliseconds) reset(cfg: Object) description: Reset the properties. parameters: cfg: Object start() description: Start emit particles. stop(clear: Boolean) description: Stop emit particles. parameters: clear: Boolean description: Whether or not clear all the particles. ``` -------------------------------- ### Hilo Drag Mixin Usage Example Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_util_drag.js.html Illustrates how to apply the `drag` mixin to a `Bitmap` instance and initiate dragging within specified bounds using `Hilo.util.copy` and `startDrag`. ```JavaScript var bmp = new Bitmap({image:img}); Hilo.util.copy(bmp, Hilo.drag); bmp.startDrag([0, 0, 550, 400]); ``` -------------------------------- ### Instantiating Hilo DOMElement Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_view_DOMElement.js.html This example demonstrates how to create a new DOMElement instance, configure its style and position, and add it to a Hilo stage. It shows how to wrap a custom div element. ```JavaScript var domView = new Hilo.DOMElement({ element: Hilo.createElement('div', { style: { backgroundColor: '#004eff', position: 'absolute' } }), width: 100, height: 100, x: 50, y: 70 }).addTo(stage); ``` -------------------------------- ### Configure Hilo.js Ticker for Stage and Camera Updates Source: https://github.com/hiloteam/hilo/blob/dev/examples/Camera3d.html Sets up the Hilo.js Ticker to manage the update loop for the stage, Tween animations, and the Camera3d. The ticker ensures that all visual elements and animations are rendered and updated at a consistent frame rate. ```JavaScript var ticker = new Hilo.Ticker(60); ticker.addTick(stage); ticker.addTick(Tween); ticker.addTick(camera); ticker.start(true); } ``` -------------------------------- ### Hilo.viewToString: Get View String Representation Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_core_Hilo.js.html Generates a path-like string representation for a specified visual object, showing its hierarchy. For example, 'Stage1.Container2.Bitmap3'. ```JavaScript viewToString: function(view) { var result, obj = view; while (obj) { result = result ? (obj.id + '.' + result) : obj.id; obj = obj.parent; } return result; } ``` ```APIDOC Hilo.viewToString(view: View): view: 指定的可视对象。 returns: String - 可视对象的字符串表示形式。 ``` -------------------------------- ### Compile and Build Hilo Framework with Gulp Source: https://github.com/hiloteam/hilo/blob/dev/README.md Instructions for setting up dependencies and building the Hilo framework and its extensions using Gulp. This includes commands for generating API documentation and running tests. ```bash npm install gulp gulp extensions gulp doc gulp test ``` -------------------------------- ### WebAudio Module Initialization and AudioContext Setup Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_media_WebAudio.js.html Initializes the WebAudio module by creating an AudioContext instance, falling back to webkitAudioContext for broader compatibility. This block ensures the Web Audio API context is available for subsequent audio operations. ```JavaScript var WebAudio = (function(){ var context = null; try { var AudioContext = window.AudioContext || window.webkitAudioContext; if (AudioContext) { context = new AudioContext(); } } catch(e) { context = null; } ``` -------------------------------- ### Hilo.Tween Basic Usage Example Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_tween_Tween.js.html Demonstrates how to initialize and use Hilo.Tween to animate a `View` object, including setting properties, duration, delay, easing function, and a completion callback. It also shows how to add Hilo.Tween to the ticker. ```JavaScript ticker.addTick(Hilo.Tween);//Tween works after being added to ticker var view = new View({x:5, y:10}); Hilo.Tween.to(view, { x:100, y:20, alpha:0 }, { duration:1000, delay:500, ease:Hilo.Ease.Quad.EaseIn, onComplete:function(){ console.log('complete'); } }); ``` -------------------------------- ### Initialize Hilo.js Stage, Camera3d, and 3D Objects Source: https://github.com/hiloteam/hilo/blob/dev/examples/Camera3d.html Initializes the Hilo.js Stage and Camera3d instance, setting up the camera's field of view and projection center. It then creates multiple Hilo.Bitmap objects, assigns them 3D coordinates, and adds them to the stage, projecting them using the camera's `project` method. ```JavaScript var Tween = Hilo.Tween; var Ease = Hilo.Ease; function init(){ var degree = Math.PI/180; var winWidth = 800; var winHeight = 600; var radius = 200; var mapScale = 1.5; var mapWidth = 1440*mapScale; var mapHeight = 900*mapScale; var gameContainer = document.getElementById("game-container"); var stage = new Hilo.Stage({ container: gameContainer, width: winWidth, height: winHeight }); var camera = new Hilo.Camera3d({ fv : winWidth/2, fx : winWidth/2, fy : winHeight/2, stage : stage }); var angle = 360 / 8; var view3d_list = []; for(var i = 0; i < 8; i++) { var offset_angle = degree * (angle * i), x_3d = Math.sin(offset_angle) * radius, y_3d = Math.cos(offset_angle) * radius; var view = new Hilo.Bitmap({ image: 'images/tmallIcon.jpg', x: 0, y: 0, scaleX: 0.1, scaleY: 0.1, pivotX: 43, pivotY: 50, onUpdate:function(){ var vector2d = camera.project(this.vector3d, this); } }).addTo(stage); view.vector3d = { x : x_3d, y : y_3d, z : 0 }; view3d_list.push(view); } ``` -------------------------------- ### Instantiate Hilo DOMElement with Custom Styles Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/DOMElement.html Demonstrates how to create a new Hilo.DOMElement instance, attach a native DOM div element with custom styles, and add it to the stage. This example shows basic setup for integrating HTML elements into a Hilo application, setting its position and dimensions. ```JavaScript var domView = new Hilo.DOMElement({ element: Hilo.createElement('div', { style: { backgroundColor: '#004eff', position: 'absolute' } }), width: 100, height: 100, x: 50, y: 70 }).addTo(stage); ``` -------------------------------- ### Display JsDoc Toolkit Command Line Help Source: https://github.com/hiloteam/hilo/blob/dev/tools/jsdoc-toolkit-2.4.0/README.txt This command shows the available command-line options and usage notes for JsDoc Toolkit, providing guidance on how to use the tool effectively. ```Bash/Zsh (Mac/Linux) java -jar jsrun.jar app/run.js --help ``` -------------------------------- ### Simplify JsDoc Toolkit Execution with jsrun.sh Source: https://github.com/hiloteam/hilo/blob/dev/tools/jsdoc-toolkit-2.4.0/README.txt The "jsrun.sh" script streamlines running JsDoc Toolkit by automatically handling long paths and passing arguments. It also integrates with "JSDOCDIR" and "JSDOCTEMPLATEDIR" environment variables for flexible configuration, making it ideal for build environments. ```Bash/Zsh (Mac/Linux) Usage: jsrun.sh ``` -------------------------------- ### Link Next Tween Transformation (JavaScript) Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_tween_Tween.js.html Connects a new Tween instance to the current one, allowing for sequential animations. The start time of the linked tween is dynamically calculated based on its `delay` property. If `delay` is a string starting with '+' or '-', the next tween starts relative to the current tween's end time; otherwise, it starts relative to the current tween's start time. This method supports chaining. ```javascript link: function(tween){ var me = this, delay = tween.delay, startTime = me._startTime; var plus, minus; if(typeof delay === 'string'){ plus = delay.indexOf('+') == 0; minus = delay.indexOf('-') == 0; delay = plus || minus ? Number(delay.substr(1)) * (plus ? 1 : -1) : Number(delay); } tween.delay = delay; tween._startTime = plus || minus ? startTime + me.duration + delay : startTime + delay; me._next = tween; Tween.remove(tween); return tween; }, ``` -------------------------------- ### get(specified:String) Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/LoadQueue.html get resource object by id or src ```APIDOC Method: get Signature: get(specified:String):Object Description: get resource object by id or src Parameters: specified: String - id or src Returns: Object - resource object ``` -------------------------------- ### Run JsDoc Toolkit from Command Line Source: https://github.com/hiloteam/hilo/blob/dev/tools/jsdoc-toolkit-2.4.0/README.txt These commands demonstrate how to execute JsDoc Toolkit from the command line on different operating systems. They use "java -jar jsrun.jar" to run the "app/run.js" script, specifying a template and the source code file. Output documentation is saved to a new "out" directory by default, or to a custom directory if specified with "-d". ```Windows Command Prompt java -jar jsrun.jar app\run.js -a -t=templates\jsdoc mycode.js ``` ```Bash/Zsh (Mac/Linux) java -jar jsrun.jar app/run.js -a -t=templates/jsdoc mycode.js ``` -------------------------------- ### CSS Styling for Hilo.js Camera Example Layout Source: https://github.com/hiloteam/hilo/blob/dev/examples/Camera3d.html Defines the layout and styling for the game container and control buttons used in the Hilo.js Camera3d example. It positions elements like angle sliders, zoom, and reset buttons within the page. ```CSS #game-container{ border:solid 1px #000; width: 800px; height: 600px; margin: 20px auto; } #button-container{ position: absolute; left: 50%; top: 20px; width: 800px; height: 600px; margin-left: -400px; } button, input, label { position: absolute; } #x_angle { left: 20px; bottom: 60px; } #y_angle { left: 20px; bottom: 40px; } #z_angle { left: 20px; bottom: 20px; } #x_angle_range { left: 70px; bottom: 60px; } #y_angle_range { left: 70px; bottom: 40px; } #z_angle_range { left: 70px; bottom: 20px; } #start { left: 20px; bottom: 0; } #zoomin { left: 70px; bottom: 0; } #reset { left: 120px; bottom: 0; } #fv { left: 20px; bottom: -30px; } #fv_range { left: 160px; bottom: -30px; } ``` -------------------------------- ### Hilo.js Fish Sprite Animation with Random Tint Source: https://github.com/hiloteam/hilo/blob/dev/examples/tint.html This JavaScript code initializes a Hilo.js stage and a ticker for animation. It then creates a texture atlas from a 'fish.png' image. Thirty fish sprites are generated, each assigned a random starting position, rotation, and a unique tint color. The sprites are animated to move across the canvas, wrapping around the edges when they go off-screen, demonstrating basic sprite animation and tinting capabilities in Hilo.js. ```JavaScript function init(){ //init stage var stage = new Hilo.Stage({ renderType:renderType, container: gameContainer, width: stageWidth, height: stageHeight }); //start stage ticker var ticker = new Hilo.Ticker(60); ticker.addTick(stage); ticker.start(); //init texture atlas var atlas = new Hilo.TextureAtlas({ image: 'images/fish.png', width: 174, height: 1512, frames: { frameWidth: 174, frameHeight: 126, numFrames: 12 }, sprites: { fish: {from:0, to:7} } }); //create a fish sprite var maxX = stageWidth + 174; var maxY = stageHeight + 126; var minX = -174; var minY = -126; var num = 30; while(num--){ var fish = new Hilo.Sprite({ frames: atlas.getSprite('fish'), x: Math.random()*stageWidth, y: Math.random()*stageHeight, interval: 6, timeBased: false, loop: true, alpha:1, tint:Math.random()*0xffffff, pivotX:87, pivotY:63, onUpdate: function(){ if(this.x > maxX){ this.x = minX; } else if(this.x < minX){ this.x = maxX; } if(this.y > maxY){ this.y = minY; } else if(this.y < minY){ this.y = maxY; } this.x += this.vx; this.y += this.vy; } }).addTo(stage); var speed = 2; fish.rotation = Math.random()*360; fish.vy = Math.sin(fish.rotation*Math.PI/180) * speed; fish.vx = Math.cos(fish.rotation*Math.PI/180) * speed; } } ``` -------------------------------- ### WebAudio Constructor and Private Initialization Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_media_WebAudio.js.html The constructor initializes WebAudio instance properties and calls the private `_init` method. The `_init` method sets up the Web Audio context, creates a GainNode for volume control, connects it to the destination, and binds event handlers. ```JavaScript return Class.create(/** @lends WebAudio.prototype */{ Mixes: EventMixin, constructor: function(properties){ ``` -------------------------------- ### Create Tween Animation from Start to End Properties (JavaScript) Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_tween_Tween.js.html Creates a tween animation for a target object or array of objects, transitioning from specified start properties to target properties. Supports staggering for array targets, allowing a delay between the start of each individual tween. ```javascript fromTo: function(target, fromProps, toProps, params){ params = params || {}; var isArray = target instanceof Array; target = isArray ? target : [target]; var tween, i, stagger = params.stagger, tweens = []; for(i = 0; i < target.length; i++){ tween = new Tween(target[i], fromProps, toProps, params); if(stagger) tween.delay = (params.delay || 0) + (i * stagger || 0); tween.start(); tweens.push(tween); } return isArray?tweens:tween; } ``` -------------------------------- ### Link a Tween to another Tween Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_tween_Tween.js.html Links a subsequent Tween to the current one, determining its start time based on a delay. The delay can be a number (offset from current tween's start) or a string ('+X' or '-X' for offset from current tween's end). This method ensures the next tween starts correctly in a sequence. Returns the linked Tween instance for further chaining. ```JavaScript link: function(tween){ var me = this, delay = tween.delay, startTime = me._startTime; var plus, minus; if(typeof delay === 'string'){ plus = delay.indexOf('+') == 0; minus = delay.indexOf('-') == 0; delay = plus || minus ? Number(delay.substr(1)) * (plus ? 1 : -1) : Number(delay); } tween.delay = delay; tween._startTime = plus || minus ? startTime + me.duration + delay : startTime + delay; me._next = tween; Tween.remove(tween); return tween; } ``` -------------------------------- ### ParticleSystem Class Constructor Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/ParticleSystem.html Documentation for the ParticleSystem class constructor, detailing parameters for creating a particle system object, including comprehensive particle configuration options. ```APIDOC ParticleSystem Constructor: ParticleSystem(properties: Object) parameters: properties: Object description: The properties to create a view object, contains all writeable props of this class. properties.particle: Object description: The config of particle. properties.particle.x: Number (Optional, Default: 0) description: The x position. properties.particle.y: Number (Optional, Default: 0) description: The y position. properties.particle.vx: Number (Optional, Default: 0) description: The x velocity. properties.particle.vy: Number (Optional, Default: 0) description: The y velocity. properties.particle.ax: Number (Optional, Default: 0) description: The x acceleration. properties.particle.ay: Number (Optional, Default: 0) description: The y acceleration. properties.particle.life: Number (Optional, Default: 1) description: The time particle lives(in second). properties.particle.alpha: Number (Optional, Default: 1) description: The alpha. properties.particle.alphaV: Number (Optional, Default: 0) description: The alpha decline rate. properties.particle.scale: Number (Optional, Default: 1) description: The scale. properties.particle.scaleV: Number (Optional, Default: 0) description: The scale decline rate. ``` -------------------------------- ### Ticker.start() Method Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_util_Ticker.js.html Starts the ticker, initiating the animation loop. It can optionally use requestAnimationFrame for smoother animations if available and the interval is less than 17ms, otherwise falls back to setTimeout. Prevents multiple starts. ```APIDOC start(useRAF: Boolean): Start the ticker. @param {Boolean} useRAF Whether or not use requestAnimationFrame, default is true. ``` ```JavaScript start: function(useRAF){ if(useRAF === undefined){ useRAF = true; } if(this._intervalId) return; this._lastTime = +new Date(); var self = this, interval = this._interval, raf = window.requestAnimationFrame || window[browser.jsVendor + 'RequestAnimationFrame']; var runLoop; if(useRAF && raf && interval < 17){ this._useRAF = true; runLoop = function(){ self._intervalId = raf(runLoop); self._tick(); }; }else{ runLoop = function(){ self._intervalId = setTimeout(runLoop, interval); self._tick(); }; } this._paused = false; runLoop(); } ``` -------------------------------- ### WebGLRenderer Class API Reference Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/WebGLRenderer.html Detailed API documentation for the WebGLRenderer class, including its constructor, static methods, instance methods, and properties. It outlines the purpose, parameters, and return types for each member. ```APIDOC Class: WebGLRenderer Constructor: WebGLRenderer(properties: Object) properties: Object — The properties to create a renderer, contains all writeable props of this class. Static Methods: isSupport(): boolean Description: Checks if WebGL is supported. Readonly. Instance Methods: clear(x: Number, y: Number, width: Number, height: Number): void Description: Clear the given region of canvas. draw(target: View): void Description: Draw the visual object. endDraw(target: View): void Description: The handling method after draw the visual object. hide(): void Description: Hide the visual object. remove(target: View): void Description: Remove the visual object from canvas. resize(width: Number, height: Number): void Description: Resize the renderer's canvas. startDraw(target: View): void Description: Prepare for draw visual object. transform(): void Description: Transform the visual object. Properties: [Static] ATTRIBUTE_NUM: Number Description: The num of vertex attributes. Readonly. [Static] contextOptions: Object Description: WebGL context Options. See: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getContextAttributes gl: WebGLRenderingContext Description: The WebGL context of the renderer. Readonly. [Static] MAX_BATCH_NUM: Number Description: The max num of batch draw, default is 2000. ``` -------------------------------- ### Example: Applying Hilo Drag Mixin to Bitmap Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_util_drag.js.html This example demonstrates how to apply the `drag` mixin to a `Bitmap` instance and initiate dragging within specified bounds. It uses `Hilo.util.copy` to mix the drag functionality into the bitmap object. ```JavaScript var bmp = new Bitmap({image:img}); Hilo.util.copy(bmp, Hilo.drag); bmp.startDrag([0, 0, 550, 400]); ``` -------------------------------- ### Hilo WebSound API Reference Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_media_WebSound.js.html Detailed API documentation for the static `WebSound` object, including methods for audio activation, retrieval, and management. ```APIDOC WebSound: @class Audio playing manager. @static @module hilo/media/WebSound @requires hilo/media/HTMLAudio @requires hilo/media/WebAudio @requires hilo/util/util _audios: Object Description: Internal object to store audio instances. enableAudio(): void Description: Activates audio function. Requires user action events to activate. Currently supports WebAudio. getAudio(source: String|Object, preferWebAudio: Boolean = true): WebAudio|HTMLAudio Description: Gets an audio element. Defaults to WebAudio if supported. Parameters: source: String|Object Description: If String, it's the source of the audio; If Object, it should contain a src property. preferWebAudio: Boolean (optional, default: true) Description: Whether or not to use WebAudio first. Returns: WebAudio|HTMLAudio Description: Audio playing instance. removeAudio(source: String|Object): void Description: Removes an audio element. Parameters: source: String|Object Description: If String, it's the source of the audio; If Object, it should contain a src property. _normalizeSource(source: String|Object): Object Description: Normalizes the audio source input. Parameters: source: String|Object Description: The source to normalize, either a string URL or an object with a src property. Returns: Object Description: An object with a 'src' property. ``` -------------------------------- ### Macaca UI Test Framework Initialization and Execution Source: https://github.com/hiloteam/hilo/blob/dev/test/html/index.html This JavaScript snippet configures the Macaca UI testing framework. It sets the UI style to 'bdd', defines a test timeout of 10 seconds, and a slow threshold of 5 seconds. Finally, it initiates the execution of the configured UI tests. ```JavaScript _macaca_uitest.setup({ ui: 'bdd', timeout: 10000, slow: 5000 }); _macaca_uitest.run(); ``` -------------------------------- ### Create Tween Animation from Start Properties (JavaScript) Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_tween_Tween.js.html Creates a tween animation for a target object or array of objects, transitioning from specified start properties to its current properties. This method is a convenience wrapper around `fromTo`, setting the target properties to null. ```javascript from: function(target, fromProps, params){ return Tween.fromTo(target, fromProps, null, params); } ``` -------------------------------- ### Initialize and Start Audio Playback (Internal) Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/src/docs_api-en_code_media_WebAudio.js.html This internal method sets the gain node's volume based on mute status, connects the audio node to the gain node, and starts playback from a specified offset. It updates the internal state to reflect that audio is playing. ```JavaScript this._gainNode.gain.value = this.muted ? 0 : this.volume; audioNode.connect(this._gainNode); audioNode.start(0, this._offset); this._audioNode = audioNode; this._startTime = this._context.currentTime; this.playing = true; ``` -------------------------------- ### Hilo Camera Class API Reference Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/src/docs_api-zh_code_game_Camera.js.html Documents the `Camera` class, its constructor parameters, and properties. It details how to initialize a camera instance and its configurable attributes like width, height, scroll, target, bounds, and deadzone. ```APIDOC Camera Class: Represents a camera. Module: hilo/game/Camera Requires: hilo/core/Class, hilo/util/util Constructor: __init__(properties: Object) properties: Object - Parameters to create the object. Can include all writable properties of this class. Properties: width: Number - Camera width. height: Number - Camera height. scroll: Object - Scroll values {x:0, y:0}. target: View - The target the camera follows. bounds: Array - Rectangular area for camera movement boundaries [x, y, width, height]. deadzone: Array - Rectangular area where the camera does not move [x, y, width, height]. Methods: tick(deltaTime: Number) deltaTime: Number - Time elapsed since last update. Description: Updates the camera's position based on its target, deadzone, and bounds. follow(target: Object, deadzone: Array) target: Object - The target to follow, must have x, y properties. deadzone: Array - Rectangular area where the camera does not move [x, y, width, height]. Description: Sets the camera's target and optionally its deadzone, then updates the camera. ``` -------------------------------- ### getTotal() Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/LoadQueue.html get all resource count ```APIDOC Method: getTotal Signature: getTotal():Uint Description: get all resource count Returns: Uint - all resource count ``` -------------------------------- ### Initialize Code PrettyPrint Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/BitmapText.html This JavaScript snippet applies styling classes to `
` tags for code formatting and then invokes the `prettyPrint` function from the Google Code Prettify library to render the code blocks with syntax highlighting and line numbers.

```JavaScript
//make code pretty $('pre').addClass('prettyprint linenums fixedFont'); window.prettyPrint && prettyPrint();
```

--------------------------------

### getLoaded()

Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/LoadQueue.html

get loaded resource count

```APIDOC
Method: getLoaded
Signature: getLoaded():Uint
Description: get loaded resource count
Returns:
  Uint - loaded resource count
```

--------------------------------

### Initialize Hilo.js Stage and DragonBones Animation

Source: https://github.com/hiloteam/hilo/blob/dev/src/extensions/dragonbones/demo/dragon.html

This JavaScript code initializes a Hilo.js stage and ticker, then integrates DragonBones for skeletal animation. It loads texture and skeleton data, builds an armature, adds it to the stage, and sets up continuous animation playback with a click listener to switch animations.

```JavaScript
var dragonbonesFactory, armature, armatureDisplay, stage, ticker; stage = new Hilo.Stage({
 container:'stage',
 width:Math.min(innerWidth, 440),
 height:Math.min(innerHeight, 600),
 renderType:'webgl'
});
ticker = new Hilo.Ticker(60);
ticker.addTick(stage);
ticker.start();
var initArmature = function(){
 dragonbonesFactory = new dragonBones.HiloFactory();
 dragonbonesFactory.addTextureAtlas(new dragonBones.TextureAtlas(textureImage, textureData));
 dragonbonesFactory.addDragonBonesData(dragonBones.DataParser.parseDragonBonesData(skeletonData));
 armature = dragonbonesFactory.buildArmature(skeletonData.armature[0].name);
 dragonBones.WorldClock.clock.add(armature);
 armatureDisplay = armature.getDisplay();
 armatureDisplay.x = (stage.width >> 1) - 30;
 armatureDisplay.y = (stage.height >> 1) + 50;
 armatureDisplay.scaleX = armatureDisplay.scaleY = 0.4;
 stage.addChild(armatureDisplay);
 ticker.addTick(dragonBones);
 var list = armature.animation._animationList;
 var animIndex = 0;
 armature.animation.gotoAndPlay(list[animIndex], -1, -1, 0);
 window.addEventListener(Hilo.event.POINTER_START, function(){
 animIndex = (++animIndex)%list.length;
 armature.animation.gotoAndPlay(list[animIndex], -1, -1, 0);
 });
};
var textureImage = new Image();
textureImage.onload = function(){
 initArmature();
};
textureImage.src = './data/dragon/texture.png';
```

--------------------------------

### WebAudio API Reference

Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-zh/symbols/WebAudio.html

Comprehensive documentation for the WebAudio class, including its properties, constructor, and methods for audio playback control and management.

```APIDOC
Properties:
  autoPlay: Boolean
    Description: Whether to autoplay. Default is false.
  duration: Number (Read-only)
    Description: Audio duration.
  enabled: [Static]
    Description: Whether the browser has activated WebAudio.
  isSupported: [Static]
    Description: Whether the browser supports WebAudio.
  loaded: Boolean (Read-only)
    Description: Whether audio resources are loaded.
  loop: Boolean
    Description: Whether to loop playback. Default is false.
  muted: Boolean
    Description: Whether to mute. Default is false.
  playing: Boolean (Read-only)
    Description: Whether audio is currently playing.
  src: String
    Description: Resource address of the audio to play.
  volume: Number
    Description: Audio volume. Range: 0-1.

Constructor:
  WebAudio(properties: Object)
    Parameters:
      properties: Object
        Description: Property parameters for creating the object. Can include all writable properties of this class.

Methods:
  clearBufferCache(url: String): [Static]
    Description: Clears audio buffer cache.
    Parameters:
      url: String
        Description: Audio URL, clears all cache by default.
  enable(): [Static]
    Description: Activates WebAudio. Note: Requires user event to trigger. After activation, audio can play without user events.
  load()
    Description: Loads audio file. Note: Uses XMLHttpRequest, so be aware of cross-domain issues.
  pause()
    Description: Pauses audio.
  play()
    Description: Plays audio. If already playing, it restarts.
  resume()
    Description: Resumes audio playback.
  setMute(muted)
    Description: Sets whether to mute.
    Parameters:
      muted: (Type not specified)
  setVolume(volume)
    Description: Sets volume.
    Parameters:
      volume: (Type not specified)
  stop()
    Description: Stops audio playback.
```

--------------------------------

### getSize(identify:Boolean)

Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/LoadQueue.html

get resource size, loaded or all.

```APIDOC
Method: getSize
Signature: getSize(identify:Boolean):Number
Description: get resource size, loaded or all.
Parameters:
  identify: Boolean - loaded or all resource. default is false, return all resource size. when set true, return loaded resource size.
Returns:
  Number - resource size.
```

--------------------------------

### getContent(specified:String)

Source: https://github.com/hiloteam/hilo/blob/dev/docs/api-en/symbols/LoadQueue.html

get resource object content by id or src

```APIDOC
Method: getContent
Signature: getContent(specified:String):Object
Description: get resource object content by id or src
Parameters:
  specified: String - id or src
Returns:
  Object - resource object content
```