Sep 23

The CSS Ninja details how Gmail’s drag and drop from the desktop works; when you drag a file from the desktop into Gmail the file will automatically start uploading.

The CSS Ninja recreated the code in a demo (source code [zip]).

The code works in Firefox and Chrome. On Firefox the File API is used (detailed in another blog post) while on Chrome a different API is used.

How does Chrome work?

Using a bit of CSS trickery we can create the illusion of having File API support and still allow users to drag and drop files from the desktop into Gmail. I accomplish this by having the drop zone, which becomes visible on a dragenter event, contain an invisible file input with a 100% width and height of the drop zone area. The file input also has the attribute multiple on it allowing a user to drop multiple files.

HTML:

<div id=“drop”>
<h1>Drop files here</h1>
To add them as attachments

<input id=“filesUpload” type=“file” /></div>
 

The drop zone is hidden by default until a dragenter event happens on the BODY tag:

CSS:

#drop {
position: relative;
}
#drop input {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
opacity: 0;
}
 

When the drop input is activated a change event is fired and the files can be enumerated:

JAVASCRIPT:

dropArea.addEventListener(“change”, TCNDDU.handleDrop, false);

TCNDDU.handleDrop = function (evt) {
var files = evt.target.files;
dropArea.style.display = “none”;
for(var i = 0, len = files.length; i &lt;len; i++) {
// iterate over file(s) and process them for uploading
}
};
 

The actual uploading is handled by XHR2:

Using XHR2 and the upload attribute to attach progress events so we can do a real progress bar that indicates to the user how much the file has uploaded.

Continue reading »

Tagged with:
Aug 25

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

Cross browser implementation

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

Performance

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

State stack & transformation

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

Compositing

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

Anti-aliasing

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

Clearing the canvas

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

[via Mr. Doob]

Cross browser implementation

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

Performance

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

State stack & transformation

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

Compositing

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

Anti-aliasing

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

Clearing the canvas

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

Continue reading »

Tagged with:
Aug 16

If you’ve seen some of the cool work that folks like Mr. Doob or Gerard Ferrandez have done with HTML5/CSS3/SVG/etc., you’ve probably seen them emulating nifty 3D effects in the browser (move your mouse within the demo inline below to pan the camera):

The demo above, by Gerard, uses SVG plus various mathematical tricks to emulate 3D.

Mr. Doob has a similar demo that emulates 3D but using the Canvas tag using his Three.js library:

What both of these samples have in common is they are using special math to simulate three dimensions on a two-dimensional surface (i.e. our screen using SVG, the Canvas tag, or CSS3 Transforms).

I’ve realized recently that the Flash world is a bit ahead of us in the HTML5 world in terms of doing nifty effects using special tricks such as simulating 3D in a 2D space. I’ve been actually trying to go deep into learning Flash so that I can learn some of these tricks but use them in an HTML5 context.

I reached out to Gerard Ferrandez recently to ask him where he learned the math to do his demos, and he told me he learned them from the Flash world. He pointed me to an absolutely excellent Flash tutorial series that explains in depth how to do such 3D tricks in your own code. It’s straightforward to learn the math but apply it in an HTML5 context. The tutorial series is very complete and easy to understand, basically explaining how to do perspective drawing, first invented in the Renaissance. A classic perspective drawing from the Renaissance:

Notice the lines superimposed on the painting above; shapes that are closer to the viewer are scaled larger, while shapes in the background are smaller. In addition, the location of the shapes on the painting change based on where they located along what is called the ‘vanishing point’. Instead of emulating these with paint, as the Old Masters used to do, we use simple mathematics that can then determine the correct x and y coordinates on our fake 2D ‘window’ in order to simulate a perspective point, then draw it using SVG, Canvas, etc.:

As I continue learning tricks from our Flash friends but in an HTML5 context I’ll keep posting here on Ajaxian.

Continue reading »

Tagged with:
Aug 11

The HTML5 love continues to be doled out by Paul Irish. First, he offered up Modernizr and now, he’s teamed up with Divya Manian to create an HTML5 boilerplate which leverages best practices to get your started.

It’s essentially a good starting template of html and css and a folder structure that works. But baked into it is years of best practices from front-end development professionals. Take a peek through the source to get a feel of what’s inside. And if you think there’s too much? Delete key that badboy.

