The Nature of Code

December 7th, 2012 by Adrian

The Nature of Code

Daniel Shiffman‘s book ‘The Nature of Code‘ has finally been released. It is available for free online, or you can download an offline copy by donating your chosen amount to the author (and/or the Processing Foundation). The print version of the book is coming soon.

It is well written, very clear to follow, with small bitesize pieces of code that illustrate what is being discussed. This a fantastic resource and we should all be very grateful to Daniel for his generosity to the creative coding community.

You can read the book online here, and download the Processing code examples here.

Follow Daniel on Twitter.

Posted in Books, Processing, Sample Code | No Comments »

HTML, CSS & JS Online Code Editors/Playgrounds

October 10th, 2012 by Adrian

Over the last year or so there has been increase in the number of online HTML, CSS & JS editors. These are usually intended to demo small snippets of code that can be saved and shared. The feature sets of each service differ slightly, so you may need to try a few before you find the one that suits your specific requirements. Here are a few to get you started (with the most popular/fully-featured near the top). Many of these are based on CodeMirror or ACE.


jsFiddle – This is probably the most popular of these type of tools. It is pretty comprehensive and allows you to save and share your code. It includes HTML, CSS and JavaScript. You can choose from a wide range of pre-defined JavaScript frameworks, and you can also link to your own if it is not listed. It supports SCSS (Sass 3) and CoffeeScript if you are into those. You can choose from a variety of DTDs and modify the <body> tag (if needed). It has buttons for tidying up your code and JSLint support is included. The documentation is pretty comprehensive and the UI is nice and clean and easy to use. There is no code completion or code hinting as you type and your code doesn’t automatically run (you have to click the ‘Run’ button, or use the keyboard shortcut, to see your results). jsFiddle’s Twitter account is here.


JS Bin – This was created by Remy Sharp and is gaining in popularity. By default it has shortcuts to a huge list of JavaScript libraries, which you can include in your code. It supports many different flavours of HTML, CSS and JavaScript meta-languages (templating) like Markdown, Jade, LESS, Stylus, CoffeeScript, Processing, Traceur and TypeScript (Zen Coding is also supported). It has in in-built Console panel and the Output panel is automatically updated as you type. It automatically saves your code and there are a variety of sharing options. JavaScript error checking is provided via JSHint. A nice simple and clean tool, but again, no code completion or code hinting. A couple of great features it does have though is called Codecast (which enables people to watch as you type) and and Remote Rendering (which can be used to view your output on multiple devices in realtime). The documentation and help is pretty good too and the editor can be customised in great detail. Remy has done a fantastic job with this and he is always adding new and improved features. Follow JS Bin on Twitter.


Codepen – This tool was co-created by Mr CSS-Tricks (Chris Coyier) himself. It has a nice clean and well presented UI and the homepage is great for seeing other people’s demos (picked by the staff, or ranked as ‘popular’ or ‘recent’). The sharing and embedding options are good and forking other people’s projects is really easy (you can also see various Stats and Comments too). You can choose from a selection of colour schemes for the code editor (and select from three different fonts). Like jsFiddle and JS Bin, there is support for a variety of templating tools like HAML, Markdown, Slim, LESS, SCSS, SASS and CoffeeScript. It has built-in support for CSS Normalize, CSS Reset-prefix-free and Modernizr, and shortcuts to the latest versions of a few of the most popular JavaScript libraries. I think the strongest feature of this site is the way other people’s demos are showcased and easily accessible. This seems to be where all the cool kids hang out!


Dabblet – This tool was created by the very talented Lea Verou (who now works for the W3C), (check out her ‘Projects‘ page). This tool is focused on HTML and CSS (not JavaScript) and provides syntax highlighting and realtime updates. I particularly like the popup panels for CSS colors, gradients,  pixel dimensions, degrees and seconds. Plus the easy slider to increase the font size of the text in your code editor is handy. It has support for -prefix-free built in (it was created by Lea too) and is tightly integrated with github:gist. dabblet itself is open source and made available on github.


HTML5 Rocks Playground – This playground is really intended to show predefined examples of HTML5 code. You can’t use it to write your own snippets that can be saved and shared. But, for seeing how to do things (by the experts) in HTML, CSS, JavaScript this site is really great. Worth bookmarking.

jsdo.it

jsdo.it is a Japanese online playground that has some very talented individuals using it. It is the sister site to the Flash AS3 online playground wonderfl. It pushes other peoples creations to the homepage (which is good for inspiration) and allows you to fork their code and modify it as you like. There are categories too (such as Application, User Interface, CSS, Game etc) which is useful. You can ‘Fav’ other peoples creations and you can ‘Follow’ them too (like you can on Codepen).


Tinkerbin – This editor has the basic features (separate panels for HTML, CSS, JavaScript and Output, but not resizable by dragging) and support for HAML, SCSS, SASS, LESS and CoffeeScript. You can save your snippets (each save is assigned it’s own unique short URL which you can pass on to other people) but it is pretty limited and doesn’t have some of the advanced features that jsFiddle, JS Bin and Codepen have.


