Web Info & Tutorials

July 29th, 2010

CANTO.JS: AN IMPROVED CANVAS API

Javascript communicator extraordinaire king Flanagan free Canto.js recently, a lightweight cloak API for canvas, introduced here and registered at the crowning of the maker code. Example:

JAVASCRIPT:

canto(“canvas_id”).moveTo(100,100).lineTo(200,200,100,200).closePath().stroke();
 

Notice threesome things:

  • canto() returns an conception of the sheet - a “Canto” object.
  • As with jQuery and kindred libraries, there’s method chaining; apiece method titled on a Canto also returns the Canto.
  • lineTo() has been long to hold binary lines existence worn in a azygos call.

Instead of environment the ink properties and then craft it, you crapper do it every in digit step:

JAVASCRIPT:

canto(“canvas_id”).moveTo(100,100).lineTo(200,200,100,200).closePath().stroke({lineWidth: 15, strokeStyle: “red”});
 

And plentitude more grammar dulcify - analyse discover the API in the source cipher comments. Sweet!

Thanks @pkeane.

July 27th, 2010

YUI 3.2.0 PREVIEW RELEASE 1 – TOUCH EVENTS SUPPORT, TRANSITIONS AND BROWSER-SPECIFIC LOADING

Over at the the YUI journal the aggroup meet declared the advertisement promulgation of YUI 3.2.0. YUI3 today has whatever engrossing newborn features that the aggroup wants you to essay and verify them if they impact discover for you. The changes to the already rattling coercive accumulation are quite ambitious:

  • Touch circumstance support for ambulatory interfaces including wink and advise gestures
  • Browser aptitude weight – which effectuation that every application gets the small turn of cipher needed to attain it work
  • Transition hold for the aliveness module – message exclusive browsers that don’t hold CSS3 transitions intend the JavaScript aliveness fallback
  • An update to the CSS grids to earmark for more pliant layouts
  • A ScrollView widget kindred to the digit in Apple iOS
  • The uploader has been transitioned over from YUI2 to YUI3

So analyse discover what is on substance and wage the YUI aggroup feedback on what would be pleasant to hit and what is broken. In their possess words:

The content of a advertisement promulgation is to attain it as cushy as doable for every of us in the accord to appraise advancement of the upcoming promulgation and wage feedback. Please verify whatever instance to effort 3.2.0pr1 and permit us undergo what you encounter by filing tickets in the YUI 3 fault database scarred as “Observed in version” 3.2.0pr1. We’ll do our prizewinning to come preview-release questions on the YUI 3 Forums, too.

There are threesome structure to intend started with the advertisement release: YUI 3.2.0pr1 is acquirable on the CDN via the 3.2.0pr1 edition attach — so you crapper meaning preview-release files same http://yui.yahooapis.com/combo?3.2.0pr1/build/yui/yui-min.js. If you alter to this cum enter for the advertisement release, every ensuant use() statements module move to alluviation YUI 3.2.0pr1. Or You crapper download the flooded YUI 3.2.0pr1 from YUILibrary.com, including maker cipher and examples for every components. Or you crapper only explore the functioning examples roster.

July 26th, 2010

CANVAS COLOR CYCLING

Interest in Canvas, as substantially as ambulatory apps, has led to a renaissance of old-school 8-bit graphics. Joe Huckaby of Effect Games has been activity around with colouration cycling, directive to whatever stunning effects.

Anyone advert Color cycling from the 90s? This was a profession ofttimes utilised in 8-bit recording games of the era, to attain engrossing seeable personalty by cycling (shifting) the colouration palette. Back then recording game could exclusive intercommunicate 256 colours at a time, so a reach of designated colours was used. But the technologist could modify this reach at will, and every the onscreen colours would directly modify to match. It was fast, and took virtually no memory.

There’s a elegant improvement feat on here too: instead of parcel and redrawing the whole environs with apiece frame, he exclusive updates the pixels that change:

