Mozilla

JavaScript Articles

Sort by:

View:

  1. Detecting and generating CSS animations in JavaScript

    When writing of the hypnotic spiral demo the issue appeared that I wanted to use CSS animation when possible but have a fallback to rotate an element. As I didn’t want to rely on CSS animation I also considered it pointless to write it by hand but instead create it with JavaScript when the browser supports it. Here’s how that is done.

    Testing for the support of animations means testing if the style attribute is supported:

    var animation = false,
        animationstring = 'animation',
        keyframeprefix = '',
        domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
        pfx  = '';
     
    if( elm.style.animationName ) { animation = true; }    
     
    if( animation === false ) {
      for( var i = 0; i < domPrefixes.length; i++ ) {
        if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
          pfx = domPrefixes[ i ];
          animationstring = pfx + 'Animation';
          keyframeprefix = '-' + pfx.toLowerCase() + '-';
          animation = true;
          break;
        }
      }
    }

    [Update - the earlier code did not check if the browser supports animation without a prefix - this one does]

    This checks if the browser supports animation without any prefixes. If it does, the animation string will be ‘animation’ and there is no need for any keyframe prefixes. If it doesn’t then we go through all the browser prefixes (to date :)) and check if there is a property on the style collection called browser prefix + AnimationName. If there is, the loop exits and we define the right animation string and keyframe prefix and set animation to true. On Firefox this will result in MozAnimation and -moz- and on Chrome in WebkitAnimation and -webkit- so on. This we can then use to create a new CSS animation in JavaScript. If none of the prefix checks return a supported style property we animate in an alternative fashion.

    if( animation === false ) {
     
      // animate in JavaScript fallback
     
    } else {
      elm.style[ animationstring ] = 'rotate 1s linear infinite';
     
      var keyframes = '@' + keyframeprefix + 'keyframes rotate { '+
                        'from {' + keyframeprefix + 'transform:rotate( 0deg ) }'+
                        'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+
                      '}';
     
      if( document.styleSheets && document.styleSheets.length ) {
     
          document.styleSheets[0].insertRule( keyframes, 0 );
     
      } else {
     
        var s = document.createElement( 'style' );
        s.innerHTML = keyframes;
        document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
     
      }
     
    }

    With the animation string defined we can set a (shortcut notation) animation on our element. Now, adding the keyframes is trickier. As they are not part of the original Animation but disconnected from it in the CSS syntax (to give them more flexibility and allow re-use) we can’t set them in JavaScript. Instead we need to write them out as a CSS string.

    If there is already a style sheet applied to the document we add this keyframe definition string to that one, if there isn’t a style sheet available we create a new style block with our keyframe and add it to the document.

    You can see the detection in action and a fallback JavaScript solution on JSFiddle:

    JSFiddle demo.

    Quite simple, but also a bit more complex than I originally thought. You can also dynamically detect and change current animations as this post by Wayne Pan and this demo by Joe Lambert explains but this also seems quite verbose.

    I’d love to have a CSSAnimations collection for example where you could store different animations in JSON or as a string and have their name as the key. Right now, creating a new rule dynamically and adding it either to the document or append it to the ruleset seems to be the only cross-browser way. Thoughts?

  2. Calculated drop shadows in HTML5 canvas

    One of the best new features of HTML5 when it comes to visual effects is the canvas element and its API. On the surface, it doesn’t look like much – just a rectangle in the page you can paint on and wipe. Much like an etch-a-sketch. However, the ability to transform, rotate and scale its coordinate system is very powerful indeed once you master it.

    Today I want to quickly show how you can do (well simulate) something rather complex with it, like a calculated drop shadow on an element. To see what I mean with this, check out the following demo which is also available on the Demo Studio:


    See animated version on JSFiddle

    (This is using JSFiddle to show you the demos, so you can click the different tabs to see the JavaScript and CSS needed for the effects. All of the demos are also available on GitHub.)

    As you can see, the shadow becomes more blurred and less pronounced the further away the “sun” is from it. You can use the mouse to see the effect in the following demo:


    See mouse enabled demo on JSFiddle

    Let’s take a look how that is done. The first step is to have a canvas we can paint on – you do this simply by having a mouse detection script (which we used for years and years) and a canvas with access to its API:


    See step one on JSFiddle

    Click the play button of the above example and you see that you can paint on the canvas. However, the issue is that you keep painting on the canvas instead of only having the orb follow the cursor. To do this, we need to wipe the canvas every time the mouse moves. You do this with clearRect()


    See step two on JSFiddle

    Running the above example now shows that the orb moves with the mouse. Cool, so this is going to be our “sun”. Now we need to place an object on the canvas to cast a shadow. We could just plot it somewhere, but what we really want is it to be in the middle of the canvas and the shadow to go left and right from that. You can move the origin of the canvas’ coordinate system using translate(). Which means though that our orb is now offset from the mouse:


    See step three on JSFiddle

    If you check the “fix mouse position” checkbox you see that this is fixed. As we move the coordinate system to the half of the width of the canvas and half of its height, we also need to substract these values from the mouse x and y position.

    Now we can draw a line from the centre of the canvas to the mouse position to see the distance using c.moveTo( 0, 0 );c.lineTo( distx, disty ); where distx and disty are the mouse position values after the shifting:


    See step four on JSFiddle

    In order to find out the distance of the shadow, all we need to do is multiply the mouse coordinates with -1 – in this demo shown as a red line:


    See step five on JSFiddle

    This gives us a shadow distance from the centre opposite of the mouse position, but we don’t want the full length. Therefore we can apply a factor to the length, in our case 0.6 or 60%:


    See step six on JSFiddle

    Now we are ready for some drop shadow action. You can apply shadows to canvas objects using shadowColor and its distance is shadowOffsetX and shadowOffsetY. In our case, this is the end of the red line, the inversed and factored distance from the mouse position to the centre of the canvas:


    See step seven on JSFiddle

    Now, let’s blur the shadow. Blurring is done using the shadowBlur property and it is a number starting from 0 to the strength of the blur. We now need to find a way to calculate the blur strength from the distance of the mouse to the centre of the canvas. Luckily enough, Pythagoras found out for us years ago how to do it. As the x and y coordinate of the mouse are the catheti of a right-angled triangle, we can calculate the length of the hypothenuse (the distance of the point from the centre of the canvas) using the Square root of the squares of the coordinates or Math.sqrt( ( distx * distx ) + ( disty * disty ) ).

    This gives us the distance in pixels, but what the really want is a number much lower. Therefore we can again calculate a factor for the blur strength – here we use an array for the weakest and strongest blur blur = [ 2, 9 ]. As the canvas itself also has a right-angled triangle from the centre to the top edge points we can calculate the longest possible distance from the center using longest = Math.sqrt( ( hw * hw ) + ( hh * hh ) ) where hw is half the width of the canvas and hh half the height. Now all we need to do is to calculate the factor to multiply the distance with as blurfactor = blur[1] / longest. The blur during the drawing of the canvas is the distance of the mouse position multiplied with the factor or currentblur = parseInt( blurfactor * realdistance, 10 );. We disregard blur values below the range we defined earlier and we have our blurred shadow:


    See step eight on JSFiddle

    In order to make the shadow weaker the further away the mouse is we can use the alpha value of its rgba() colour. The same principle applies as with the blur, we set our edge values as shadowalpha = [ 3, 8 ] and after calculating them from the distance we apply their inverse as the alpha value with c.shadowColor = 'rgba(0,0,0,' + (1 - currentalpha / 10) + ')';. This blurs and weakens the shadow:


    See step nine on JSFiddle

    You can do a lot more with this, for example we could also scale the sun orb the further out it gets or use a second shape to resize and blur it. You can also go completely overboard.

    Found a way to optimise this? Tell us about it!

  3. speak.js: Text-to-Speech on the Web

    Text-to-Speech (TTS) can make content more accessible, but there is so far no simple and universal way to do that on the web. One possible approach is shown in this demo, which is powered by speak.js, a new 100% pure JavaScript/HTML5 TTS implementation. speak.js is a port of eSpeak, an open source speech synthesizer, from C++ to JavaScript using Emscripten.

    Compiling an existing speech synthesis engine to JavaScript is a good way to avoid writing a complicated project like eSpeak from scratch. Once compiled, the eSpeak code in speak.js doesn’t know it’s running on the web: speak.js uses the Emscripten emulated filesystem to ‘fake’ the normal file reading and writing calls that the eSpeak C++ code has (fopen, fread, etc.). This allows the normal eSpeak datafiles to be used (either through an xhr, or by converting them to JSON and bundling them with the script file). The result of running the compiled eSpeak code is that it ‘writes’ a .wav file with the generated audio to the emulated filesystem. speak.js then takes that data, encodes it using base64, and creates a data URL. That URL is then loaded in an HTML5 audio element, letting the browser handle playback. (Note that while that is a very simple way to do things, it isn’t the most efficient. speak.js has not yet focused on speed, but with some additional work it could be much faster, if that turns out to be an issue.)

    Why would you want TTS in JavaScript? Well, with speak.js you can bundle a single .js file in your website, and then generating speech is about as simple as writing

    speak("hello world")

    (see the speak.js website for instructions). The generated speech will be exactly the same on all platforms, unlike if your users each did TTS in their own way (using an OS capability, or a separate program). speak.js can also be used to build browser addons in a straightforward way, since it’s pure JavaScript – no need for platform dependent binaries, and the addon will work the same on all OSes.

    A few more comments:

    • JavaScript is getting more and more capable all the time. The development versions of the top JavaScript engines today can run code compiled from C++ only 3-5X slower than a fast C++ compiler, and getting even better. As a consequence, expanding the capabilities of the web platform can in many cases be done in JavaScript or by compiling to JavaScript, instead of adding new code to the browsers themselves, which inevitably takes longer – especially if you wait for all browsers to implement a particular feature.
    • While speak.js uses only standards-based APIs, due to browser limitations it can’t work everywhere yet. It won’t work in IE, Safari or Opera since they don’t support typed arrays, nor in Chrome since it doesn’t support WAV data URLs. So currently speak.js only works properly in Firefox. However, the missing features just mentioned are not huge and hopefully those browser makers will implement them soon. It is also possible to implement workarounds in speak.js for these issues (see next comment).
    • Help with improving speak.js is very welcome! One important thing we need is to implement workarounds for the issues that prevent speak.js from running on the browsers it currently can’t run on. Another goal is to build browser addons using speak.js. Please get in touch on github if you want to help out.
    • eSpeak supports multiple languages so speak.js can too. You do need to include the additional language files though. Here is an experimental build where you can switch between English and French support (note that it is an unoptimized build, so it will run slower).
  4. Webinar: History API with Syd Lawrence

    Update 2011-08-19: We had intended to record this webinar and make it available for those who couldn’t attend. Due to a convergence of technical difficulties, the recording was not successful. Apologies for failing on that promise. You can see Syd’s slides and a recording of a similar talk Syd gave at the Heart & Sole conference earlier this year.

    On Thursday, August 18th at 16:00 UTC, the latest installment of the MDN webinar series will be presented by Syd Lawrence, on the topic of using the History API to make AJAX sites more friendly. The History API is also the topic for the August DevDerby and this week’s Ask MDN session on Twitter (which Syd will also be helping out with). So you can get your head full of History API know-how, whip up an amazing History API demo, and submit it for the DevDerby!

    Syd Lawrence is a freelance front-end web developer, living in Winchester UK, who speaks at a variety of conferences and is also a part-time lecturer at Winchester University in digital media development.

    This is the third MDN webinar, and our third experiment in webinar technology. This time around, we’re using BigBlueButton, an open-source web-conferencing system (thanks to our friends at Blindside Networks). It was used for the Knight-Mozilla News (MoJo) Learning Lab in July, and worked pretty well for that. Since it’s open source, if there’s something about it you don’t like, you can do something about it.

    Add this event to your calendar:

    To join the webinar:

    1. Go to the BigBlueButton server for Mozilla.
    2. For Full Name, enter your name.
    3. Select “Mozilla Developer Network” in the Room list.
    4. For Password, enter MDNHacks.

    Note: Big Blue Button uses Flash, so make sure you have the latest version installed, especially if you are running Mac OS X Lion.

  5. Rendering 3D with CSS and JavaScript with dom3d (guest post)

    James Long Today we have a guest post by James Long (@jlongster).

    James is the tech lead for mozilla.com on the Web Development team. James is passionate about interactive graphics on the open web.

    Today he explains how you can create 3D objects using CSS without having 3D transforms support. Take it away, James.


    Recently I was tinkering with CSS3 and I discovered that it enabled me to do primitive 3D rendering, which I found fascinating! This led to the creation of dom3d, a JavaScript library that uses CSS to render basic 3D objects.

    Now the question is: why? Aren’t canvas, WebGL, and even SVG better technologies to work with for this? Possibly. However, CSS is becoming a powerful language for describing complex effects and shapes, and we should experiment.

    Keep that in mind, because CSS definitely isn’t intended to do this, but it’s worth trying to see where we should take CSS in the future.

    Advantages

    Although this is more of an experiment, it has a few real world benefits:

    All rendering libraries available for the web (canvas, WebGL, SVG) require a canvas, which is a constrained box on the page with a specific width and height. It is not possible to render anything outside this box. The canvas also captures all DOM events (like clicks), even completely transparent sections. Theoretically, this could make it difficult to do effects that overlay large parts of the page or are somehow deeply integrated to the content.

    Using CSS, we aren’t constrained to a box, and the effect can overlay large portions of the page without covering any the the links or other content requiring interaction.

    Other advantages include no need to initialize canvas 2D or WebGL, and a simplistic API making it easy to pick up even if you don’t know much about 3D. It might be easier for kids to start playing around with this before they jump into WebGL or something else. Also, because it’s just a dump of DOM elements you can embed it anywhere (without animation).

    So keep in mind that this is a hack, but with the above advantages. This might be good for certain effects: 3D cursor, nav transitions, and others.

    How it works

    Three-D objects are just a bunch of triangles put together, so let’s start with one simple triangle. If we get that working, it’s a simple step forward to render multiple triangles to form a 3D object.

    Rendering a 3d triangle on a 2D screen involves something called “projection”. This is the act of taking a 3D point and projecting it onto a 2D screen. Plug in a 3D triangle to a simple math equation, and you get a 2D triangle representing how the 3D one would look on the screen.

    The math is remarkably simple but may seem weird if you aren’t familiar with linear algebra. You can take a look at the renderer code.

    Now comes the fun part: can you render any 2D triangle simply with CSS3 transforms? Turns out you can! It just takes some fiddling to figure out which transforms to generate. CSS3 transforms are composed of translate, scale, rotate, and skew values, and we need a few equations to compute these values for a specific 2D triangle.

    First, let’s take a simple DOM element and turn it into a triangle. We can do this with the linear-gradient background image (another way is border triangles).

    JSFiddle demo.

    Now let’s draw the following blue triangle with the points [20, 20], [50, 120], and [120, 30]. A vital step is to set a few initial reference points which set everything in the same space. Our equations will assume these coordinate spaces. This is how the points A, B, C and the side AB are related.

    Triangle comparison

    If we take a closer look at this, we can derive the transform values. First, get an idea of which angles and values we need and then use geometry to form the equations (in pseudo-code). The red box represents the DOM element, the form AB represents the side formed by points A and B, and rotation occurs clockwise.

    dissecting triangles

    rotation = atan2(AB.x, AB.y)
    AC' = rotate(AC, -rotation)
    width = AC'.x
    height = length(AB)
    skew = atan2(AC'.y, AC'.x)
    translate = A

    Awesome! Let’s try it out. Here is a live DOM element being transformed by applying each of our equations:

    JSFiddle demo.

    The resulting triangle matches our target triangle! Here is the final CSS:

    width: 93px;
    height: 104px;
    background: -moz-linear-gradient(-0.727211rad, #0000FF 50%, transparent 0pt);
    -moz-transform: translate(20px, 20px) rotate(-0.291457rad) skewY(0.391125rad);
    -moz-transform-origin: top left;

    Note: The tranform-origin: top left line is important. Normally transforms happen relative to the center of the element, but our equations assume the top left.

    Note: dom3d also generates code with the -webkit and -o prefixes for WebKit and Opera support.

    You can view the implementation of these equations. It turns out that these equations work for any triangle, as long as the points given are in counter-clockwise order, which is standard in the graphics world.

    Taking it all the way

    Since we can project a 3D triangle into 2D space and render it with CSS, all we have to do now is apply that to several 3D triangles to form a 3D object!

    We need some 3D data at this point. I used Blender to export a teapot into the simple OBJ file format and wrote a script to dump the data as JavaScript. Rendering all those triangles with this technique produces the following:

    JSFiddle demo.

    Teapot! However, we can do much better. A big part of the 3D effect is shading. If we calculate normals, a vector representing where the triangle is facing, and specify a light direction, we can take the dot product of the normal and light for each triangle to get flat shading. View the code for flat shading.

    JSFiddle demo.

    There are many tweaks that take this even further. For example, the above objects have z-indexing enabled. Without this, a triangle that is supposed to be behind another may actually appear on top because it was rendered later. The dom3d uses a heap to render the triangles from back to front.

    Real-time animation can be achieved with a setTimeout or requestAnimationFrame function that continually renders the object. The dom3d supports the scale, translate, yaw, and pitch transformations, but there’s nothing stopping you from modifying the object data however you like between renderings. See some examples over at the dom3d website.

    Here is the code which renders the teapot animation with dom3d:

    JSFiddle demo.

    It’s more appropriate for webpages to update an animation in response to user interaction instead of constantly rendering and hogging the CPU. See the pole example on the dom3d site for an example.

    Improvements and last thoughts

    The most interesting possibility with this is to include actual page elements as part of 3D objects. A navigation item could pop out and swirl around in 3d space, and the nav item is seamlessly transformed along with it.

    That’s where this hack starts to show its faults, though. Unfortunately this is a little too hacky to provide an appropriate web experience. Because it tricks DIVs into fake triangles, it removes the possibility of integrating any page elements with it. With the coming of 3D CSS transforms though, we can start building true 3D objects made up of any kind of page elements. The only restriction with 3D transforms is that the 3D objects need to built with rectangles instead of triangles.

    Other people have already experimented with 3D transforms, like building a pure CSS 3D city. There’s another cool library, Sprite3D, which provides a JavaScript API for building basic 3d objects from page elements.

    The most glaring problem with dom3d is the seams in the object, which appear in all browsers. Apparently there are a few bugs in rendering engines when stressing their CSS3 transforms and using linear-gradients!

    The dom3d library provides an API to work with all of this, but is hasn’t been documented very well yet. Feel free to browse the README and code on github. These APIs could be improved as well. It also provides an SVG rendering backend, seen here, but I don’t this is the right direction to take. We should focus on building basic 3D objects with page elements.

    This was a fun experiment and I’m excited by how fast and capable browsers are becoming. The web is an exciting platform and getting richer and more powerful every year!

  6. Animating with javascript: from setInterval to requestAnimationFrame

    Animating DOM elements[1] or the content of a canvas is a classical use case for setInterval. But the interval is not as reliable as it seems, and a more suitable API is now available…

    Animating with setInterval

    To animate an element moving 400 pixels on the right with javascript, the basic thing to do is to move it 10 pixels at a time on a regular interval.

    JSFiddle demo.

    An HTML5 game based on this logic would normally run at ~60fps[2], but if the animations were too complex or running on a low-spec. device (a mobile phone for instance) and processing a frame were taking more than 16ms, then the game would run at a lower framerate: when processing 1 frame takes 33ms, the game runs at 30fps and game elements move twice as slowly as they should. Animations would still look smooth enough, but the game experience would be altered.

    Animating at constant speed

    To animate at constant speed, we need to calculate the time delta since the last frame and move the element proportionally.

    Animating with requestAnimationFrame

    Since the interval parameter is irrelevant in complex animations, as there’s no guarantee that it will be honored, a new API has been designed: requestAnimationFrame. It’s simply a way to tell the browser “before drawing the next frame on the screen, execute this game logic/animation processing”. The browser is in charge of choosing the best moment to execute the code, which results in a more efficient use of resources[3].

    Here’s how an animation with requestAnimationFrame would be written.
    Note: Following code snippets don’t include feature detections and workarounds necessary to work in current browsers. Should you want to play with them, you should try the ready-to-use animLoop.js.

    Dealing with inactive tabs

    requestAnimationFrame was built with another benefit in mind: letting the browser choose the best frame interval allows to have a long interval in inactive tabs. Users could play a CPU intensive game, then open a new tab or minimize the window, and the game would pause[4], leaving resources available for other tasks.
    Note: the potential impact of such behavior on resource and battery usage is so positive that browser vendors decided to adopt it for setTimeout and setInterval as well[5].

    This behavior also means that the calculated time delta might be really high when switching back to a tab containing an animation. This will result in animation appearing to jump or creating “wormholes[6], as illustrated here.

    Wormholes can be fixed by clamping the time delta to a maximum value, or not rendering a frame when the time delta is too high.

    JSFiddle demo.

    Problems with animation queues

    Libraries such as jQuery queue animations on elements to execute them one after the other. This queue is generally only used for animations that are purposefully consecutive.
    But if animations are triggered by a timer, the queue might grow without bound in inactive tabs, as paused animations stack up in the queue. When switching back to affected tabs, a user will see a large number of animations playing consecutively when only one should happen on a regular interval:

    JSFiddle demo.

    This problem is visible in some auto-playing slideshows such as mb.gallery. To work around it, developers can empty animation queues before triggering new animations[7].
    JSFiddle demo.

    Conclusion

    The delays of setTimeout and setInterval and of course requestAnimationFrame are unpredictable and much longer in inactive tabs. These facts should be taken into account not only when writing animation logic, but in fps counters, time countdowns, and everywhere time measurement is crucial.

    [1] The DOM can now be animated with CSS3 Transitions and CSS3 Animations.
    [2] 1 frame every 16ms is 62.5 frames per second.
    [3] See the illustration of this fact on msdn.
    [4] The behavior of requestAnimationFrame in inactive tabs is still being worked on at the w3c, and might differ in other browsers.
    [5] See related Firefox bug and related chromium bug.
    [6] This term was first coined by Seth Ladd in his “Intro to HTML5 Game Development” talk.
    [7] See documentation of your js library, such as effects and stop() for jQuery.

  7. Ask MDN: Our experts are ready to answer your questions

    [Update] The panel of experts and time of the first event have been added below.

    Something amazing is starting next week. No, not pay day. It’s more important than that. Got it yet? No? It’s Ask MDN, silly! Still no idea what that is? Don’t worry, it’s new and I’m here to tell you all about it.

    Introducing Ask MDN

    Ask MDN is a new initiative from MDN and the Developer Engagement team here at Mozilla.

    For one hour a week on Twitter we will get a panel of experts together to answer your questions about a specific topic related to Web development.

    Every week we choose a different topic, which will be announced in advance so you have plenty of opportunity to send in a question for our experts (who also change each week).

    After each week we will archive the questions and answers so you can search through them and continue learning long into the future. We see this as being just as valuable a resource for learning as the documentation is on MDN.

    Engaging with the developer community on Twitter

    We’re starting Ask MDN because we believe that there isn’t much help for developers on Twitter outside of questions and answers between friends.

    With Ask MDN we want to bring together the developer community and our long-standing relationship with experts. We want to make it super easy to get a trusted and valued opinion on something that’s been bugging you, no matter how simple.

    Announcing the first topic: HTML5 gaming and creative JavaScript

    The first Ask MDN hour on Twitter is next week and it will be focussing on HTML5 gaming and creative JavaScript (animations, graphics, etc).

    We’ve already got a great panel of experts lined up ready to answer your questions. They include game developers, authors, JavaScript ninjas, and Flash heavy-weights (there is a still a lot that we can learn from the Flash guys).

    We’ll announce the next topic after the HTML5 gaming hour is over.

    When and where?

    The live HTML5 gaming and creative JavaScript Q&A will take place on Friday the 29th of July at 6pm in the UK (BST), and will be moderated through the @AskMDN Twitter account. Make sure to follow that account to keep up-to-date with what’s happening.

    We chose 6pm in the UK because it’s a time that the majority of the world will be able to access; it’s morning in the US, and evening in Europe. We appreciate that this isn’t perfect for everyone, but we haven’t gotten around to building a time machine just yet.

    The first event will occur at the following times around the world:

    • 10am in San Francisco (PDT)
    • 1pm in New York (EDT)
    • 7pm in Paris, Berlin and Madrid (CEST)

    Find the time where you live to make sure you don’t miss out.

    Who are the experts?

    We’re really proud to bring you an astounding panel of experts, each carefully chosen to give a fascinating insight into the tech surrounding HTML5 gaming and creative JavaScript.

    You don’t get a chance like this often, so make sure you submit a question to the panel.

    Seb Lee-Delisle

    Seb (@seb_ly) is an internationally recognised creative coder best known for his award-winning Flash work. He has recently been teaching developers the delights of creative JavaScript through his workshops in the UK and US.

    Seb was recently interviewed as one of our People of HTML5.

    Rob Evans

    Rob (@IsogenicEngine) is the developer behind Isogenic Engine, one of the most promising HTML5 gaming engines out there today.

    Dominic Szablewski

    Dominic (@phoboslab) is the developer behind the Impact HTML5 gaming engine, one of the most popular publicly-accessible engines out there right now.

    Andreas Røsdal

    Andreas (@andreasrosdal) is the developer behind Freeciv.net, which is a HTML5 version of the strategy game Freeciv.

    Tom Schuster

    Tom (@evilpies) is a core contributor to Mozilla’s SpiderMonkey JavaScript engine. His knowledge with JavaScript performance and optimisation will be invaluable.

    Michal Budzynski

    Michal (@michalbe) is the developer behind onGameStart, the first large-scale HTML5 gaming conference in the world.

    Benoit Jacob

    Benoit (@BenoitJacob) is a Software Developer here at Mozilla who works on graphics and WebGL. As a result of this he has in-depth knowledge about hardware acceleration in these kinds of environments.

    Rob Hawkes

    Rob (@robhawkes) is me. I am a Technical Evangelist at Mozilla with experience developing games and creative experiments with HTML5 and JavaScript. I will be on the panel, but my main role will be moderating the discussion and keeping things running smoothly.

    Getting involved

    It’s going to be a great experience so I encourage you to get involved by following @AskMDN on Twitter.

    Submit your questions about HTML5 gaming and creative JavaScript in an @ reply to our account. Nearer the hour itself we’ll announce a hash-tag that can also be used to submit questions.

    Got a topic that you want us to cover in a future Ask MDN hour? Send it as an @ reply on Twitter, or reply in the comments below.

    Taking things forward

    This is just the beginning. We have big plans for Ask MDN, but we won’t be able to do any of it without you.

    Get involved today and help us make the Web a better place.

  8. HTML5 and CSS3: Exploring Mobile Possibilities – presentation at London Ajax Mobile Event

    In the beginning of July, I was attending and giving a presentation at the London Ajax Mobile Event about possibilities offered by HTML5 and CSS3 when it comes to developing mobile web sites and applications.

    Short introduction of me

    Being my first post here at Mozilla Hacks, I thought I’d start by briefly introducing myself first: My name is Robert Nyman and I’ve recently joined Mozilla as a Technical Evangelist, talking about HTML5, the Open Web and how we can help web developers. I’ve been working since 1999 with Front End development for the web, and I regularly blog at http://robertnyman.com, tweet as @robertnyman and love to travel and meet people!

    The London Ajax Mobile Event

    The conference took place at the Vodafone headquarters in London, arranged by Sitepen CEO and Dojo co-founder Dylan Schiemann. It was packed to the brim with speakers, from early morning raging on into the night. Various talks were given on a number of topics – from mobile apps and implementations to a more experimenting approach and future visions.

    My presentation

    You can see the slides from my HTML5 and CSS3: Exploring Mobile Possibilities below or download the slides at SlideShare

    The aim of my talk was to give both an introduction and reiterate on some of the important options we have when developing web sites, especially when it comes to the mobile world. With the CSS3 field I covered CSS Media Queries and Flex Box and the options they give us in creating more flexible layouts and presentation alternatives. I also spoke about CSS Transitions and Animations and how they can assist in an easy manner to get nice effects, that are also hardware-accelerated on certain devices.

    When it comes to the HTML5 part, I’m excited by all the new HTML5 form elements and how they can improve both user experience and the input of data. As support grows for this in web browsers, I believe it will make things a lot easier for both developers and end users.

    I briefly touched on link protocols, such as tel: and sms:, to trigger mobile-specific actions when activating a link, and then various useful APIs such as Web Storage, Offline Applications, History API and Geolocation (not all necessary official HTML5 APIs, but usually used in conjunction with them).

    I ended the talk with touching on tool such as Steve Souders’ Mobile Perf bookmarklet and weinre, for remote debugging on mobile devices.

    You and mobile

    What I am interested in is if you are developing for a multitude of mobile and other devices, what you believe are the biggest obstacles as well as the most promising options. Any thoughts, please let me know!

  9. Doom on the Web

    Update: We had a doubt whether this port of the Open Source Doom respected its term of use. We decided to remove it from our Website before taking an informed and definitive decision.

    This is a guest post written by Alon Zakai. Alon is one of the Firefox Mobile developers, and in his spare time does experiments with JavaScript and new web technologies. One of those experiments is Emscripten, an LLVM-to-JavaScript compiler, and below Alon explains how it uses typed arrays to run the classic first-person shooter Doom on the web.

    As a longtime fan of first-person shooters, I’ve wanted to bring them to the web. Writing one from scratch is very hard, though, so instead I took the original Doom, which is open source, and compiled it from C to JavaScript using Emscripten. The result is a version of Doom that can be played on the web, using standard web technologies.

    Doom renders by writing out pixel data to memory, then copying that pixel data to the screen, after converting colors and so forth. For this demo, the compiled code has memory that is simulated using a large JavaScript array (so element N in that array represents the contents of memory address N in normal native code). That means that rendering, color conversion, and copying to the screen are all operations done on that large JavaScript array. Basically the code has large loops that copy or modify elements of that array. For that to be as fast as possible, the demo optionally uses JavaScript typed arrays, which look like normal JavaScript arrays but are guaranteed to be flat arrays of a particular data type.

    // Create an array which contains only 32-bit Integers
    var buffer = new Int32Array(1000);
    for ( var i = 0 ; i < 1000 ; i++ ) {
        buffer[i] = i;
    }

    When using a typed array, the main difference from a normal JavaScript array is that the elements of the array all have the type that you set. That means that working on that array can be much faster than a normal array, because it corresponds very closely to a normal low-level C or C++ array. In comparison, a normal JavaScript array can also be sparse, which means that it isn't a single contiguous section of memory. In that case, each access of the array has a cost, that of calculating the proper memory address. Finding the memory address is much faster with a typed array because it is simple and direct. As a consequence, in the Doom demo the frame rate is almost twice as fast with typed arrays than without them.

    Typed arrays are very important in WebGL and in the Audio Data API, as well as in Canvas elements (the pixel data received from getImageData() is, in fact, a typed array). However, typed arrays can also be used independently if you are working on large amounts of array-like data, which is exactly the case with the Doom demo. Just be careful that your code also works if the user's browser does not support typed arrays. This is fairly easy to do because typed arrays look and behave, for the most part, like normal ones — you access their elements using square brackets, and so forth. The main potential pitfalls are:

    • Typed arrays do not have the slice(). Instead they have the subarray(), which does not create a copy of the array — instead it's a view into the same data.
    • Don't forget that the type of the typed array is silently enforced. If you write 5.25 to an element of an integer-typed array and then read back that exact same element, you get 5 and not 5.25.