Fiddle Salad – With this editor, you choose your coding style up-front. You are presented with the options of HTML (or HAML, Zen Coding, Markdown, CoffeeCup, Jade), CSS (or LESS, SCSS, SASS, Stylus), JavaScript (or CoffeeScript, Python, Roy), and then you hit the ‘Go’ button to start. The interface looks pretty busy (and not as clean as some of the other tolls listed above), but it does include a handy ‘Documentation’ panel which provides you with links to W3C’s CSS and HTML documentation, as well as jQuery (and the templating engines mentioned). Also, all the UI panels can be moved and resized which is pretty handy. Once you dig a little deeper you’ll realise that a lot of time and effort has gone into making this quite a fully featured tool. It has several different frameworks and libraries for you to choose from and select for import. It also has a number of ‘Tools’ such as validation and beautify tools (though some of these are just links to external websites). One thing that this has that some of the other tools don’t is code completion and code hinting (very useful in CSS). Overall I think this tool shows promise, but at the time of writing it doesn’t quite have the polish of jsFiddleJS Bin or Codepen.


ztxt – This is open source and available on github (thanks to Zevan Rosser). There is not a hosted version of this, the intention is that you download a copy of ztxt and then either run it locally using MAMP (or WAMP), or you host it on your own live webserver. I like the way that it can be used locally and allows access to your local filesystem. More information on ztxt can be seen on YouTube here.


Tinker – This is fairly bare-bones, but it does have a clean UI (with draggable editing areas) and offers syntax highlighting and saving (to a unique short URL). Clutter-free and to the point. It is open source and available to download from github (thanks to Chiel Kunkels).


CSS Desk – Created by Josh Pyles, this editor is for HTML and CSS only (no separate JavaScript). It has syntax highlighting, line numbers and realtime output. I like the fact that it allows you to easily save your edit out as a downloadable HTML file. You can save your snippet to a unique short URL for sharing. Minimal, but functional for CSS demos.


Liveweave – Created by Amit Sen, this tool requires you to have all your CSS and JavaScript in the HTML page (there is not separate panels like the other editors). It allows you to save your page as a downloadable HTML file which is handy. But for me, the killer feature (which most of the other editors don’t have) is auto-completion and code completion, a very useful addition (who can possibly remember all those CSS attributes and values?)


Cssizer – This tool (built by David Morrow) is also designed for HTML and CSS (not JavaScript) and has a limited feature set. However it does have syntax highlighting, realtime preview, and saving of snippets to a unique short URL (which get saved for you if you login using Twitter). You can also validate your code with an automated link to W3C. It is also open source and available to download from github.


pastebin.me – Created by Dale Harvey as a personal project, this tool is pretty bare-bones. A single editing panel with a non-realtime output panel. No syntax highlighting or features that the other editor have. It is available to download from github.


Html5Snippet – This is quite a slick editor with a number of saving and sharing features. I like the way you can download your code as separate files (.html .css .js) in a ZIP file. The editor also includes a huge list of predefined JavaScript frameworks and libraries. You can follow Html5Snippet on Twitter here.


Google Code Playground – This is similar to the HTML5 Rocks Playground, in that it is intended to demonstrate pre-written chunks of code (not as an editor for you to create your own and save) that you can tweak to see the results. The great thing about this is that it is chock-full of fantastic examples of accessing Google APIs, ranging from Google Translate and Google Calendar, through to Google Search, Maps and YouTube. If you are planning on using a Google API, it is worth checking here first to see if there is an example that will help. The link to the documentation is context sensitive, depending on what type of example you are viewing at the time.


TheCodePlayer – At the time of writing this site doesn’t allow you to create your own snippets and save them. But it does allow to play back the creation of their example HTML, CSS and JavaScript examples, which is very nice. It looks like in the future they are planning on opening the editor up for public use, to allow you to contribute your examples. I’d say ‘Keep an eye on this one’. Follow their Twitter stream here.

That pretty much wraps it up for now. I’m sure there are a bunch of other ones I’ve missed off this list (eg. Plunker), let me know in the comments if there is one I should take a look at. Enjoy!

Posted in CSS, HTML, HTML5, Javascript, Sample Code, Tool | 1 Comment »

Accessing Google’s URL Shortening API from Flash (AS3)

January 17th, 2011 by Adrian

Google URL Shortener