Straight from the site, here are some of the features that make this very cool:

  • Cross-browser compatible (IE6, yeah we got that.)
  • HTML5 ready. Use the new tags with certainty.
  • Optimal caching and compression rules for grade-A performance
  • Best practice site configuration defaults
  • Mobile browser optimizations
  • Progressive enhancement graceful degradation … yeah yeah we got that
  • IE specific classes for maximum cross-browser control
  • Handy .no-js and .js classes to style based on capability
  • Want to write unit tests but lazy? A full, hooked up test suite is waiting for you.
  • Javascript profiling…in IE6 and IE7? Sure, no problem.
  • Console.log nerfing so you won’t break anyone by mistake.
  • Never go wrong with your doctype or markup!
  • An optimal print stylesheet, performance optimized
  • iOS, Android, Opera Mobile-adaptable markup and CSS skeleton.
  • IE6 pngfix baked in.
  • .clearfix, .visuallyhidden classes to style things wisely and accessibly.
  • .htaccess file that allows proper use of HTML5 features and faster page load
  • CDN hosted jQuery with local fallback failsafe.
  • Think there’s too much? The HTML5 Boilerplate is delete-key friendly. :)

I’ve heard several people mention about getting some sort of HTML5 template to work from setup so it’s nice to see one completed and out in the wild. This should be a big help.

The project uses everyone’s favorite source control system Github so you can grab it from there or download a zipped up file from the site.

Continue reading »

Tagged with:
Jun 21

Aaron has a nice editorial piece on going from zero-install to instant-install in which he discusses the notion of web apps:

Bringing back a lightweight notion of installation offers an interesting way out of Web constraints. If an author uses APIs like window.open() and desktop notifications in an annoying way, his app will be uninstalled. The UA can make it easy for the user to discover the uninstall button, so there’s a strong incentive for authors to not be assholes. Since there are a manageable number of apps installed at any one time (by definition, since they were manually installed), UAs can offer permanent storage to apps. If the apps abuse the privilege, the user can easily scan a list, see which one is doing it and uninstall it.

He discusses the revolution of the “zero install” Web. We pass people URLs. We link to things. We don’t think of this as “running apps”. He then brings up the issues of this freedom. Since my mum doesn’t think of this as running apps, we shouldn’t grant access to these URLs, and we end up with a strong sandbox, which limits functionality.

With “installable web apps” we get some of the best of both worlds, but it doesn’t quite feel like we have matched a perfect equilibrium yet. As a power user, I am excited about taking a strong sandboxed model and opening it up with APIs that all go through the sandbox. This means that I can monitor everything that is going on. Add to this social monitoring (so if something bad happens it quickly moves through the social network to be fixed and blocked) and I look forward to a blended world of permissions. We have long had the ability to break through the sandbox in browsers. Unfortunately, these methods are browser specific, and result in annoying prompts that drive you nuts. As we scale out the permissions, this becomes more annoying. To get around this, some platforms are asking the user to accept permission at install time. You have the advantage that: a) the user has to agree before anything is even downloaded; b) one click, at the time of install, and you are off to the races.

However, there are huge problems: When prompted at this time, there is a strong likelihood that the user is trying to do something and will thus say YES YES YES no matter what. Some may question an 8-ball app that asks for deep permissions, but even then…. we run into the same prompty neglect that we get on the desktop. Have you ever downloaded a Mac app, ran it, and then when the “this app came from the Internet” dialog showed up…. said “you know what. Naaaah”? And what about nuance? Weather apps ask for access to the GPS. What if you want to use the app (and search for an area) but don’t want to give location information? Some systems won’t let you download the app (this is where the Web Geolocation API is great!)

Installable == special powers. Uninstalled == less powers. I still have hope that after these first steps we get the right metaphors that offer simplicity for users, but nice fine grained control and awareness.

Continue reading »

Tagged with:
May 19

The WebM project is dedicated to developing a high-quality, open video format for the web that is freely available to everyone.

The WebM launch is supported by Mozilla, Opera, Google and more than forty other publishers, software and hardware vendors.

WebM is an open, royalty-free, media file format designed for the web.

WebM defines the file container structure, video and audio formats. WebM files consist of video streams compressed with the VP8 video codec and audio streams compressed with the Vorbis audio codec. The WebM file structure is based on the Matroska container.

It happened. Today, Google is up on stage at I/O unveiling a new WebM project alongside a slew of partners (notably: Mozilla and Opera on the browser side) that gets the On2 codec out into the open. This is huge news for the fight for Open Video, and everyone will now have eyes on Safari and IE. Microsoft posted a month back about their stance, probably to get it out before this announcement. If folks don’t support this….. it is weak.

YouTube will be a huge push here, and you can go to their html5 version: http://www.youtube.com/html5 and check it out. Today it is available in trunk builds on Chromium and Firefox. Soon, an Opera beta, Chrome dev release, and more.

