Processing.js Experiment

Over the last few weeks when I wasn’t working or fighting hackers on my blog (If You follow me on Twitter you know what I mean), I had the chance to give Processing.js a try.

Over the last few weeks when I wasn’t working or fighting hackers on my blog (If You follow me on Twitter you know what I mean), I had the chance to give Processing.js a try, Processingjs is a port of the Processing programming language,and it lets You program images, interactions and animations for the web without using Flash or Java applets, it uses JavaScript to draw shapes and manipulate images on the HTML5 canvas element (You’ll need a browser that supports it …cough..IE…cough…ISSUE 15), so if you like building data visualizations, creating user-interfaces and developing web-based games Processing.js might be your thing.
So I decided to do a simple test and boy it was really simple to implement existing Processing sketches.
Here’s a little 3 steps explanation on how I did that experiment;

Step Number 1.-

First things first in order to play with Processing.js you’ll need to download and include it inside the tag of your html file.

?View Code HTML4STRICT
1
 <script src="script/js/processing-js/processing-0.9.6.min.js" type="text/javascript"><!--mce:0--></script>

Step Number 2.-

Now on the body tag You’ll need to open up a new canvas tag, and that’s where the processing.js will be running.

?View Code HTML4STRICT
1
You need a <a href="http://www.google.com/chrome" target="_blank">modern browser</a> to view this.

So what’s going on here ? You need to tell the canvas the location of the sketch that you’ll be running (in this case the worms.pjs file), in the datasrc attribute and a explaining text in case the user’s browser dont support HTML5 yet other way all they’ll see is a blank screen.

Step Number 3.-

The actual Processing.js that will display those playfull worms on Your HTML, if you’ve used Processing before you’ll notice that there’s actually nothing diffrent form what You do in a regular Processing sketch and if you copy and paste this in the Processing enviroment it will run as any other sketch.

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
Mover[] movers = new Mover[30];
 
void setup() {
  size(viewportwidth,viewportheight);
  smooth();
  background(0);
  // Initializing all the elements of the array
  for (int i = 0; i < movers.length; i++) {
    movers[i] = new Mover(); 
  }
}
 
void draw() {
  noStroke();
  fill(10,0);
  rect(0,0,width,height);
 
  // Calling functions of all of the objects in the array.
  for (int i = 0; i < movers.length; i++) {
    movers[i].update();
    movers[i].checkEdges();
    movers[i].display(); 
  }
}
 
class Mover {
 
  PVector location;
  PVector velocity;
  PVector acceleration;
  float topspeed;
 
  Mover() {
    location = new PVector(random(width),random(height));
    velocity = new PVector(0,0);
    topspeed = 4;
  }
 
  void update() {
 
    // Our algorithm for calculating acceleration:
    PVector mouse = new PVector(mouseX,mouseY);
    PVector dir = PVector.sub(mouse,location);  // Find vector pointing towards mouse
    dir.normalize();     // Normalize
    dir.mult(0.5);       // Scale 
    acceleration = dir;  // Set to acceleration
 
    // Motion 101!  Velocity changes by acceleration.  Location changes by velocity.
    velocity.add(acceleration);
    velocity.limit(topspeed);
    location.add(velocity);
  }
 
  void display() {
    stroke(0);
    fill(175);
    ellipse(location.x,location.y,16,16);
  }
 
  void checkEdges() {
 
    if (location.x > width) {
      location.x = 0;
    } else if (location.x < 0) {
      location.x = width;
    }
 
    if (location.y > height) {
      location.y = 0;
    }  else if (location.y < 0) {
      location.y = height;
    }
 
  }
 
}

So that’s it You may open your html file in the browser and will see a nice animated wormy things chasing your mouse across the screen.

Hope this little explaings helps You get started with Processing.js, I’ll be doing a little more of experimentation with it myself and tell You how it goes.

Until next time See You.

Using HYPE Framework’s ContextSavePNG

One of the first things You want to do when playing with the HYPE framework is to output your creations to a printable file and guess what?  Joshua and Branden have already think on that, hype includes a the class ContextSavePNG that will let you output your hype generated images to a printable .png. Here’s a simple example on how to use the ContextSavePNG class of the hype framework.

For this short example i’m using one of the files included in the hype framework zip that You can download here “\hype-hype-605a391\examples\Flash\SimpleBallistic\02_simpleBallistic.fla”

Here’s the ActionScript code of that file:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/***********************************************
 
	HYPE
	http://www.hypeframework.org
	developed by Branden Hall and Joshua Davis.
 
************************************************/
 
import hype.extended.behavior.SimpleBallistic;
import hype.extended.color.ColorPool;
import hype.extended.trigger.ExitShapeTrigger;
import hype.extended.trigger.RandomTrigger;
import hype.framework.core.ObjectPool;
import hype.framework.core.TimeType;
import hype.framework.display.BitmapCanvas;
import hype.framework.rhythm.SimpleRhythm;
 
MyExitShape.visible = false;
 
var myWidth = stage.stageWidth;
var myHeight = stage.stageHeight;
 
var bmc:BitmapCanvas = new BitmapCanvas(myWidth, myHeight);
addChild(bmc)
 
var clipContainer:Sprite = new Sprite();
 
var color1:ColorPool = new ColorPool(
	0x587b7C, 0x719b9E, 0x9FC1BE, 0xE0D9BB, 0xDACB94, 0xCABA88, 0xDABD55, 0xC49F32, 0xA97409
);
 
var color2:ColorPool = new ColorPool(
	0xFFFFFF, 0xCCCCCC, 0x999999, 0x666666
);
 
var pool:ObjectPool = new ObjectPool(MyCircle, 800);
 
function addNextClip(r:SimpleRhythm) {
	var clip:MyCircle = pool.request() as MyCircle;
 
	if (clip != null) {
		clip.x = myWidth / 2;
		clip.y = 100;
 
		clip.scaleX = clip.scaleY = 0.05 + (Math.floor(Math.random() * 3) * 0.3);
 
		color1.colorChildren(clip);
 
		// target Object, drag, minForce, maxForce, gravity, gravityAngle
 
		var ballistic:SimpleBallistic = new SimpleBallistic(clip, 0.97, 2, 3, 0.25, 90);
		ballistic.start();
 
		// exit callback function, target Object, shape, shapeFlag
 
		var onExit:ExitShapeTrigger = new ExitShapeTrigger(onExitShape, clip, MyExitShape, true);
		onExit.start();
 
		var randomSplit:RandomTrigger = new RandomTrigger(onSplit, clip, 50);
		randomSplit.start();
	}
}
 
function onExitShape(clip):void {
	clipContainer.removeChild(clip);
	pool.release(clip);
}
 
function onSplit(parentClip):void {
	var clip:MyCircle = pool.request() as MyCircle;
 
	if (clip) {
		clip.x = parentClip.x;
		clip.y = parentClip.y;
 
		clip.scaleX = clip.scaleY = 0.05 + (Math.floor(Math.random() * 3) * 0.05);
 
		color2.colorChildren(clip);
 
		// target Object, drag, minForce, maxForce, gravity, gravityAngle
 
		var ballistic:SimpleBallistic = new SimpleBallistic(clip, 0.97, 4, 6, 0.2, 90);
		ballistic.start();
 
		// exit callback function, target Object, shape, shapeFlag
 
		var onExit:ExitShapeTrigger = new ExitShapeTrigger(onExitShape, clip, MyExitShape, true);
		onExit.start();
	}
}
 
var rhythm:SimpleRhythm = new SimpleRhythm(addNextClip);
rhythm.start(TimeType.TIME, 1);
 
pool.onRequestObject = function(clip) {
	clipContainer.addChild(clip);
}
 
bmc.startCapture(clipContainer, false);

The first thing you need to save your actionscript generated visuals to an image file is to import the ContextSavePNG class.

?View Code ACTIONSCRIPT3
1
import hype.extended.util.ContextSavePNG;

Then just before the line were you start capturing your clip into the bitmap canvas you call the setupLargeCanvas method of the BitmapCanvas class, by setting the argument to 10 you are telling hype that the output image will be the orginal size of your swf times 10, so in this example the original .fla size is 640 px width x 360 px height the exported .png will be 6400 px width x 3600 px height, pretty cool right ? with a file this size you could print a poster once you export the file to. png that in other form will be very hard to output an image that size.

?View Code ACTIONSCRIPT3
1
bmc.setupLargeCanvas(10);

Next you need to create an instance of the ContextPNG class and pass it the parameter of the BitmapCanvas you want to encode in this case the bmc. Now at the time that you run your .swf and hit the right click you will get the EncodePNG button when you click it your hype animation will pause and a small progress bar will appear in the center of your .swf indicating that the bmc is being encoded after that the button will change to SavePNG and when you hit that button vuala you have an scaled up transparent .png file out of your .swf.

?View Code ACTIONSCRIPT3
1
2
var savePNG:ContextSavePNG = new ContextSavePNG(bmc);
bmc.startCapture(clipContainer, false);

Don’t forget to check out http://www.hypeframework.org/blog for more information and the latest updates on HYPE.

See You around and happy coding.

Adobe Flash CS5 Review pt 3: The Code Snippets Panel

So for the third part of this series and I guess the last now that Adobe released the CS5 and You can explore the new Flash CS5 by Your own, in the above video I’m showing you the ActionScript 3.0 code snippets panel  this cool little panel will be loved by designers and new coders alike. Lee Brimelow had  already made one snippets panel and this one is based on that, to use it you simply select your movie clip and drag one snippet from this panel, your timeline will automatically add an ActionScript layer with the code needed. You can also create your own snippets so if you’re new to coding or a designer this panel will help you out a lot.

Download the Flash CS5 trial here and start playing.

Happy Coding !!!

Adobe Flash CS5 Review pt 2: Custom class code hinting and completition

Flash CS5 Features 02 Custom class code hinting and completion. from David Gamez on Vimeo.

Ok  so for the second part of this series I’m showing You a little video of  something you’ll love if you use to code in FlashIDE  ActionScript editor.

The improved editor now let’s  you work with custom code hinting and completition and it works pretty fast it’s as easy as setting your classpaths and the editor will recognize all of your libraries and custom classes.

To be totally honest, I would not leave the ActionScript editor I’m using now for the one that comes with the Flash IDE but it definitely eases up the workflow if you’re using it.

See You around.

Adobe Flash CS5 Review pt 1: The XFL file format

Ok this will be the first of  a series of post of some of the new features of Adobe Flash CS5, and I say some because the new Flash comes with tons of new and improved features that said lest move on.

Flash CS5 Features 01 XML-Based-Flas (XFL) from David Gamez on Vimeo.

In Flash CS5 there’s a new file format in the house that it’s called .XFL  that is a new  XML based  format that allows You to exchange and work on files more easy, how to use it ?  just save your file  as .xfl in this way all your assets and properties are not packaged in a .fla file instead they will be saved in a folder structure that you can open and modify without the Flash ide, the properties of the document and graphic elements of the library are exported in XML files and  can be edited from any text editor and modify its properties. Even Actionscript code of the frames is exported.

I see this feature as a very neat one that will let us have more control over our Flash work and expands the possibilities for new types of workflow.

Until the next feature,  See You around.

Merry Xmas a la HYPE Framework

A little something using  the wonderful HYPE Framework by Joshua Davis and Branden Hall

This movie requires Flash Player 10

A little something using  the wonderful HYPE Framework by Joshua Davis and Branden Hall

Merry Christmas and happy holidays to all !!!

Using Flex PMD in FlashDevelop 3

FlashDevelop 3

Adobe recently made available Flex PMD a tool that lets you keep track of your code bad practices and helps you  by auditing your source directory and displaying  common errors such as:

  • Unused code (functions, variables, constants, etc.)
  • Inefficient code (misuse of dynamic filters, heavy constructors, etc.)
  • Over-complex code (nested loops, too many conditionals, etc.)
  • Over-long code (classes, methods, etc.)
  • Incorrect use of the Flex component lifecycle (commitProperties, etc).

A report is produced describing the violations of a given rule set. FlexPMD includes a rule set that is broad ranging and continually growing. It is also straightforward to create your own new rules.

Originally Flex PMD can be called from: Ant, The Command Line and Maven, but thanks to the FlashDevelop (FD3 from now on ) community a plugin has been made available that lets you use FlexPMD in the FD3 IDE and throws the result right in the Output and Results window of FD3.

flexpmdinfd3

Installation

1. Download flashdevelopPMD from http://www.kemelyon.com/flashdevelop/flashdevelopPMD.zip

2. Copy PMD.dll into the plugins folder of your FD Application Files.

fdsettings

fdplugins

3. Download flexPMD from Adobe Labs (http://opensource.adobe.com/wiki/displa … /Downloads) and extract to your disk.

adobeos

Set “PMD jar Location” in Tools -> Settings -> FlexPMD to your “flex-pmd-command-line-1.0.RC3.jar”

flexpmdlocation

Usage

Press Ctrl-Shift-A to run FlexPMD in current Project. This version only checks code inside the “src” folder, so you don’t see warnings in your libraries.

To use your own ruleset, set “PMD Ruleset” in Tools -> Settings -> FlexPMD

Thanks again to the FlashDevelop community for spending time in making this useful plugins.

Flint Actionscript 3 Particle System Example

.swfgeek Logo Particles

Richard Lord has recently released the Version 0.9.4 of Flint.

I made this example
using Flint particle system is an Actionscript 3.0 Open Source project with the aim of create a library that handles the common functionality for all particle systems. To see it work just click anywhere on stage and it will make a nice Firework out of my “Logo”

I just tried it myself and i must say it’s super easy to use and to extend. You can find Flint source on the google code page of Flint with working examples in the downloads section there’s also some very good examples and tutorials on Flint Particle System Site and you can keep track of Richard on his blog.

The latest version comes packed with all kind of particles goodies like:

* Access all properties in Actions, Initializers, Counters and Activities so they can be modified while the emitter is running.
* AlphaInit initializer sets the initial alpha value for all particles
* ImageClasses and SharedImages initializers set the particle image to one selected from a group, with weighting to adjust the selection
* MouseExplosion action pushes particles away from the mouse
* MouseGravity action pulls particles towards the mouse
* TurnAwayFromMouse action causes particles to turn away from the mouse
* GreyscaleZone uses a greyscale image to define a zone, with weighting based on the luminence of each pixel
* Pulse counter emits particles in regular bursts
* PerformanceAdjusted counter adjusts the rate of particle emission if the frame-rate drops
* TwoWay energyEasing functions have an energy peak half-way through the particle’s lifetime

Heres the link to my example using Flint, and Flex 3 as much as I would love to add the code right below my post the IG Syntax HighLighter seems to not be getting very well with the latest update of wordpress so to get the code just right click on my example and it will take you there.

Update you can now view the code right here:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package {
 
    import flash.display.Bitmap;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.filters.BlurFilter;
    import flash.filters.ColorMatrixFilter;
    import flash.geom.Point;
 
    import org.flintparticles.actions.*;
    import org.flintparticles.counters.*;
    import org.flintparticles.emitters.*;
    import org.flintparticles.energyEasing.Quadratic;
    import org.flintparticles.events.FlintEvent;
    import org.flintparticles.initializers.*;
    import org.flintparticles.zones.*;
 
    [SWF( frameRate='61', backgroundColor='#000000')]
 
    public class LogoFireworks extends Sprite
    {
        [Embed(source="assets/sgw.png")]
 
        public var Logo:Class;
        public var bitmap:Bitmap = new Logo();
        public var ev:FlintEvent;
        private var emitter:PixelEmitter = new PixelEmitter();
 
        public function LogoFireworks()
        {
            ViewSource.addMenuItem(this, "srcview/index.html");
            stage.scaleMode = "noScale";
            stage.align ="TL";
            init();
        }
 
        public function init():void
        {
            stage.addEventListener(MouseEvent.MOUSE_DOWN,startFlint);
            stage.addEventListener(MouseEvent.MOUSE_UP,stopFlint)
        }
        public function prepareToFlint(event:MouseEvent):void
         {
          stage.addEventListener(MouseEvent.MOUSE_DOWN,startFlint);
          stage.addEventListener(MouseEvent.MOUSE_UP,stopFlint)
 
         }
 
        public function startFlint(Event:MouseEvent):void
        {
            emitter.addFilter( new BlurFilter( 2, 2, 1 ) );
            emitter.addFilter( new ColorMatrixFilter( [ 1,0,0,0,0,
                                                        0,1,0,0,0,
                                                        0,0,1,0,0,
                                                        0,0,0,0.96,0 ] ) );
            emitter.setCounter( new Blast( 1500 ) );
            emitter.addInitializer( new ColorInit(Math.random()* 0xFFFF3300,Math.random()* 0xFFFFFF00 ) );
            emitter.addInitializer( new Lifetime( 7) );
            emitter.addInitializer( new Position( new DiscZone( new Point( 0, 0 ), 10 ) ) );
            emitter.addInitializer( new Velocity( new BitmapDataZone( bitmap.bitmapData,-211, -550 ) ) );
            emitter.addAction( new Age( Quadratic.easeIn ) );
            emitter.addAction( new Fade( 1.0, 0 ) );
            emitter.addAction( new Move() );
            emitter.addAction( new LinearDrag( 0.5 ) );
            emitter.addAction( new Accelerate( 0, 70 ) );
            addChild( emitter );
            emitter.x = stage.stageWidth/2;
            emitter.y = stage.stageHeight -(5);
            emitter.start( );
            emitter.addEventListener( FlintEvent.EMITTER_EMPTY, restart);
        }
 
        public function stopFlint(Event:MouseEvent):void
        {
            stage.removeEventListener(MouseEvent.MOUSE_DOWN,startFlint)
        }
 
        public function restart( ev:FlintEvent ):void
        {
            mouseEn();
        }
 
        public function mouseEn():void
        {
            stage.addEventListener(MouseEvent.MOUSE_DOWN,startFlint);
        }
    }
}

Drawing API and Mouse Events

DrawingAPI
Click on the image to see the example and get the code.

A pair of days ago I found the blog of Sorin Haidan in wish he post some very useful tutorials on Flash and Actionscript 3.0 in a very understandable way, I found one that caught my attention called Draw Custom shapes with ActionScript 3.0. In this tutorial he explains how to make a “Ball” appear on screen every time you click and move your mouse on the screen by using the Drawing API and MouseEvents, the change of the color on the ball was achieved doing a loop in a 10 frame movie clip with a ball of different gradient fill on each frame, so occurred to me to wrap that code on a class on a Flex 3 Actionscript Project and get rid of the Flash assets by drawing the ball in a dynamic way and this let me Change the color of the Ball more than the 10 times of Sorin example, so check the example be sure to check Sorin’s blog .
In my example if you right click on the file you get to see the source that it’s also included below this text here’s what I got: Drawing API Ball Example.

Thanks Sorin for letting me mess around with his code keep up with those good tutorials.

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
/////---- Class by Dave Ga?mez (.swfgeek) 24-February-2008 http://www.swfgeek.net----\\\
///---- Original Example by: Sorin Haidan in his  Draw Custom shapes with ActionScript 3.0. Tutorial ----\
///---- Found on his blog http://biochimistu.blogspot.com/ ---- \
*/
 
package {
 
    import flash.display.GradientType;
    import flash.display.SpreadMethod;
    import flash.display.Sprite;
    import flash.display.StageScaleMode;
    import flash.display.StageAlign;
    import flash.events.MouseEvent;
    import flash.geom.Matrix;
    import com.adobe.viewsource.ViewSource;
 
    [SWF(backgroundColor="0x000000",frameRate="31")]
 
    public class DrawingAPI extends Sprite
    {
        private var sprite:Sprite;
        private var holder:Sprite;
        private var myCircle:Sprite;
        private var fillType:String;
        private var colors:Array;
        private var alphas:Array;
        private var ratios:Array;
        private var matr:Matrix;
        private var spreadMethod:String;
        private var focalPointRatio:Number;
 
        public function DrawingAPI()
        {
            init();
        }
 
        private function init():void
        {
            ViewSource.addMenuItem(this, "srcview/index.html");
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;
            stage.addEventListener(MouseEvent.MOUSE_DOWN,prepareToDraw);
 
        }
 
        public function prepareToDraw(event:MouseEvent):void
         {
          stage.addEventListener(MouseEvent.MOUSE_MOVE,drawGraphics);
          stage.addEventListener(MouseEvent.MOUSE_UP,stopDrawing);
 
         }
 
        public function drawGraphics(event:MouseEvent):void
        {
         fillType = GradientType.RADIAL;
         colors = [0xFFFFFF, Math.random()*0xFFFFFF];
         alphas = [1, 1];
         ratios = [0x37, 0xFF];
         matr= new Matrix();
         matr.createGradientBox(100, 100, Math.random()*360, -40, 0);
         spreadMethod = SpreadMethod.PAD;
         focalPointRatio = 1;
         holder = new Sprite();
         addChild(holder);
         myCircle = new Sprite();
         myCircle.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr,spreadMethod);
         myCircle.graphics.drawCircle(0,0,40);
         myCircle.graphics.endFill();
         holder.addChild(myCircle);
         holder.x = mouseX;
         holder.y = mouseY;
         holder.scaleX = holder.scaleY = Math.random()*2+0.5;
         holder.rotation = Math.random()*360;
         holder.alpha = Math.random()+0.7;
       }
 
        public function stopDrawing(event:MouseEvent):void
       {
        stage.removeEventListener(MouseEvent.MOUSE_MOVE,drawGraphics)
       }
    }
}

ColorMatrixFilter Fun in Actionscript 3.0

ColorMatrixFilter

Based on the great tutorial of Lee Brimelow, called Advanced Filter Effects I started messing around with the ColorMatrixFilter(); an Actionscript 3.0 Class that lets you apply a 4×5 matrix transformation in the RGB color and alpha values to the pixels of an image, and produce a new RGBA alpha value this can be applied to any display object.
So it’s quite addicting messing around with those values and get different results, this example is not at all finished it’s quite buggy still you can get some nice waving effects anyway check it out here:
ColorMatrixFilterExample and be sure to stop by www.gotoandlearn.com Lee has an unique way of explaining things very good and make difficult things look like is a piece of cake.