Sunday, 22 May 2011

HTML5 Canvas template

I’ve been playing around with the HTML5 canvas element recently, and have been copying and pasting the same HTML tags every time I create a new document. So I have written this quick and dirty template to get me started faster. I have also included a 1 pixel border around the canvas, so the edges can be seen.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>HTML5 Canvas template</title>

 <style>
  canvas{ 
   border: 1px solid #999999;
  }
 </style>
 
 <script>
 
  function init(){
  
   var context= document.getElementById('canvas').getContext('2d');
  
  }
  
 </script>
 
</head>
<body onload="init()">
 
 <canvas id="canvas" width="800" height="600"></canvas> 

</body>
</html>

Friday, 20 May 2011

Playpause Button in Actionscript 3

I have provided code for a play/pause button that can be used for a video player or whatever you require this button for. I have created the play and pause shapes using the AS3 drawing API and have added a mouse click event which toggles between the play and pause states.

/**
 * PLAY/PAUSE BTN CLASS
 * CREATED BY ILIKE2FLASH.COM
 *
**/
package com.ilike2flash  {
 
 import flash.display.Shape;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 
 public class PlayPauseBtn extends Sprite {
  
  private var tri:Sprite;
  private var pau:Sprite;
  
  public function PlayPauseBtn() {
   
   buttonMode = true;
    
   var bg:Shape = new Shape();
   bg.graphics.beginFill(0x000000,0.8);
   bg.graphics.drawEllipse(0, 0, 82, 82);
   bg.graphics.endFill();
   addChild(bg);
   
   tri = new Sprite();
   tri.graphics.beginFill(0xffffff);
   tri.graphics.moveTo(0, 0);
   tri.graphics.lineTo(30, 18);
   tri.graphics.lineTo(0, 36);
   tri.graphics.endFill();
   tri.x = 32;
   tri.y = 23;
   addChild(tri);
   
   pau = new Sprite();
   pau.graphics.beginFill(0xffffff);
   pau.graphics.drawRect(0, 0, 11, 40);
   pau.graphics.drawRect(18, 0, 11, 40);
   pau.graphics.endFill();
   pau.x = 26;
   pau.y = 21;
   pau.visible = false;
   addChild(pau);
   
   addEventListener(MouseEvent.CLICK, clicked);
  }
  
  public function clicked(e:MouseEvent=null):void 
  {
   tri.visible = !tri.visible;
   pau.visible = !pau.visible;
  }
 }
}

To use the button, you create a new instance of the PlayPauseBtn class like below.

import com.ilike2flash.PlayPauseBtn;
var playpausebtn:PlayPauseBtn = new PlayPauseBtn();
addChild(playpausebtn);

Monday, 16 May 2011

News ticker in Actionscript 3

In this tutorial you will learn how to create a news ticker in Actionscript 3. The news ticker contains multiple rotating blocks that hold images and text. The text and images will be loaded using XML. You will need some images for this tutorial as well as the LoaderMax plugin which can be downloaded from greensock.com

News ticker in Actionscript 3

Step 1


Open up your favourite text editor and copy the following xml and save it with the file name Ticker.xml. You will need to save your images in a folder called ‘Images’.

<tickers>
<ticker img = "images/image1.jpg" text = "text1"  link ="http://www.link1.com" />
<ticker img = "images/image2.jpg" text = "text2"  link ="http://www.link2.com" />
<ticker img = "images/image3.jpg" text = "text3"  link ="http://www.link3.com" />
<ticker img = "images/image2.jpg" text = "text4"  link ="http://www.link4.com" />
</tickers>


Step 2

Open up a new AS3 flash file with the stage dimensions 200x200. Then save the file with the name ‘Ticker’ in the same directory as your xml file.


Step 3

Select the Rectangle tool and drag a rectangle shape on the stage with dimensions 200x40. Convert the rectangle shape into a movie clip (F8) and tick the Export to ‘Actionscript checkbox’ and give the class name: ‘TickerBox’.

Double click on the movie clip to go inside in and select the Text tool with dynamic text and drag a dynamic text field with the instance name: ‘output_txt’. You will need to embed the characters glyphs you intend to use. I have embedded the lowercase and numerical glyphs. Now place an empty movie clip at the top left of the rectangle with a 2 pixel offset with the instance name: ‘container’. Then return to the main timeline and delete the movie clip from the stage. The movie clip will be added dynamically, so will not be needed on the stage.


Step 4

Open up an AS3 class with name Ticker and add the following code.