Last Wednesday (12th Jan 2011) Google released an API for accessing their goo.gl URL shortening service, which is great for web developers. However, for us Flash developers things aren’t quite so simple as it is for everyone else. This is due to the security restrictions imposed when accessing the goo.gl domain. There is a crossdomain policy file at the root of their server (http://goo.gl/crossdomain.xml) but it is very restrictive and of no use to us, causing security errors inside your Flash movie once it has been deployed online.

Goo.gl cross domain policy file

So I have written an ActionScript class and PHP script which makes the whole process easier for everybody. Here is a demo of it in action …

The source files and this Flash CS5 demo can be downloaded from GitHub.
https://github.com/adrianparr/as3googleurlshortener

The PHP file acts as a proxy so we circumvent the security restrictions. The code also makes use of as3corelib for the JSON decoding.

Many thanks to Vijay Joshi for his example of using cURL to send the JSON data from PHP to the Google web service.

Posted in ActionScript 3.0, Google, Sample Code | 3 Comments »

AS3 Encoder/Decoder for Special Characters

January 7th, 2011 by Adrian

Here is a little tool that I have made which can be used to encode and decode strings into URL escape sequences (eg. convert special characters so they are safe to transmit in a query string). I recently also had the need to encode and decode HTML named entity references (eg. ” becomes &rdquo;) and after a long hunt around the web I couldn’t find one in AS3. So I have also written a static class called HTMLEntities which has the public methods ‘encode’ and ‘decode’. Hopefully you will find it useful. All the source code is available below.

Download a ZIP of the source code here

NOTE: If you use the HTMLEntities class, you may want to remove the entry for the apostrophe (‘) which encodes it as &apos; because it is not supported by Internet Explorer. Apostrophes are better off being encoded as &#39;

Here are some useful lists of the HTML Named Entities …

And these are handy conversion tools …

Posted in ActionScript 3.0, Sample Code | 5 Comments »

Test for Capabilities.screenDPI

January 6th, 2011 by Adrian

With all the interest in mobile development there come the issue of dynamically resizing UI elements based on the pixel density of the screen. For example, if a button is set to be 100 pixels wide, it will appear at different physical widths depending on the device being used. This is because your desktop monitor may have a pixel density (DPI or PPI) of 86dpi but you mobile phone may have a pixel density of 326dpi (as is the case with the retina display on the iPhone 4). This may meant that you nicely designed UI is unusable, with items being too small to click on with your finger!

An article regarding this was posted back in Jan 2010 on the Adobe Developer Connection by Christian Cantrell titled ‘Authoring mobile Flash content for multiple screen sizes‘, and more recently (Nov 2010) a whitepaper by Allen Ellison titled ‘Flash sizing Zen: Making Flash fit on mobile devices‘.

In Christian’s article he mentions using the AS3 Capabilities class and the method screenDPI, however as Renaun Erickson pointed out yesterday there is a problem with the returned value from this method when using AIR on devices.

Here is a little test SWF which shows you what Flash thinks your system is displaying (correctly or incorrectly).

Download a ZIP of the FLA source file here

An image of the various sample sizes can be viewed here

Confirming that 86 pixels equals 1 inch on my 19" (1280x1024) monitor

Here are some useful links regarding pixel density, DPI and PPI …

Posted in ActionScript 3.0, AIR, Android, Bug, Flash, iPhone, Mobile, Sample Code | 2 Comments »

QR Code Generator

December 16th, 2010 by Adrian

Over the last couple of days I’ve been messing around with QR Codes and the Google Chart API. Basically I wanted to create a QR code in Flash using Google Charts to do the hard work. However, once I had it sending the data and loading the PNG back in locally, I soon discovered that Google Charts doesn’t have a crossdomain policy file (http://code.google.com/crossdomain.xml). This basically meant I couldn’t access the ‘content’ of the Loader object and I couldn’t access the BitmapData of the loaded PNG.

I then remembered reading about using a server-side script to act as a proxy, which would circumvent the security restrictions within Flash. After a lot of digging around on the web I came across a great article on Activetuts+ which had sample PHP code I could use. Success! It was now working online without any security sandbox violations.

Now I had access to the BitmapData of the loaded PNG I could make use of corelib to allow the user to save the resulting image as a PNG or JPEG to their computer. After that I added the ability to print the QR Code on to an A4 sheet directly from Flash. And finally I thought I’d have a go at using AlivePDF to create a PDF file on-the-fly which the user can save to their computer using FileReference (Flash Player 10 and above). I found this blog post by Alex Britez useful when generating the PDF using AlivePDF.

So here is the final SWF and a ZIP file containing all the (FlashDevelop) source is below.

You can view the SWF in it’s own page here.

Download the zipped source here

You can view the Main document class on Snipplr here.

Maybe now I should look at reading a QR Code using AS3.

Posted in ActionScript 3.0, Flash, Sample Code | 7 Comments »

Snipplr

November 25th, 2010 by Adrian

Snipplr

Over the last 12 months I’ve been using Snipplr to save code snippets online. It’s a great service for storing, sharing and accessing those bits of code that come in handy. You can also search for other peoples code and mark them as ‘favourites’ and follow people etc.

My snippets can be seen here.

My only criticism would be regarding the search results and the use of ‘tags’. You are able to ‘tag’ your snippets with keywords, but these don’t seem to be taken into account when doing a search. So this limits the results a bit.

Earlier in the year Snipplr was acquired by Envato (Owners of activedentuts+ and many more), which may mean some improvements are on the way.

Posted in ActionScript 3.0, Sample Code | 3 Comments »

Rotating Spiral

November 25th, 2010 by Adrian

Spiral Screenshot

After recently seeing Chris Johnson’s Rotating Spiral Chrome Experiment using JavaScript and SVG (and very good it is too), I decided to create something similar in Flash. Now, let me first start off by saying that Chris’s spiral is a lot cleverer than mine because his is created programmatically, whereas mine is just a vector created in Adobe Illustrator and controlled using AS3 in Flash.

My Flash version can be see here.

Note, I did not create this to be some kind of benchmark testing tool between Flash and SVG rendering speeds. Please don’t post loads of comments telling me that one is better/faster than the other etc.

I’ve added some stats output just to see how it performs on different machines and for my own use. I’ve also added some controls, such as framerate, rotation speed, shade, quality, direction, colours and full screen mode. There are also some keyboard controls …

SPACE = Hide/show control bar and stats
S = Hide/show shade
Q = Toggle quality
D = Toggle direction

Thanks to Keith Peters for his Minimal Comps, MrDoob for his Stats Performance Monitor and Jack Doyle for TweenLite.

You can download my FlashDevelop Project (source code) from here.

If I get time I may update this to draw the spiral programmatically using pure AS3.
Here are some resources on creating spiral effects using AS3 …

Posted in Flash, Sample Code | 2 Comments »

Setting the Tab Order of TLFTextFields

July 7th, 2010 by Adrian

I have just spent ages trying to set the tabIndex order of a bunch of TLFTextFields in Flash CS5. With the old Classic TextFields you would have done something along the lines of …

holder_mc.tf1.tabIndex = 1;
holder_mc.tf2.tabIndex = 2;
holder_mc.tf3.tabIndex = 3;
holder_mc.tf4.tabIndex = 4;
holder_mc.tf5.tabIndex = 5;

But with the new TLFTextFields this doesn’t work. You can’t just set the tabIndex property of the TLFTextField directly. When you do, it just doesn’t work.

Then I stumbled across this little bit of info in the docs

tabIndex Documentation

So, for my simple example above to work with TLFTextFields instead of Classic TextFields I ended up writing …

InteractiveObject(holder_mc.tlf1.getChildAt(1)).tabIndex = 1;
InteractiveObject(holder_mc.tlf2.getChildAt(1)).tabIndex = 2;
InteractiveObject(holder_mc.tlf3.getChildAt(1)).tabIndex = 3;
InteractiveObject(holder_mc.tlf4.getChildAt(1)).tabIndex = 4;
InteractiveObject(holder_mc.tlf5.getChildAt(1)).tabIndex = 5;

I hope this helps and that you get it to work quicker than I did!

NOTE 1: I’ve noticed that when the user tabs to a Classic TextField the text is selected, but when you tab to a TLFTextField the caret is positioned at the beginning and no text is automatically selected.

NOTE 2: I’ve also noticed that the selection colour for a Classic TextField is black, but the selection colour for a TLFTextField is light blue. This can look a bit strange when you have a mixture textfields on screen near each other.

Posted in ActionScript 3.0, Sample Code | 1 Comment »

stop(); Action Ignored on Nested Movieclip

December 24th, 2009 by Adrian

Recently I stumbled across this post by Ryan Creighton at Untold Entertainment from back in October 2008 titled ‘stop(); Action Ignored on Nested Movieclip‘. It basically demonstrates how (in AS3) a child movieclip does not stop on the first frame (even though you have put a stop(); action on it) when it’s parent/container is dynamically attached to the stage.

To me this does seem like a bug. Unless I am missing some subtle difference in this area between AS2 and AS3 that I am missing. If so, please can someone explain it to me?

I’ve knocked up a couple of examples to demonstrate …

Firstly, here is the AS2 version that attaches the container movieclip to the stage using the old attachMovie method. Sure enough, the child movieclip does as it is told and stays on frame 1.

And here is the AS3 version that instantiates the Contaner class and adds it to the display list using addChild. As you can see the child movieclip ignores the stop() command on frame 1 and goes to frame 2 instead. Why?

You can download a ZIP file containing the source files for these two examples here.

More discussion about this issue can be found on actionscript.org, but no-one really explains why this is happening. Any ideas?

Posted in ActionScript 3.0, Bug, Sample Code | 3 Comments »

Printing a PDF document from AIR without displaying it or the control bar (using PDF cross-scripting)

October 6th, 2009 by Adrian

Recently I had a project where I needed to allow the user to print out a PDF document from my AIR application, but I really didn’t need the user to actually view the document first and I didn’t want to display the default PDF control bar. I needed some way to send the PDF file to the printer directly from ActionScript. Enter PDF cross-scripting and Acrobat JavaScript. The following information should help you achieve the same result (note you need to have access to a copy of Adobe Acrobat Pro to add the JavaScript code to your PDF file).

There are several steps required for this to work …

  1. Open the PDF document you want to print in Adobe Acrobat Pro.
  2. Add the JavaScript code to your document and save it.
  3. Create an HTML page that contains a JavaScript function and embed the PDF document.
  4. In your Flash (or Flex) file add a button that prompts the user to print the document.
  5. Add the ActionScript 3.0 code that communicates with the HTML page you created in step 3.
  6. Publish your AIR file (making sure you include the HTML and PDF files).
  7. Test your AIR app.

Here is a copy of the PDF file I am printing in the following example.

Right, let’s explain each of the above steps in more detail.

Step 1

I presume you already have a PDF file prepared which you wish to print. Open this file up in Adobe Acrobat Pro. I’m pretty sure this works in version 7.0 and onwards.

Step 2

Open the ‘JavaScript Functions’ dialog box in Adobe Acrobat Pro by going to ‘Advanced’ > ‘Document Processing’ > ‘Document JavaScripts’.

Acrobat Document JavaScript Menu

Enter ‘myOnMessage’ in to the textfield and click on the ‘Add…’ button.

Acrobat JavaScript Functions

Then enter the following JavaScript code in to the window and click on the ‘OK’ button.

JavaScript Editor

function myOnMessage(aMessage)
{
      if (aMessage.length==1) {
            switch(aMessage[0])
            {
                  case "Print":
                        //app.alert("Trying to print PDF");
                        print({
                              bUI: true,
                              bSilent: false,
                              bShrinkToFit: true
                        });
                        break;
                  default:
                        app.alert("Unknown message: " + aMessage[0]);
             }
      }
      else
      {
            app.alert("Message from hostContainer: \n" + aMessage);
      }
}

var msgHandlerObject = new Object();
msgHandlerObject.onMessage = myOnMessage;
msgHandlerObject.onError = myOnError;
msgHandlerObject.onDisclose = myOnDisclose;

function myOnDisclose(cURL,cDocumentURL)
{
      return true;
}

function myOnError(error, aMessage)
{
      app.alert(error);
}

this.hostContainer.messageHandler = msgHandlerObject;

Then remember to re-save your PDF file.

Step 3

Create a blank HTML file and save it next to the PDF file. Then add the following code …

<html>
    <head>
    <title>Load PDF</title>
    <script>
        function callPdfFunctionFromJavascript(arg)
        {
            pdfObject = document.getElementById("PDFObj");
            try {
                 pdfObject.postMessage([arg]);
            }
            catch (e)
            {
                alert( "Error: \n name = " + e.name + "\n message = " + e.message );
            }
        }
    </script>
    </head>
    <body>
        <object id="PDFObj" data="document.pdf" type="application/pdf" width="800" height="600"/>
    </body>
</html>

Step 4

For this example I’m using Flash CS3. Create a movieclip on stage that acts as a button prompting the user to print the PDF document. Give the button instance the name of ‘button’.

Step 5

In this example I have put all the ActionScript code into the document class. The code looks like this …

package
{
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.events.Event;
    import flash.html.HTMLLoader;
    import flash.html.HTMLPDFCapability;
    import flash.net.URLRequest;

    public class PrintPdfFromAir extends MovieClip
    {
       
        private var _htmlLoader:HTMLLoader;

        public function PrintPdfFromAir():void
        {
            button.mouseEnabled = false;
            button.alpha = 0.3;
            button.buttonMode = true;
            button.addEventListener(MouseEvent.CLICK, onButtonClick);
           
            trace("HTMLLoader.pdfCapability: "+HTMLLoader.pdfCapability);
           
            if (HTMLLoader.pdfCapability == HTMLPDFCapability.STATUS_OK) {
                _htmlLoader = new HTMLLoader();
                _htmlLoader.addEventListener(Event.COMPLETE, onHtmlLoader_COMPLETE);
                var urlRequest:URLRequest = new URLRequest("load_pdf.html");
                _htmlLoader.load(urlRequest);
                addChild(_htmlLoader);
            }
        }
       
        private function onHtmlLoader_COMPLETE(event:Event):void
        {
            button.alpha = 1;
            button.mouseEnabled = true;
        }
       
        private function onButtonClick(event:MouseEvent):void
        {
            _htmlLoader.window.callPdfFunctionFromJavascript('Print');
        }

    }

}

Basically, we disable to button straight away and add a CLICK event listener. We then check the ‘HTMLLoader.pdfCapability’ property to see if the user has Adobe Reader 8.1 or greater installed on their system. If it equals ‘HTMLPDFCapability.STATUS_OK’ then we can continue. We then create a new instance of the HTMLLoader class, add a listener for the COMPLETE event. We then create an instance of the URLRequest class passing it the name of the HTML file we created in step 3. Next we call the ‘load’ method on our _htmlLoader instance, passing it the urlRequest instance. Then we add the _htmlLoader instance to the stage using addChild.

Normally, when you want to actually display the PDF file on screen, you also need to specify the width and height of the HTMLLoader instance. But in our case we don’t want to actually display it to the user. You may be wondering why we add it to the display list using addChild if we don’t want it to be visible. But I have found that it doesn’t work if you don’t add it to the display list. Not specifying the width and height also means it is not visible (which is what we want on this occasion).

Now we just have the two event handlers to write. The event handler for the HTMLLoader COMPLETE event just makes the button on screen active. We didn’t want the user to be able to click it before the COMPLETE event was fired.

The event handler for the button CLICK event calls the JavaScript function inside the HTML page, which we wrote in step 3.

Step 6

Now you are ready to publish the SWF file and then package it up as an AIR app in the usual way. The important thing to remember is to include the two external files (HTML and PDF) in the AIR Settings dialog box.

Include files

You can create a self-signed certificate for the purposes of testing. I have included my self-signed certificate with the source files (the password is ’1234′) which you can use if you wish, or you could just create a new one.

Step 7

Once you have exported your AIR file it is a good idea to test it on a few different computers to make sure it works properly. Try it on a machine that doesn’t have Adobe Reader installed, or one that has an older version (< 8.1).

Download example AIR app

Download the example AIR file

Click here to download the example AIR file

Download source files

Download ZIP file containing source files

You can download a ZIP file containing my example source files from here.

Useful links

Here are some other blog posts and articles I found useful …

Posted in ActionScript 3.0, AIR, Sample Code | 10 Comments »

Streaming Video using FMS Gotchya’s

September 17th, 2009 by Adrian

I have just come across a few issues whilst building a video player that plays streaming video from a Flash Media Server.

I thought I had everything set up fine but then when I tested I got the following error message …

ReferenceError: Error #1069: Property onBWDone not found on flash.net.NetConnection and there is no default value.

So to resolve this you need to set the client property of the netConnection instance to the object on which callback methods should be invoked. For example …

netConnection.client = this;

and then you need to have an empty public method called onBWDone, like this …

public function onBWDone(...args):void
{
    trace("onBWDone: "+args);
}

Sometimes you may get the following error message …

ReferenceError: Error #1069: Property onFCSubscribe not found on XXX and there is no default value.

In which case you’ll need to add …

public function onFCSubscribe(info:Object):void
{
    trace("onFCSubscribe");
}

The same goes for this error message …

ReferenceError: Error #1069: Property close not found on XXX and there is no default value.

In which case you’ll need to add …

public function close(...args):void
{
    trace("close: "+args);
}

I then discovered that the netConnection with the server was being closed after 5 minutes of inactivity (e.g. pause the video and leave it for 5 minutes). What you need to do in this case is listen for the ‘NetConnection.Connect.IdleTimeOut’ NetStatusEvent, and gracefully close the netStream yourself. For example …

import flash.events.NetStatusEvent;
netConnection.addEventListener(NetStatusEvent.NET_STATUS, onNetConnection_NET_STATUS);

private function onNetConnection_NET_STATUS(event:NetStatusEvent):void
{
    switch (event.info.code) {
        case "NetConnection.Connect.IdleTimeOut":
        netStream.close();
        netStream = null;
        // Display a still image or message to the user ro something
        break;
    }
}

Posted in ActionScript 3.0, Sample Code, Video | 1 Comment »

Make your cursor always point to the middle of the screen

August 14th, 2009 by Adrian

Yesterday I was taking a look at Balsamiq Mockups and liked the way that the mouse always pointed to the centre of the screen when in fullscreen mode. So I thought I’d quickly knock something to together that did this, and share it here.

It’s pretty simple stuff, but handy to have available to copy-and-paste, if you need something similar.

The code is all in the document class …

package
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.ui.Mouse;

    public class Main extends MovieClip
    {
       
        private var mouseIsOverStage:Boolean;
        private var arrow:Arrow;

        public function Main():void
        {
            arrow = new Arrow();
            Mouse.hide();
            stage.addEventListener(Event.MOUSE_LEAVE, onStage_MOUSE_LEAVE);
            stage.addEventListener(MouseEvent.MOUSE_MOVE, onStage_MOUSE_MOVE);
        }
       
        private function onStage_MOUSE_LEAVE(event:Event):void
        {
            mouseIsOverStage = false;
            removeChild(arrow);
        }
       
        private function onStage_MOUSE_MOVE(event:MouseEvent):void
        {
            if (!mouseIsOverStage) {
                mouseIsOverStage = true;
                onStage_MOUSE_ENTER();
            }
            arrow.x = stage.mouseX;
            arrow.y = stage.mouseY;
            var dx:Number = arrow.x - stage.stageWidth/2;
            var dy:Number = arrow.y - stage.stageHeight/2;
            var radians:Number = Math.atan2(dy, dx);
            arrow.rotation = radians * 180/Math.PI;
            event.updateAfterEvent();
        }
       
        private function onStage_MOUSE_ENTER():void
        {
            arrow.x = stage.mouseX;
            arrow.y = stage.mouseY;
            addChild(arrow);
        }
       
    }

}

Download the source files here

Posted in ActionScript 3.0, Sample Code | No Comments »

Drawing circles based on mouse position

May 20th, 2009 by Adrian

This morning I had a need to draw some circles on the stage by clicking-and-dragging, this led me to building a little visual display for lines, mid-points, rects, ellipses, angles, and circles (from centre and from corner).

It is all pretty simple stuff, but I thought I’d post it in case anyone else finds it useful.

You can download a ZIP file of the source code from here.

Posted in ActionScript 3.0, Flash, Sample Code | 4 Comments »

SWFAddress 2.1 + SWFObject 2.1 + Flash CS3 (AS3) Example

August 21st, 2008 by Adrian

SWFAddressSWFObjectFlash CS3

I was looking around for a simple example of using SWFAddress 2.1 with SWFObject 2.1 and Flash CS3 (ActionScript 3.0) and came across this blog post by Rachel. She has kindly put a simple demo online and made the source code available.

There are a few things that I have updated and am making available here (at the bottom of this post) …

  • Updated SWFAddress from v2.0 to v2.1
  • Updated SWFObject from v1.5 to v2.1
  • Reorganised the folder structure (see below)Folder structure

Download the updated source files here …

SWFAddress2.1_SWFObject2.1_AS3.zip (583 KB)

UPDATE 20/04/09: Lee Brimlow has a good tutorial on using SWFAddress 2.2 on his gotoandlearn() website. I suggest you check it out.

Posted in ActionScript 3.0, Sample Code | 15 Comments »

Custom Context Menu in AS3

April 15th, 2008 by Adrian

I’ve just been having a play with creating a custom context menu in Flash using AS3. Here is the movie …

And here is the ActionScript …

package {
    import flash.display.Sprite;
    import flash.ui.ContextMenu;
    import flash.ui.ContextMenuItem;
    import flash.events.ContextMenuEvent;
    import flash.net.navigateToURL;
    import flash.net.URLRequest;

    public class Main extends Sprite
    {
        private var menuItemLabel:String = "© Adrian Parr";
        private var url:String = "http://www.adrianparr.com";
        private var cm:ContextMenu;

        public function Main()
        {
            cm = new ContextMenu();
            cm.hideBuiltInItems();
            var cmi:ContextMenuItem = new ContextMenuItem(menuItemLabel);
            cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemSelected);
            cm.customItems.push(cmi);
            this.contextMenu = cm;
        }
       
        private function menuItemSelected(evt:ContextMenuEvent):void
        {
            var req:URLRequest = new URLRequest(url);
            navigateToURL(req, '_blank');
        }
    }
}