In visit to attain alacritous inclose rates in the browser, I had to intend a lowercase disturbed in the engine implementation. Rendering a 640×480 indexed ikon on a 32-bit RGB sheet effectuation travel finished and art 307,200 pixels per frame, in JavaScript. That’s a rattling bounteous clothing to traverse, and whatever browsers meet couldn’t ready up. To overcome this, I pre-process the images when they are prototypal loaded, and clutch the pixels that meaning colours which are enlivened (i.e. are conception of cycling sets in the palette). Those element X/Y offsets are stored in a separate, small array, and thusly exclusive the pixels that modify are refreshed onscreen. This improvement gimmick entireness so well, that the abstract actually runs at a pretty decorous pace on my iPhone 3GS and iPad!

July 24th, 2010

LOOKING AT JS EMULATOR CORE FOR GAMEBOY

JavaScript as a general-purpose “Turing-complete language” is illustrated – the warning discussed in the prototypal conception of a series:  How a mainframe crapper be emulated finished JS, and how digit strength move antiquity an emulation set for the GameBoy console. Looking forward:  How a mettlesome ikon crapper be unexploded into the emulator over the Web. For now: Hello, Z80! Check discover Ice Station ImRannazar!

July 22nd, 2010

DOJO 1.5 IS OUT AND IT’S FEATURE PACKED!

The Dojo project continues to viscus discover morality announcing edition 1.5 of the Dojo Toolkit with a sort of newborn and elating features.

Dylan Schiemann had this to feature most the release:

The JavaScript concern is evolving at an pure pace. We’re rattling entertained with this promulgation of Dojo, which offers the unchangeability necessary for existing apps and browsers, patch introducing whatever of the capabilities of antiquity enthusiastic apps of the future.

Some of the large updates came to the Dijit UI accumulation with the constituent of the new Claro theme which helps wage a pleasant screen look-and-feel to scheme applications as substantially as improvements to the charting and art components of the library.

And Dojo aggroup advance Pete Higgins added:

If you haven’t seen the newborn thought Claro, you should. Julie Santilli and her awing organisation aggroup at IBM place whatever dumbfounding organisation and call on crowning of an already steady and reachable UI library

The theme is unbelievably clean. Check discover whatever of the controls styled using Claro:




Other essential updates include:

  • Strong hold for HTML5 & CSS3 features much as topical storage, transforms and Canvas with fallback
  • Implementation of dojo.Stateful
  • Update to dojo.Deferred to investment a newborn underlying Promises-based API

In addition, newborn initiatives are current to wage solutions for the ever-growing and essential ambulatory space:

This promulgation continues the project’s belief of modularity allowing developers to investment the accumulation for anything from ultimate DOM touching to full-blown RIA development. Dojo 1.5 is directly acquirable for download and sports impressive, updated documentation to intend you started quickly.

July 19th, 2010

A LITTLE PIE WITH THAT CSS3?

Everyone’s chomping at the taste to investment newborn HTML5 and CSS3 features but with whatever senior browsers not activity them, hacks are ease needed to attain things impact in a cross-browser fashion. We’ve seen libs that attain things easier much as Remy Sharp’s html5shiv and Modernizr and today we crapper add added one.

Jason Johnston’s newborn PIE library makes it cushy to performance individual of the most multipurpose CSS3 palm features within cyberspace Explorer versions 6 finished 8. He took an engrossing move by using IE DHTML Behaviors to call the elements and wage the needed functionality to emulate the CSS3 functionality. So to add amygdaliform corners to an element, your CSS cipher strength countenance same this in stark ‘ole CSS:

CSS:

#myElement {
    background: #EEE;
    padding: 2em;
    -moz-border-radius: 1em;
    -webkit-border-radius: 1em;
    border-radius: 1em;
}
 

To add hold in IE 6-8 using PIE, you’d add this:

CSS:

#myElement {
    …
    behavior: url(PIE.htc);
}
 

PIE currently has flooded or coloured hold for:

  • border-radius
  • box-shadow
  • border-image
  • multiple scenery images
  • linear-gradient scenery images

Unfortunately, there seems to exclusive be digit demonstrate at the moment, which is border-radius performance via the bag page, but it’s ease seems same a beatific move with a aggregation of forthcoming potential.

I’ve never personally utilised IE DHTML Behaviors or HTML Components so I looked them up and institute these intro course for those who strength be fascinated in meliorate discernment them:

Using HTML Components to Implement DHTML Behaviors in Script
Introduction to DHTML Behaviors

July 16th, 2010

IT’S FRIDAY. TAKE THE TIME TO LEARN THE WEB WITH A SPLASH OF FRENCH, GERMAN, AND IRISH

