Interactive Physics Animations Javascript Canvas 02

Adding more circles, each a multiple of the first circle’s coordinates. I like the effect of having them all move in unison. Ceck the source: interactive physics animations via javascript & canvas | 02

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

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
width = canvas.width;
height = canvas.height;
x = width / 2;
y = height / 2;
draw();

$(“#canvas”).mousedown(function (event) {
var dx, dy, dist;
dx = event.pageX – this.offsetLeft – x;
dy = event.pageY – this.offsetTop – 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) { x = event.pageX - this.offsetLeft - clickX; y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, width, height); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2, false); context.arc(x*2, y*2, radius, 0, Math.PI * 2, false); context.arc(x*3, y*3, radius, 0, Math.PI * 2, false); context.arc(x*4, y*4, radius, 0, Math.PI * 2, false); context.arc(x*5, y*5, radius, 0, Math.PI * 2, false); context.arc(x*6, y*6, radius, 0, Math.PI * 2, false); context.fill(); } }); [/cc]

Interactive Physics Animations Javascript Canvas 01

Adding a second circle, always at twice the x and y as the first. The first is still draggable. View the source: interactive physics animations via javascript & canvas | 01

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

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
width = canvas.width;
height = canvas.height;
x = width / 2;
y = height / 2;
draw();

$(“#canvas”).mousedown(function (event) {
var dx, dy, dist;
dx = event.pageX – this.offsetLeft – x;
dy = event.pageY – this.offsetTop – 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) { x = event.pageX - this.offsetLeft - clickX; y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, width, height); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2, false); context.arc(x*2, y*2, radius, 0, Math.PI * 2, false); context.fill(); } }); [/cc]

Interactive Javascript Canvas 00

I’ve played a lot with physics experiments in flash and moving more to javascript and canvas for simple things I wanted to test it out with some physics and animations. I’ve been curious to find out how the performance compares. Obviously this will depend on the browser, but the browsers that do support canvas should be able to handle some interactive physics animations.

I have this project I keep coming back to, it’s been in as2 and then in as3 and has have multiple faces. But the gist is there are a bunch of circles or balls and they float around in a specified area. There are physics “controls” exposed to the user and they can control the velocity of the balls, the gravity, air friction or drag, elasticity and they can even grab a ball and throw it across the stage (canvas). Here are a couple iterations of this: BFA Portfolio, Current Interactive POG Portfolio, Dribbble likes, Lastfm scrobbles.

I’m going to rebuild the basic functionality via javascript. I have had this on my list of things to explore for months now, in fact, ever since I saw Keith Peters go through his month long javascript exploration, he had a specific example that made me think I really needed to do it. I started and then life happened… But now I’m ready to start documenting my progress and trying to share what I’ve learned.

I’ll start with his initial example he titles JavaScript Day 27: Mouse Part II.
View my version here: interactive physics animations via javascript & canvas.

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

canvas = $(“#canvas”)[0];
context = canvas.getContext(“2d”);
width = canvas.width;
height = canvas.height;
x = width / 2;
y = height / 2;
draw();

$(“#canvas”).mousedown(function (event) {
var dx, dy, dist;
dx = event.pageX – this.offsetLeft – x;
dy = event.pageY – this.offsetTop – 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) { x = event.pageX - this.offsetLeft - clickX; y = event.pageY - this.offsetTop - clickY; draw(); } }); function draw() { context.clearRect(0, 0, width, height); context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2, false); context.fill(); } }); [/cc]

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’

Link: A Quick Look Into The Math Of Animations With JavaScript

Here’s an article with a great and simple look into programming movement with simple math and javascript! Some creative examples and lots of jsfiddle links at the end to play with.

Link: A Quick Look Into The Math Of Animations With JavaScript – (http://coding.smashingmagazine.com/2011/10/04/quick-look-math-animations-javascript/) from (author unknown) at Smashing Magazine Feed

Hiatus Apologies

I’ve neglected this site lately, 6 months to be exact. Combine busy times, new jobs, summer trips skipping the country and websites are sometimes the first to be neglected.

oh canada

But, I’m planning on being back. I want to shift towards sharing more links and quick tips, partly because reading the internet had become more of a 140 characters ADHD process. I’ll be writing less tutorials in the sense that I’ve been writing, but I’m planning on having much more content, just less demanding on my time. I don’t have time to write a book and no one wants to read it anyways (myself included). We just want to see cool new things and tips and quick solutions to issues. So, I’m going to be sharing a lot more links pointing to cool things and tricks. I’ve shifted from flash animation it seems to more jQuery and CMS programming and less flash. But I don’t mind too much, although I still enjoy flash immensely, many of the same things we once had to rely on plugins to achieve, we can now do with javascript. It’s really the same end result just using different technologies. So expect some snippets and quick examples rather than complete walkthroughs. I’ll focus on all things interactive (as usual) but will include a broader range of things.

On another note, I’ve started a new job (again). I’m now at The Jones Group, downtown Atlanta. The advertising industry wasn’t for me, and I’m happy to be Interactive Director at the Jones Group working on making some really cool & interactive websites! You can bet, I’ll be sharing details of them as they launch (I’ve actually got a backlog waiting already).

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.