You can download the Flash source files here.

Posted in ActionScript 3.0, Flash, Sample Code | 23 Comments »

Colour Line Drawing – Part 2

April 2nd, 2008 by Adrian

Following on from yesterday’s post, I’ve had chance to update the Colour Line Drawing demo to include gradual colour changing (instead of random) and fixed the saving of the image to a jpeg file.

The saving of the image is done using the as3corelib library (thanks to Henry Jones for providing an example of this). Thanks also to Ryan Taylor for his color spectrum blog post.

Colour Line Drawing Screengrab

Click here to launch the demo.

You can download the source files here.

Here is the code in the Main document class …

package {
    import flash.display.MovieClip;
    import flash.display.Graphics;
    import flash.display.Stage;
    import flash.display.BitmapData;
   
    import flash.events.MouseEvent;
    import flash.events.KeyboardEvent;
   
    import flash.ui.Mouse;
    import flash.ui.Keyboard;
   
    import flash.utils.ByteArray;
   
    import flash.net.navigateToURL;
    import flash.net.URLRequestHeader;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.net.URLRequestMethod;
   
    import com.adobe.images.JPGEncoder;

    public class Main extends MovieClip
    {
        private var canvas:MovieClip;
        private var serverPath:String = "";
        private var colourIncrement:int = 0;
       
        public function Main():void
        {
            Mouse.hide();
            stage.showDefaultContextMenu = false;
            stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
           
            canvas = new MovieClip();
            canvas.graphics.beginFill(0x000000);
            canvas.graphics.drawRect(0, 0, 500, 375);
            canvas.graphics.endFill();
            canvas.graphics.moveTo(mouseX, mouseY);
            canvas.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoved);
            canvas.addEventListener(MouseEvent.CLICK, clearScreen);
            addChild(canvas);
        }
       
        private function mouseMoved(evt:MouseEvent):void
        {
            var nColorPercent:Number = colourIncrement / 200;
            colourIncrement += 1;
            var nRadians:Number = (-360 * nColorPercent) * (Math.PI / 180);
            var nRed:Number = Math.cos(nRadians) * 127 + 128 < < 16;
            var nGreen:Number = Math.cos(nRadians + 2 * Math.PI / 3) * 127 + 128 << 8;
            var nBlue:Number = Math.cos(nRadians + 4 * Math.PI / 3) * 127 + 128;
            var nColour:Number = nRed | nGreen | nBlue;

            canvas.graphics.lineStyle(60, nColour, 1);
            canvas.graphics.lineTo(mouseX, mouseY);
            evt.updateAfterEvent();
        }
       
        private function clearScreen(evt:MouseEvent):void
        {
            canvas.graphics.clear();
            canvas.graphics.beginFill(0x000000);
            canvas.graphics.drawRect(0, 0, 500, 375);
            canvas.graphics.endFill();
            canvas.graphics.moveTo(mouseX, mouseY);
        }
       
       
        private function reportKeyDown(evt:KeyboardEvent):void
        {
            if (evt.keyCode == Keyboard.SPACE) {
                createJPG(canvas, 90, "colour_line_drawing");
            } else if (evt.keyCode == Keyboard.ESCAPE) {
                if (stage.displayState == "normal") {
                    stage.displayState = "fullScreen";
                }
            }
        }
       
        function createJPG(m:MovieClip, q:Number, fileName:String)
        {
            var jpgSource:BitmapData = new BitmapData (m.width, m.height);
            jpgSource.draw(m);
            var jpgEncoder:JPGEncoder = new JPGEncoder(q);
            var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
           
            var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
                       
            var jpgURLRequest:URLRequest = new URLRequest ( serverPath+"jpg_encoder_download.php?name=" + fileName + ".jpg");      
            jpgURLRequest.requestHeaders.push(header);             
            jpgURLRequest.method = URLRequestMethod.POST;              
            jpgURLRequest.data = jpgStream;
           
            var jpgURLLoader:URLLoader = new URLLoader();      
            navigateToURL(jpgURLRequest, "_blank");
        }
       
    }
}

Posted in ActionScript 3.0, Flash, Sample Code | 4 Comments »

Setting the framerate dynamically using AS3

April 2nd, 2008 by Adrian

Here is a little example to show you how to dynamically set the framerate of your Flash movie using AS3. In this example I have also included a slider component to allow you to change the framerate, to prove that it is doing it on-the-fly.

You can download the source files here.

Here is the AS3 code in the Main document class …

package
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import fl.events.SliderEvent;

    public class Main extends MovieClip
    {

        private var myBall:MovieClip;
        private var sliderValue:Number = 1;
       
        public function Main():void
        {
            stage.frameRate = sliderValue;
           
            myBall = new Ball();
            myBall.x = 0 - myBall.width/2;
            myBall.y = stage.stageHeight/2;
            addChild(myBall);
           
            sliderLabel.text = sliderValue+" fps";
           
            myBall.addEventListener(Event.ENTER_FRAME, frameLoop);
            slider.addEventListener(SliderEvent.THUMB_DRAG, sliderDrag);
        }
       
        private function frameLoop(evt:Event):void {
            myBall.x += 10;
            if (myBall.x > stage.stageWidth + myBall.width) {
                myBall.x = 0 - myBall.width/2;
            }
        }

        private function sliderDrag(e:SliderEvent):void {
            sliderValue = e.target.value;
            stage.frameRate = sliderValue;
            sliderLabel.text = sliderValue+" fps";
        }
       
    }
}