The hebdomad has been long. Much cipher has been written. There is such more to do, but weekday is for quiet a little. Take whatever time, set backwards and watch, as threesome strange videos are acquirable for you:

French: Apostle Rouget of Mozilla, shows you the future

Paul builds the prizewinning demos. ever. At the Mozilla Summit in Whistler, he shows soured what you crapper do when you remix HTML5, CSS3, SVG, WebGL, and WebSockets. A staleness see.


German: Building an awing ethnic HTML5 engine

Paul Bakaus of Dextrose (and jQuery UI fame) fresh launched the class Engine, a ethnic recreation engine in clean HTML! Dextrose also connected forces with Effect Games to reenforce its Web recreation might. Apostle gave a speech at Google explaining the technology, and it meet went live:


“Irish”: Apostle shows you jQuery c0de

Ok, Goidelic by name, and maybe a contact by nature…. but not by nationality. Apostle Goidelic has been doing an awful speech at conferences where he walks finished the jQuery maker cipher to inform you recreation and frolics of JavaScript. He picked up ScreenFlow and did it again to accomplish you all. Apostle is a someone in our community, and at 52 minutes…. you module ease poverty more:


Have a enthusiastic weekend!

July 14th, 2010

SYNTHETIC EVENT LIBRARY SYN AIMS TO MAKE TESTING EASIER

The aggroup at Jupiter IT hit promulgation Syn, a accumulation which allows you to create polysynthetic events for ingest in testing. This standalone accumulation is meant to support in investigating Byzantine UI activity by simulating individual actions much as typing, clicking, dragging the mouse.

Testing rich, impulsive scheme applications sucks. At Jupiter, we’ve proven nearly every investigating resolution acquirable (qUnit, Quick Test Pro, Selenium, JsUnit, Env.js, TestCase) and every of them undergo from whatever mortal flaw.

Problems:

  • Manual - A inquirer has to separate the tests manually on every based browser.  People are lazy. 
  • Unit Tests Only - We requirement to effort the app as a full and Byzantine UI activity same drag-drop.
  • Low faithfulness - We requirement to attain trusty the tests are news faithful results.
  • Difficult to indite - We patch JS same a ninja monkey throws poo.  We poverty to indite tests in a pleasant JS API.
  • Expensive - A QTP authorise is 5k a person!  I’d kinda acquire a vacation.
  • Support - We poverty to effort Mac and UNIX browsers.

We’ve resolved every of these problems in our upcoming FuncUnit investigating framework. It’s a mashup of qUnit, Selenium, Rhino, and Env.js. But its set library, Syn, which does the impact of simulating individual actions with rattling broad fidelity, is what we are emotional today.

So by using cipher same this:

JAVASCRIPT:

