FaviconThe Quick & Easy Way of Getting into YUI: SimpleYUI 3 Sep 2010, 8:00 am

The Yahoo! YUI is an incredibly feature-rich JavaScript library with a LOT of functionality but getting your head around all of those features can be tough. The YUI team wants to help developers get up and running more quickly and announced yesterday the release of SimpleYUI; a basic and more streamlined version of the YUI library.

SimpleYUI will contain basic DOM access and manipulation including support for CSS 3 selectors in the selector engine, animations via the new transition module, the event system, Ajax and JSON support.

The great thing is that when you're ready to leverage more advanced features like managed attributes and custom events, you still have the ability to do on-demand loading just like you'd expect from the full-featured version of YUI. This includes any YUI 2 or 3 component or YUI 3 Gallery module.

JAVASCRIPT:
<script type="text/javascript" src="http://yui.yahooapis.com/3.2.0pr2/build/quickyui/quickyui-min.js"></script>

<script>
Y.use('dd-drag','yui2-datatable', 'gallery-accordion', function(Y) {
     
      // here you can use YUI 3 Drag and drop, YUI 2 DataTable, Accordian or any other control contributed to the gallery by the community   

});
</script>
 

YUI team member Eric Miraglia put up a nice post about SimpleYUI which shows you some of the goodness include.

FaviconA Periodic Table for HTML 3 Sep 2010, 6:30 am

Josh Duck has put together a fun and useful list of the 104 elements currently in the HTML5 working draft but organized like a periodic table of elements:

When you click on one of the tags more information appears:

Who says chemistry can't be fun?

[via Jackson Harper]

FaviconThe Node.js now running on webOS – and more Web improvements 2 Sep 2010, 9:20 pm

By Dion Almaer
webOS 2.0 SDK has just launched, and it has node.js built in (and more). The following is taken from my personal blog

At our last Palm Developer Day, Ben and I discussed future APIs for webOS including "JavaScript services" as a way to write code that runs on the other side of the device service bus using JavaScript.

If you think about it, node delivers a services platform for the cloud, so is there a way that we could work together? We got together with Ryan Dahl of Node to try this out, and it turns out that node works fantastically well on a mobile device! Major kudos should go to the V8 team for creating a great VM and to Ryan for writing efficient code that scaled down from the cloud to the device.

Today we announce that node is part of webOS 2.0:

The popular Node.js runtime environment is built into webOS 2.0, which means that you can now develop not just webOS apps but also services in JavaScript. The active Node ecosystem is on hand to provide community support and a rapidly growing library of modules that you can use in your webOS services.

Besides powering the new Synergy APIs, JavaScript services strengthen webOS's support for background processing and add new capabilities—like low-level networking, file system access, and binary data processing—to the web technology stack.

I am really excited about this move for us. The node community is top class. I get to see this time and time again, most recently over the weekend and this week as I judge the node knockout. There is magic in the air with Node. It feels like the Rails days. I remember being so happy to jump to Rails and get away from the heavy world of Enterprise Java. It was a breath of fresh air to not have to argue with folks about every piece of the stack. "What about JSF with HiveMind and Commons-Logging and ...." Argh! Too. Much. Choice. And, a logging abstraction above Log4J was hilarious :)

Node is low level, yet simple. It is more like Sinatra than Rails. The event-based opinions keep you in good stead, and with cloud solutions such as Heroku and no.de you have great deployment stories, unlike Rails back in the day.

If you check out the modules that are growing daily, and the fun real-time hacks from the knockout you will get a good feel for node.

It feels great to have webOS as the first mobile device that embeds node. With db8 we offer a JSON store than can sync to the cloud (e.g. sync with CouchDB). This stack is starting to look pretty great.

FaviconA Drumbeat for the Open Web 2 Sep 2010, 6:30 am

I stumbled on the Mozilla Foundation's Drumbeat project recently:

Drumbeat gathers smart, creative people like you around big ideas, practical projects and local events that improve the open web.

It's very well done combination of projects + community.

Drumbeat Toronto Meetup

There's a whole slew of cool projects already one here. A small sample:





FaviconExtending HTML5 1 Sep 2010, 6:30 am


Google Rich Snippet
Oli Studholme has an excellent new article on HTML5 Doctor on the different ways HTML5 can be extended with things like microformats, the link tag, and more. Why would you want to do this?

While HTML5 has a bunch of semantic elements, including new ones like <article> and <nav>, sometimes there just isn’t an element with the right meaning. What we want are ways to extend what we’ve got, to add extra semantics that are machine-readable — data that a browser, script, or robot can use.

First, he starts with the options HTML4 gave us and what options we now have with HTML5:

There were five fundamental ways we could extend HTML 4:

  • <meta> element
  • class attribute
  • rel attribute
  • rev attribute
  • profile attribute

In HTML5, rev has fallen by the wayside, becoming obsolete since hardly anyone used it correctly, and because it can be replaced by relprofile is also obsolete, and there is no support for namespaces in HTML5. However,<meta>class, and rel are all in HTML5. In fact, <meta> now has spec-defined names and a way to submit newname values, and rel has several new link types defined in the HTML5 specification and a way to submit more too.

