<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Overfloater &#187; javascript</title>
	<atom:link href="http://blog.thejit.org/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thejit.org</link>
	<description>Data Visualization, JavaScript and Computer Science related stuff</description>
	<lastBuildDate>Sun, 18 Jul 2010 13:38:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Doctor Who villains from 1963 to 2010 visualized</title>
		<link>http://blog.thejit.org/2010/07/17/doctor-who-villains-from-1963-to-2010-visualized/</link>
		<comments>http://blog.thejit.org/2010/07/17/doctor-who-villains-from-1963-to-2010-visualized/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 21:34:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript information visualization toolkit (JIT)]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1530</guid>
		<description><![CDATA[While browsing the internet I got to the Guardian&#8217;s Datablog, a blog that gathers interesting information and datasets to explore and make visualizations. Latest post was about Every Doctor Who villain since 1963. There&#8217;s information about each villain&#8217;s first and last year of appearance, their motivation/evil plan, the name of the actors who played the [...]]]></description>
			<content:encoded><![CDATA[<p>While browsing the internet I got to the <a href="http://www.guardian.co.uk/news/datablog">Guardian&#8217;s Datablog</a>, a blog that gathers interesting information and datasets to explore and make visualizations. Latest post was about <a href="http://www.guardian.co.uk/news/datablog/2010/jul/16/doctor-who-villains-list">Every Doctor Who villain since 1963</a>. There&#8217;s information about each villain&#8217;s first and last year of appearance, their motivation/evil plan, the name of the actors who played the role of Doctor Who while that villain was making an appearance, the title of the stories where that villain was in, etc.</p>
<p>I created a &#8220;dynamic&#8221; TreeMap visualization with that data. Here&#8217;s a short screencast I made explaining the TreeMap functionalities (I have a horrible english accent&#8230; I know). You can also play with the demo <a href="http://demos.thejit.org/doctorwho/">here</a>.</p>
<p><object width="500" height="400"><param name="movie" value="http://www.youtube.com/v/vAGk9gIzzEM&amp;hl=en_US&amp;fs=1?rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/vAGk9gIzzEM&amp;hl=en_US&amp;fs=1?rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="400"></embed></object></p>
<h4>The Code</h4>
<p>For this example I used a special build of the Toolkit which is currently hosted at <a href="http://github.com/philogb/jit">GitHub</a>. The TreeMap example code looks just like the <a href="http://thejit.org/demos/">TreeMap demos code</a> but I also added an <em>onBeforeCompute</em> callback that checks for the <em>Doctor Actor Name</em> and <em>Villain Motivation</em> filters to fade nodes respectively:</p>
<pre name="code" class="js:nogutter:nocontrols">
onBeforeCompute: function() {
  tm.graph.eachNode(function(n) {
    var prev = false;
    if(n.data.motivations) {
      prev = true;
      if(motivation != 'All'
        &#038;&#038; n.data.motivations.indexOf(motivation) == -1) {
        n.setData('alpha', 0, 'end');
        n.ignore = true;
      } else {
        n.setData('alpha', 1, 'end');
        delete n.ignore;
      }
    }
    if(n.data.doctorActorNames) {
      if(doctorName != 'All'
        &#038;&#038; n.data.doctorActorNames.indexOf(doctorName) == -1) {
        n.setData('alpha', 0, 'end');
        n.ignore = true;
      } else if(!prev) {
        n.setData('alpha', 1, 'end');
        delete n.ignore;
      }
    }
  });
},
</pre>
<p>The anchor click callbacks set the current selected value to the <em>doctorName</em> and <em>motivation</em> variables and also perform an animation by fading nodes and repositioning the remaining visible nodes:</p>
<pre name="code" class="js:nogutter:nocontrols">
anchors.addEvent('click', function(e) {
  doctorName = this.innerHTML;
  tm.compute('end');
  tm.fx.animate({
    modes: {
      position: 'linear',
      'node-property': ['alpha', 'width', 'height']
    },
    duration: 1000,
    fps: 50,
    transition: $jit.Trans.Quart.easeInOut
  });
});
</pre>
<p>The <em>tm.compute(&#8216;end&#8217;);</em> call will trigger the <em>onBeforeCompute</em> callback that will set correct alpha values for the nodes. Then we perform an animation of node positions and node alpha, width and height properties.</p>
<p>I hope you have fun with the <a href="http://demos.thejit.org/doctorwho/">demo</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2010/07/17/doctor-who-villains-from-1963-to-2010-visualized/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The JavaScript InfoVis Toolkit 2.0 is out!</title>
		<link>http://blog.thejit.org/2010/06/28/the-javascript-infovis-toolkit-2-0-is-out/</link>
		<comments>http://blog.thejit.org/2010/06/28/the-javascript-infovis-toolkit-2-0-is-out/#comments</comments>
		<pubDate>Mon, 28 Jun 2010 12:01:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[2.0]]></category>
		<category><![CDATA[JavaScript information visualization toolkit (JIT)]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[version]]></category>
		<category><![CDATA[visualization]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1492</guid>
		<description><![CDATA[After more than a year of hard work I&#8217;m proud to announce the release of the JavaScript InfoVis Toolkit 2.0!
What&#8217;s the JavaScript InfoVis Toolkit?
The JavaScript InfoVis Toolkit provides web standard based tools to create interactive data visualizations for the Web.
What&#8217;s new in this version?
This version introduces radical new features, an API redesign and new visualizations. [...]]]></description>
			<content:encoded><![CDATA[<p>After more than a year of hard work I&#8217;m proud to announce the release of the <a target="_blank" href="http://thejit.org">JavaScript InfoVis Toolkit 2.0</a>!</p>
<h4>What&#8217;s the JavaScript InfoVis Toolkit?</h4>
<p>The <a target="_blank" href="http://thejit.org">JavaScript InfoVis Toolkit</a> provides web standard based tools to create interactive data visualizations for the Web.</p>
<h4>What&#8217;s new in this version?</h4>
<p>This version introduces radical new features, an API redesign and new visualizations. If you don&#8217;t want to read the whole article and just want to play with the examples you can go to <a href="http://thejit.org/demos/" target="_blank">the demos page</a>.</p>
<h4>New Visualizations</h4>
<p>With this version of the Toolkit the number of available visualizations has doubled. Some of the new visualizations are the AreaChart, BarChart and PieChart, which were described in more detail in <a href="http://blog.thejit.org/2010/04/24/new-javascript-infovis-toolkit-visualizations/">this article</a>. I&#8217;ve also added Sunburst and Force-Directed visualizations. I wrote about these visualizations before <a href="http://blog.thejit.org/2009/10/05/sunburst-visualization/">here</a> and <a href="http://blog.thejit.org/2009/09/30/force-directed-layouts/">here</a>. I also want to thank <a href="http://quux.com.ar" target="_blank">Pablo Flouret</a>, who contributed most of the code for the Icicle visualization, also a new addition to the toolkit.</p>
<p>You can play now with these visualizations at the <a href="http://thejit.org/demos/">demos page</a>!</p>
<h4>Features common to all visualizations</h4>
<p>I&#8217;ve also enhanced all visualizations with new configuration options that enable new features. These features are:</p>
<ul>
<li><em>Panning</em> and <em>zooming</em> across all visualizations.</li>
<li>A new <em>event system</em> that enables you to attach events to DOM elements or to native canvas nodes and also add support for <em>touch events</em>, <em>drag and drop</em>, etc.</li>
<li><em>Complex animations</em> have the ability to animate <b>any style property</b> of a node, edge or label. There is also support for animating canvas specific properties like shadowBlur, shadowColor, fillStyle, etc.</li>
</ul>
<h4>A new TreeMap visualization</h4>
<p>The underlying rendering functions in the TreeMap visualization have changed. While in prior versions of the Toolkit the TreeMap was DOM-based, this new version renders the TreeMap entirely in Canvas. This enables you to add custom nodes of any shape or nature you like (can be images, circles, polygons) and also to take advantage of the new animation engine of the toolkit to add smooth transitions for the drill-down. These new things can be tested at the TreeMap section in the <a target="_bank" href="http://thejit.org/demos/">demos page</a>.</p>
<h4>API Redesign</h4>
<p>The old API was too low level. Before creating any visualization you had to manually create a Canvas widget and pass it as parameter to the visualization class. Also, many other parameters like width and height of the canvas were required. For Background canvases the API had a couple of flaws, and it wasn&#8217;t clear how to use it either. Many of these things have been solved with the new API design. The Canvas class became an inner class implicitly created when making a new visualization. Width and height of the canvas are set to the container&#8217;s <em>offsetWidth</em> and <em>offsetHeight</em> if they&#8217;re not provided, and background canvases are easier to attach to the visualization.<br />
Most of all, there is now a single global object in the library: <b>$jit</b>. This declares the namespace for the library and makes sure you won&#8217;t have conflicts with <em>any other JavaScript library</em>.</p>
<h4>A new Website</h4>
<p>Last but not least, I worked on a <a href="http://thejit.org/">website redesign</a>, taking advantage of the new HTML5/CSS3 features supported by major browsers. There&#8217;s also a detailed <a href="http://thejit.org/docs/">documentation page</a> to get you started.</p>
<h4>It&#8217;s alpha</h4>
<p>Finally I&#8217;d like to say that this is an <em>alpha</em> version. There are lots of known bugs and <b>I&#8217;m counting on you</b> to <a href="http://github.com/philogb/jit">report bugs, send fixes, and collaborate in any aspect of the toolkit</a>.</p>
<h4>Thanks</h4>
<p>To <a href="http://quux.com.ar">Pablo Flouret</a> for contributing code to the toolkit, and to my wife, <a href="http://sourberries.tumblr.com/">Luz Caballero</a> for making me happy.</p>
<p>Now go get the <a href="http://thejit.org/">Toolkit</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2010/06/28/the-javascript-infovis-toolkit-2-0-is-out/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>News from the JavaScript InfoVis Toolkit 2.0 World</title>
		<link>http://blog.thejit.org/2010/05/30/news-from-the-javascript-infovis-toolkit-2-0-world/</link>
		<comments>http://blog.thejit.org/2010/05/30/news-from-the-javascript-infovis-toolkit-2-0-world/#comments</comments>
		<pubDate>Sun, 30 May 2010 18:35:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript information visualization toolkit (JIT)]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[javascript infovis toolkit]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1476</guid>
		<description><![CDATA[We&#8217;re not that far. Not at all. I was actually going to write some completion percentage, but I think I&#8217;ll just leave that as a mystery and surprise you when the time comes. But until then&#8230; some videos from the 2.0 world!
Animated TreeMaps
In order to show some of the new features I&#8217;ve been writing a [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;re not that far. Not at all. I was actually going to write some completion percentage, but I think I&#8217;ll just leave that as a mystery and surprise you when the time comes. But until then&#8230; some videos from the 2.0 world!</p>
<h4>Animated TreeMaps</h4>
<p>In order to show some of the new features I&#8217;ve been writing a simple example with TreeMap animations. TreeMap animations are integrated into the built-in classes of the Toolkit, but you can also create your own animations by altering either built-in Node/Edge params, or also canvas specific styles like shadows.</p>
<p>Here&#8217;s a short video of an Animated TreeMap, it also has animations when switching layouts. I think it&#8217;s better seen in fullscreen.</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/KaEvu5YRwLk&#038;hl=en_US&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/KaEvu5YRwLk&#038;hl=en_US&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<h4>Zooming and Panning</h4>
<p>The new Event system allows many customizations, such as Dragging and Dropping nodes, (right)clicking native Canvas nodes, etc. This will be the subject of a longer post, since there is a lot of machinery involving Native Canvas, SVG and HTML events, event delegation, etc. I&#8217;ve also been working in making a modular Canvas class enabling canvas background extensions.</p>
<p>Some of these changes had some desirable effects, such as enabling Panning and Zooming in a generic way, across all visualizations, as can be seen in this video:</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/CpXpAiZT1n0&#038;hl=en_US&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/CpXpAiZT1n0&#038;hl=en_US&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<h4>A Force Directed Example</h4>
<p>These features can be combined into useful and interesting examples. This Force Directed example uses the new Event system, zooming, panning and animations to make a complete graph editing tool. These are some of the graph interactions that can be made with the JavaScript InfoVis Toolkit (also better seen in fullscreen):</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/gSdlgRSEy_s&#038;hl=en_US&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/gSdlgRSEy_s&#038;hl=en_US&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p>I hope you liked it. I know I&#8217;m having a great time working in this project. </p>
<p>I&#8217;ll be back with more updates.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2010/05/30/news-from-the-javascript-infovis-toolkit-2-0-world/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Speaker at YOW! Australia 2010</title>
		<link>http://blog.thejit.org/2010/05/03/speaker-at-yow-australia-2010/</link>
		<comments>http://blog.thejit.org/2010/05/03/speaker-at-yow-australia-2010/#comments</comments>
		<pubDate>Mon, 03 May 2010 18:57:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[talk]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1456</guid>
		<description><![CDATA[Just a quick post to tell you that I&#8217;ve been invited to speak at YOW! Australia Developer Conference in Brisbane and Melbourne in December. YOW! is the new name for the JAOO (a.k.a Java and OO) conferences that have been running for over 13 years around the world already. YOW! Australia 2010 will include talks [...]]]></description>
			<content:encoded><![CDATA[<p>Just a quick post to tell you that I&#8217;ve been invited to speak at <a href="http://www.yowconference.com.au/">YOW! Australia Developer Conference</a> in Brisbane and Melbourne in December. YOW! is the new name for the <a href="http://jaoo.dk/">JAOO</a> (a.k.a Java and OO) conferences that have been running for over 13 years around the world already. <a href="http://www.yowconference.com.au/">YOW! Australia 2010</a> will include talks by <a href="http://www.yowconference.com.au/brisbane/speakers/details.html?speakerId=1616">Guy L. Steele, Jr.</a>, <a href="http://www.yowconference.com.au/brisbane/speakers/details.html?speakerId=1635">Erik Meijer</a> and me among others -yes, I can&#8217;t believe I just put myself in the same list as these people!.</p>
<p>Anyway, I&#8217;ll keep you updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2010/05/03/speaker-at-yow-australia-2010/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaScript Animations</title>
		<link>http://blog.thejit.org/2010/03/25/javascript-animations/</link>
		<comments>http://blog.thejit.org/2010/03/25/javascript-animations/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 20:44:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[animation]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1401</guid>
		<description><![CDATA[JavaScript animations are a key aspect of dynamic Web Sites and Application development. Moreover, most JavaScript Frameworks or Libraries provide APIs for dealing with at least three main things:

Advanced DOM manipulation
Ajax
Animations

When developing Web Sites most JavaScript effects involve rendered DOM Elements, but sometimes JavaScript animations are used in other contexts, like when using the Canvas. [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript animations are a key aspect of dynamic Web Sites and Application development. Moreover, most JavaScript Frameworks or Libraries provide APIs for dealing with at least three main things:</p>
<ul>
<li>Advanced DOM manipulation</li>
<li>Ajax</li>
<li>Animations</li>
</ul>
<p>When developing Web Sites most JavaScript effects involve rendered DOM Elements, but sometimes JavaScript animations are used in other contexts, like when using the Canvas. In the <a href="http://thejit.org">JavaScript InfoVis Toolkit</a> the main target of my animations are Graphs, and in the next version also Nodes and Edges as separate entities.</p>
<p>Today I&#8217;d like to describe how to create a generic animation class that can be used or extended for any purpose. I&#8217;ll try to be minimalistic and to present only the needed code for making animations. Then you might find useful to add some code to perform specific animation tasks targeting for example specific style properties of a DOM Element.</p>
<h4>Defining an Animation Class</h4>
<p>Before creating an Animation class we might want to consider what to expose as options to the user. The options I thought of are:</p>
<ul>
<li>The duration of the animation (in milliseconds)</li>
<li>The frames per second of the animation</li>
</ul>
<p>Additionally we&#8217;d like to add a couple of controllers, one when a step of the animation is executed and one when the animation has completed:</p>
<pre name="code" class="js:nogutter">
var options = {
  duration: 1000,
  fps: 40,
  onStep: function(delta) {},
  onComplete: function() {}
};
</pre>
<p><em>delta</em> gives us an idea of the <em>progress</em> of the animation. When the animation starts delta will be equal to zero. When the animation ends it&#8217;ll be equal to one.</p>
<p>We will also need a <em>start</em> method to trigger the animation and a <em>step</em> method that will compute <em>delta</em> at each step.</p>
<p>Now that we defined our options we can start thinking about our implementation.</p>
<h4>Implementing the Animation class</h4>
<p>Our Animation class will be a class constructor that sets all the options and properties that we defined before and a prototype with the methods <em>start</em> and <em>step</em>. The class could be used like this:</p>
<pre name="code" class="js:nogutter">
var fx = new Effect({
  duration: 1000,
  fps: 40,
  onStep: function(delta) {
    /* do stuff */
  },
  onComplete: function() {
    alert('done!');
  }
});
//start the animation
fx.start();
</pre>
<p>Here&#8217;s the code I came up with, inspired by the <a href="http://mootools.net">MooTools</a> Framework:</p>
<pre name="code" class="js:nogutter">
//define the class constructor
function Effect(opt) {
  this.opt = {
    duration: opt.duration || 1000,
    fps: opt.fps || 40,
    onStep: opt.onStep || function(){},
    onComplete: opt.onComplete || function(){}
  };
}

Effect.prototype = {
  //define how the animation starts
  start: function() {
    //return if we're currently performing an animation
    if(this.timer) return;
    //trigger the animation
    var that = this, fps = this.opt.fps;
    this.time = +new Date;
    this.timer = setInterval(function() { that.step(); },
                             Math.round(1000/fps));
  },
  //triggered at each interval step
  step: function() {
    var currentTime = +new Date, time = this.time, opt = this.opt;
   //check if the time interval already exceeds the duration
   if(currentTime < time + opt.duration) {
     //if not, calculate our animation progress
      var delta = (currentTime - time) / opt.duration;
      opt.onStep(delta);
    } else {
      //we already exceeded the duration, stop the effect
      //and call the onComplete callback
      this.timer = clearInterval(this.timer);
      opt.onStep(1);
      opt.onComplete();
    }
  }
};
</pre>
<p>One very common operation to do with delta is to change the interval [0, 1] of delta to our desired <em>from</em> and <em>to</em> values that we want to compute for our element. A clever thing to do would be to declare this method as a class method for Effect. We'll call it compute:</p>
<pre name="code" class="js:nogutter">
Effect.compute = function(from, to, delta) {
  return from + (to - from) * delta;
};
</pre>
<p>Now If we wanted for example to animate an element's width style from <em>0</em> to <em>10px</em> we could do:</p>
<pre name="code" class="js:nogutter">
var elem = document.getElementById("myElementId"),
    style = elem.style;
var fx = new Effect({
  duration: 500,
  onStep: function(delta) {
    style.width = Effect.compute(0, 10, delta) + 'px';
  }
});
fx.start();
</pre>
<h4>Extending the Effect class</h4>
<p>The animation code defined above could be extended in different ways. For example, this class could be slightly modified to accept a DOM element in its constructor and modify style properties of that element when performing an animation. The code could look like this:</p>
<pre name="code" class="js:nogutter">
var elem = document.getElementById("myElementId");
var fx = new Effect({
  element: elem,
  duration: 1000
});
fx.start({
  'width': [0, 20, 'px'],
  'height': [0, 5, 'em']
});
</pre>
<p>The code would now look more or less like this:</p>
<pre name="code" class="js:nogutter">
//define the class constructor
function Effect(opt) {
  this.opt = {
    element: opt.element,
    duration: opt.duration || 1000,
    fps: opt.fps || 40,
    onComplete: opt.onComplete || function(){}
  };
}

Effect.prototype = {
  //props contains a hash with style properties
  start: function(props) {
    if(this.timer) return;
    var that = this, fps = this.opt.fps;
    this.time = +new Date;
    this.timer = setInterval(function() { that.step(props); },
                             Math.round(1000/fps));
  },
  //triggered at each interval step
  step: function(props) {
     var currentTime = +new Date, time = this.time, opt = this.opt;
     if(currentTime < time + opt.duration) {
      var delta = (currentTime - time) / opt.duration;
     //set the element style properties
     this.setProps(opt.element, props, delta);
    } else {
      this.timer = clearInterval(this.timer);
      this.setProps(opt.element, props, 1);
      opt.onComplete();
    }
  },
  //set style properties. Properties must be
  //in camelcase format.
  setProps: function(elem, props, delta) {
    var style = elem.style;
    for(var prop in props) {
      var values = props[prop];
      style[prop] = Effect.compute(values[0], values[1], delta)
        + (values[2] || '');
    }
  }
};
</pre>
<p>Other extensions might involve normalizing style keywords, adding effect transitions, adding <em>pause</em> <em>resume</em> methods, and/or using more OO JS idioms when coding these classes.</p>
<p>I hope you got to know a little bit more about animation internals and please if you have any advice on this code, which as I told before is just for demonstration, I'll be pleased to hear you!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2010/03/25/javascript-animations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Voronoi Tessellation</title>
		<link>http://blog.thejit.org/2010/02/12/voronoi-tessellation/</link>
		<comments>http://blog.thejit.org/2010/02/12/voronoi-tessellation/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 21:19:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1332</guid>
		<description><![CDATA[This is going to be the first of a couple of posts related to Voronoi Tessellations, Centroidal Voronoi Tessellations and Voronoi TreeMaps. In this post I&#8217;ll explain what a Voronoi Tessellation is, what can it be used for, and also I&#8217;ll describe an interesting algorithm for creating a Voronoi Tessellation given a set of points [...]]]></description>
			<content:encoded><![CDATA[<p>This is going to be the first of a couple of posts related to Voronoi Tessellations, Centroidal Voronoi Tessellations and Voronoi TreeMaps. In this post I&#8217;ll explain what a Voronoi Tessellation is, what can it be used for, and also I&#8217;ll describe an interesting algorithm for creating a Voronoi Tessellation given a set of points (or sites as I&#8217;ll call them from now on).</p>
<h4>What is a Voronoi Tessellation?</h4>
<p><img src="/wp-content/voronoitessellation.png" style="border: 1px solid cyan; padding: 3px; margin: 5px 13px 5px 0pt; float: left;" /></p>
<p>Given a set <em>P := {p1, &#8230;, pn}</em> of sites, a Voronoi Tessellation is a subdivision of the space into <em>n cells</em>, one for each site in <em>P</em>, with the property that a point <em>q</em> lies in the cell corresponding to a site <em>pi</em> iff <em>d(pi, q) < d(pj, q)</em> for <em>i</em> distinct from <em>j</em>. The segments in a Voronoi Tessellation correspond to all points in the plane equidistant to the two nearest sites.<br />
Voronoi Tessellations have <a href="http://en.wikipedia.org/wiki/Voronoi_diagram#Applications">applications</a> in computer science, chemistry, etc. but I&#8217;m most interested in Voronoi Diagrams for constructing Voronoi TreeMaps (more on that in later posts).</p>
<h4>How do I create a Voronoi Tessellation?</h4>
<p>One algorithm for creating Voronoi Tessellations was discovered by <a href="http://ect.bell-labs.com/who/sjf/">Steven Fortune</a> in 1986. </p>
<p>This algorithm is described as a plane sweep algorithm. Fortune&#8217;s Algorithm maintains both a <em>sweep line</em> (in red) and a <em>beach line</em> (in black) which move through the plane as the algorithm progresses. </p>
<p><img src="/wp-content/Fortunes-algorithm.gif" style="border: 1px solid cyan; padding: 3px; margin-left:100px;" /></p>
<p>The structures used in this algorithm are an EventQueue, EdgeList and a binary Tree that tracks the state of the beach line.</p>
<p>The EventQueue stores two distinct type of events that are related to changes in the beach line. These events happen when:</p>
<ul>
<li>A site <em>s</em> crosses the sweep line: in this case a new parabola with minimum at <em>s</em> is added to the beach line. A Voronoi Edge is born.</li>
<li>A circle that touches three sites staying behind the sweep line is found and is tangent to the sweep line (see image below). A Voronoi Vertex is found.</li>
</ul>
<p><img src="/wp-content/fort2.png" style="border: 1px solid cyan; padding: 3px; margin: 7px auto; clear:both;" /></p>
<p>At each of these stages the EdgeList is updated until the algorithm is completed.</p>
<h4>Implementations</h4>
<p>I haven&#8217;t found any interesting implementation of this algorithm in JavaScript. Actually, I didn&#8217;t find a working implementation of this algorithm in JavaScript. There&#8217;s <a href="http://www.raymondhill.net/voronoi/voronoi.php">this version</a> of a JavaScript applet for making Voronoi Tessellations, but it doesn&#8217;t seem to work right (the corners of the image generally hold two or more sites in the same cell). Also, the code was based in a C# implementation and <a href="http://www.raymondhill.net/voronoi/voronoi.js">isn&#8217;t very pretty</a>. Then there&#8217;s <a href="http://jtauber.com/blog/2008/11/27/voronoi_canvas_tutorial_part_i/">this blog</a> that mentions the algorithm but there&#8217;s no visible implementation, just a JQuery demo that animates parabolas when a mouse crosses a site, but no Voronoi Diagram.</p>
<p>So I made my own implementation, which I tried to make as similar as possible to the original C implementation from Steven Fortune. If you click on the image you can <a href="/wp-content/voronoijs/voronoi.html">see it in action</a>. Just refresh the page for new Voronoi Tessellations of random positioned sites.</p>
<p><a href="/wp-content/voronoijs/voronoi.html" style="text-decoration:none;"><br />
<img src="/wp-content/voronoiimpl.png" style="border: 1px solid cyan; padding: 3px; margin: 7px auto; clear:both;" /><br />
</a> </p>
<p>Any comments or advices about how to make this implementation better are welcomed!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2010/02/12/voronoi-tessellation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ECMA Harmony and the Future of JavaScript</title>
		<link>http://blog.thejit.org/2009/11/08/ecma-harmony-and-the-future-of-javascript/</link>
		<comments>http://blog.thejit.org/2009/11/08/ecma-harmony-and-the-future-of-javascript/#comments</comments>
		<pubDate>Sun, 08 Nov 2009 22:14:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[ecma]]></category>
		<category><![CDATA[harmony]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1218</guid>
		<description><![CDATA[I like to see language implementors (or creators in this case) talk about the design challenges or choices they&#8217;re facing with in the next version of their languages. 
In this video Brendan Eich, the creator of JavaScript, talks about the ES 3.1/4/5 thingy and also explains what features will be added to JavaScript in some [...]]]></description>
			<content:encoded><![CDATA[<p>I like to see language implementors (or creators in this case) talk about the design challenges or choices they&#8217;re facing with in the next version of their languages. </p>
<p>In this video <a href="http://en.wikipedia.org/wiki/Brendan_Eich">Brendan Eich</a>, the creator of JavaScript, talks about the <em>ES 3.1/4/5</em> thingy and also explains what features will be added to JavaScript in some near future (at least for the ECMA standard).</p>
<p>I&#8217;ll add a couple of comments about the JS features I liked below the video.</p>
<div><object width="500" height="324"><param name="movie" value="http://d.yimg.com/m/up/ypp/default/player.swf"></param><param name="flashVars" value="vid=16429147&#038;"></param><param name="allowfullscreen" value="true"></param><param name="wmode" value="transparent"></param><embed width="500" height="324" allowFullScreen="true" src="http://d.yimg.com/m/up/ypp/default/player.swf" type="application/x-shockwave-flash" flashvars="vid=16429147&#038;"></embed></object></div>
<h4>New stuff I liked about the language</h4>
<p>Most of the things I liked about the new features of the language are related to Meta-Programming. These new features describe new behaviors in object properties, like <em>getters</em> and <em>setters</em>, but they are also related to object and property mutability, configuration, visibility, etc.</p>
<p><b>Getters and Setters</b></p>
<p>Getters and Setters were implemented by B.E. more than nine years ago at mozilla, but a new syntax is introduced in the standard by adding a static function to the <em>Object</em> class.</p>
<pre name="code" class="js:nogutter:nocontrols">
Object.defineProperty(obj, "length", {
  get: function() {
    return this.computeLength();
  },
  set: function(value) {
    this.changeLength(value);
  }
});
</pre>
<p>In this example the <em>defineProperty</em> static method of the <em>Object</em> class adds the <em>length</em> property to the <em>obj</em> object. The <em>get</em> and <em>set</em> methods will be called when accessing or modifying the <em>length</em> property.<br />
<em>Object.getOwnPropertyDescriptor</em> retrieves the property descriptor of the defined property.</p>
<p><b>Defining Methods and Richer Property Descriptors</b><br />
The <em>Object.defineProperty</em> method can also be used to define instance methods:</p>
<pre name="code" class="js:nogutter:nocontrols">
Object.defineProperty(Array.prototype, "inject", {
  value: function(memo, iterator, context) {
    iterator = iterator.bind(context);
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  configurable: false,
  enumerable: false,
  writable: false
});
</pre>
<p>The method does something similar as <em>inject_into</em> or <em>reduce</em> methods do in other languages:</p>
<pre name="code" class="js:nogutter:nocontrols">
[ 1, 2, 3 ].inject(0, function(a, b) { return a+b; }); //6
</pre>
<p>If <em>configurable=true</em>, the property will be enabled for deletion or to be changed in other ways.</p>
<p>You can set a property to be non-enumerable by setting <em>enumerable=false</em>, and it won&#8217;t be detected in a <em>for in</em> loop (or in any other <em>&#8220;prop&#8221; in obj</em> expression). This means that for example we could augment <em>Object.prototype</em> with methods without having to iterate through them in a <em>for in</em> loop.</p>
<p>The <em>writable</em> property if setted to <em>false</em> won&#8217;t allow you to change the value of that property.</p>
<p><b>Object.create</b></p>
<p>Still no support is added for classical inheritance patterns (which makes me happy I must confess).<br />
Instead, the differential inheritance pattern gets a function that had (somewhat) been implemented by frameworks like <a href="http://code.google.com/closure/">Closure</a>, <a href="http://mootools.net">MooTools</a> and others with the <a href="http://code.google.com/closure/library/docs/introduction.html#oop">inherits</a> and <a href="http://mootools.net/docs/core/Core/Core#merge">$merge</a> functions.<br />
<em>Object.create</em> can be used for implementing prototypical inheritance: you can create a new class <em>A</em> that inherits from <em>B</em> by cloning an object and augmenting it with a <em>Properties</em> object. For example:</p>
<pre name="code" class="js:nogutter:nocontrols">
var Person = function() {};
Person.prototype.eat = function() {
  alert("eating");
};
//Ninja extends Person
var Ninja = function() {};
Ninja.prototype = Object.create(Person.prototype, {
  doKungFu: function() {
    alert("wootoo");
  }
});

var n = new Ninja();
n.eat(); //eating
n.doKungFu(); //wootoo
</pre>
<p>However, don&#8217;t forget to instantiate the superclass in your subclass constructor:</p>
<pre name="code" class="js:nogutter:nocontrols">
var Point = function(x, y) {
  this.x = x;
  this.y = y;
};

Point.prototype.distanceToOrigin = function() {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};
//Complex extends Point
var Complex = function(x, y) {
  Point.call(this, x, y); //call the superclass
};

Complex.prototype = Object.create(Point.prototype, {
  add: function(complex) {
    this.x += complex.x;
    this.y += complex.y;
  }
});
</pre>
<p><b>Object.preventExtensions, Object.seal, Object.freeze</b></p>
<p>Mutability is nice but sometimes we need to make our objects immutable for design reasons, for security reasons. These methods change the mutability level of an object.</p>
<ul>
<li><em>Object.preventExtensions</em> prevents an object from extending (i.e adding new properties to it). Still the properties it has can be deleted and their value can be changed.</li>
<li><em>Object.seal</em> does everything <em>Object.preventExtensions</em> does and also sets <em>configurable=false</em> for its properties, so they can&#8217;t be deleted. The Object properties can be changed though.</li>
<li><em>Object.freeze</em> makes the object completely immutable. <em>Object.freeze</em> does the same <em>Object.preventExtensions</em> and <em>Object.seal</em> do but also sets <em>writable=false</em> for all object properties.</li>
</ul>
<p>I hope this was useful to you. There are a lot more interesting language features to come, so you can read the ECMA <a href="http://www.ecmascript.org/">draft</a> if you&#8217;re interested in knowing more about this new version.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2009/11/08/ecma-harmony-and-the-future-of-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sunburst Visualization</title>
		<link>http://blog.thejit.org/2009/10/05/sunburst-visualization/</link>
		<comments>http://blog.thejit.org/2009/10/05/sunburst-visualization/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 17:29:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript information visualization toolkit (JIT)]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[JIT]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1155</guid>
		<description><![CDATA[In a previous post I showed the ForceDirected visualization I&#8217;m working on for version 1.2 of the JavaScript InfoVis Toolkit, today I&#8217;d like to talk about another visualization I&#8217;ve been working on, the Sunburst Visualization.
What&#8217;s the Sunburst Visualization?
I guess an example could help here:

A Sunburst visualization is a radial space-filling visualization technique for displaying tree [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://blog.thejit.org/2009/09/30/force-directed-layouts/">previous post</a> I showed the ForceDirected visualization I&#8217;m working on for version 1.2 of the <a href="http://thejit.org">JavaScript InfoVis Toolkit</a>, today I&#8217;d like to talk about another visualization I&#8217;ve been working on, the <a href="http://www.cc.gatech.edu/gvu/ii/sunburst/">Sunburst Visualization</a>.</p>
<h4>What&#8217;s the Sunburst Visualization?</h4>
<p>I guess an example could help here:</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/iFiGpXbYRdU&#038;hl=en&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/iFiGpXbYRdU&#038;hl=en&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p>A Sunburst visualization is a radial space-filling visualization technique for displaying tree like structures. There are other space-filling visualization methods that use other visual encodings for describing hierarchies. For example, the Treemap is a space-filling visualization that uses &#8220;containment&#8221; to show &#8220;parent-child&#8221; relationships.</p>
<p>There are a couple of subtle changes that can improve the way the information is communicated by this visualization.</p>
<ul style="margin-bottom:20px;">
<li>The &#8220;classic&#8221; Sunburst visualization uses horizontal labels for node names. One problem with this is that as I mentioned in a <a href="http://blog.thejit.org/2009/08/30/html-svg-or-canvas-labels/">previous post</a> labels can be occluded. One solution for this is to rotate labels in a way that they&#8217;re not occluded.</li>
<li>
A simple yet important thing to do when rotating labels is to rotate the labels in a way that they&#8217;re always facing <em>up</em>.</p>
<div style="text-align:center">In this example some labels are upside-down:</div>
<p><img align="center" src="/wp-content/labels-updown.png" style="width: 231px; border: 1px solid magenta; margin: 5px auto 5px auto; padding: 3px;" /></p>
<div style="clear:both"></div>
<div style="text-align:center">A simple check could make labels more readable:</div>
<p><img align="center" src="/wp-content/rotated-labels.png" style="width: 313px; border: 1px solid magenta; margin: 5px auto 5px auto; padding: 3px;" /></p>
<div style="clear:both"></div>
<li>
Another interesting thing that can be used with the <a href="https://developer.mozilla.org/en/Drawing_text_using_a_canvas#section_4">Canvas Text API</a> is the <em>maxWidth</em> parameter. This is an optional parameter that can be used to try to force the text to fit some width. I use this parameter when plotting the Sunburst visualization:<br />
<img align="center" src="/wp-content/font-fitting.png" style="width: 270px; border: 1px solid magenta; margin: 5px auto 5px auto; padding: 3px;" />
</li>
</ul>
<h4>Node Styling and Behavior</h4>
<p>The visualization also implements events for hovering and clicking nodes. You can also provide any number of styles to be smoothly updated when hovering and clicking nodes. There&#8217;s also <em>onClick</em> and <em>onHover</em> callbacks that are called when a node is clicked or hovered respectively.<br />
For example, this is the configuration I used in the previous example:</p>
<pre name="code" class="js:nogutter:nocontrols">
        NodeStyles: {
          attachToDOM: false,
          attachToCanvas: true,
          stylesHover: {
            'color': '#d33'
          },
          stylesClick: {
            'color': '#3dd'
          },
          onClick: function(node) {
            //build right column relations list
            buildRightColumnRelationsList(node);

            //hide tip
            sb.tips.tip.style.display = 'none';

            //rotate
            sb.rotate(node, 'animate', {
              'duration': 1500,
              'transition': Trans.Quart.easeInOut
            });
          }
        },
</pre>
<p>You can also add tool-tips as I did in the example. The configuration I used was:</p>
<pre name="code" class="js:nogutter:nocontrols">
        Tips: {
          allow: true,
          attachToDOM: false,
          attachToCanvas: true,
          onShow: function(tip, node, elem) {
            tip.innerHTML = node.name;
          }
        },
</pre>
<p>Node styling and tool-tips can be attached to DOM elements (like HTML or SVG labels) or they can also be attached to the Canvas. The latter method uses an internal MouseEventManager to calculate the position of the mouse event and determine which node of the graph is being hovered or clicked.</p>
<h4>Collapsing and Expanding Subtrees</h4>
<p>I&#8217;ve been also implementing animations for collpasing/expanding subtrees:</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/ck3Mm9THtlY&#038;hl=en&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ck3Mm9THtlY&#038;hl=en&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p>The collapsing process reduces the angle span occupied by a parent node and sets its children alpha value to zero. There&#8217;s also a visual mark set for collapsed nodes.</p>
<p><img align="center" src="/wp-content/node-collapse3.png" style="border: 1px solid magenta; margin: 5px auto 5px auto; padding: 3px;" /></p>
<p>I hope you like this visualization. There&#8217;s still much work to do, mostly regarding browser compatibility. I&#8217;ll keep you up to date with the progress of this visualization and the next visualization I&#8217;ll be implementing in the next post <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2009/10/05/sunburst-visualization/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Force Directed Layouts</title>
		<link>http://blog.thejit.org/2009/09/30/force-directed-layouts/</link>
		<comments>http://blog.thejit.org/2009/09/30/force-directed-layouts/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 22:29:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript information visualization toolkit (JIT)]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[visualization]]></category>
		<category><![CDATA[information visualization]]></category>
		<category><![CDATA[JIT]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1098</guid>
		<description><![CDATA[I&#8217;m currently working on three new visualizations for the JavaScript InfoVis Toolkit that will be added in version 1.2. 
I started the development of these new visualizations a couple of weeks ago, and while trying to incorporate these new visualizations harmoniously into the Toolkit I&#8217;ve found myself considering new design and code abstractions I haven&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on three new visualizations for the <a href="http://thejit.org">JavaScript InfoVis Toolkit</a> that will be added in version 1.2. </p>
<p>I started the development of these new visualizations a couple of weeks ago, and while trying to incorporate these new visualizations harmoniously into the Toolkit I&#8217;ve found myself considering new design and code abstractions I haven&#8217;t thought about before. That&#8217;s good for the Toolkit, and also good for my brain <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>One of the visualizations I&#8217;ll be incorporating in the next major release is a Force-Directed visualization. I first want to thank <a href="http://www.marcuscobden.co.uk/">Marcus Cobden</a> for donating a lot of code related to this algorithm that you can find <a href="http://groups.google.com/group/javascript-information-visualization-toolkit/msg/05d16602f2449f3d">here</a>. </p>
<p>My code is based in his donation and also in a nice overview of Force-Directed layout algorithms that I&#8217;ve found <a href="http://www.cs.brown.edu/~rt/gdhandbook/chapters/force-directed.pdf" target="_blank">here</a>.</p>
<h4>So what are Force-Directed Layout Algorithms?</h4>
<p>Force-Directed Layout algorithms are graph drawing algorithms based only on information contained within the structure of the graph itself rather than relying on contextual information. The most straightforward Force-Directed algorithm uses repulsive forces between nodes and attractive forces between adjacent nodes. This physical model produces some local <em>minima</em> in which the graph, well, gets to a stable configuration and is drawn in an aesthetically pleasing way.</p>
<p>The main algorithm consists on a main loop that simulates the system for some iterations and then plots the graph. The system will consist on repulsive forces between all graph nodes and attractive forces between adjacent nodes. The force models considered correspond to <a href="http://en.wikipedia.org/wiki/Hooke%27s_law">Hooke&#8217;s law</a> and <a href="http://en.wikipedia.org/wiki/Coulomb%27s_law">Coulomb&#8217;s law</a>. </p>
<p>Here&#8217;s an example with some JSON data I also use for other examples at the <a href="http://thejit.org/demos">demos page</a>:</p>
<p><img src="/wp-content/force-directed.png" alt="Force Directed Image" style="border: 1px solid cyan; margin: 5px 13px 5px 0pt; padding: 3px; float: left;" /></p>
<p>There are lots of refinements and different methods for making Force-Directed Layouts. Some are just based on the model I described before, others are based on what&#8217;s called Graph Theoretic Distances: If for two adjacent nodes their ideal distance is set as <em>d</em>, then for nodes with shortest path distance of <em>n</em> their ideal layout distance should be <em>n * d</em>. Attractive and repulsive forces are used to make a graph system with random nodes positions get to a <em>local minima</em> based on these rules.</p>
<p>I implemented the first model I described. For each iteration the <em>computePositionStep</em> method is called to update all nodes positions based on attractive and repulsive forces. The formal parameters passed to the method are <em>property</em> which is an array of node properties which contain positions to be updated and <em>opt</em> which is an object containing layout options like generic repulsive and attractive force functions. <em>$C</em> creates a new <a href="http://thejit.org/docs/files/Complex-js.html">Complex Number</a>.</p>
<pre name="code" class="js:nogutter:nocontrols">
  computePositionStep: function(property, opt) {
    var graph = this.graph, GUtil = Graph.Util;
    var min = Math.min, max = Math.max;
    var dpos = $C(0, 0);
    //calculate repulsive forces
    GUtil.eachNode(graph, function(v) {
      //initialize disp
      $each(property, function(p) {
        v.disp[p].x = 0; v.disp[p].y = 0;
      });
      GUtil.eachNode(graph, function(u) {
        if(u.id != v.id) {
          $each(property, function(p) {
            var vp = v.getPos(p), up = u.getPos(p);
            dpos.x = vp.x - up.x;
            dpos.y = vp.y - up.y;
            var norm = dpos.norm() || 1;
            v.disp[p].$add(dpos
                .$scale(opt.nodef(norm) / norm));
          });
        }
      });
    });
    //calculate attractive forces
    var T = !!graph.getNode(this.root).visited;
    GUtil.eachNode(graph, function(node) {
      GUtil.eachAdjacency(node, function(adj) {
        var nodeTo = adj.nodeTo;
        if(!!nodeTo.visited === T) {
          $each(property, function(p) {
            var vp = node.getPos(p), up = nodeTo.getPos(p);
            dpos.x = vp.x - up.x;
            dpos.y = vp.y - up.y;
            var norm = dpos.norm() || 1;
            node.disp[p].$add(dpos.$scale(-opt.edgef(norm) / norm));
            nodeTo.disp[p].$add(dpos.$scale(-1));
          });
        }
      });
      node.visited = !T;
    });
    //arrange positions to fit the canvas
    var t = opt.t, w2 = opt.width / 2, h2 = opt.height / 2;
    GUtil.eachNode(graph, function(u) {
      $each(property, function(p) {
        var disp = u.disp[p];
        var norm = disp.norm() || 1;
        var p = u.getPos(p);
        p.$add($C(disp.x * min(Math.abs(disp.x), t) / norm,
            disp.y * min(Math.abs(disp.y), t) / norm));
        p.x = min(w2, max(-w2, p.x));
        p.y = min(h2, max(-h2, p.y));
      });
    });
  }
</pre>
<p>You can find more information about this algorithm in <a href="http://www.cs.brown.edu/~rt/gdhandbook/chapters/force-directed.pdf">this overview of Force-Directed algorithms</a>.<br />
This method is called multiple times to provide a final layout, for example like this:</p>
<pre name="code" class="js:nogutter:nocontrols">
      for(var i=0; i &lt; times; i++) {
        opt.t = opt.tstart * (1 - i/(times -1));
        this.computePositionStep(property, opt);
      }
</pre>
<p>Where <em>times</em> corresponds to the number of iterations of the simulation, and is generally <em>&gt; 50</em> and <em>t</em> can be thought as the global temperature of a system that gets cooler with each iteration.</p>
<h4>Performance</h4>
<p>Although there are a couple of methods to reduce the complexity of this algorithm, this implementation runs like <em>O(V^3)</em>, which can be considered as really bad performance.</p>
<p>This is not desirable for real-time interactive visualizations, in which everlasting computation algorithms can lead to blocking browser popups like <em>&#8220;This Script is Taking too long&#8230;&#8221;</em> or things like that.</p>
<p>One way you can avoid these popups is by making incremental computations. This can be done by splitting the main algorithm that has for example 100 iterations into smaller pieces of 20 iterations each. The main iteration loop could then be changed into something like this:</p>
<pre name="code" class="js:nogutter:nocontrols">
  computePositions: function(property, opt, incremental) {
    var times = this.config.iterations, i = 0, that = this;
    if(incremental) {
      (function iter() {
        for(var total=incremental.iter, j=0; j&lt;total; j++) {
          opt.t = opt.tstart * (1 - i++/(times -1));
          that.computePositionStep(property, opt);
          if(i >= times) {
            incremental.onComplete();
            return;
          }
        }
        incremental.onStep(Math.round(i / (times -1) * 100));
        setTimeout(iter, 1);
      })();
    } else {
      for(; i < times; i++) {
        opt.t = opt.tstart * (1 - i/(times -1));
        this.computePositionStep(property, opt);
      }
    }
  }
</pre>
<p>This method could be called for example like this:</p>
<pre name="code" class="js:nogutter:nocontrols">
    //compute positions incrementally and animate.
    fd.computePositions(property, opt, {
      iter: 20,
      onStep: function(perc) {
        Log.write(perc + '% loaded...');
      },
      onComplete: function() {
        Log.write('done');
       fd.animate();
      }
    });
</pre>
<p>And the main computation would be split into smaller parts calling on each step of the computation the <em>onStep</em> callback.</p>
<h4>Graph Operations</h4>
<p>For graph operations (Adding/Removing nodes and edges, Graph Sum and Graph Morphing) I make all iterations in the first layout and then only apply 20 iterations after some operation has been completed. Here's a video:</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/q8bY-1Lseh0&#038;hl=en&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/q8bY-1Lseh0&#038;hl=en&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<h4>When (*not*) to use Force-Directed Layouts</h4>
<p>Force-Directed Layouts can be a good choice when you're drawing general graphs and you don't have domain specific (or any other topological) information about them.<br />
Tree structures however are a special case of graphs: this means that tree structures have more constrains and therefore there's more contextual information for drawing a Tree than for drawing a general graph.<br />
Also, Trees are easier to grasp for the human eye than "general graphs". There's that intrinsic notion of hierarchy that can be used to draw aesthetically pleasing graph layouts. Think about the "general graph" layouts that start with the drawing of a <a href="http://en.wikipedia.org/wiki/Spanning_tree">spanning tree</a> and then add the "extra edges" to complete the graph structure (for example <a href="http://thejit.org/Jit/Examples/RGraph/example3.html">here</a> and <a href="http://thejit.org/Jit/Examples/Hypertree/example3.html">here</a>). The Multitrees method I mentioned <a href="http://blog.thejit.org/2009/08/16/multitrees-part-1/">a couple of posts ago</a> was also developed to try to extract more contextual information about a graph and draw it based on a notion of partial hierarchy.</p>
<p>Because of this, in my opinion, it wouldn't be wise to plot Trees that have many nodes with this Force-Directed algorithm: this extra-information about trees isn't used in this layout. However, if you're planning on drawing general graphs and you don't have any other information about them, then this algorithm can detect interesting symmetries and make aesthetically pleasing drawings.</p>
<p>I'll keep you updated with the other visualizations I'm working on in the next posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2009/09/30/force-directed-layouts/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>HTML, SVG or Canvas Labels?</title>
		<link>http://blog.thejit.org/2009/08/30/html-svg-or-canvas-labels/</link>
		<comments>http://blog.thejit.org/2009/08/30/html-svg-or-canvas-labels/#comments</comments>
		<pubDate>Sun, 30 Aug 2009 11:44:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript information visualization toolkit (JIT)]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[labels]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[svg]]></category>

		<guid isPermaLink="false">http://blog.thejit.org/?p=1077</guid>
		<description><![CDATA[As you might know, the JavaScript InfoVis Toolkit uses the HTML5 Canvas element for plotting and animating graphs. This is all very nice, Canvas performance compared to other techniques for plotting these things (SVG for example) is by far superior. But of course, there are drawbacks.
Canvas better performance is due to the fact that there [...]]]></description>
			<content:encoded><![CDATA[<p>As you might know, the <a href="http://thejit.org">JavaScript InfoVis Toolkit</a> uses the HTML5 Canvas element for plotting and animating graphs. This is all very nice, Canvas performance compared to other techniques for plotting these things (SVG for example) is by far superior. But of course, there are drawbacks.</p>
<p>Canvas better performance is due to the fact that there are no tracked elements: the Canvas is simply an image and you&#8217;re drawing there just like you&#8217;d be drawing something in <em>paint</em>. One big problem is that there&#8217;s no native possibility to add events to what&#8217;s drawn in Canvas, like a plotted node, edge or label.</p>
<p>As opposed to Canvas, SVG has a DOM/XML like spec: you have all these tags (<b>&lt;g&gt; &lt;text&gt; &lt;rect&gt;</b>) and each of them is just like a DOM element: you can add click event handlers, individual styling with CSS, etc.<br />
Having to keep track of all these elements and handling a DOM-tree makes the performance of SVG not suitable for visualizing (and animating) medium to large datasets on the web.</p>
<h4>Using HTML labels</h4>
<p>Just like SVG, HTML is a DOM/XML-like spec, where you can add event handlers to each element. Also, every web developer knows HTML so exposing HTML labels through user-defined controller methods in the library seemed to me like a good choice. For controller methods like <em>onCreateLabel</em> or <em>onPlaceLabel</em> an HTML element is passed and the user can style or add event-handlers to it.</p>
<p>For example, here&#8217;s a fragment of the code used in the <a href="http://thejit.org/Jit/Examples/RGraph/example1.html">RGraph demo</a>. You can see the rest of the code <a href="http://thejit.org/Jit/Examples/RGraph/example1.code.html">here</a>:</p>
<pre name="code" class="js:nogutter:nocontrols">
        //Add the name of the node in the correponding label
        //and a click handler to move the graph.
        //This method is called once, on label creation.
        onCreateLabel: function(domElement, node){
            domElement.innerHTML = node.name;
            domElement.onclick = function(){
                rgraph.onClick(node.id);
            };
        },
        //Change some label dom properties.
        //This method is called each time a label is plotted.
        onPlaceLabel: function(domElement, node){
            var style = domElement.style;
            style.display = '';
            style.cursor = 'pointer';

            if (node._depth <= 1) {
                style.fontSize = "0.8em";
                style.color = "#ccc";

            } else if(node._depth == 2){
                style.fontSize = "0.7em";
                style.color = "#494949";

            } else {
                style.display = 'none';
            }

            var left = parseInt(style.left);
            var w = domElement.offsetWidth;
            style.left = (left - w / 2) + 'px';
        }
</pre>
<p>In my opinion this is a good approach, good points are:</p>
<ol>
<li>I'm using well known HTML elements.</li>
<li>Dealing with DOM elements let's you add event handlers, individual styling and things like that.</li>
</ol>
<p>Weak points are:</p>
<ol>
<li>I'm using a DOM tree, which means that if labels are plotted at all times I'm exhaustively updating the DOM and this might lead to performance problems.</li>
<li>HTML is good for structuring pages, but for example you might want to apply transformations to HTML elements (like rotating labels, etc), and these aren't supported by all browsers yet.
<p>So one of the problems that might arise is, for example, the fact that in radial layouts labels might be occluded:</p>
<p><img src="/wp-content/occlude.png" title="occluded labels" alt="occluded labels" style="border: 1px solid cyan; margin: 7px auto; padding: 1px;" />
</li>
</ol>
<h4> Using SVG labels</h4>
<p>So I began exploring other possibilities to create labels. For this I abstracted the Label interface I had and split it into:</p>
<ul>
<li>Graph.Label.Native <em>(for native canvas labels)</em></li>
<li>Graph.Label.DOM<em>(abstract class for dom elements)</em></li>
<li>Graph.Label.HTML<em>(extends the DOM interface with HTML specific stuff)</em></li>
<li>Graph.Label.SVG<em>(extends the DOM interface with SVG specific stuff)</em></li>
</ul>
<p>I also modified the <em>Canvas</em> class so you can specify the type of labels you want to use, <em>labels:'HTML'</em>, <em>labels:'SVG'</em> or <em>labels:'Native'</em>. Default's <em>HTML</em>.</p>
<p>The same RGraph example code now would look like this:</p>
<pre name="code" class="js:nogutter:nocontrols">
        //Add the name of the node in the correponding label
        //and a click handler to move the graph.
        //This method is called once, on label creation.
        onCreateLabel: function(domElement, node){
            domElement.firstChild
              .appendChild(document
                .createTextNode(node.name));
            domElement.onclick = function(){
                rgraph.onClick(node.id, {
                  hideLabels: false
                });
            };
        },
        //Change some label dom properties.
        //This method is called each time a label is plotted.
        onPlaceLabel: function(domElement, node){
            var bb = domElement.getBBox();
            if(bb) {
              //center the label
              var x = domElement.getAttribute('x');
              var y = domElement.getAttribute('y');
              //get polar coordinates
              var p = node.pos.getp(true);
              //get angle in degrees
              var pi = Math.PI;
              var cond = (p.theta > pi/2 &#038;&#038; p.theta < 3* pi /2);
              if(cond) {
                domElement.setAttribute('x', x - bb.width );
                domElement.setAttribute('y', y - bb.height );
              } else if(node.id == rgraph.root) {
                domElement.setAttribute('x', x - bb.width/2);
              }

              var thetap =  cond? p.theta + pi : p.theta;
                domElement.setAttribute('transform', 'rotate('
                + thetap * 360 / (2 * pi) + ' ' + x + ' ' + y + ')');
            }
</pre>
<p>This code does a little bit more than just plotting the label, it rotates the labels so they're not occluded:</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/d4moBOf-Fvs&#038;hl=en&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/d4moBOf-Fvs&#038;hl=en&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p>Good points of this approach are:</p>
<ul>
<li>Just like with any other DOM element, you can add event handlers.</li>
<li>You can apply transformations to labels.</li>
</ul>
<p>Weak points:</p>
<ul>
<li>Performance, for the same reasons as HTML.</li>
<li>IE does not support SVG.</li>
</ul>
<p>Bonus good point: Google is making work SVG in IE with some open source library that works apparently the same as the <a href="http://excanvas.sourceforge.net/">ExCanvas</a> library. Here's the <a href="http://code.google.com/p/svgweb/">Open Source project</a> that will be presented <a href="http://ajaxian.com/archives/svg-open-2009-svg-coming-of-age">here</a>.</p>
<p>That's like the main reason why I've been considering a different approach for labels <img src='http://blog.thejit.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h4>Native Canvas labels</h4>
<p>Native Canvas labels make use of the HTML5 Canvas text API to plot labels.<br />
Since the labels are just <em>painted</em> in the Canvas there's no DOM tree to update, and performance is good.<br />
The Canvas text API has <em>fillText</em>, <em>strokeText</em> and <em>measureText</em> as methods. You can read more about the Canvas Text API <a href="https://developer.mozilla.org/en/Drawing_text_using_a_canvas">here</a>.</p>
<p>This is the code I added to the <em>Graph.Label.Native</em> class:</p>
<pre name="code" class="js:nogutter:nocontrols">
Graph.Label.Native = new Class({

    plotLabel: function(canvas, node, controller) {
        var ctx = canvas.getCtx();
        var coord = node.pos.getc(true);
        ctx.fillText(node.name, coord.x, coord.y);
    },

    hideLabel: $empty
});
</pre>
<p>A very good point about this approach is <em>performance</em>. Also, the code is simpler. You don't have to keep a labelContainer and update DOM labels each time you're making an animation.</p>
<p>Weak points are:</p>
<ul>
<li>Opera does not support this feature.</li>
<li>You can't <em>natively</em> add event handlers to labels. I think I've seen someone do something similar for text in processing, but I'm not sure there's a good way of doing this without keeping track of the position of each label and perform a check each time a click is triggered in the canvas element.</li>
<li>I should change the way I define controller methods, in order to be able to pass a custom <em>label object</em> with x, y, theta, rho, width, height properties that could be modified on the fly, and then translate these changes into <em>translate</em> and <em>rotate</em> native canvas calls to be able to plot the text the way the user wants it. This seems just to damn complicated.... But I'll consider it.</li>
</ul>
<p>Anyway, these are the methods I've found to plot labels into graphs. </p>
<p>Which one do you think is the best?<br />
Do you know about any other approaches I could take to solve this problem?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.thejit.org/2009/08/30/html-svg-or-canvas-labels/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
