Aug 25

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 1920×1280 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 1920×1280 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.

Continue reading »

Tagged with:
May 10

Michael Nutt and Benny Wong have created a fun realtime web analytics product called Hummingbird. It comes with awesome buzzwords too! Node! Canvas! Web Sockets! MongoDB!

To add tracking, you simple sprinkle in Gilt.Hummingbird.track(env) like this:

Which calls the client:

Which, as you can see, sets up a tracking gif on the server. You can then access the monitoring server to watch things moving:

Very nice indeed!

Continue reading »

Tagged with:
Mar 29

Ben Alman has a mother of a post on his special events work for jQuery. I have a special penchant for custom events and the like, even though I have abused them just as I did in the old days of AOP! :)

What are special events?

The jQuery special events API is a fairly flexible system by which you can specify bind and unbind hooks as well as default actions for custom events. In using this API, you can create custom events that do more than just execute bound event handlers when triggered—these “special” events can modify the event object passed to event handlers, trigger other entirely different events, or execute complex setup and teardown code when event handlers are bound to or unbound from elements.

He does into intrigue detail on the API and gets to show you how to implement the hello world of custom events: tripleclick:

JAVASCRIPT:

  1.  
  2. (function($){
  3.  
  4.   // A collection of elements to which the tripleclick event is bound.
  5.   var elems = $([]);
  6.  
  7.   // Click speed threshold, defaults to 500.
  8.   $.tripleclickThreshold = 500;
  9.  
  10.   // Special event definition.
  11.   $.event.special.tripleclick = {
  12.     setup: function(){
  13.       // Initialize the element plugin data, including clicks counter and
  14.       // last-clicked timestamp.
  15.       $(this).data( ‘tripleclick’, { clicks: 0, last: 0 } );
  16.  
  17.       // Add this element to the internal collection.
  18.       elems = elems.add( this );
  19.  
  20.       // If this is the first element to which the event has been bound,
  21.       // bind a handler to document to catch all ‘click’ events.
  22.       if ( elems.length === 1 ) {
  23.         $(document).bind( ‘click’, click_handler );
  24.       }
  25.     },
  26.     teardown: function(){
  27.       // Remove all element plugin data.
  28.       $(this).removeData( ‘tripleclick’ );
  29.  
  30.       // Remove this element from the internal collection.
  31.       elems = elems.not( this );
  32.  
  33.       // If this is the last element removed, remove the document ‘click’
  34.       // event handler that "powers" this special event.
  35.       if ( elems.length === 0 ) {
  36.         $(document).unbind( ‘click’, click_handler );
  37.       }
  38.     }
  39.   };
  40.  
  41.   // This function is executed every time an element is clicked.
  42.   function click_handler( event ) {
  43.     var elem = $(event.target),
  44.  
  45.       // Get plugin data stored on the element.
  46.       data = elem.data( ‘tripleclick’ );
  47.  
  48.     // If more than `threshold` time has passed since the last click, reset
  49.     // the clicks counter.
  50.     if ( event.timeStamp – data.last> $.tripleclickThreshold ) {
  51.       data.clicks = 0;
  52.     }
  53.  
  54.     // Update the element’s last-clicked timestamp.
  55.     data.last = event.timeStamp;
  56.  
  57.     // Increment the clicks counter. If the counter has reached 3, trigger
  58.     // the "tripleclick" event and reset the clicks counter to 0. Trigger
  59.     // bound handlers using triggerHandler so the event doesn’t propagate.
  60.     if ( ++data.clicks === 3 ) {
  61.       elem.trigger( ‘tripleclick’ );
  62.       data.clicks = 0;
  63.     }
  64.   };
  65.  
  66. })(jQuery);
  67.  

There is a lot in his article, so give it a once over.

Continue reading »

Tagged with:
preload preload preload