Posted in ActionScript 3.0, Flash, Sample Code | 4 Comments »

Attach MovieClip from library using AS3

April 2nd, 2008 by Adrian

Here is a quick example of how to attach a MovieClip library item to the stage using AS3. In this example the linkage name has been set to ‘LibraryItem’.

Here is the code for the Main document class …

package
{
    import flash.display.MovieClip;

    public class Main extends MovieClip
    {
       
        private var myMovieClip:MovieClip;
       
        public function Main():void
        {
            myMovieClip = new LibraryItem();
            myMovieClip.x = stage.stageWidth/2;
            myMovieClip.y = stage.stageHeight/2;
            addChild(myMovieClip);
        }

    }

}

You can download the source files here.

Posted in ActionScript 3.0, Flash, Sample Code | 1 Comment »

Colour Line Drawing

April 1st, 2008 by Adrian

This afternoon my 22 month-old daughter came up to me while I was on the computer, and wanted to play with the mouse. So rather than have her delete all my work I quickly put together a little simple colourful drawing app which she could play with. It was also a good exercise for me to learn some more AS3.

Move the mouse to draw. Click to go fullscreen. Press spacebar to save image out as a JPEG (not working at present).

Here is a screengrab …

Click here to launch the app.

Here are the source files.

Main document class code here …