The project is going after:

  • Openness and innovation. A key factor in the web’s success is
    that its core technologies such as HTML, HTTP, and TCP/IP are open
    for anyone to implement and improve. With video being core to the
    web experience, a high-quality, open video format choice is needed.
    WebM is 100% free, and open-sourced under a
    BSD-style license.

  • Optimized for the web. Serving video on the web is different
    from traditional broadcast and offline mediums. Existing video
    formats were designed to serve the needs of these mediums and do
    it very well. WebM is focused on addressing the unique needs of
    serving video on the web.

    • Low computational footprint to enable playback on any device,
      including low-power netbooks, handhelds, tablets, etc.*

    • Simple container format

    • Highest quality real-time video delivery

    • Click and encode. Minimal codec profiles, sub-options; when
      possible, let the encoder make the tough choices.

* Note: The initial developer preview releases of browsers supporting WebM are not yet fully optimized and therefore have a higher computational footprint for screen rendering than we expect for the general releases. The computational efficiencies of WebM are more accurately measured today using the development tools in the VP8 SDKs. Optimizations of the browser implementations are forthcoming.

Congrats Open Web.

Continue reading »

Tagged with:
May 19

Our reptilian brains often like to lump an entity in one bucket. We see a lot of folks asking “Is Adobe friend or foe to the Open Web?” Of course, life is much more about nuance. Adobe has a large investment in Flash, but they are also a tools company.

Adobe has mentioned HTML5 tooling in the past, and we have often surmised that there is a HUGE opportunity in HTML5 tooling (which is very much lacking).

Well, now we get to see some meat to the bone as Kevin Lynch is on stage at Google I/O showing off how Adobe is getting big into HTML5.

First, Kevin is showing the HTML5 pack for Dreamweaver. It augments Dreamweaver with code hinting, an updated WebKit for the live view, the fun multiscreen demo that Adobe has been sharing for awhile, and starter layouts for HTML5.

Then we see Kevin use a new prototype tool that allows him to create a rich ad (of course! :) using CSS3 transforms and animations. This is a design tool folks. Think timelines, layers, and more.

We will embed a video of this all working when it comes in shortly.

It is still early days for these tools, but Adobe said they wanted to get them out to folks as soon as possible to start a discussion with the community. What would you like to see? Going from the world of static-ish pages to rich applications using HTML5 technology… we could sure use some help from tooling.

Continue reading »

Tagged with:
Apr 09

Tyler Gaw has built a fun kinetic video demo that uses a bunch of advanced CSS (gradients, transforms, transitions).

kinetic-css

View source to see the scenes:

HTML:

  1.  
  2. <dt>Chester <!– Quentin Tarantino –></dt>
  3.         <dd id=“scene-2″>
  4.                 <p class=“act-1″>Ok, Ted</p>
  5.                 <p class=“act-2″>pay attention here. I’m gonna make two piles here on the bar.</p>
  6.                 <p class=“act-3″><strong>one pile,</strong> <span>which is</span> <em>yours</em></p>
  7.                 <p class=“act-4″><i>and</i> <strong>another pile,</strong> <span>which could<b></b></span> <em>be yours</em></p>
  8.                 <p class=“act-5″><span>What you have to realize is we’re gonna do this thing</span> <strong>one way</strong> <em>or the other</em></p>
  9.                 <p class=“act-6″><i>Whether it’s</i> <em>you</em> <strong>who holds the axe</strong> <span>or</span></p>
  10.                 <p class=“act-7″><i>a</i> <strong>mexican maid</strong> <span>or</span></p>
  11.                 <p class=“act-8″><strong>some bum</strong> <span><b>we</b> <b>yank</b> <b>off</b> <b>the</b> <b>street</b></span></p>
  12.         </dd>
  13.  

and then the acts:

CSS:

  1.  
  2. #scene-2 .act-1 {
  3.         display: block;
  4.         top: 200px;
  5.         left: 1080px;
  6.         font-size: 380%;
  7.         overflow: hidden;
  8.         width: 260px;
  9.         -webkit-transition: left 0.1s linear;
  10. }
  11.  
  12. #scene-2 .act-1.position-1 {
  13.         left: 800px;
  14.         -webkit-transition: left 0.1s linear;
  15. }
  16.  
  17. #scene-2 .act-1.position-1.position-2 {
  18.         left: 540px;
  19.         width: 800px;
  20.         -webkit-transition: left 0.2s ease-in;
  21. }
  22.  
  23. #scene-2 .act-1.position-1.position-2.exit {
  24.         left: -800px;
  25. }
  26.  

And then the direction:

JAVASCRIPT:

  1.  
  2. direct(‘#scene-2 .act-1′, ‘position-1′, 1800);
  3.  

As Steve would say. “Oh, this was all done with HTML5.”

Continue reading »

Tagged with:
Mar 31

David Friedman calls is “silly”, but he has created something simple and fun in his new form of volume control that moves from whisper to shout as you change the volume.

whispershout

The code (which works on Firefox and Opera right now) uses different tracks for each level:

HTML:

  1.  
  2. <audio id=“apA” autobuffer=“true” onTimeUpdate=“update();”>
  3.         <source src=“ogg/Volume1.ogg” type=“audio/ogg; codecs=vorbis”>
  4. </source></audio>
  5. <audio id=“apB” autobuffer=“true”>
  6.         <source src=“ogg/Volume2.ogg” type=“audio/ogg; codecs=vorbis”>
  7. </source></audio>
  8. <audio id=“apC” autobuffer=“true”>
  9.         <source src=“ogg/Volume3.ogg” type=“audio/ogg; codecs=vorbis”>
  10. </source></audio>
  11. <audio id=“apD” autobuffer=“true”>
  12.         <source src=“ogg/Volume4.ogg” type=“audio/ogg; codecs=vorbis”>
  13. </source></audio>
  14. <audio id=“apE” autobuffer=“true”>
  15.         <source src=“ogg/Volume5.ogg” type=“audio/ogg; codecs=vorbis”>
  16. </source></audio>
  17.  

And it keeps track of the timing so it can seamlessly play with code such as:

JAVASCRIPT:

  1.  
  2. this.apA.addEventListener(“timeupdate”, timeUpdate, true);
  3.  
  4. function timeUpdate() {
  5.         //get the duration of the player
  6.         dur = audio_player.duration;
  7.         time = audio_player.currentTime;
  8.         fraction = time/dur;
  9.         percent = (fraction*100);
  10.         wrapper = document.getElementById(“duration_background”);
  11.         new_width = wrapper.offsetWidth*fraction;
  12.         document.getElementById(“duration_bar”).style.width=new_width+“px”;
  13. }
  14.  

Continue reading »

Tagged with:
Mar 25

Given the current status of Canvas and the impending release of Apple’s iPad (which will have no Flash support at all), I finally decided to bite the bullet and do a complete rewrite of the Network Graph in JavaScript and Canvas.

This is Tom Preston-Werner of GitHub, from his recent posted about migrating the network graph functionality from Flash to Canvas.

githubnetworkgraph

This isn’t the first site to move over functionality, but Tom has a really interesting perspective on why he did this, what he likes about canvas, and what he wishes it had:

Where Canvas/JavaScript is better than Flash

  • Fewer lines of code and smaller deliverable size: Smaller code base and the compiled SWF file clocks in at 111k compared to the minified Canvas version at just 25k!
  • Flash works badly on Linux (and friends)
  • Inspectable/debuggable via browser
  • No compilation step
  • Better cursor handling
  • No need to focus to receive keyboard events

Where Canvas/JavaScript is worse than Flash

  • Have to handle clipping and redraw manually (SVG does better here too)
  • No embedded font support
  • No built-in multiline text wrap (painful for Bespin! ;)
  • No HTML fragment rendering. Yes! drawElement, drawElement, drawElement. Please user agents!

Continue reading »

Tagged with:
Feb 08

It is quite interesting to see how technology moves in circles. With canvas being the new fun toy to play with for creating browser-based games we have to find solutions to fake a 3D environment to be really fast (sure there is Canvas 3D but it is overkill for most games). The trick is to dig into the tricks arsenal of old-school game development on machines full of win like the Commodore 64 or Amiga.

Louis Gorenfeld some very detailed explanations on how to fake 3D including some of the formulas used in the days of 8 bit.

He is also working on some demo code which you can help him with by providing some JS/Canvas demos:

Fake 3D

CODE:

  1. current_x = 160 // Half of a 320 width screen
  2. dx = 0 // Curve amount, constant per segment
  3. ddx = 0 // Curve amount, changes per line
  4.  
  5. for each line of the screen from the bottom to the top:
  6.   if line of screen‘s Z Map position is below segment.position:
  7.     dx = bottom_segment.dx
  8.   else if line of screen’s Z Map position is above segment.position:
  9.     dx = segment.dx
  10.   end if
  11.   ddx += dx
  12.   current_x += ddx
  13.   this_line.x = current_x
  14. end for
  15.  
  16. // Move segments
  17. segment_y += constant * speed // Constant makes sure the segment doesn’t move too fast
  18. if segment.position <0 // 0 is nearest
  19.   bottom_segment = segment
  20.   segment.position = zmap.length1 // Send segment position to farthest distance
  21.   segment.dx = GetNextDxFromTrack() // Fetch next curve amount from track data
  22. end if

[Ajaxian » Front Page]

Tagged with:
preload preload preload