package {
    import flash.display.MovieClip;
    import flash.events.*;
    import flash.net.*;
    import com.greensock.events.LoaderEvent;
    import com.greensock.loading.ImageLoader;

    public class Ticker extends MovieClip {

        private var speed:uint = 1;
        private var numOfBoxes:uint = 4;
        private var counter:uint = 0;
        
        private var xmlArray:Array      = new Array();
        private var tickerArray:Array   = new Array();

        public function Ticker() {
            //Creates a new instance of the URLoader and loads the Ticker xml.                                
            var uloader:URLLoader = new URLLoader();
            uloader.addEventListener(Event.COMPLETE, xmlLoaded);
            uloader.load(new URLRequest("Ticker.xml"));
        }

          
        private function xmlLoaded(e:Event):void {
                                  
            var xml:XML = new XML(e.target.data);
            //Parses the xml in the xmlArray and fires the init function.
            for (var i:uint = 0; i < numOfBoxes; i++) {
                 xmlArray.push({   image: xml.ticker.attribute("img")[i],
                                   txt:   xml.ticker.attribute("text")[i],
                                   url:   xml.ticker.attribute("link")[i]});                               
            }
            init();
        }
        
        
        private function init():void {
            //Creates four instances of the TickerBox with an vertical offset of 60 pixels.
            //Adds the click, roll over and roll out events to the TickerBox.
            //Sets the mouseChildren property to false, so anything inside the TickerBox can't be selected.
            //Adds the dynamic property index which is used to target the array index to get the url.
            for (var i:uint = 0; i < numOfBoxes; i++) {
                var t:TickerBox = new TickerBox();
                t.x=0;
                t.y = 0 + (i * 60);
                t.addEventListener(MouseEvent.CLICK, mouseHandler);
                t.addEventListener(MouseEvent.ROLL_OVER, mouseHandler);
                t.addEventListener(MouseEvent.ROLL_OUT, mouseHandler);
                t.mouseChildren=false;
                t.buttonMode=true;
                t.index=i;
                addChild(t);
                tickerArray.push(t);
                t.output_txt.text=xmlArray[i].txt;
            }
                stage.addEventListener(Event.ENTER_FRAME, enterHandler);
                                   
                loadImage();
          }


          private function loadImage():void {
              //Loads the images in there respective containers in order using the counter
              //and resizes the width and height of the images.
              var loader:ImageLoader = new ImageLoader(xmlArray[counter].image, {autoDispose:true,
                     container:tickerArray[counter].container,
                      width:45.25,
                      height:32.75,
                      onComplete:onImageLoad});
                                   
                      loader.load();
           }

                       
           private function onImageLoad(event:LoaderEvent):void {
                //This function will keep calling the loadImage() function until
                //all the images have been loaded.
                counter++;
                if (counter < numOfBoxes) loadImage();
            }

            private function mouseHandler(e:MouseEvent):void {
            //Removes and adds the event frame listener when you rollover and rollout.
            //Goes to the respective url when you click on a box.
                 switch (e.type) {
                     case "rollOver" : stage.removeEventListener(Event.ENTER_FRAME, enterHandler); break;
                     case "rollOut"  : stage.addEventListener(Event.ENTER_FRAME, enterHandler);     break;
                     case "click"    : navigateToURL( new URLRequest(xmlArray[e.currentTarget.index].url), "_blank"); break;
                 }
             }


            //Moves the the tickerBoxs vertically. If the boxes go over the stage height
            //then it will get re-added at the top of the stage with an offset of a
            //ticker box height.
            private function enterHandler(e:Event):void {
                for (var j:uint = 0; j < tickerArray.length; j++) {
                    tickerArray[j].y+=speed;
                    if (tickerArray[j].y>stage.stageHeight) {
                        tickerArray[j].y=0-tickerArray[j].height;
                    }
                }
           }
    }
}

Step 5

Export your movie Ctrl + Enter. Try moving your mouse over and out of the box and it should stop and start. And trying clicking on a box and it will take you to the respective url.



Any questions leave a comment below.

Thursday, 5 May 2011

Load multiple images in Actionscript 3

A common question people ask is how to load multiple external images in Actionscript 3. In AS3 you need to use the Loader and URLRequest classes to load external assets. Firstly, lets start by loading one single image. Loading one image only needs three lines of code.

//Creates a new instance of the Loader class.
//Add the URLRequest call to load the external image.
//And add the loader on the stage.
var loader:Loader = new Loader();
loader.load(new URLRequest('example.jpg'));
addChild(loader);


If you have a large image you may want to wait until the image has finished loading before adding it onto the stage. For this you need to add an 'on complete' event. To use events with the Loader class you need to use a property called 'contentLoaderInfo'.

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
loader.load(new URLRequest('example.jpg'));

function loaded(e:Event):void{
   addChild(e.target.content);
}


There are a couple different ways you can load multiple images. The first method loads the external images sequentially by calling the loadImage function every time an image has loaded. When all the image are loaded they get added to the stage.

var imagesArray:Array = new Array('image1.jpg', 'image2.jpg','image3.jpg','image4.jpg');
var loadedArray:Array = new Array();
var counter:int = 0;

function loadImage():void{
   var loader:Loader = new Loader();
   loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
   loader.load(new URLRequest(imagesArray[counter]));
}

function loaded(e:Event):void{

   loadedArray.push(e.target.content);

   if(counter == imagesArray.length-1){    
   
       for(var i:uint = 0; i < loadedArray.length; i++){
           loadedArray[i].x = 0 + i * 100;
           addChild(loadedArray[i]);
       }    
   }
   
   else{
       counter++;
       loadImage();
   }
}


loadImage();


Another method is to load all the image using a For loop. However, a drawback of this method is that the images don't load sequentially.

var imagesArray:Array = new Array('image1.jpg', 'image2.jpg','image3.jpg','image4.jpg');
var loadedArray:Array = new Array();

function loadImage():void{
   for(var i:uint = 0; i < imagesArray.length; i++){
       var loader:Loader = new Loader();
       loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
       loader.load(new URLRequest(imagesArray[i]));
   }
}

function loaded(e:Event):void{

   loadedArray.push(e.target.content);

   if(loadedArray.length == imagesArray.length){    
   
       for(var i:int = 0; i < loadedArray.length; i++){
           loadedArray[i].x = 0 + i * 100;
           addChild(loadedArray[i]);
       }    
   }
}


loadImage();

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP