Interactive Physics Animations Javascript Canvas 08

Thus far, we’ve been doing lot of setup and it hasn’t been very visually exciting. Now we start the fun stuff! Adding motion! Before we just has a draw function, but now we’ll add a function that will control the animations and we’ll also need a way to execute code repeatedly over a period of time. We’ll use a setInterval function to call first update and then draw multiple times a second and this will give the essence of animation! Here we’re just adjusting the coordinates of each of the dots every time the update function is fired, which happens to be every 100 milliseconds, or 10 times a second. interactive physics animations via javascript & canvas | 08.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;
var total_dots = 25;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
var dots = new Array();
var drag_i = -1;

var this_dot = {};
for (var i=0; i < total_dots; i++){ var this_dot = { x: Math.random()*canvas.width, y: Math.random()*canvas.height, width:canvas.width, height: canvas.height, radius:Math.random()*20+10 }; dots.push(this_dot); } draw(); $("#canvas").mousedown(function (event) { var dx, dy, dist; for (var i=0; i < dots.length; i++){ dx = event.pageX - this.offsetLeft - dots[i].x; dy = event.pageY - this.offsetTop - dots[i].y; dist = Math.sqrt(dx * dx + dy * dy); if(dist < radius) { drag = true; drag_i = i clickX = dx; clickY = dy; continue; } } }); $("#canvas").mouseup(function (event) { drag = false; drag_i = -1; }); $("#canvas").mousemove(function (event) { if(drag) { dots[drag_i].x = event.pageX - this.offsetLeft - clickX; dots[drag_i].y = event.pageY - this.offsetTop - clickY; draw(); } }); function update(){ for (var i=0; i < dots.length; i++){ if (drag_i != i){ var this_dot = dots[i]; this_dot.x += Math.random() * 10 - 5; this_dot.y += Math.random() * 10 - 5; } } } function draw() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i=0; i < dots.length; i++){ context.beginPath(); context.arc(dots[i].x, dots[i].y, dots[i].radius, 0, Math.PI * 2, false); context.fill(); context.closePath(); } } setInterval(function() { update(); draw(); }, 100); }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.

Interactive Physics Animations Javascript Canvas 7b

Here’s an interesting rendering I found when I was playing with drawing multiple dots. interactive physics animations via javascript & canvas | 07 B.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;
var total_dots = 25;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
var dots = new Array();
var drag_i = -1;

var this_dot = {};
for (var i=0; i < total_dots; i++){ var this_dot = { x: Math.random()*canvas.width, y: Math.random()*canvas.height, width:canvas.width, height: canvas.height, radius:Math.random()*20+10 }; dots.push(this_dot); } draw(); $("#canvas").mousedown(function (event) { var dx, dy, dist; for (var i=0; i < dots.length; i++){ dx = event.pageX - this.offsetLeft - dots[i].x; dy = event.pageY - this.offsetTop - dots[i].y; dist = Math.sqrt(dx * dx + dy * dy); if(dist < radius) { drag = true; drag_i = i clickX = dx; clickY = dy; continue; } } }); $("#canvas").mouseup(function (event) { drag = false; drag_i = -1; }); $("#canvas").mousemove(function (event) { if(drag) { dots[drag_i].x = event.pageX - this.offsetLeft - clickX; dots[drag_i].y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); for (var i=0; i < dots.length; i++){ context.arc(dots[i].x, dots[i].y, dots[i].radius, 0, Math.PI * 2, false); } context.fill(); } }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.

Interactive Physics Animations Javascript Canvas 07

This step we’ll add a variable to hold the total number of dots we want to create and use it in our for loop that creates the dots. We’ll also give the dots a little more randomness by varying the size with a radius value. interactive physics animations via javascript & canvas | 07.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;
var total_dots = 25;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
var dots = new Array();
var drag_i = -1;

var this_dot = {};
for (var i=0; i < total_dots; i++){ var this_dot = { x: Math.random()*canvas.width, y: Math.random()*canvas.height, width:canvas.width, height: canvas.height, radius:Math.random()*20+10 }; dots.push(this_dot); } draw(); $("#canvas").mousedown(function (event) { var dx, dy, dist; for (var i=0; i < dots.length; i++){ dx = event.pageX - this.offsetLeft - dots[i].x; dy = event.pageY - this.offsetTop - dots[i].y; dist = Math.sqrt(dx * dx + dy * dy); if(dist < radius) { drag = true; drag_i = i clickX = dx; clickY = dy; continue; } } }); $("#canvas").mouseup(function (event) { drag = false; drag_i = -1; }); $("#canvas").mousemove(function (event) { if(drag) { dots[drag_i].x = event.pageX - this.offsetLeft - clickX; dots[drag_i].y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i=0; i < dots.length; i++){ context.beginPath(); context.arc(dots[i].x, dots[i].y, dots[i].radius, 0, Math.PI * 2, false); context.fill(); context.closePath(); } } }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.

Interactive Physics Animations Javascript Canvas 06

Here we’re going to get more into the interactive programming on these dots. We started with one dot that was draggable. This update applies a drag/drop code to each dot object with some logic to keep track of which dot is being dragged. This is quite a bit different than accomplishing the same thing in flash. Flash lets us have visual objects, but here in javascript we have all these objects and they are drawn on the stage/canvas every “frame”. The elements once drawn really don’t have any properties. So we’re attaching mousedown, mouseup and mousemove events to the canvas. In flash we would be applying a click event to the objects themselves. On mousedown we check coordinates to see if we’ve clicked on any of the dots. We also need a variable to store which one is being clicked or dragged at the moment, and this is pretty easy since we set up earlier to have an array holding all our dots, we’ll just use the index of that dot. With mousemove we drag the dot that’s been clicked using that index value, and then mouseup we drop it. interactive physics animations via javascript & canvas | 06.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
var dots = new Array();
var drag_i = -1;

var this_dot = {};
for (var i=0; i < 5; i++){ var this_dot = { x: Math.random()*canvas.width, y: Math.random()*canvas.height, width:canvas.width, height: canvas.height, radius:25}; dots.push(this_dot); } draw(); $("#canvas").mousedown(function (event) { var dx, dy, dist; for (var i=0; i < dots.length; i++){ dx = event.pageX - this.offsetLeft - dots[i].x; dy = event.pageY - this.offsetTop - dots[i].y; dist = Math.sqrt(dx * dx + dy * dy); if(dist < radius) { drag = true; drag_i = i clickX = dx; clickY = dy; continue; } } }); $("#canvas").mouseup(function (event) { drag = false; drag_i = -1; }); $("#canvas").mousemove(function (event) { if(drag) { dots[drag_i].x = event.pageX - this.offsetLeft - clickX; dots[drag_i].y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i=0; i < dots.length; i++){ context.beginPath(); context.arc(dots[i].x, dots[i].y, dots[i].radius, 0, Math.PI * 2, false); context.fill(); context.closePath(); } } }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.

Interactive Physics Animations Javascript Canvas 05

Now we’ll apply this object oriented programming to each dot and give them all random placement. interactive physics animations via javascript & canvas | 05.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
var dots = new Array();

var this_dot = {};
for (var i=0; i < 5; i++){ var this_dot = { x: Math.random()*canvas.width, y: Math.random()*canvas.height, width:canvas.width, height: canvas.height, radius:25}; dots.push(this_dot); } draw(); $("#canvas").mousedown(function (event) { var dx, dy, dist; dx = event.pageX - this.offsetLeft - this_dot.x; dy = event.pageY - this.offsetTop - this_dot.y; dist = Math.sqrt(dx * dx + dy * dy); if(dist < radius) { drag = true; clickX = dx; clickY = dy; } else { drag = false; } }); $("#canvas").mouseup(function (event) { drag = false; }); $("#canvas").mousemove(function (event) { if(drag) { this_dot.x = event.pageX - this.offsetLeft - clickX; this_dot.y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i=0; i < dots.length; i++){ context.beginPath(); context.arc(dots[i].x, dots[i].y, dots[i].radius, 0, Math.PI * 2, false); context.fill(); context.closePath(); } } }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.

Interactive Physics Animations Javascript Canvas 04

This time we won’t make the canvas any different visually, it’s more just cleaning up the code. We’re making the circle into a dot object, then later it will be easier to keep track of it (and any others). interactive physics animations via javascript & canvas | 04.

[cc lang=”javascript”]
$(function () {
var canvas, context, width, height, x, y, radius = 25, clickX, clickY, drag = false;

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);

var this_dot = {
x: Math.random()*canvas.width/5,
y: Math.random()*canvas.height/5,
width:canvas.width,
height: canvas.height,
radius:25};

draw();

$(“#canvas”).mousedown(function (event) {
var dx, dy, dist;
dx = event.pageX – this.offsetLeft – this_dot.x;
dy = event.pageY – this.offsetTop – this_dot.y;
dist = Math.sqrt(dx * dx + dy * dy);
if(dist < radius) { drag = true; clickX = dx; clickY = dy; } else { drag = false; } }); $("#canvas").mouseup(function (event) { drag = false; }); $("#canvas").mousemove(function (event) { if(drag) { this_dot.x = event.pageX - this.offsetLeft - clickX; this_dot.y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); context.arc(this_dot.x, this_dot.y, this_dot.radius, 0, Math.PI * 2, false); context.arc(this_dot.x*2, this_dot.y*2, this_dot.radius, 0, Math.PI * 2, false); context.arc(this_dot.x*3, this_dot.y*3, this_dot.radius, 0, Math.PI * 2, false); context.arc(this_dot.x*4, this_dot.y*4, this_dot.radius, 0, Math.PI * 2, false); context.arc(this_dot.x*5, this_dot.y*5, this_dot.radius, 0, Math.PI * 2, false); context.arc(this_dot.x*6, this_dot.y*6, this_dot.radius, 0, Math.PI * 2, false); context.fill(); } }); [/cc]Follow the whole Interactive Physics Animations via Javascript & Canvas series.

Interactive Javascript Canvas Series

I’ve been playing with canvas and different javascript drawing libraries a lot lately in my projects at work. I’ve been antsy to play with the techniques I’ve learned and apply it to some more interactive experiments. Much like my last series on generative art in flash, but this will all be in javascript! In case you’re extra interested in this type of stuff, go check out Keith Peters’ month long exploration into javascript on his bit-101 site, he’s did some great stuff, and I learned a lot from that. I’m not going to sign up to post every day or anything, but I’ll keep it going for a while at least. So, stay tuned! And let me know if you’re really wanting to see this go into any specific directions.

Here goes nothin’

Video Player 4 introduces interactive playlists, social sharing and more

video player 4 hero shotI’ve been busy hardening and improving my video player lately and had so many updates for it I decided to upload it to activeden as a new file altogether. After some final bug fixes and testing it’s been approved for sale. I think it’s a huge improvement over the last video player. The video playing part is mainly the same (with a few small adjustments for better usability), but I’ve added tons to this update. It’s online at activeden for live preview and purchase.

An extensively customizable yet simple video player. Create and manage play lists for you video delivery as well as allow viewers to share and socially bookmark the video. Integrate the video into your user experience with javascript integration as well as Google Analytics tracking on the video interaction! Control functionality, layout and colors of the player easily! Plus don’t sweat the embed codes – an embed code generator included!

Check out the legend graphic for some views of the player and the different panes. There is the full video view, the playlist, share and detail panes. You can also view them all in fullscreen mode.

circlecube video player 4 legend