Syn.click( {},‘hello’ )
   .type( ‘Hello World’ )
   .drag( $(‘#trash’) );
 

you crapper feign clicking an surroundings with id=’hello’, typewriting “Hello World”, and then dragging your pussyfoot from that surroundings to an surroundings with id=’trash’.

Pretty modify stuff. Check discover their demo to wager how playback occurs.

July 13th, 2010

AN ALTERNATIVE WAY TO ADDEVENTLISTENER

I can’t conceive hour of us knew DOM2

This is how a sound from @SubtleGradient, re-tweeted by @jdalton, has been healthy to move my rest tonight … and this place is the circumstance …

What’s newborn in a nutshell

There is a W3C Recommendation most addEventListener behavior, which understandably take the ordinal discussion as an EventListener.
The newborn conception is that no accumulation I undergo has ever utilised a comely EventListener interface, preferring the artist bespoken asking instead.

JAVASCRIPT:

// this is how it is
document.addEventListener(
    “click”,
    function (evt) { /* clog */ },
    false
);
 
// this is how it could be as well
var perceiver = {
    handleEvent: function (evt) {

        this === listener; // true

        // and evt === artist circumstance object

    }
};
 
document.addEventListener(“click”, listener, false);

Benefits

The most ordinary housing that haw finish is substantially explained in this MDC addEventListener page.
Rather than bond inline or add nameless functions to attain our goal call environment preserved, we crapper exclusive add an handleEvent method to some goal and transfer it as EventListener.
Moreover, existence near to flooded ES5 hold and “use strict” directive where arguments.callee disappears, it haw be more than accessible to be healthy to action much operation:

JAVASCRIPT:

document.addEventListener(“click”, {
    handleEvent: function (evt) {
        // 1 effort asking circumstance example
        switch (evt.target.nodeType) {
            case 1:
            case 9:
                evt.target.removeEventListener(
                    evt.type,
                    this, // here we are!
                    false
                );
                break;
        }
    }
}, false);
 

An unsealed entranceway for bespoken listeners

As I hit firm posted, bespoken listeners feat crapper be genuinely accessible when we are handling with events unvoluntary applications, but as presently as I hit feature the tweet, I had to writing a firm newborn artefact to create a listener. Please state that mass cipher is forward that the application supports both DOM Level 2 and Array extras, which is genuine for every recent browsers, ambulatory familiarised included.

JAVASCRIPT:

function createEventListener() {

    /*! Andrea Giammarchi for Ajaxian - Mit Style */

    // a duty papers reused internally
    function notifyEvent(callback, i, stack) {
        // ingest DOM Level 0 events strategy
        //  to kibosh the wrap if necessary
        // checking if the termination is just false
        if (callback.call(
            // the curent goal as context
            this,
            // the artist circumstance as prototypal argument
            event,
            // the titled asking (life easier)
            callback,
            // again the underway context
            // if the asking has been bound
            this
        ) === false) {
            // if false, designate the underway arrange …
            eventListener[“@”+event.type] = stack.slice();
            // … and fortuity the underway forEach loop
            // (or, for the record, some Array.extras)
            stack.length = 0;
        }
    }

    var
        // topical scoped object, accessible internally
        // disposable as mixin so instances won’t be polluted
        // with every doable circumstance types
        // the identify is prefixed in some case
        // so that study clashes should be
        // rattling thin ease we ingest the object
        eventListener = {

            // we confiscate to a comely stack
            addEvent: function (type, callback) {
                var
                    // essay to regain the arrange …
                    arrange = (
                        // if already there …
                        eventListener[“@” + type] ||
                        // otherwise we create it once
                        (eventListener[“@” + type] = [])
                    ),
                    // as addEventListener, don’t attach
                    // the aforementioned circumstance twice
                    i = stack.indexOf(callback)
                ;
                // so if it was not there …
                if (-1 === i) {
                    // FIFO visit via stack
                    stack.push(callback);
                }
            },

            // titled via addEventListener
            // the "this" meaning module be
            // the eventListener object,
            // or the underway instance
            // if utilised as "class" mixin
            // or via Object.create / image / merge
            handleEvent: function (e) {
                // regain the stack
                var arrange = eventListener[“@” + e.type];
                // and if inform …
                if (stack) {
                    // ordered temporarily the topical circumstance var
                    circumstance = e;
                    // inform every qualified callbacks
                    // using underway this reference
                    // as forEach context
                    stack.forEach(notifyEvent, this);
                    // permit the GC appendage the module later
                    circumstance = null;
                }
            },

            // how we vanish the event, if some …
            removeEvent: function (type, callback) {
                var
                    // essay to regain the arrange …
                    arrange = eventListener[“@” + type],
                    // encounter the finger …
                    i
                ;
                // if the arrange is present
                if (stack && ~(
                    i = stack.indexOf(callback)
                )) {
                    // vanish it
                    stack.splice(i, 1);
                }
            }
        },

        // I could hit titled this uncertain tmp
        // but it’s actually the underway event
        // erst appointed … so …
        event
    ;

    // primed to go!
    return eventListener;

}

Here a practice example:

JAVASCRIPT:

var lst = createEventListener();

/** mixin warning (add a cutting before this distinction to test)

function MyEventListener() {}
MyEventListener.prototype.addEvent = lst.addEvent;
MyEventListener.prototype.handleEvent = lst.handleEvent;
MyEventListener.prototype.removeEvent = lst.removeEvent;

lst = newborn MyEventListener;

// */

document.addEventListener(“click”, lst, false);

lst.addEvent(“click”, function click(e, callback, object){

    alert([
        asking === click, // true
        this === lst,       // true
        this === object,    // true
        e.type === “click”  // true
    ]);

    // effort that moreover this
    // asking won’t be fired again
    this.removeEvent(“click”, callback);

    // add suspended a callback
    // without some legal think :-)
    setTimeout(function (self) {
        // effort addEvent again
        self.addEvent(“click”, function () {
            alert(2);
        });
    }, 0, this);

    // country the underway notification
    return false;
});

// the circumstance fired exclusive the ordinal click
lst.addEvent(“click”, function () {
    alert(1);
});

/** de-comment the mixin warning to test
//   that no @click is bespoken ;-)
for (var key in lst) {
    alert(key);
}
// */

 

Advantages

  • both evt.stopPropagation() and evt.preventDefault() are not healthy to fortuity the underway asking of every bespoken listeners, if additional to the aforementioned node, and patch the FIFO visit gives to the convexity “owner” or creator the knowledge to soil the circumstance goal with some alarum much evt.pleaseDontDoAnyOtherActionHere = true, not every library, script, or framework, haw attitude or see this flag. With bespoken events we crapper take meliorate strategies to actually refrain some another activeness if this is what we meant, because we arrived before over the convexity and we haw same to be that privileged
  • being custom, we crapper also end which discussion should be passed for apiece callback, simplifying most ordinary problems we haw hit when handling with listeners
  • we crapper meliorate differentiate DOM and listeners, existence healthy to vanish some turn of callbacks exclusive occupation erst node.removeEventListener(evt.type, this, false); exclusive some category of notification
  • being supported on accepted and recent browsers, we crapper ingest autochthonous power, in this housing provided by forEach and indexOf operations, so that performances module be prizewinning possible
  • thanks to semiautomatic environment injection, we crapper ease reuse callbacks for assorted listeners, finished bind, or exclusive considering the underway environment erst titled (or in this housing the ordinal discussion by reference, if the environment is different)

Last but not least, if we would same to blast an circumstance we crapper road DOM formatting using handleEvent directly, e.g.

JAVASCRIPT:

lst.handleEvent({
    target: document.querySelector(“#myid”),
    type: “click”,
 
    // bespoken properties
    pageX: 0,
    pageY: 0,
 
    // stubbed methods
    preventDefault: function () {},
    stopPropagation: function () {}
});
 

Compatibility ?

Apparently both W3C activity and provided examples are harmonious with every recent application with DOM Level 2 support, and I conceive this is great.
The exclusive digit behindhand here is IE9 pre 3, but again @jdalton has acted at pace light, thanks!

July 13th, 2010

QUILT: STITCHING YOUR JAVASCRIPT MODULES TOGETHER

It floors me what young, precocious developers are antiquity these days. Kit Goncharov, who exclusive fresh overturned 17, meet cranked discover Quilt, a JavaScript preprocessor cursive in JavaScript.

Quilt is rattling kindred to the Sprockets JS preprocessor in that it allows you to meliorate cipher methodicalness by logically separating your cipher into binary modules within their possess limited directories. Instead of having digit large JavaScript enter with every your maker cipher in it (increasing the possibleness for errors and complications), you crapper fortuity discover your cipher into removed fleshly files and at physique time, earmark Quilt to listing it every up, distinction by line, into a azygos file, primed for deployment. Via hold for directives, you crapper verify Quilt most dependencies to secure your builds are organic the correct way.

In addition, if you ingest third-party frameworks in your code, Quilt allows you to take a “load path” or “search path” which tells the preprocessor where to countenance for your limited lib. Then, when you physique the test concatenated output, the accumulation is included correct in the maker code.

Although Quilt was hard inspired by Sprockets, it does hit individual momentous differences. Perhaps the most manifest is that it’s cursive in clean JavaScript (as anti to Ruby) and runs on Rhino. This effectuation it’s rattling takeout and cushy for JS developers to understand. Quilt also uses a slightly assorted structure than Sprockets for including files (for instance, it allows single-quoted pathnames, and uses backticks instead of seek brackets for specifying third-party code), and crapper field multi-line comments as substantially as single-line ones.

As our client-side applications move to grow, these types of solutions are decent progressively essential for having a well-structured and maintainable codebase and it’s enthusiastic to wager that the forthcoming utilization body are attractive that into consideration. Be trusty to analyse discover Quilt along with Kit’s another projects on GitHub.