Mozilla

Web Developers Articles

Sort by:

View:

  1. Welcoming the new kid: Web Platform Docs

    Documenting the open Web and Web standards is a big job! As Mozillians, we’re well aware of this — documenting the open Web has been the mission of the Mozilla Developer Network for many years. Anything we can do to further the cause of a free and open Web is a worthwhile endeavor. With so many different groups involved in the design and development of new Web standards, it can be tricky to figure out the current right way to use them. That’s why we’re excited to be able to share this news with you.

    Introducing Web Platform Docs

    Mozilla, along with a group of major Web-related organizations convened by the World-Wide Web Consortium (W3C), has announced the start of Web Platform Docs (WPD), a new documentation site for Web standards documentation, which will be openly-licensed and community-maintained. The supporting organizations, known as the “stewards,” have contributed an initial batch of content to the site from their existing resources. The body of content is very much in an alpha state, as there is much work to be done to integrate, improve, and augment that content. to achieve the vision of WPD as a comprehensive and authoritative source for Web developer documentation. The stewards want to open the site for community participation as early as possible. With your help, WPD can achieve its vision being a comprehensive and authoritative source for Web developer documentation.

    Web Platform Docs has a similar goal to MDN: to help web developers improve their ability to make sites and applications using web standards. Mozilla welcomes this effort and joins with the other stewards in financially supporting the Web Platform Docs project, and in providing seed content for it. This new project is very much aligned with Mozilla’s mission to promote openness, innovation, and opportunity on the Web.

    What does this mean for MDN?

    MDN already provides a wealth of information for Web developers and for developers who use or contribute to Mozilla technology. That isn’t going to change. Some members of the MDN community, including both paid staff and volunteers, are actively involved with the Web Platform Docs project. Web Platform Docs incorporates some seed content from MDN, namely tutorial and guide content. Anyone is welcome to use MDN content under its Creative Commons Attribution-ShareAlike license (CC-BY-SA), whether on WPD or elsewhere.

    Licensing issues

    Licensing is where things get a little bit complicated. MDN and WPD use different contributor agreements and different licenses for reuse. By default, WPD contributors grant W3C the ability to relicense their original content under an open license (Creative Commons Attribution (CC-BY)). MDN content is licensed by the contributors under CC-BY-SA. The copyright belongs to the contributors, not to Mozilla, so we don’t have the right to change the license. Therefore, content that originates from MDN must be specially marked and attributed when it appears on WPD. If you create an account on WPD and create a new page, you’ll see that there is an option to indicate that the content you’re contributing came from MDN, and to provide the original URL on MDN. If you do copy MDN content (and we would be happy if you did so), we ask that you comply with the license requirements. There is also a way on WPD to mark sections of articles as coming from MDN, for cases where they get merged into CC-BY content.

    Get involved

    We encourage all Mozillians to visit the Web Platform Docs site, take a look, and get involved. By working with the other stewards to jointly build a complete, concise, and accurate suite of documentation of and for Web standards, we can help make the future of the World Wide Web brighter than ever!

  2. Push the Web Further at Hackanooga

    If you enjoy pushing the limits of the open web platform, we want you to join us September 14-16 in The Gig City (Chattanooga, Tennessee) for a weekend of good food, good friends, and—most importantly—a unique opportunity to play on a citywide, 1 gigabit per second network.

    What happens when you hack with WebGL, WebRTC, Websockets and video—the coolest, newest open web technologies—on a network 200 times faster than the typical residential internet connection? What kinds of apps become possible?

    Travel grants

    If you’re already sold, head on over and apply. We’re awarding a number of grants for you to hang and hack in the American south. Your flight, meals, and accommodation will be paid for. And you’ll leave having made something cool—something only possible on a gigabit network.

    Just take 5 minutes to fill out this form, and we’ll get back to you by August 21st.

    If you need some convincing, read on.

    No more constraints

    If you’ve ever written software for mobile or web, you know all about constraints.

    Sometimes those constraints are plain as day. You can’t do heavy computation on a mobile device, because they’re relatively slow and you’ll quickly drain the battery. Apps written for mobile should be lean.

    Sometimes the constraints are more implicit. They’re just baked into your understanding of how development works.

    In a web app, you have a client and server. The connectivity between client and server is scarce, so you want to minimize the data traveling across the network. You don’t want your users sitting around waiting for an app to load, or for a video to buffer. Apps written for web should be frugal with data transfer.

    But if all of your users are on fast networks—think 100Mbps to 1Gbps—these sorts of constraints start to matter less.

    On a superfast network, it doesn’t really matter where the data lives in the network. It can travel so fast that it’s virtually instantaneous. It can travel faster than your computer can write the data to your hard drive.

    On a superfast network, it also doesn’t matter where the computation happens. It’s already the case with cloud computing that the very computation-heavy tasks and storage take place remotely. Your computer is just a thin client to the network. Think about what that would mean on a gigabit network—your entire operating system, identity and filesystem could be rapidly accessed from anywhere on the network.

    Real-time crunching of very heavy data could happen anywhere on the network. Anything, really—could happen anywhere, on the network.

    Hacking for public benefit

    OK, so what? New paradigms are fun to think about, but none of this matters until it has an impact on real people.

    That’s what US Ignite is all about—showing what kinds of apps are only possible on gigabit networks. Demonstrating that if the U.S. becomes more competitive in broadband & networks, people will be happier, healthier and more well informed.

    On the ideas front, we have a massive brainstorm underway around the question of “what’s possible with gigabit networks.”

    And on the coding front, we’ve already held the first Ignite hack days in San Francisco, with some interesting results. Hackanooga is already gearing up to be a blast.

    How it will work

    We have room for 80 participants. This is not a spectator sport—everyone who attends must contribute to coding, designing, and testing real prototype applications.

    Between now and the event, we’ll work together to form teams around specific app ideas. We’ll try to pick app ideas on which we can make substantial progress over the course of the weekend. If you want to work on a specific type of problem, or a specific technology, let us know.

    We’ll prepare your team as much as possible, rounding up resources, shoring up expertise, and connecting you with local institutions as appropriate.

    When you arrive, you’ll meet the whole Hackanooga class of 2012; eat, drink and be merry. Then, we’ll get out of your way so you can make.

    You’ll have access to wired, 1Gbps connectivity, local cloud infrastructure, and lots of coffee. We’ll show off all the results at the end.

    Work from this weekend can evolve to become submissions in the Mozilla Ignite apps challenge, with nearly $500k in awards for your prototype apps. It’s a great way to meet team members & partner institutions to get a head start on the challenge.

    Apply now!

    We’ll be flying around 10 participants from all over to attend Hackanooga. If you’re interested, apply here!

    Not only is Chattanooga an awesome place to visit, but you’ll be charting a far-out future for the web, pushing today’s technologies on tomorrow’s networks.

    If you have any questions, shoot us an email at ignite AT mozillafoundation DOT org, and make sure to follow @mozillaignite for the latest news.

  3. HTML5 Web applications and libraries survey – first results

    At Mozilla, we are dedicated to keep the web open and independent of a single company or technology. This means that users should have a choice of browsers and technology to use to go online and should not be blocked out because they can’t afford a certain device or are forbidden to change their browser.

    In the world of mobile web development there is currently a massive debate going on about the need for support of various browsers seeing that the most successful phone systems both use the same browser engine. This is good, and we need this debate. It is not good though when developers block out users because they concentrate on targetting a browser. Sometimes this is not by choice of the developer – they are simply using tools that do that blocking for them and the usefulness of the tool outweighs the qualms developers have about that.

    We are now planning to talk to library and tool developers and help them support more than one browser engine to prevent this. As a start of that process we wanted to get a glimpse of what people are using right now so we make sure we have the most impact when we help. This is why we started a quick online survey asking developers about their tools for mobile development.

    We are happy to report that to date we have 480 answers and it is time to take a first stab at looking at the data.

    We are very aware that this is *not* a scientifically clean research and should be taken with a grain of salt (we haven’t asked how many times people used the tools or how much of their work is building mobile apps) but it gives us a good first glimpse at what makes most sense for us to do.

    So without further ado, here are the raw numbers as charts:

    Platforms

    Not many surprises there, iOS and Android are in the lead, quite a lot of people see the web as a must-have (but this is a survey called out by Mozilla…) and Blackberry and Windows Mobile are not that hight on people’s radar.

    What platforms are you targeting with your apps – iOS
    focus 208 43%
    must have 168 35%
    supported 43 9%
    sometimes 24 5%
    not at all 36 8%
    What platforms are you targeting with your apps – Android
    focus 147 31%
    must have 183 38%
    supported 85 18%
    sometimes 33 7%
    not at all 31 6%
    What platforms are you targeting with your apps – Blackberry
    focus 5 1%
    must have 11 2%
    supported 83 17%
    sometimes 136 28%
    not at all 244 51%
    What platforms are you targeting with your apps – Web
    focus 306 64%
    must have 121 25%
    supported 26 5%
    sometimes 18 4%
    not at all 8 2%
    What platforms are you targeting with your apps – Windows phone
    focus 8 2%
    must have 36 8%
    supported 112 23%
    sometimes 137 29%
    not at all 186 39%

    Libraries

    jQuery rules supreme but Sencha touch and Zepto also have their place. Interestingly enough a lot of answers discarded libraries completely and considered them an overhead that will cause damage in the future.

    What libraries do you use to build mobile web apps/sites?
    jQuery 349 73%
    jQuery mobile 248 52%
    Zepto.js 90 19%
    JO 5 1%
    XUI.js 18 4%
    Sproutcore 7 1%
    Sencha touch 72 15%
    JQTouch 50 10%
    Mootools mobile 11 2%
    M project 1 0%
    Nimblekit 2 0%
    Lime.js 9 2%
    Wink 1 0%
    Uxebu Bikeshed 1 0%
    Other 126 26%
    People may select more than one checkbox, so percentages may add up to more than 100%.

    Conversion frameworks

    You do love your PhoneGap / Cordova, it seems. There is not too much competition in this market and a lot of feedback was questioning the sense of converting apps as “building them natively makes more sense”.

    Which frameworks do you use to convert apps to native apps?
    PhoneGap 257 90%
    Appcellerator 45 16%
    MoSync 2 1%
    Other 31 11%
    People may select more than one checkbox, so percentages may add up to more than 100%.

    Visual editors

    The space of visual editors seems to be not to frequented with this audience – would be interesting to see if there is already a mass market for WYSIWYG-like tools in the web app space.

    Do you use any visual tools/converters to build apps? If so, which?
    Adobe Edge 14 35%
    Sencha Animator 9 23%
    Other 18 45%
    People may select more than one checkbox, so percentages may add up to more than 100%.

    Webkit only?

    71% of the audience saying they test on other browsers than webkit is making us happy of course, but seeing that a lot of the tools in use are webkit only makes that number questionable. Then again, we didn’t qualify what testing entices in this case.

    Do you test on non-Webkit browsers?
    Yes 340 71%
    No 139 29%

    Reasons to test for webkit only

    The main reason here is a lack of time to test on other platforms which is understandable – we can assume that a lot of projects from a planning perspective have 99% iOS/Android written all over them. The “lack of incentive” number is high, too, which is understandable – if you can’t show the numbers, you don’t get the time to support.

    If no, can you tell us why?
    Fixed environment defined by client needs 36 23%
    Lack of time to support more browser platforms 85 54%
    Lack of incentive – I don’t know what the benefit of supporting more is 65 42%
    Lack of documentation how to install and debug on non-webkit browsers 39 25%
    Bugginess of other browsers on test platforms 24 15%
    Lack of support for other browsers on target hardware 55 35%
    Other 16 10%
    People may select more than one checkbox, so percentages may add up to more than 100%.

    More to come

    These are just the numbers right now. Soon we’ll be publishing also the free-form comments we got but for now this should get some discussion going and gives us a great start.

    And finally – a massive thank you for everybody who participated in this survey!

  4. The Web Developer Toolbox: Modernizr

    This is the third in a series of articles dedicated to useful libraries that all web developers should have in their toolbox. The intent is to show you what those libraries can do and help you to use them at their best. This third article is dedicated to the Modernizr library.

    Introduction

    Modernizer is a library originally written by Faruk Ateş.

    It is one of the key libraries for building cross-browser websites or applications in a modern fashion. The heart of the library is the web design pattern known as Progressive enhancement & Graceful degradation. This design pattern does not require Modernizr, but Modernizr can make things a lot easier. It detects the availability of native implementations for next-generation web technologies such as HTML5 or CSS3 and allow you to adapt your application accordingly, which is way better than trying some ugly voodoo user-agent sniffing.

    Basic usage

    Using this library is amazingly simple: Download it, link it to your pages—you’re done!

    Modernizr will automatically add some CSS classes to the root html element. For example if you want to test Web Sockets support, it will add a websockets class to the html element if the browser supports that feature, otherwise it will add the no-websockets class. It will do the same with JavaScript by adding a global variable Modernizr.websocket with a boolean value.

    Let’s see a simple example: Doing some stuff with RGBa colors.

    First: Download a customized version of Modernizr

    Modernizr, download page.

    Second: Link it to your document

    <!DOCTYPE html>
    <!--
    The "no-js" class is here as a fallback. 
    If Modernizr is not running, you'll know 
    something is wrong and you will be able to act 
    accordingly. In contrast, if everything goes well, 
    Modernizr will remove that special class.
    -->
    <html class="no-js">
    <head>
        <meta charset="utf-8">
        <title>I want to do stuff with RGBa</title>
        <script src="modernizr.js"></script>
    </head>
    <body>
    ...
    </body>
    </html>

    Third: Use it

    With CSS

    .rgba div {
        /* Do things with CSS for browsers that support RGBa colors */
    }
     
    .no-rgba div {
        /* Do things with CSS for browsers that DO NOT support RGBa colors */
    }

    With JavaScript

    if(Modernizr.rgba) {
        // Do things with JS for browsers that support RGBa colors
    } else {
        // Do things with JS for browsers that DO NOT support RGBa colors
    }

    Let’s see this silly example in action:

    Advanced usage

    The basic usage is already awesome when you have to deal with a heterogeneous environment (such as mobile browsers for example), but there’s more.

    Conditional loading

    Modernizr offers a convenient way to do conditional loading. Actually, the YepNope library is a standalone spin-off of the Modernizr project. So, if you wish, you can bundled YepNope directly inside Modernizr. It’s perfect if you want to load based polyfills depending on specific browser capacity.

    Modernizr.load({
        test: Modernizr.indexeddb,
        nope: "indexeddb-polyfill.js"
    });

    This is a very powerful tool: do not hesitate to read the documentation. Note that the Modernizr team maintain a list of very accurate polyfills. Feel free to use whatever you need (with caution, of course).

    Custom tests

    Modernizr come with a set of 44 tests for mainstream technologies. If you need to test some other technologies, Modernizr provide an API to build and plug your own tests.

    // Let's test the native JSON support ourselves
    Modernizr.addTest('json', function(){
        return window.JSON
            && window.JSON.parse
            && typeof window.JSON.parse === 'function'
            && window.JSON.stringify
            && typeof window.JSON.stringify === 'function';
    });
    

    Assuming the above test passes, there will be now a json class on the HTML element and Modernizr.json will be true. Otherwise, there will be a no-json class on the HTML element and Modernizr.json will be false.

    Dealing with CSS prefix

    CSS prefixes is a very sensitive subject. Modernizr provides cross-browser code to take care of this issue. Modernizr offers a very useful tool to deal with this: Modernizr.prefixed(). This method works with CSS properties (in the CSS OM camelCase style) as well as with DOM properties.

    For example, Modernizr.prefixed("transition") will return “MozTransition” with Firefox but “WebkitTransition” with Safari and Chrome.

    Testing media-queries

    There is currently no simple way to test a media query from JS in any browser. To help with that, Modernizr has a special tool: Modernizr.mq(). This method will test the media query of your choice and will return true or false accordingly.

    if(Modernizr.mq("screen and (max-width: 400px)")) {
        // Do some stuff for small screens
    }

    Limits and precautions

    This library is a fantastic tool but it’s not magic. You should use it with caution and do not forget about other techniques to deal with unpredictable behaviors. For example, do not forget to rely on the CSS cascade when it’s sufficient.

    The following example is a huge misuse of Modernizr:

    div {
        color : white;
    }
     
    .rgba div {
        background : rgba(0,0,0,.8);
    }
     
    .no-rgba div {
        background : #333;
    }

    If for some reason Modernizr is not executed, your text will not be readable (white text over a white background). In this specific case, you are better doing the following (which, by the way, is also easier to read and maintain):

    div {
        color : white;
        background : #333;
        background : rgba(0,0,0,.8);
    }

    So, don’t be blind when you use this library, take the time to think about what will happen if Modernizr is not available. In many case you have existing fallbacks, don’t forget to use them.

    Conclusion

    Modernizr is the most useful tool when you have to build large cross-browser stuff, from the oldest Internet Explorer 6 to the latest Firefox Nightly. Once you master it, you will be able to add some magic to your sites and applications. However, as with all the powerful tools, it takes some time to become comfortable with and to use it wisely at its full potential. But, Modernizr is definitely worth the effort.

  5. getUserMedia is ready to roll!

    We blogged about some of our WebRTC efforts back in April. Today we have an exciting update for you on that front: getUserMedia has landed on mozilla-central! This means you will be able to use the API on the latest Nightly versions of Firefox, and it will eventually make its way to a release build.

    getUserMedia is a DOM API that allows web pages to obtain video and audio input, for instance, from a webcam or microphone. We hope this will open the possibility of building a whole new class of web pages and applications. This DOM API is one component of the WebRTC project, which also includes APIs for peer-to-peer communication channels that will enable exchange of video steams, audio streams and arbitrary data.

    We’re still working on the PeerConnection API, but getUserMedia is a great first step in the progression towards full WebRTC support in Firefox! We’ve certainly come a long way since the first image from a webcam appeared on a web page via a DOM API. (Not to mention audio recording support in Jetpack before that.)

    We’ve implemented a prefixed version of the “Media Capture and Streams” standard being developed at the W3C. Not all portions of the specification have been implemented yet; most notably, we do not support the Constraints API (which allows the caller to request certain types of audio and video based on various parameters).

    We have also implemented a Mozilla specific extension to the API: the first argument to mozGetUserMedia is a dictionary that will also accept the property {picture: true} in addition to {video: true} or {audio: true}. The picture API is an experiment to see if there is interest in a dedicated mechanism to obtain a single picture from the user’s camera, without having to set up a video stream. This could be useful in a profile picture upload page, or a photo sharing application, for example.

    Without further ado, let’s start with a simple example! Make sure to create a pref named “media.navigator.enabled” and set it to true via about:config first. We’ve put the pref in place because we haven’t implemented a permissions model or any UI for prompting the user to authorize access to the camera or microphone. This release of the API is aimed at developers, and we’ll enable the pref by default after we have a permission model and UI that we’re happy with.

    There’s also a demo page where you can test the audio, video and picture capabilities of the API. Give it a whirl, and let us know what you think! We’re especially interested in feedback from the web developer community about the API and whether it will meet your use cases. You can leave comments on this post, or on the dev-media mailing list or newsgroup.

    We encourage you to get involved with the project – there’s a lot of information about our ongoing efforts on the project wiki page. Posting on the mailing list with your questions, comments and suggestions is great way to get started. We also hang out on the #media IRC channel, feel free to drop in for an informal chat.

    Happy hacking!

  6. The Web Developer Toolbox: ThreeJS

    This is the second of a series of articles dedicated to the useful libraries that all web developers should have in their toolbox. The intent is to show you what those libraries can do and help you to use them at their best. This second article is dedicated to the ThreeJS library.

    Introduction

    ThreeJS is a library originally written by Ricardo Cabello Miguel aka “Mr. Doob“.

    This library makes WebGL accessible to common human beings. WebGL is a powerful API to manipulate 3D environments. This web technology is standardized by the Kronos group and Firefox, Chrome and Opera now implement it as a 3D context for the HTML canvas tag. WebGL is basically a web version of another standard : OpenGL ES 2.0. As a consequence, this API is a “low level” API that require skills and knowledge beyond what web designers are used to. That’s where ThreeJS comes into play. ThreeJS gives web developers access to the power of WebGL without all the knowledge required by the underlying API.

    Basic usage

    The library has good documentation with many examples. You’ll notice that some parts of the documentation are not complete yet (feel free to help). However, the library and examples source code are very well structured, so do not hesitate to read the source.

    Even though ThreeJS simplifies many things, you still have to be comfortable with some basic 3D concepts. Basically, ThreeJS uses the following concepts:

    1. The scene: the place where all 3D objects will be placed and manipulated in a 3D space.
    2. The camera: a special 3D object that will define the rendering point of view as well as the type of spatial rendering (perspective or isometric)
    3. The renderer: the object in charge of using the scene and the camera to render your 3D image.

    Within the scene, you will have several 3D objects which can be of the following types:

    • A mesh: A mesh is an object made of a geometry (the shape of your object) and a material (its colors and texture)
    • A light point: A special object that defines a light source to highlight all your meshes.
    • A camera, as described above.

    The following example will draw a simple wireframe sphere inside an HTML element with the id “myPlanet”.

    /**
     * First, let's prepare some context
     */
     
    // The WIDTH of the scene to render
    var __WIDTH__  = 400,
     
    // The HEIGHT of the scene to render
        __HEIGHT__ = 400,
     
    // The angle of the camera that will show the scene
    // It is expressed in degrees
        __ANGLE__ = 45,
     
    // The shortest distance the camera can see
        __NEAR__  = 1,
     
    // The farthest distance the camera can see
        __FAR__   = 1000
     
    // The basic hue used to color our object
        __HUE__   = 0;
     
    /**
     * To render a 3D scene, ThreeJS needs 3 elements:
     * A scene where to put all the objects
     * A camera to manage the point of view
     * A renderer place to show the result
     */
    var scene  = new THREE.Scene(), 
        camera = new THREE.PerspectiveCamera(__ANGLE__, 
                                             __WIDTH__ / __HEIGHT__, 
                                             __NEAR__, 
                                             __FAR__),
        renderer = new THREE.WebGLRenderer();
     
    /**
     * Let's prepare the scene
     */
     
    // Add the camera to the scene
    scene.add(camera);
     
    // As all objects, the camera is put at the 
    // 0,0,0 coordinate, let's pull it back a little
    camera.position.z = 300;
     
    // We need to define the size of the renderer
    renderer.setSize(__WIDTH__, __HEIGHT__);
     
    // Let's attach our rendering zone to our page
    document.getElementById("myPlanet").appendChild(renderer.domElement);
     
    /**
     * Now we are ready, we can start building our sphere
     * To do this, we need a mesh defined with:
     *  1. A geometry (a sphere) 
     *  2. A material (a color that reacts to light)
     */
    var geometry, material, mesh;
     
    // First let's build our geometry
    //
    // There are other parameters, but you basically just 
    // need to define the radius of the sphere and the 
    // number of its vertical and horizontal divisions.
    //
    // The 2 last parameters determine the number of 
    // vertices that will be produced: The more vertices you use, 
    // the smoother the form; but it will be slower to render. 
    // Make a wise choice to balance the two.
    geometry = new THREE.SphereGeometry( 100, 20, 20 );
     
    // Then, prepare our material
    var myMaterial = {
        wireframe : true,
        wireframeLinewidth : 2
    }
     
    // We just have to build the material now
    material = new THREE.MeshPhongMaterial( myMaterial );
     
    // Add some color to the material
    material.color.setHSV(__HUE__, 1, 1);
     
    // And we can build our the mesh
    mesh = new THREE.Mesh( geometry, material );
     
    // Let's add the mesh to the scene
    scene.add( mesh );
     
    /**
     * To be sure that we will see something, 
     * we need to add some light to the scene
     */
     
    // Let's create a point light
    var pointLight = new THREE.PointLight(0xFFFFFF);
     
    // and set its position
    pointLight.position.x = -100;
    pointLight.position.y = 100;
    pointLight.position.z = 400;
     
    // Now, we can add it to the scene
    scene.add( pointLight );
     
     
    // And finally, it's time to see the result
    renderer.render( scene, camera );

    And if you want to animate it (for example, make the sphere spin), it’s this easy:

    function animate() {
        // beware, you'll maybe need a shim 
        // to use requestAnimationFrame properly
        requestAnimationFrame( animate );
     
        // First, rotate the sphere
        mesh.rotation.y -= 0.003;
     
        // Then render the scene
        renderer.render( scene, camera );
    }
     
    animate();

    JSFiddle demo.

    Advanced usage

    Once you master the basics, ThreeJS provides you with some advanced tools.

    Rendering system

    As an abstraction layer, ThreeJS offer options to render a scene other than with WebGL. You can use the Canvas 2D API as well as SVG to perform your rendering. There is some difference between all these rendering contexts. The most obvious one is performance. Because WebGL is hardware accelerated, the rendering of complex scene is amazingly faster with it. On the other hand, because WebGL does not deal always well with anti-aliasing, the SVG or Canvas2D rendering can be better if you want to perform some cell-shading (cartoon-like) stuff. As a special advantage, SVG rendering gives you a full DOM tree of objects, which can be useful if you want access to those objects. It can have a high cost in term of performance (especially if you animate your scene), but it allows you to not rebuild a full retained mode graphic API.

    Mesh and particles

    ThreeJS is perfect for rendering on top of WebGL, but it is not an authoring tool. To model 3D objects, you have a choice of 3D software. Conveniently, ThreeJS is available with many scripts that make it easy to import meshes from several sources (Examples include: Blender, 3DSMax or the widely supported OBJ format).

    It’s also possible to easily deploy particle systems as well as using Fog, Matrix and custom shaders. ThreeJS also comes with a few pre-built materials: Basic, Face, Lambert, Normal, and Phong). A WebGL developer will be able to build his own on top of the library, which provide some really good helpers. Obviously, building such custom things requires really specific skills.

    Animating mesh

    If using requestAnimationFrame is the easiest way to animate a scene, ThreeJS provides a couple of useful tools to animate meshes individually: a full API to define how to animate a mesh and the ability to use “bones” to morph and change a mesh.

    Limits and precaution

    One of the biggest limitations of ThreeJS is related to WebGL. If you want to use it to render your scene, you are constrained by the limitations of this technology. You become hardware dependent. All browsers that claim to support WebGL have strong requirements in terms of hardware support. Some browsers will not render anything if they do not run with an appropriate hardware. The best way to avoid trouble is to use a library such as modernizr to switch between rendering systems based on each browser’s capabilities. However, take care when using non-WebGL rendering systems because they are limited (e.g. the Phong material is only supported in a WebGL context) and infinitely slower.

    In terms of browser support, ThreeJS supports all browsers that support WebGL, Canvas2D or SVG, which means: Firefox 3.6+, Chrome 9+, Opera 11+, Safari 5+ and even Internet Explorer 9+ if you do not use the WebGL rendering mode. If you want to rely on WebGL, the support is more limited: Firefox 4+, Chrome 9+, Opera 12+, Safari 5.1+ only. You can forget Internet Explorer (even the upcoming IE10) and almost all mobile browsers currently available.

    Conclusion

    ThreeJS drastically simplifies the process of producing 3D images directly in the browser. It gives the ability to do amazing visual effects with an easy to use API. By empowering you, it allow you to unleash your creativity.

    In conclusion, here are some cool usages of ThreeJS:

  7. The Web Developer Toolbox: Raphaël

    This is the first of a series of articles dedicated to the useful libraries that all web developers should have in their toolbox. My intent is to show you what those libraries can do and help you to use them at their best. This first article is dedicated to the Raphaël library.

    Introduction

    Raphaël is a library originally written by Dmitry Baranovskiy and is now part of Sencha Labs.

    The goal of this library is to simplify work with vector graphics on the Web. Raphaël relies on the SVG W3C Recommendation (which is well supported in all modern browsers) and falls back to the Micrsoft VML language in order to address legacy versions of Internet Explorer. It also tries to harmonize some working issues across SVG implementations such as the SVG Animations. As a consequence, Raphaël is a very nice wrapper to produce consistent kick-ass graphics all over the Web.

    Basic usage

    The library has very good documentation with many examples. Do not hesitate to use it extensively.

    The following example will draw a simple red circle inside an HTML element with the id “myPaper”.

    // the following example creates a drawing zone
    // that is 100px wide by 100px high.
    // This drawing zone is created at the top left corner
    // of the #myPaper element (or its top right corner in
    // dir="rtl" elements)
    var paper = Raphael("myPaper", 100, 100); 
     
    // The circle will have a radius of 40
    // and its center will be at coordinate 50,50
    var c = paper.circle(50, 50, 40); 
     
    // The circle will be filled with red
    // Note that the name of each element property
    // follow the SVG recommendation
    c.attr({
        fill: "#900"
    });

    Advanced usage

    Despite the fact that Raphaël reduces the possibilities offered by SVG (mainly because of the VML fallback) it allows one to perform very advanced stuff:

    • Advance Matrix transformation
    • Advance event handler
    • Cross browser animations
    • Easy drag system
    • Path intersection detection

    Raphaël is also extensible through an extension system that allows you to build custom functions.

    For example, here’s an extension to draw pie charts:

    /**
     * Pie method
     *
     * cx: x position of the rotating center of the pie
     * cy: y position of the rotating center of the pie
     * r : radius of the pie 
     * a1: angle expressed in degrees where the pie start
     * a2: angle expressed in degrees where the pie end
     */
    Raphael.fn.pie = function (cx, cy, r, a1, a2) {
        var d,
            flag = (a2 - a1) &gt; 180; 
     
        a1 = (a1 % 360) * Math.PI / 180;
        a2 = (a2 % 360) * Math.PI / 180; 
     
        d = [
            // Setting the rotating axe of the pie
            "M", cx, cy,
     
            // Go to the start of the curve
            "l", r * Math.cos(a1), r * Math.sin(a1),
     
            // Drawing the curve to its end
            "A", r, r, "0", +flag, "1",
            cx + r * Math.cos(a2), cy + r * Math.sin(a2),
     
            // Closing the path
            "z"
        ]; 
     
        return this.path(d.join(' '));
    };

    Note: In the example above, you have to be familiar with the SVG path syntax (Raphaël will convert it to the VML syntax under the hood), but once it’s done you can reuse it as any other Raphaël primitive. Look at this extension working to draw a color wheel on jsFiddle.

    JSFiddle demo.

    Limits and precaution

    If you are not familiar with SVG and/or want to support legacy MS Internet Explorer browsers, this tool is made for you. However, it’s a JavaScript library, which means that you have to know JavaScript to use it. You cannot use SVG and ask Raphaël to parse it and interpret it (to do that, it exists other libraries).

    In terms of browser support, Raphaël gives you a large base. Raphaël currently supports Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.

    In fact, the only browser that can not take advantage of Raphaël is the native browser for Android 1.x and 2.x (and obviously many feature phone browsers). This is due to the fact that those browsers do not support any vector language. Android starts (partially) supporting SVG with Android 3.0 so take care if you want to work with all mobile devices.

    Conclusion

    Raphaël was the first library to allow web designers and web developers to use SVG in the wild. If you want to write some nice applications without the need of the full SVG DOM API or if you have to support legacy browsers, this library will give you some power.

    In conclusion, here are some cool usages of Raphaël:

  8. Ask your HTML5 Browser Tools Questions for SXSW Panel.

    At this years “South by Southwest” (SXSW) Interactive event I’m joining Paul Irish from Google, Mike Taylor from Opera, Brandon Satron from Telerik and Javascript Developer and author Garann Means in a panel on “The State of Browser Developer Tools

    The group has a Google Moderator page where you can ask your questions in advance. Please do so.

    Not able to attend the panel at SXSW? No problem. I’ll post a collection of the questions and answer right here on Hacks sometime after the event.

  9. Q & A With Michal Biniek: HTML5 Hacker and Frequent Dev Derby Winner

    Editor’s Note: Michal Biniek is a frontend developer on the Innogames Lagoonia team, and an enthusiast of JavaScript and new web technologies like HTML5/CSS3, WebSockets, and WebRTC. Back in November, michal.b took 2nd place in the MDN Developer Derby with Rob in Soundland, a fanciful Canvas demo.

    It was the fourth time one of Michal’s demos made to the Derby finals, and it was the third time he’d placed. If you’ve been following Dev Derby since it launched last year, you might remember seeing Fly, fly! or Too Many Fish in the Sea. Congratulations Michal, we can’t wait to see your next demo! Submissions are now open for upcoming Derbies: CSS 3D transforms, Audio, and the Web Sockets API.


    Tell us about developing Rob in Soundland and where your idea came from?

    My first idea for the Canvas demo was to prepare some kind of visualization – a sound visualization which could make a nice connection between two senses – vision and hearing. I thought it would be also nice if the user could interact with the application through keyboard or mouse.

    Finally I decided to prepare a simple game with third-person view in an infinite world, where the main character – Rob – wanders through the colorful (almost psychedelic) squares which are playing different notes.

    Interesting fact is that the game doesn’t contain any external media elements like images or sounds. Everything is generated using HTML5 technologies: Images are pre-generated at the start of the game and sounds are created and played ad hoc using the Audio Data API.

    Rob in Soundland - Canvas demo screenshot

    Do you remember your first computer and your first website?

    My first computer was Elwro Junior – the Polish version of a ZX Spectrum computer (English description here). A few years later I got my first PC with a 486 25MHz processor inside and a magical ‘turbo’ button.

    My history with websites started around 1999 when I prepared a site about my hobbies – skiing and astronomy. I even put some animations using JavaScript and DHTML (a buzzword from long ago):
    Never the marquee tag ;)


    How did you get started coding and hacking?

    I started coding on ZX Spectrum in BASIC, but shortly after that I moved to Turbo Pascal on the new PC. I think it is also important that my father was an IT teacher at school – so when I had some problems with programming I could always ask him for help.

    For me, the visual is one of the most important aspects of an application. That’s why I found Delphi/C++ Builder a really nice solution for building UIs. This is also the reason why I liked HTML from the beginning – as a perfect language for UIs, which with JavaScript is much easier to run animations rather that trying to run it on forms.

    You mentioned you’re from Wroclaw, Poland, and work as a Web developer for Innogames? Do you work remotely? What tools do you use for development?

    Actually, I live in Hamburg, where I got the software developer job at Innogames half a year ago. However, I still quite often visit Wroclaw.

    I’m working in team that works on Lagoonia, one of the latest games developed by Innogames. Modern Javascript engines in browsers enable us to take full advantage of JavaScript (and new features from HTML5 like sound and canvas). We can create games which easily compete with Flash-based games without additional runtime machine!

    Lagoonia by Innogames

    I usually use Eclipse to develop JavaScript applications. I find it a quite good code editor (however sometimes slow) with code auto-completion that works quite well. For testing and debugging, I use Firebug and the built-in console in Firefox, one of the best debugging tools for web applications ever.

    Do you play online games? What games influence your work? What do you play the most these days?

    I discovered online games while I was a student. I started with FPS shooters then switched to MMORPGs like MuOnline. I think that multiplayer games are the future of gaming – it is usually much more fun to play with real players rather than against a computer.

    My current company – Innogames is also focused on online games (mainly browser games) where the most important part is cooperation with other users.

    We can still observe old games (even from the days of the ZX Spectrum) refreshed with new fancy graphics and multiplayer mode which are bestsellers nowadays. However, many indie games show us completely new concepts of games – and I think these types of games influence me the most.

    Apart from that, I really like Valve games – especially for great stories in games like Half Life/Portal universum.

    The Nyan Cat version of your August History API demo reminded us how fast memes can travel on the Internet. Tell us about Fly, fly! and how the idea came to you?

    It was quite hard to find an original idea for the usage of History API, which in my opinion is prepared especially for websites using AJAX to set up the content. However, it could also be used as a timeline for virtual travels. The initial idea for this project was a flight by plane through the different cities.
    However I found it boring and I decided to add the popular Nyan Cat – one of the most positive memes – as an optional mean of transport. This choice causes the Nyan Cat to leave a rainbow-colored contrail in the sky, instead of leaving white lines, which makes the world more colorful and friendly for people.

    In addition, everything was matched to the original concept of the demo, even the different graphics looks much better – dark background, Nyan Cat instead of a plane, and a colorful path for the journey.

    Fly, fly - History API demo

    You’ve submitted 7 Dev Derby demos since the program launched, and 4 of them have placed as finalists. Congratulations and thank you! Are you working on another demo? Any other cool projects you want to tell us about?

    Thank you! Currently I’m working on another simple game using touch events, however a project grew up a bit and I’m not sure if I’ll find enough time to finish it before the deadline.
    Zombie-kiwi-touchevents-demo screenshot

    In the meantime I’m working with my colleague Barry Nagel on our own framework for HTML5 games, which is named Machine5. The goal of this project is to find the simplest way to create stunning HTML5 games and to provide a simple and easily maintainable project structure for developers.

    Machine5 game engine


    When you think about HTML5 & new Web technologies what are you most excited about?

    I’m really glad that the Canvas element is currently widely available and I can freely use it. It is a perfect solution for simple games – and I hope soon WebGL will be also available on all browsers, because it is a great feature that allows creating fullscreen games. Using these technologies together with new audio APIs and WebSockets or WebRTC as a communication stream, we can soon expect real FPS games like Counter Strike or a less violent type of game such as Sims MMO version ;)

    Anybody else who helps on your demos? Anyone you want to mention?

    I’d like to thank to Robert Zatycki for all the brainstorms about possible ideas for games and other applications. Some concepts which we were talking about were used in games.

    And I’d also like to thank to my brothers – Paweł and Łukasz who tested carefully my demos before I released them and for their frank feedback.

    What inspired you to participate in Dev Derby? Can you say something more about Open Source, Mozilla and why you contribute?

    Before the Dev Derby contest, I’d prepared some demos for Chrome Experiments and for Opera Widgets websites. Then I got a message from John Karahalis, where he mentioned a new Mozilla project for demos especially for new technologies.

    Currently I find the MDN is one of the best resources for JavaScript. All the work done by Mozilla to contribute, prepare and promote new technologies is great and really important for the modern internet. Firefox is one of the most popular web browsers, (and in Poland the most popular!) which I think is the best example that users also appreciate Mozilla’s excellent product.

    One idea of Open Source is really important: even nowadays when almost every concept can be patented, there are still a lot of people who are open to sharing their experience with other developers without any profit. I find that sharing code can be the best way to get feedback about code quality and to get suggestions for other possible (sometimes better) solutions for an application.

  10. Mozilla’s Boot to Gecko – The Web is the Platform

    Mozilla’s Boot to Gecko (B2G) is about building a complete, standalone operating system for the open web. It aims at making web technologies the number one choice for applications on desktop and mobile, and we believe it can displace proprietary, single-vendor stacks for application development. And we have made some exciting progress that we want to share with you!

    Continued…