This new player has the following updates:

  • Includes an embed script generator built specifically for this video player! Embed script generator with a Live Preview!
  • Use an external xml playlist or set playlist values in flashvars settings. (No need for xml if you don’t want it)
  • Social Bookmarking with facebook, twitter, delicious, google buzz & linkedin
  • Send emails through the player to share the video with friends
  • Google Analytics Integration (event tracking) – Uses your analytics account on a per video setting in flashvars.
  • All colors fully customizable in flashvars or xml
  • Display video title and description – html content (may contain links) in the detail pane.
  • Video controls also in context menu (right-click menu)
  • Loop the video once, twice however many times you wish and even infinitely!
  • Disable tooltips completely if you wish
  • Keyboard shortcut integration! Press the space bar to pause/play the video just like in most video playback programs.
  • Volume setting cached across sessions for a better user experience
  • Double click video for fullscreen

As well as all that made version 3 video player great as well:

  • Supports flv, f4v and any container format using H.264: mp4, m4a, mov, mp4v, 3GP, 3G2.
  • All images and video loaded externally
  • Run this player without additional files, just pass in the flv path.
  • Supports most image file types: jpg, gif, png.
  • Google Analytics Integration (event tracking) – Uses your analytics account on a per video setting in flashvars.
  • Load any dimension video. Completely resizable
  • Set player width and height
  • Set video width and height
  • Full screen capabilities
  • All colors fully customizable
  • Use a preview/thumbnail image.
  • Auto play option
  • Auto load option – in case you had a bunch of video on one page you wouldn’t want them all to auto load.
  • Video scale/stretching options: none, exact, uniform, fill.
  • Javascript callback functions for loading video and finishing video playback.
  • Show/hide a big play button over the video option
  • Show/hide “vcr” video player controls or have them auto-hide
  • Advanced volume controls, click to mute or drag to desired volume. Volume fades rather than cuts.
  • Support for a logo
  • Controls auto-hide
  • Time code display in current time or elapsed time. click to toggle
  • Tooltips for controls
  • Send video files to player dynamically with javascript integration (with an html link on a page send a video to play)
  • Replay video after complete
  • Progressive play and load displays. Watch as the video loads and see the scrub bar update as you watch.
  • Scrub bar is interactive click and drag. Tooltip to display hovered time.
  • Animated play controls.
  • Buttons states & tooltips.
  • All player graphics are vector shapes and very small in size.
  • Fully rearrange player controls
  • Option to disable fullscreen
  • Display video title and description – html content (may contain links)

Here’s a screenshot of the embed code generator:

embed generator preview

Access the html page URL and swf path from flash with as3

To get the url of the html page that contains the flash/swf file we need a little help from the browser. I’ve written about the following methods before, but they were in as2 with “Get current url to Flash swf using an External Interface call” and “Get Current URL and Query String Parameters to Flash in as2“. In as3, we’ll still need access to javascript in the form of ExternalInterface, so if you want to do this on a site that doesn’t allow javascript you’ll have to keep searching (or jump to the bottom for an alternative method). We don’t need to do anything with the javascript or have access to the pages source code, javascript just has to be enabled, and it works in every browser I have access to. All we do is call a javascript line from within the swf which gets the url in the browser, namely:
window.location.href
That is the javascript we need to call. But we do it from an externalInterface call like so:
ExternalInterface.call("window.location.href.toString")
or to make sure all browsers play nicely we can wrap it in a function in case the browser doesn’t want to execute that as a line, this seems to work more solidly:
ExternalInterface.call("function(){ return window.location.href.toString();}")
also note that we’re specifically applying the toString method, this is needed so the javascript actually executes something and can return it.

Other things you may want to do related to this is getting the query string variables form the url, which also uses externalInterface. You can also use this same method to get the domain, path, protocol, and even referrer. You could use some nice regex or substrings to find these from the full url, but it is already accessible. I can see a potential need for the speed to get the full url and then use internal code to cut it however I need it. But, I’m not convinced that using an external interface call takes that much time (but it’d be an interesting experiment to say the least).

You may want to find the url to the actual swf, and this doesn’t require javascript at all, the swf does know where it is even if it doesn’t know where it is embedded. We can use the loderInfo object and the url property. This returns the url to the swf file regardless of what page or even domain it is embedded on:
this.loaderInfo.url