package {
    import flash.display.Sprite;
    import flash.display.Graphics;
    import flash.display.Stage;
    import flash.display.BitmapData;
   
    import flash.events.MouseEvent;
    import flash.events.KeyboardEvent;
   
    import flash.ui.Mouse;
    import flash.ui.Keyboard;
   
    import flash.utils.ByteArray;
   
    import flash.net.navigateToURL;
    import flash.net.URLRequestHeader;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.net.URLRequestMethod;
   
    import com.adobe.images.JPGEncoder;

    public class Main extends Sprite
    {
        private var canvas:Sprite;
        private var serverPath:String = "";
       
        public function Main():void
        {
            Mouse.hide();
            stage.showDefaultContextMenu = false;
            stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
           
            canvas = new Sprite();
            canvas.graphics.beginFill(0x000000);
            canvas.graphics.drawRect(0, 0, 500, 375);
            canvas.graphics.endFill();
            canvas.graphics.moveTo(mouseX, mouseY);
            canvas.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoved);
            canvas.addEventListener(MouseEvent.CLICK, mouseClicked);
            addChild(canvas);
        }
       
        private function mouseMoved(evt:MouseEvent):void{  
            canvas.graphics.lineStyle(40, (Math.random()*0xFFFFFF), 1);
            canvas.graphics.lineTo(mouseX, mouseY);
            evt.updateAfterEvent();
        }
       
        private function mouseClicked(evt:MouseEvent):void {
            if (stage.displayState == "normal") {
                stage.displayState = "fullScreen";
            }
        }
       
        private function reportKeyDown(evt:KeyboardEvent):void {
            if (evt.keyCode == Keyboard.SPACE) {
                createJPG(canvas, 90, "sketch");
            }
        }
       
        function createJPG(m:Sprite, q:Number, fileName:String) {
            var jpgSource:BitmapData = new BitmapData (m.width, m.height);
            jpgSource.draw(m);
            var jpgEncoder:JPGEncoder = new JPGEncoder(q);
            var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
           
            var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
                       
            var jpgURLRequest:URLRequest = new URLRequest ( serverPath+"jpg_encoder_download.php?name=" + fileName + ".jpg");      
            jpgURLRequest.requestHeaders.push(header);      
            jpgURLRequest.method = URLRequestMethod.POST;            
            jpgURLRequest.data = jpgStream;
           
            var jpgURLLoader:URLLoader = new URLLoader();      
            navigateToURL(jpgURLRequest, "_blank");
        }
       
    }
}

Posted in ActionScript 3.0, Flash, Sample Code | No Comments »

« Previous Entries