Even better, WAI-ARIA’s role and aria-* attributes are allowed in HTML5, and HTML5 validators can check HTML5+ ARIA. Other new methods of extending HTML5 include custom data attributes (data-*), microdata, and RDFa. Guest doctor Chris Bewick introduced us to HTML5’s new data-* attribute system, which is perfect for adding private custom data for JavaScript, and we’ll no doubt meet microdata and RDFa sooner or later.

Finally there are microformats. As Dr. Bruce touched on microformats in his article on the <time> element, let’s delve a little deeper into what microformats are and how to use them in HTML5.

Oli then does a great deep dive of microformats, going over the different ones defined by the community to date (there are 33 microformat specifications!) and covering some of the common patterns that you can use if you need to roll your own microformat. If you've been wondering how to use things like hCard, hCalendar, XHTML Friends Network (XFN), etc. in your own systems then definitely give this article a gander.

[via John Allsop]

FaviconRaphaël 1.5 Released 31 Aug 2010, 6:30 am


Dmitry Baranovskiy and team have released another version of Raphaël, an excellent drawing and animation library backed by SVG (VML on Internet Explorer). New features in Raphaël 1.5 include custom attributes and keyframes. Keyframes can be defined similar to CSS3 Animations:

JAVASCRIPT:
el.animate({
    "20%": {cy: 200, easing: ">"},
    "40%": {cy: 100},
    "60%": {cy: 200},
    "80%": {cy: 300, callback: function () {}},
    "100%": {cy: 200}
}, 5000);
 

Check out a demo of the new keyframe animation.

Custom attributes is also a new feature that makes it easier to do things like animating a portion of an attribute segment (demo).

Full release notes:

  • fixed IE8 issue with the HTML element named Raphael
  • fixed precision for arcs in IE
  • added caching to getPointAtSegmentLength function
  • added ability to do more than one animation of an element at the same time
  • added "cubic-bezier()" as an easing method
  • added new syntax for animation (keyframes)
  • hsl2rgb now accept h as degree (0..360), s and b as % (0..100)
  • show="new" instead of target="blank" for SVG
  • added angle method
  • added snapTo method
  • cached popup || activeX for IE
  • fixed insertAfter
  • fixed timeouts for animation
  • added customAttributes

BTW I just noticed that Dmitry is now at Sencha; they're assembling quite the team! Congrats Dmitry!

FaviconNew SVG Web Release: Owlephant 30 Aug 2010, 7:05 pm

The SVG Web team has announced a new release. SVG Web is a drop in JavaScript library that makes it easy to display SVG graphics on Internet Explorer 6, 7, and 8 using Flash.

The new SVG Web release, like all of their releases, is named after especially silly D&D monsters. The new release is code named Owlephant:

You've heard of Elephants, you've heard of Owls… put them together and you get the fearsome Owlephant. If you encounter one, be sure it will be the last thing you ever, um, encounter. Hoot…. stomp!

With this release SVG Web now scores 55.45% on the SVG compatibility charts, almost at the same level as IE 9 (58%).

Major aspects of this new release includes overhauls and fixes for gradients, clipping, events, text placement, and more. It also includes a huge step forward in SMIL animation support, including being able to animate path segments and interpolate their values, scripting SMIL with JavaScript, and more.

This release has been built by the community, with major contributions from Bruce Duncan from VisualMining.com; Ken Stacey from SVGMaker.com; and the always awesome (and project co-leader) Rick Masters. Thanks to the many people like Michael Neutze, Bruce Rindahl, and more for their bug testing and evangelism!

Everything fixed in this release:

  • Issue 471 : Radial gradient different between Flash and Native renders
  • Issue 349 : gradients with bounding box cooordinates are positioned wrongly on circles
  • Issue 475 : 'this' not getting set correctly in SVG element event callback
  • Issue 477 : The change in the size of the ClipPath area is not reflected by Flash Renderer.
  • Issue 483 : Changing gradient stop does not trigger redraw of referencing elements
  • Issue 484 : Dynamic clip-path attribute changes are not reflected.
  • Issue 476 : set Element Problems and numerous SMIL issues
  • Issue 489 : Support beginElement() for animation elements
  • Issue 494 : SVGTextNode.onDrawGlyph not removing glyph clones
  • Issue 495 : Support units-per-em on SVG fonts
  • Issue 492 : 'button' property missing in mouse event object
  • Issue 472 : get svg.js even more compressed with Google's closure compiler (30K reduction)
  • Issue 499 : Object loaded svg with scripts not firing window load or SVGLoad event
  • Issue 488 : Updating styles via Javascript does not visibly update child nodes in IE/Flash
  • Issue 496 : Support exponents in path values
  • Issue 502 : Radial Gradient userSpaceOnUse Matrix calculated incorrectly
  • Issue 503 : Radial Gradient focalLen not used for stroke
  • Issue 504 : Radial Gradient userSpaceOnUse Matrix calculated incorrectly for SVGCircle and SVGEllipse nodes
  • Issue 497 : bad 'target' when click on text node
  • Issue 342 : Event handler fires only after second mouse click.
  • Issue 507 : Namespaced elements not allowed until svg element added to page
  • Issue 158: Rotated text not rendering for native fonts (Mostly Fixed)
  • Issue 467 : Namespace exception loading video example in IE8
  • Issue 510 : Font Family not used when surrounded by single quotes in Flash 10.1
  • Issue 57 : SVG default fill-rule 'nonzero' not supported by flash 9
  • Issue 123 : Nested svg elements don't show up in the DOM correctly
  • Issue 145: dynamically creating SMIL elements and attributes
  • Issue 356 : Show SVG Web Release Name and Revision in Right Click Menu
  • Issue 513 : getElementsByTagNameNS returning text nodes
  • Issue 515 : Call handleEvent on EventListener objects passed to addEventListener
  • Issue 517 : Elements with fill set to 'none' should produce mouse events but do not
  • Issue 518 : Avoid redraw on change to pointer-events attribute
  • Issue 523 : Event listener from object element may be applied to svg element erroneously
  • Issue 522 : Need way to create element with self declared namespace
  • Issue 525 : Image element not respecting display='none'
  • Issue 524 : Jquery $(window).scroll event will not fire
  • Issue 527 : Excessive messages for detached event listeners
  • Issue 528 : Exception if remove event listener from detached element, then add to document
  • Issue 321 : Support for animating path 'd' attribute (and interpolate between values)
  • Issue 514 : clip-path not used when part of style attribute value
  • Issue 526 : Object using clip path cannot have its opacity animated
  • Issue 535 : Nested svg disappears when animated
  • Issue 536 : Problems tracking whether elements attached to document or not
  • Issue 537 : Animation added in onload listener does not initialize
  • Issue 538 : Node removed while invalid causes endless frame listening
  • Issue 539 : Animation with invalid or forward href causes exception
  • Issue 540 : script stack space quota is exhausted by large svg file
  • Issue 511 : Keyboard events are not supported properly