For ExternalInterface to work in IE you need valid classid and id attributes in the tag. This is one of the reasons I use swfobject to handle my embed codes. It takes care of the Internet Exploder.

If your set up fails it may be because it throws a security error. To solve this to set the param allowScriptAccess to ‘always’ and in your actionscript add your domain, in order to enable the use of ExternalInterface.

[cc lang=”html”]

[/cc]
[cc lang=”actionscript”]
flash.system.Security.allowDomain(sourceDomain)
[/cc]

DEMO

get href url tutorial demo
This demo, gets all of the above mentioned values/properties and more. I threw in what I could think of that may be useful or interesting. It shows a couple ways to get the window location href as well as a way it won’t work. Then there are the rest of the properties available using this same method: href, host, hostname, hash (anchor link ‘#’), pathname (url after the domain), port, protocol, search (query string values), the document title and even referrer. Then from the loaderInfo object we can access the url of the swf as well as other things but most used is the bytesTotal and bytesLoaded. Now check out the demo here (adding an fpo hash and query string to the link just for demonstration purposes, feel free to play with the url and see the values updated.
[cc lang=”actionscript”]
import flash.external.ExternalInterface;

displayText.appendText(‘ExternalInterface.call(“function(){ return document.location.href.toString();}”): ‘ + ExternalInterface.call(“function(){ return document.location.href.toString();}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“function(){ return window.location.href.toString();}”): ‘ + ExternalInterface.call(“function(){ return window.location.href.toString();}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.href.toString”): ‘ + ExternalInterface.call(“window.location.href.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.href”): ‘ + ExternalInterface.call(“window.location.href”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.host.toString”): ‘ + ExternalInterface.call(“window.location.host.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.hostname.toString”): ‘ + ExternalInterface.call(“window.location.hostname.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.hash.toString”): ‘ + ExternalInterface.call(“window.location.hash.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.pathname.toString”): ‘ + ExternalInterface.call(“window.location.pathname.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.port.toString”): ‘ + ExternalInterface.call(“window.location.port.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.protocol.toString”): ‘ + ExternalInterface.call(“window.location.protocol.toString”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“window.location.search.toString”): ‘ + ExternalInterface.call(“window.location.search.toString”) + “\n”);

displayText.appendText(‘ExternalInterface.call(“function(){ return document.title;}”): ‘ + ExternalInterface.call(“function(){ return document.title;}”) + “\n”);
displayText.appendText(‘ExternalInterface.call(“function(){ return document.referrer;}”): ‘ + ExternalInterface.call(“function(){ return document.referrer;}”) + “\n”);

displayText.appendText(‘this.loaderInfo.url: ‘ + this.loaderInfo.url + “\n”);
displayText.appendText(‘this.loaderInfo.bytesLoaded: ‘ + this.loaderInfo.bytesLoaded + “\n”);
displayText.appendText(‘this.loaderInfo.bytesTotal: ‘ + this.loaderInfo.bytesTotal + “\n”);
[/cc]

Finally a method I’ve used in my video players when I want users to be able to share the link through the player is send an explicit ‘permalink’ in the flashvars or xml playlist. Then the video can be embedded on any site and users can share the original video url. Plus then I don’t have to rely on javascript. I’ve written about flashvars in the past though, so I’ll leave it to you to put 2 and 2 together. Flashvars is one more plug for swfobject to me though, because it makes it so I only have to declare them once and it handles all the browser specific code.

Anyways, this demo has been tested in mac firefox, chrome, safari and windows ie7, ie8, firefox and chrome. If you have a different browser please comment that it works (or not) so we can get a full spectrum, thanks!

Download Source Files

Related tools/resources:

Actionscript (as3) Javascript Communication | Call Flash to and from javascript

Often we need to have different parts of a website talk to each other. This can get tricky when we are using multiple technologies and need the communication in real-time. Going from flash to html is done through javascript on the browser side and in actionscript we use something called ExternalInterface. The ExternalInterface class is an application programming interface that enables straightforward communication between ActionScript and the SWF container– for example, an HTML page with JavaScript or a desktop application that uses Flash Player to display a SWF file. We can send things form actionscript to javascript as well as from the html and javascript into flash and actionscript.

I’ve written about this before. It got old though and I had reports that it was having issues in certain browsers, so I had a minute to look at it and decided it needed a rebuild. This version uses as3 and swfobject. I was tempted to throw jQuery in there as well, but didn’t want to confuse anyone. This is simple javascript. I did have to throw some css3 on it for style though. I did use swfobject because it makes life easier, but it’s not required.

So, just like in as2, communication between actionscript and javascript still requires our friend ExternalInterface to link them but the setup/syntax changed a bit with as3. From the docs here are a few pointers of what we can accomplish with External Interface:

From ActionScript, you can do the following on the HTML page:

  • Call any JavaScript function.
  • Pass any number of arguments, with any names.
  • Pass various data types (Boolean, Number, String, and so on).
  • Receive a return value from the JavaScript function.

From JavaScript on the HTML page, you can:

  • Call an ActionScript function.
  • Pass arguments using standard function call notation.
  • Return a value to the JavaScript function.

It’s really cool that we can pass various data types. Here I’ve got an example that simply sends a string back and forth. We have the actionscript to javascript lane as well as the javascript to actionscript lane. So to set it up we need to know the names of our functions. Here I’ve tried to name them exactly what they are. There is a function in my javascript to both send and receive text to actionscript. Also, there are corresponding functions in my actionscript code: one to send and one to receive. These functions pass the data back and forth.

The magic is set up with the call and addCallback methods of ExternalInterface.

To call a javascript function from actionscript we use the call method. The first argument is the name of the javascript function as a String and any following (optional) arguments are the parameters that are passed to said function. So we need a function in the javascript on that page which is set up to accept some data or at least set up to do something (we don’t actually have to pass data, it could be just a trigger for something on the page). Then in our actionscript we call:
ExternalInterface.call("name_of_js_function", "data passed to js");

Then to go back from javascript to actionscript there is a little bit more set-up involved. We will use the addCallback method here and this sets the actionscript function to be able to accept a call from javascript. The first argument is the function name in javascript (again as a String), and the second argument is the function name in actionscript that you want to be called:
ExternalInterface.addCallback("name_of_js_function", name_of_as3_function);
Then you write your actionscript function to do what you want:
function name_of_as3_function():String {
//do something
return something;
}

Demo

View the actionscrip javascript communication DEMO
If that doesn’t make sense try the demo to see it in action. I’ve got the source code listed on the demo page as well as the working example.

Source Code

JavaScript

[cc lang=”javascript”]
function receiveTextFromAS3(Txt) {
document.getElementById(‘htmlText’).value = Txt;
}
function sendTextToAS3(){
var Txt = document.getElementById(‘htmlText’).value;
var flash = document.getElementById(“as3_js”);
flash.sendTextFromJS(Txt);
document.getElementById(‘htmlText’).value = “”;
}

var flashvars = {};
var params = {};
var attributes = {};
attributes.id = “as3_js”;
//attributes.name = “as3_js”;
swfobject.embedSWF(“AS3_Javascript.swf”, “alt”, “450”, “450”, “9.0.0”, false, flashvars, params, attributes);
[/cc]

HTML

[cc lang=”html”]

[/cc]

Actionscript – AS3

[cc lang=”actionscript”]
import flash.external.ExternalInterface;

//Set up Javascript to Actioscript
ExternalInterface.addCallback(“sendTextFromJS”, receiveTextFromJS);
function receiveTextFromJS(t:String):void {
theText.text = t;
}

//Actionscript to Javascript
function sendTextFromAS3(e:MouseEvent):void {
ExternalInterface.call(“receiveTextFromAS3”, theText.text);
theText.text = “”;
}
button.addEventListener(MouseEvent.CLICK, sendTextFromAS3);
button.buttonMode = true;
[/cc]

Source Files

Download the source files here:
FLA, HTML, SWF, ZIP.