Download the release now and get started!

Please note that there are some breaking changes in this release that will affect code that uses older versions of SVG Web; more details here. Also note that SVG Web does not yet support the native SVG functionality in IE 9 preview releases.

[Disclosure: I'm a member of the SVG Web team]

FaviconDesign 3D Models in a Browser 30 Aug 2010, 7:00 am

Perfect for a Monday is a cool 3D model editor built using the Canvas tag and created by Jayesh Salvi:

FaviconView Source Tutorial: Content Site Using HTML5 Canvas + CSS3 30 Aug 2010, 6:00 am

Via Phil Franks comes an interesting HTML5/CSS3 site for There Studio, which is a kind of coworking space in London:

The site itself has a number of circles with information bouncing on the screen that respond to mouse clicks and moves.

Let's crack the site open using View Source and see how they are doing things. First, they have a repeated background with a little plus symbol with the following style rule on the <body> tag:

CSS:
background: #ddd url('../images/bg.gif') 50% 0 repeat fixed;
 

The textual content in each of the circles is clean semantic HTML that is search engine friendly:

HTML:
<div class="section who first">
  <h3>Who</h3>
  <p>Creatives, makers, thinkers <span class="ampersand">&amp;</span> doers</p>
</div>

To turn that into this:

The <h3> is first transformed into having an underline with the padding and margin being on the bottom:

CSS:
h3 {
        border-bottom: 1px solid #ccc;
        display: block;
        font-size: 25px;
        font-weight: normal;
        padding: 0 0 10px;
        margin: 0 0 8px;
}
 

JavaScript creates the circle. The script tags themselves are at the end of the HTML page at the bottom of the <body> tag, a good performance practice in general.

The heart of drawing each circle is in the createBall and createContentBall methods. If a ball will have HTML content, then the createContentBall method is used, otherwise the createBall method is used. Let's look at the createContentBall method; we'll break it down:

JAVASCRIPT:
function createContentBall(className,size,color,html) {
  var element = document.createElement( 'div' );
  element.className = className;
  element.width = element.height = size;
  element.style.position = 'absolute';
  element.style.left = -size + 'px';
  element.style.top = -size + 'px';
  element.style.cursor = "default";
  canvas.appendChild(element);
  elements.push( element );
  var circle = document.createElement( 'canvas' );
  circle.width = size;
  circle.height = size;
  if (className !=='image' && className !=='image first') {
    var graphics = circle.getContext( '2d' );
    graphics.fillStyle = color;
    graphics.beginPath();
    graphics.arc( size * .5, size * .5, size * .5, 0, PI2, true );
    graphics.closePath();
    graphics.fill();
  }
  element.appendChild( circle );
  content = document.createElement( 'div' );
  content.className = "content";
  content.onSelectStart = null;
  content.innerHTML = html;
  element.appendChild(content);
  if (className !=='image' && className !=='image first' ) {
    content.style.width = (size - contentPadding*2) + 'px';
    content.style.left = (((size - content.clientWidth) / 2)) +'px';
    content.style.top = ((size - content.clientHeight) / 2) +'px';
  }
  var b2body = new b2BodyDef();
  var circle = new b2CircleDef();
  circle.radius = size / 2;
  circle.density = ballDensity;
  circle.friction = ballFriction;
  circle.restitution = ballRestitution;
  b2body.AddShape(circle);
  b2body.userData = {element: element};
  b2body.position.Set( Math.random() * stage[2], Math.random() * (stage[3]-size) + size/2);
  b2body.linearVelocity.Set( Math.random() * 200, Math.random() * 200 );
  bodies.push( world.CreateBody(b2body) );
}
 

First, we create an absolutely positioned DIV that will house our Canvas tag:

JAVASCRIPT:
var element = document.createElement( 'div' );
element.className = className;
element.width = element.height = size;
element.style.position = 'absolute';
element.style.left = -size + 'px';
element.style.top = -size + 'px';
element.style.cursor = "default";
canvas.appendChild(element);
elements.push( element );
 

Then we draw the actual circle itself using the Canvas tag and append it to our container DIV (Note that an SVG circle created programmatically could have also been used here):

JAVASCRIPT:
var circle = document.createElement( 'canvas' );
circle.width = size;
circle.height = size;
if (className !=='image' && className !=='image first') {
   var graphics = circle.getContext( '2d' );
   graphics.fillStyle = color;
   graphics.beginPath();
   graphics.arc( size * .5, size * .5, size * .5, 0, PI2, true );
   graphics.closePath();
   graphics.fill();
}
element.appendChild( circle );
 

Then we create another DIV to house the HTML content itself:

JAVASCRIPT:
content = document.createElement( 'div' );
content.className = "content";
content.onSelectStart = null;
content.innerHTML = html;
element.appendChild(content);
if (className !=='image' && className !=='image first' ) {
   content.style.width = (size - contentPadding*2) + 'px';
   content.style.left = (((size - content.clientWidth) / 2)) +'px';
   content.style.top = ((size - content.clientHeight) / 2) +'px';
}
 

Notice that we are setting content.onSelectStart to null above; this is so that when you run the mouse button over the text it doesn't select (An alternative way to do this is to use the HTML pointer-events CSS property).

Next comes code to deal with the physics of the circles, which uses Box2D.js, a JavaScript physics engine ported from Flash:

JAVASCRIPT:
var b2body = new b2BodyDef();
var circle = new b2CircleDef();
circle.radius = size / 2;
circle.density = ballDensity;
circle.friction = ballFriction;
circle.restitution = ballRestitution;
b2body.AddShape(circle);
b2body.userData = {element: element};
b2body.position.Set( Math.random() * stage[2], Math.random() * (stage[3]-size) + size/2);
b2body.linearVelocity.Set( Math.random() * 200, Math.random() * 200 );
bodies.push( world.CreateBody(b2body) );
 

Basically, we define a circle, give it a radius, density, friction, and restitution, and then add it to our collection of shapes with a position and linear velocity. Box2D will then handle the physics and we can just take the values back out to draw things on the screen with a setInterval, which happens in the loop method:

JAVASCRIPT:
function loop() {
  delta[0] += (0 - delta[0]) * .5;
  delta[1] += (0 - delta[1]) * .5;
  world.m_gravity.x = 0 // -(0 + delta[0]);
  world.m_gravity.y = -(100 + delta[1]);
  mouseDrag();
  world.Step(timeStep, iterations);
  for (i = 0; i <bodies.length; i++) {
    var body = bodies[i];
    var element = elements[i];
    element.style.left = (body.m_position0.x - (element.width>> 1)) + 'px';
    element.style.top = (body.m_position0.y - (element.height>> 1)) + 'px';
    if (ballRotation && element.tagName == 'DIV') {
      var rotationStyle = 'rotate(' + (body.m_rotation0 * 57.2957795) + 'deg)';
      element.style.WebkitTransform = rotationStyle;
      element.style.MozTransform = rotationStyle;
      element.style.OTransform = rotationStyle;
    }
  }
}
 

This method gets called with a setInterval periodically. Basically, we apply a delta and a gravity at each time step; see if the mouse is being pressed down (with hooks for touch devices like the iPhone to see if a finger is being pressed down); tell the Box2D World about our gravity and delta and to make an iteration step; and finally use the computed physics values from Box2D to apply CSS3 rotation transforms on our parent DIV and move the element's CSS top and left values around the screen.

FaviconFind Info On Webkit Spec Extensions 27 Aug 2010, 7:00 am

I stumbled across http://webkit.org/specs recently, which is basically a nifty listing of all custom extensions Apple/Webkit has made to web specs, written up as specs themselves so that other browsers can implement them:

There were some on here that I had never even heard of. The first is the Timed Media Elements spec, which is a fancy name for basically CSS that can control playback of video and audio:

CSS:
myVideo {
  media-play-state: paused; /* Pause the video. */
  media-play-rate: 50%; /* Play at half speed. */
  media-loop-count: 2;
}
 

Another interesting spec contains extensions to CSS Media Queries, basically making it possible for user agents to query whether CSS Transforms, Animations, 3D Transforms, and Transitions are available so you can apply different style sheets for platforms that support these CSS effects:

HTML:
<link rel="stylesheet" media="screen and (transform-2d)" />
 

FaviconIt’s Gmail: The Game! 27 Aug 2010, 6:00 am

TechCrunch reports on a Googler, Paul Truong, who created an HTML5-based game for Gmail called Galactic Inbox using his 20% time:

When you start it up, a little Gmail logo envelope guy pops out of a “20% Projects Lab” and starts flying. Essentially, he’s a spaceship and can shoot objects coming his way. It’s simple, but fun.

Read more on the Gmail Blog.

Play the game yourself (note that you must be using a modern browser)!

[via Bryan Neuberg]

FaviconHow to Drag Out Files Like Gmail 26 Aug 2010, 7:00 am

Ryan Seddon, aka the CSS Ninja, has a nice blog post up where he reverse engineers the new feature in Gmail where you can drag attachments from an email on to your desktop.

Note that the feature only currently works in Chrome.

Ryan begins with the following code:

JAVASCRIPT:
var file = document.getElementById("dragout");

file.addEventListener("dragstart",function(evt){
  evt.dataTransfer.setData("DownloadURL",fileDetails);
},false);
 

Describing the code Ryan says:

From the code above you attach an ondragstart event listener to something you want to “drag out” and save to your file system. On the dragstart event you set the data using the new “DownloadURL” type and pass file information to it.

Note though that in order to pass the correct data to the dragstart event you need to provide a download URL that can be passed to the setData("DownloadURL" call. Ryan uses the HTML5 data-* attribute to pass this custom data in:

HTML:
<a href="Eadui.ttf" id="dragout" draggable="true" data-downloadurl="
    application/octet-stream
    :Eadui.ttf
    :http://thecssninja.com/gmail_dragout/Eadui.ttf"
>
Font file</a>
 

The custom attribute uses three different fields of data separated by colons:

The files mime type, the name you wish it to be saved as (this can be anything) and the url to where the file can be downloaded from.

Nice find Ryan!

FaviconinnerShiv: Make innerHTML + HTML5 Work in IE 26 Aug 2010, 6:00 am

(Various Shivs)

Via JD Bartlett comes HTML5 innerShiv for IE. Before innerShiv, the following would not work in IE:

HTML:
var s = document.createElement('div');
s.innerHTML = "<section>Hi!</section>";
document.body.appendChild(s);
 

For example, let's imagine we have some CSS that defines the following for the HTML5 elements footer, header, and section:

CSS:
footer, header, section {
  border:1px solid #ccc;
  display:block;
  padding:10px;
}
 

Unfortunately, even if you are using one of the tricks to force IE to deal with HTML5 elements shivs don't work when dealing with innerHTML before an element is appended to the DOM:

However, the shiv doesn't work in Internet Explorer when an element's content is added with innerHTML before being appended to the document. That's a common use case, and noticeable in libraries like jQuery when you try to append or load (etc.) HTML5 content

Some example bad JQuery code that runs into this problem:

JAVASCRIPT:
$('#example-1').append("<section><header><h3>Example 1:\
  a broken section</h3></header><p>This section element should\
  have a black border like the others. It doesn't in Internet\
  Explorer. :(</p></section>"
);
 

JD's library is the solution to this problem:

innerShiv is a function which takes your HTML string, adds it to a hidden document-appended element in IE, and returns an IE-safe document fragment or collection

Now you can do the following to have things work:

JAVASCRIPT:
$('#example-2').append(innerShiv("<section><header><h3>\
  Example 2: a successfully styled section</h3></header>\
  <p>This section element should have a gray border like the\
  others. And it does! Even in Internet Explorer! Yay!.</p>\
  </section>"
));
 

Note that you don't have to use JQuery to use innerShiv.

FaviconAdobe Releases Web Fonts 25 Aug 2010, 7:00 am

Last week Adobe announced they are jumping into the Web Fonts game in a partnership with Typekit:

For this debut of Adobe Web Fonts, I think we’ve made some great choices. Everyone knows Myriad and Minion — pervasive workhorse sans serif and serif typefaces, respectively, which will prove to be as useful on the web as they have been in print. Thomas Phinney’s Hypatia Sans and Carol Twombly’s Chaparral are distinctive and versatile. Adobe Text is Robert Slimbach’s newest design which a lot of people haven’t even seen yet (so far it has only been available as a registration benefit for CS5 customers) but I’m certain it will quickly establish itself as a flexible and reliable text typeface, and I’m pleased it will now get a wider audience.

Richard Lipton’s classic Bickham Script is one of our most popular display typefaces and a distinctive addition to the Adobe Web Fonts collection. More of Robert Slimbach’s work now available for web use include Adobe GaramondCaflisch ScriptCronos, and the “display” designs for Garamond Premier (based on Claude Garamond’s beautiful Gros Canon type).

Speaking of which: You will find that we’ve included optical size variations for some of our typefaces. These designs are carefully crafted to look their best at small sizes (“caption”), medium- to large-size headings (“subhead”), or in headlines and other large sizes (“display”). On the web, these distinctions are less resolved than in print, but optical sizes will give you more options to find just the right font for your needs — and giving users better options for fine typography is what Adobe Originals are all about.

Remember, Adobe Web Fonts support the same languages and scripts as their desktop counterparts. Most are “Pro” fonts — meaning their character set supports Central European languages. Adobe Text, Garamond Premier, Hypatia Sans, Minion, and Myriad also support Greek and Cyrillic. (Select the “All Characters” Subset option in Typekit to use them.)

It's exciting to see Adobe supporting web fonts!

FaviconReal World Canvas Tips from Hakim El Hattab 25 Aug 2010, 6:00 am

From Hakim El Hattab (who has some very nifty HTML5 experiments up) comes some nice tips on using the Canvas tag:

Cross browser implementation

There are no real discrepancies between the canvas outputs of different browsers so long as the JavaScript code is written correctly (if not, browsers tend to try and fix things for you, often resulting in varying results).

Performance

When working with animation on canvas, performance can be a challenge since bitmap operations are very processing expensive, especially at high resolutions. One important optimization rule to follow is to reuse as many pixels as possible between frames. What I mean by that is the fewer pixels that need to be processed each frame, the faster your program will run. A good example of this is when erasing pixels with the clearRect(x,y,w,h)method, it is very beneficial to clear and redraw only the pixels that have changed and not, for instance, a full screen 1920x1280 sized canvas. Unlike the Flash Player’s redraw regions, this management of “dirty rectangles” needs to be done manually for canvas.

State stack & transformation

The canvas can be manipulated via transformations such as rotation and scaling, resulting in a change to the canvas co-ordinate system. This is where it’s important to know about the state stack for which two methods are available: “save” (pushes the current state to the stack) and “restore” (reverts to the previous state). This enables you to apply transformation to a drawing and then restore back to the previous state to make sure the next shape is not affected by any earlier transformation. The states also include properties such as the fill and stroke colors.

Compositing

A very powerful tool at hand when working with canvas is compositing modes which, amongst other things, allow for masking and layering. As an example, you can check out Bakemono, where composite modes are used to mask the eye and mouth. There's a wide array of available composite modes and they are all set through the canvas context's “globalCompositeOperation” property.

Anti-aliasing

To allow for sub-pixel drawings, all browser implementations of canvas employ anti-aliasing (although this does not seem to be a requirement in the HTML5 spec). Anti-aliasing can be important to keep in mind if you want to draw crisp lines and notice the result looks blurred. To work around this you will need to either round to integer values or offset by half a pixel depending on if you’re drawing fills or strokes.

Clearing the canvas

To clear the entire canvas of any existing pixels you would normally use the clearRect(x,y,w,h) function but there is another option available. Whenever the width/height of the canvas are set, even if they are set to the value they already have, the canvas is reset. This is good to know when working with a dynamically sized canvas as you will notice drawings disappearing.

[via Mr. Doob]

Cross browser implementation

There are no real discrepancies between the canvas outputs of different browsers so long as the JavaScript code is written correctly (if not, browsers tend to try and fix things for you, often resulting in varying results).

Performance

When working with animation on canvas, performance can be a challenge since bitmap operations are very processing expensive, especially at high resolutions. One important optimization rule to follow is to reuse as many pixels as possible between frames. What I mean by that is the fewer pixels that need to be processed each frame, the faster your program will run. A good example of this is when erasing pixels with the clearRect(x,y,w,h)method, it is very beneficial to clear and redraw only the pixels that have changed and not, for instance, a full screen 1920x1280 sized canvas. Unlike the Flash Player’s redraw regions, this management of “dirty rectangles” needs to be done manually for canvas.

State stack & transformation

The canvas can be manipulated via transformations such as rotation and scaling, resulting in a change to the canvas co-ordinate system. This is where it’s important to know about the state stack for which two methods are available: “save” (pushes the current state to the stack) and “restore” (reverts to the previous state). This enables you to apply transformation to a drawing and then restore back to the previous state to make sure the next shape is not affected by any earlier transformation. The states also include properties such as the fill and stroke colors.

Compositing

A very powerful tool at hand when working with canvas is compositing modes which, amongst other things, allow for masking and layering. As an example, you can check out Bakemono, where composite modes are used to mask the eye and mouth. There's a wide array of available composite modes and they are all set through the canvas context's “globalCompositeOperation” property.

Anti-aliasing

To allow for sub-pixel drawings, all browser implementations of canvas employ anti-aliasing (although this does not seem to be a requirement in the HTML5 spec). Anti-aliasing can be important to keep in mind if you want to draw crisp lines and notice the result looks blurred. To work around this you will need to either round to integer values or offset by half a pixel depending on if you’re drawing fills or strokes.

Clearing the canvas

To clear the entire canvas of any existing pixels you would normally use the clearRect(x,y,w,h) function but there is another option available. Whenever the width/height of the canvas are set, even if they are set to the value they already have, the canvas is reset. This is good to know when working with a dynamically sized canvas as you will notice drawings disappearing.

FaviconMotorola Purchases 280 North 24 Aug 2010, 6:26 pm

I don't usually post acquisition news on here, but I just wanted to congratulate 280 North, who we've covered on here many times and are fellow members of the Ajax community. 280 North produces the awesome Cappuccino language/framework, including the 280 Slides presentation web application. Techcrunch is reporting that Motorola has bought 280 North. From Motorola:

I can confirm that Motorola acquired 280 North earlier this summer. The transaction provides Motorola with specialized web-app engineering talent and technology that will help facilitate the continued expansion of Motorola’s application ecosystem. We believe 280 North will be instrumental in helping us continue to foster the Android ecosystem with innovative web-based technologies and applications. Terms of the transaction were not disclosed.

Congrats!

[via John Resig]

FaviconCSS Media Queries: Bees Knees Or Spawn of Satan? 24 Aug 2010, 7:00 am

The last month has seen an interesting back and forth over CSS Media Queries. In a nutshell, CSS Media Queries make it possible to apply style sheets only if certain properties are available on the display device. For example, you could have a stylesheet only display for screen devices with a maximum screen width of 480px (i.e. a mobile device) using the following CSS Media Query, bolded below:

CSS:
<link rel="stylesheet" type="text/css"
          media="screen and (max-device-width: 480px)"
          href="shetland.css" />
 

Things kicked off with a nice introductory article by Ethan Marcotte introducing CSS Media Queries in order to have responsive and adaptable web designs.

Things started to get interesting with a counter-article by Jason Grigsby titled "CSS Media Query for Mobile is Fool's Gold". Jason claims:

Unfortunately, CSS media query is fool’s gold for mobile devices. It hides tough problems and gives developers a false promise of a simple solution for designing to multiple screens.

His chief issues with CSS Media Queries can be boiled down to:

The idea of adding more code—adding more to download—in order to optimize for mobile should be the first clue that this isn’t a good solution.

From a high level his other objections are:

  • That speed matters more on mobile devices
  • That letting the browser scale images for you is a bad idea since delivering images at the maximum size then scaling them down is wasteful on mobile devices
  • That resizing images on mobile browsers is cpu and memory intensive, both of which mobile devices can lack

Jason also discusses some interesting workarounds people have proposed for the above issues still using CSS Media Queries, such as delivering different images at different sizes using different CSS Media Queries and using hidden CSS background images but:

However, the iPhone still downloads the images even though they are not displayed.

He does find some workarounds but there are issues:

Two methods that appear to work are:

  • Setting the parent of an element with a background image to display:none.
  • Using media query min-width declaration to only specify a minimum browser width for the desktop image and a max-width for the mobile image does result in only the mobile image being downloaded in Mobile Safari.

These two options mean that using CSS media queries isn’t completely impossible, but using the parent element to hide images and changing existing desktop CSS to add min-width declarations are significant changes to existing CSS. It isn’t going to be as simple as adding a CSS media query for mobile and calling your job done.

In the end Jason argues for separate web sites for mobile, but:

There are some good uses of CSS media queries. If you’re building a discrete web application where you have more control and can make sure that the desktop web isn’t bloated, it can make sense.

Also, Ros Hodgekiss from Campaign Monitor wrote an exceptional article on how you can use media queries in html email to provide a mobile optimized layout. This is perhaps the ideal use case because when you send html email, you have no choice but to send a single html document regardless of what device the recipient will be using.

In response to Jason's CSS Media Query smackdown PPK wrote up an editorial titled "Combining Media Queries and JavaScript":

On Tuesday Jason Grigsby challenged the conventional view that media queries are all we need to make a website mobile-friendly. Although he’s right when he points out some serious problems, I do not think that media queries are the “fool’s gold,” as Jason says. The message seems to be more that media queries alone are not enough to make your sites mobile-friendly. An additional component is required.

PPK argues that CSS Media Queries have their place:

Media queries are silver bullets when it comes to pure CSS. Restricting the width of your site, moving sidebars and main navigations elsewhere, media queries can do all that and more.

The trick, however, is that a pure CSS approach is not enough. In addition we need a JavaScript that also reads out the media queries and uses the data to decide whether to download the complicated mapping script, whether to download the low-source or the full-source images, or possibly none.

As far as I know there is no direct access to media queries from JavaScript. You can’t read out whether the example media query above has fired or not.

He then talks about a nifty way to pair up JS and CSS Media Queries:

Fortunately, there is a pretty safe way of using JavaScript in conjunction with media queries. It turns out that all browsers I tested so far have paired the width and device-width media queries with the values of document.documentElement. clientWidth and screen.width, respectively.

This is a general rule. All mobile browsers that support media queries exhibit these pairings. It’s hard to believe, but I haven’t found any exceptions yet — and rest assured that I searched for them, because I could not believe that it would be this simple. And I will continue to keep an eye on this and report problems as soon as I find them.

...

When these scripts are added to media queries, we’re a whole lot closer to making one website that reacts to a mobile (or rather, a narrow-screen) environment both in its CSS and in its asset management.

Finally, Bruce Lawson tag teamed into the rumble with an article on the topic titled "There's more to mobile than than media queries":

In our enthusiasm to try out media queries and in our rush to skim the latest articles and tutorials, it's easy to overlook caveats and restrictions. Media queries are good at what they do but are just a single tool for a job where two or three are probably needed. In particular, combining them with JavaScript as PPK and others advocate seems to me the most practical solution for web developers to adopt at the moment.

[CC-A by Paolo Camera]

Tell me below whether you think CSS Media Queries are your friend or foe?

FaviconBlow Things Up! 24 Aug 2010, 6:00 am

Jonas Wagner has ported the Flash 2D physics engine Box2DFlash to JavaScript:

In his demo Jonas uses the Canvas tag to map the physics simulations on. Click on it to create explosions:

Jonas talks about the approach he used to convert the original library from ActionScript to JavaScript:

At first I thought this conversion would be trivial as both actionscript and javascript are dialects of ECMAScript. Well, I was wrong. Nevertheless I continued to follow my regex based approach, basically trying to ram my head through a wall. After a few attempts I succeeded to convert Box2DAS3 to javascript. It had a nasty bug though. Two solid cubes were able to penetrate each other when they fell on their edges. The reason? ActionScript supports 'properties'. I didn't know about this and the conversion script does not support it. In the end I fixed the few properties in the translated code by hand because I was too lazy to add support for getters and setters to the conversion script. Now it seems to work pretty well. Please keep in mind, this is not a generic actionscript to javascript compiler, it's just a script that happens to work for box2dflash.

The explosions in the demo are simulated by shooting out a few tracer particles with a high density and velocity. The benefit over just applying an impulse to each object is that the strength of the impulse is proportional to the surface area. Also the force of the explosion will to some extent be redirected to the side by the floor. When using this in production code you would probably want to destroy the tracer particles after their first collision or a few seconds.

You can grab the converted JavaScript yourself. There isn't any current documentation but you can follow the existing Flash box2dflash documentation.

Here's what the explode function looks like in Jonas' test demo for example:

JAVASCRIPT:
function explode(x, y) {
    var ntracer = 25;
    while(explosionParticles.length){
        world.DestroyBody(explosionParticles.pop());
    }
    for(var i = 0; i <ntracer; i++) {
        var a = Math.PI/ntracer*2*i;
        var vx = Math.cos(a);
        var vy = Math.sin(a);
        var bodyDef = new b2BodyDef();
        bodyDef.position.Set(x+vx, y+vy);
        bodyDef.isBullet = true;
        var body = world.CreateBody(bodyDef);
        var shapeDef = new b2CircleDef();
        shapeDef.radius = 0.1;
        //var shapeDef = new b2PolygonDef();
        //shapeDef.SetAsBox(1.0, 1.0);
        shapeDef.restitution = 0.0;
        shapeDef.density = 5000.0/ntracer;
        shapeDef.friction = 0.0;
        body.CreateShape(shapeDef);
        body.SetMassFromShapes();
        body.ApplyImpulse({x: vx*500, y:vy*500}, {x:x, y:y});
        body.w = 1.0;
        body.h = 1.0;
        explosionParticles.push(body);
    }
}
 

This library is useful for games and fancy user interfaces using HTML5.

[via Mr. Doob]

FaviconThe CSS3 Song 23 Aug 2010, 7:00 am

Don't be bummed it's Monday, 'cuse the CSS3 Song is here to cheer you up:

How can you go wrong with lyrics like this:

CSS3
Web animation done properly
CSS3
Degrading gracefully

I had a dream, an awesome dream
People surfing in the park
On Windows, Linux and Mac
And their page load speeds were oh-so-high
No big JavaScript library
Just to show some eye-candy

CSS3
Web animation done properly
CSS3
Degrading gracefully

As we surf down the superhighway
Did you ever even think
We could replace <marquee> and <blink>?
With just one, just one line of code
But it's open to abuse
We must be careful not to overuse it

CSS3
Web animation done properly
CSS3
Degrading gracefully

CSS3
Web animation done properly
CSS3
Degrading gracefully
Degrading gracefully
With HTML5, naturally

[via Bruce Lawson]

FaviconPure Pulsing CSS Map Markers 23 Aug 2010, 6:00 am

Via Zachary Johnson (aka the Zachstronaut) comes a cool experiment using pure CSS to generate pulsing rings/map markers. He's put together a nice video explaining the concept:

He has a cool demo (Chrome or Safari + Snow Leopard only) of the effect:

The pulsing effect, for example, is generated by a CSS3 Animation:

CSS:
@-webkit-keyframes ringpulser
        {
                0%
                {
                        opacity: 1.0;
                        -webkit-transform: scale(0.2);
                }
               
                80%
                {
                        opacity: 0.0;
                        -webkit-transform: scale(1.0);
                }
               
                100%
                {
                        opacity: 0.0;
                        -webkit-transform: scale(0.2);
                }
        }
 

The map itself is rotated to a 3D angle using a CSS 3D Transform:

CSS:
#map
        {

            position: absolute;
            top: -430px;
            left: 50px;
            background: url(planis-map.jpg) top left no-repeat;
            width: 800px;
            height: 548px;
            -webkit-transform-style: preserve-3d;
            -webkit-transform: rotateX(60deg) translate3d(0, 0, -500px);
            opacity: 0.75;
        }
 

While the pin, marker, and pinhead themselves are a combination of CSS 3D, CSS Transforms, CSS Gradients, and more:

CSS:
        .marker
        {
                position: absolute;
                width: 100px;
                height: 100px;
                -webkit-perspective: 600;
        }
       
        .pin
        {
            position: absolute;
            top: 10%;
            left: 52%;
            border-left: 2px solid transparent;
            border-right: 2px solid transparent;
            border-top: 40px solid #666;
            -webkit-transform: rotate(9deg);
            width: 0;
            height: 0;
        }
       
        .pinhead
        {
            position: absolute;
            top: 8%;
            left: 49%;
            width: 15px;
            height: 15px;
            -webkit-border-radius: 15px;
            background: #999 -webkit-gradient(
                radial, 95% 40%, 5, 85% 40%, 10, from(rgba(0, 0, 0, 0.40)), to(rgba(0, 0, 0, 0))
        )