{"rowid": 237, "title": "Circles of Confusion", "contents": "Long before I worked on the web, I specialised in training photographers how to use large format, 5\u00d74\u2033 and 10\u00d78\u2033 view cameras \u2013 film cameras with swing and tilt movements, bellows and upside down, back to front images viewed on dim, ground glass screens. It\u2019s been fifteen years since I clicked a shutter on a view camera, but some things have stayed with me from those years.\n\nIn photography, even the best lenses don\u2019t focus light onto a point (infinitely small in size) but onto \u2018spots\u2019 or circles in the \u2018film/image plane\u2019. These circles of light have dimensions, despite being microscopically small. They\u2019re known as \u2018circles of confusion\u2019.\n\nAs circles of light become larger, the more unsharp parts of a photograph appear. On the flip side, when circles are smaller, an image looks sharper and more in focus. This is the basis for photographic depth of field and with that comes the knowledge that no photograph can be perfectly focused, never truly sharp. Instead, photographs can only be \u2018acceptably unsharp\u2019. \n\nAcceptable unsharpness is now a concept that\u2019s relevant to the work we make for the web, because often \u2013 unless we compromise \u2013 websites cannot look or be experienced exactly the same across browsers, devices or platforms. Accepting that fact, and learning to look upon these natural differences as creative opportunities instead of imperfections, can be tough. Deciding which aspects of a design must remain consistent and, therefore, possibly require more time, effort or compromises can be tougher. Circles of confusion can help us, our bosses and our customers make better, more informed decisions.\n\nAcceptable unsharpness\n\nMany clients still demand that every aspect of a design should be \u2018sharp\u2019 \u2013 that every user must see rounded boxes, gradients and shadows \u2013 without regard for the implications. I believe that this stems largely from the fact that they have previously been shown designs \u2013 and asked for sign-off \u2013 using static images.\n\nIt\u2019s also true that in the past, organisations have invested heavily in style guides which, while maybe still useful in offline media, have a strictness that often fails to allow for the flexibility that we need to create experiences that are appropriate to a user\u2019s browser or device capabilities.\n\nWe live in an era where web browsers and devices have wide-ranging capabilities, and websites can rarely look or be experienced exactly the same across them. Is a particular typeface vital to a user\u2019s experience of a brand? How important are gradients or shadows? Are rounded corners really that necessary? These decisions determine how \u2018sharp\u2019 an element should be across browsers with different capabilities and, therefore, how much time, effort or extra code and images we devote to achieving consistency between them. To help our clients make those decisions, we can use circles of confusion.\n\nCircles of confusion\n\nUsing circles of confusion involves plotting aspects of a visual design into a series of concentric circles, starting at the centre with elements that demand the most consistency. Then, work outwards, placing elements in order of their priority so that they become progressively \u2018softer\u2019, more defocused as they\u2019re plotted into outer rings.\n\nIf layout and typography must remain consistent, place them in the centre circle as they\u2019re aspects of a design that must remain \u2018sharp\u2019.\n\nWhen gradients are important \u2013 but not vital \u2013 to a user\u2019s experience of a brand, plot them close to, but not in the centre. This makes everyone aware that to achieve consistency, you\u2019ll need to carve out extra images for browsers that don\u2019t support CSS gradients.\n\nIf achieving rounded corners or shadows in all browsers isn\u2019t important, place them into outer circles, allowing you to save time by not creating images or employing JavaScript workarounds.\n\nI\u2019ve found plotting aspects of a visual design into circles of confusion is a useful technique when explaining the natural differences between browsers to clients. It sets more realistic expectations and creates an environment for more meaningful discussions about progressive and emerging technologies. Best of all, it enables everyone to make better and more informed decisions about design implementation priorities.\n\nInvolving clients allows the implications of the decisions they make more transparent. For me, this has sometimes meant shifting deadlines or it has allowed me to more easily justify an increase in fees. Most important of all, circles of confusion have helped the people that I work with move beyond yesterday\u2019s one-size-fits-all thinking about visual design, towards accepting the rich diversity of today\u2019s web.", "year": "2010", "author": "Andy Clarke", "author_slug": "andyclarke", "published": "2010-12-23T00:00:00+00:00", "url": "https://24ways.org/2010/circles-of-confusion/", "topic": "process"} {"rowid": 223, "title": "Calculating Color Contrast", "contents": "Some websites and services allow you to customize your profile by uploading pictures, changing the background color or other aspects of the design. As a customer, this personalization turns a web app into your little nest where you store your data. As a designer, letting your customers have free rein over the layout and design is a scary prospect. So what happens to all the stock text and images that are designed to work on nice white backgrounds? Even the Mac only lets you choose between two colors for the OS, blue or graphite! Opening up the ability to customize your site\u2019s color scheme can be a recipe for disaster unless you are flexible and understand how to find maximum color contrasts.\n\nIn this article I will walk you through two simple equations to determine if you should be using white or black text depending on the color of the background. The equations are both easy to implement and produce similar results. It isn\u2019t a matter of which is better, but more the fact that you are using one at all! That way, even with the craziest of Geocities color schemes that your customers choose, at least your text will still be readable.\n\nLet\u2019s have a look at a range of various possible colors. Maybe these are pre-made color schemes, corporate colors, or plucked from an image.\n\n\n\nNow that we have these potential background colors and their hex values, we need to find out whether the corresponding text should be in white or black, based on which has a higher contrast, therefore affording the best readability. This can be done at runtime with JavaScript or in the back-end before the HTML is served up.\n\nThere are two functions I want to compare. The first, I call \u201950%\u2019. It takes the hex value and compares it to the value halfway between pure black and pure white. If the hex value is less than half, meaning it is on the darker side of the spectrum, it returns white as the text color. If the result is greater than half, it\u2019s on the lighter side of the spectrum and returns black as the text value.\n\nIn PHP:\n\nfunction getContrast50($hexcolor){\n return (hexdec($hexcolor) > 0xffffff/2) ? 'black':'white';\n}\n\nIn JavaScript:\n\nfunction getContrast50(hexcolor){\n return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';\n}\n\nIt doesn\u2019t get much simpler than that! The function converts the six-character hex color into an integer and compares that to one half the integer value of pure white. The function is easy to remember, but is naive when it comes to understanding how we perceive parts of the spectrum. Different wavelengths have greater or lesser impact on the contrast.\n\nThe second equation is called \u2018YIQ\u2019 because it converts the RGB color space into YIQ, which takes into account the different impacts of its constituent parts. Again, the equation returns white or black and it\u2019s also very easy to implement.\n\nIn PHP:\n\nfunction getContrastYIQ($hexcolor){\n\t$r = hexdec(substr($hexcolor,0,2));\n\t$g = hexdec(substr($hexcolor,2,2));\n\t$b = hexdec(substr($hexcolor,4,2));\n\t$yiq = (($r*299)+($g*587)+($b*114))/1000;\n\treturn ($yiq >= 128) ? 'black' : 'white';\n}\n\nIn JavaScript:\n\nfunction getContrastYIQ(hexcolor){\n\tvar r = parseInt(hexcolor.substr(0,2),16);\n\tvar g = parseInt(hexcolor.substr(2,2),16);\n\tvar b = parseInt(hexcolor.substr(4,2),16);\n\tvar yiq = ((r*299)+(g*587)+(b*114))/1000;\n\treturn (yiq >= 128) ? 'black' : 'white';\n}\n\nYou\u2019ll notice first that we have broken down the hex value into separate RGB values. This is important because each of these channels is scaled in accordance to its visual impact. Once everything is scaled and normalized, it will be in a range between zero and 255. Much like the previous \u201950%\u2019 function, we now need to check if the input is above or below halfway. Depending on where that value is, we\u2019ll return the corresponding highest contrasting color.\n\nThat\u2019s it: two simple contrast equations which work really well to determine the best readability.\n\nIf you are interested in learning more, the W3C has a few documents about color contrast and how to determine if there is enough contrast between any two colors. This is important for accessibility to make sure there is enough contrast between your text and link colors and the background.\n\nThere is also a great article by Kevin Hale on Particletree about his experience with choosing light or dark themes. To round it out, Jonathan Snook created a color contrast picker which allows you to play with RGB sliders to get values for YIQ, contrast and others. That way you can quickly fiddle with the knobs to find the right balance.\n\nComparing results\n\nLet\u2019s revisit our color schemes and see which text color is recommended for maximum contrast based on these two equations.\n\n\n\nIf we use the simple \u201950%\u2019 contrast function, we can see that it recommends black against all the colors except the dark green and purple on the second row. In general, the equation feels the colors are light and that black is a better choice for the text.\n\n\n\nThe more complex \u2018YIQ\u2019 function, with its weighted colors, has slightly different suggestions. White text is still recommended for the very dark colors, but there are some surprises. The red and pink values show white text rather than black. This equation takes into account the weight of the red value and determines that the hue is dark enough for white text to show the most contrast.\n\nAs you can see, the two contrast algorithms agree most of the time. There are some instances where they conflict, but overall you can use the equation that you prefer. I don\u2019t think it is a major issue if some edge-case colors get one contrast over another, they are still very readable.\n\nNow let\u2019s look at some common colors and then see how the two functions compare. You can quickly see that they do pretty well across the whole spectrum.\n\n\n\nIn the first few shades of grey, the white and black contrasts make sense, but as we test other colors in the spectrum, we do get some unexpected deviation. Pure red #FF0000 has a flip-flop. This is due to how the \u2018YIQ\u2019 function weights the RGB parts. While you might have a personal preference for one style over another, both are justifiable.\n\n\n\nIn this second round of colors, we go deeper into the spectrum, off the beaten track. Again, most of the time the contrasting algorithms are in sync, but every once in a while they disagree. You can select which you prefer, neither of which is unreadable.\n\nConclusion\n\nContrast in color is important, especially if you cede all control and take a hands-off approach to the design. It is important to select smart defaults by making the contrast between colors as high as possible. This makes it easier for your customers to read, increases accessibility and is generally just easier on the eyes. \n\nSure, there are plenty of other equations out there to determine contrast; what is most important is that you pick one and implement it into your system.\n\nSo, go ahead and experiment with color in your design. You now know how easy it is to guarantee that your text will be the most readable in any circumstance.", "year": "2010", "author": "Brian Suda", "author_slug": "briansuda", "published": "2010-12-24T00:00:00+00:00", "url": "https://24ways.org/2010/calculating-color-contrast/", "topic": "code"} {"rowid": 228, "title": "The Great Unveiling", "contents": "The moment of unveiling our designs should be among our proudest, but it never seems to work out that way. Instead of a chance to show how we can bring our clients\u2019 visions to life, critique can be a tense, worrying ordeal. And yes, the stakes are high: a superb design is only superb if it goes live. Mismanage the feedback process and your research, creativity and hard work can be wasted, and your client may wonder whether you\u2019ve been worth the investment.\n\nThe great unveiling is a pivotal part of the design process, but it needn\u2019t be a negative one. Just as usability testing teaches us whether our designs meet user needs, presenting our work to clients tells us whether we\u2019ve met important business goals. So how can we turn the tide to make presenting designs a constructive experience, and to give good designs a chance to shine through?\n\nTiming is everything\n\nFirst, consider when you should seek others\u2019 opinions. Your personal style will influence whether you show early sketches or wait to demonstrate something more complete. Some designers thrive at low fidelity, sketching out ideas that, despite their rudimentary nature, easily spark debate. Other designers take time to create more fully-realised versions. Some even argue that the great unveiling should be eliminated altogether by working directly alongside the client throughout, collaborating on the design to reach its full potential. \n\nWhatever your individual preference, you\u2019ll rarely have the chance to do it entirely your own way. Contracts, clients, and deadlines will affect how early and often you share your work. However, try to avoid the trap of presenting too late and at too high fidelity. My experience has taught me that skilled designers tend to present their work earlier and allow longer for iteration than novices do. More aware of the potential flaws in their solutions, these designers cling less tightly to their initial efforts. Working roughly and seeking early feedback gives you the flexibility to respond more fully to nuances you may have missed until now.\n\nPlanning design reviews\n\nPresent design ideas face-to-face, or at least via video conference. Asynchronous methods like e-mail and Basecamp are slow, easily ignored, and deny you the opportunity to guide your colleagues through your work. In person, you profit from both the well-known benefits of non-verbal communication, and the chance to immediately respond to questions and elaborate on rationale.\n\nBe sure to watch the numbers at your design review sessions, however. Any more than a handful of attendees and the meeting could quickly spiral into fruitless debate. Ask your project sponsor to appoint a representative to speak on behalf of each business function, rather than inviting too many cooks.\n\nWhere possible, show your work in its native format. Photocopy hand-drawn sketches to reinforce their disposability (the defining quality of a sketch) and encourage others to scribble their own thoughts on top. Show digital deliverables \u2013 wireframes, design concepts, rich interactions \u2013 on screen. The experience of a design is very different on screen than on paper. A monitor has appropriate dimensions and viewport size, presenting an accurate picture of the design\u2019s visual hierarchy, and putting interactive elements in the right context. On paper, a link is merely underlined text. On screen, it is another step along the user\u2019s journey.\n\nDon\u2019t waste time presenting multiple concepts. Not only is it costly to work up multiple concepts to the level required for fair appraisal, but the practice demonstrates a sorry abdication of responsibility. Designers should be custodians of design. Asking for feedback on multiple designs turns the critique process into a beauty pageant, relinquishing a designer\u2019s authority. Instead of rational choices that meet genuine user and business needs, you may be stuck with a Frankensteinian monstrosity, assembled from incompatible parts: \u201cThis header plus the whizzy bit from Version C\u201d.\n\nThis isn\u2019t to say that you shouldn\u2019t explore lots of ideas yourself. Divergent thinking early in the design process is the only way to break free of the clich\u00e9d patterns and fads that so often litter mediocre sites. But you must act as a design curator, choosing the best of your work and explaining its rationale clearly and succinctly. Attitude, then, is central to successful critique. It can be difficult to tread the fine line between the harmful extremes of doormat passivity and prima donna arrogance. Remember that you are the professional, but be mindful that even experts make mistakes, particularly when \u2013 as with all design projects \u2013 they don\u2019t possess all the relevant information in advance. Present your case with open-minded confidence, while accepting that positive critique will make your design (and ultimately your skills) stronger.\n\nThe courage of your convictions\n\nUltimately, your success in the feedback process, and indeed in the entire design process, hinges upon the rationale you provide for your work. Ideally, you should be able to refer to your research \u2013 personas, usability test findings, analytics \u2013 to support your decisions. To keep this evidence in mind, print it out to share at the design review, or include it in your presentation. Explain the rationale behind the most important decisions before showing the design, so that you can be sure of the full attention of your audience.\n\nOnce you\u2019ve covered these points, display your design and walk through the specific features of the page. A little honesty goes a long way here: state your case as strongly as your rationale demands. Sure of your reasoning? Be strong. Speculating an approach based on a hunch? Say so, and encourage your colleagues to explore the idea with you and see where it leads.\n\nOf course, none of these approaches should be sacrosanct. A proficient designer must be able to bend his or her way of working to suit the situation at hand. So sometimes you\u2019ll want to ignore these rules of thumb and explore your own hunches as required. More power to you. As long as you think as clearly about the feedback process as you have about the design itself, you\u2019ll be able to enjoy the great unveiling as a moment to be savoured, not feared.", "year": "2010", "author": "Cennydd Bowles", "author_slug": "cennyddbowles", "published": "2010-12-12T00:00:00+00:00", "url": "https://24ways.org/2010/the-great-unveiling/", "topic": "business"} {"rowid": 233, "title": "Wrapping Things Nicely with HTML5 Local Storage", "contents": "HTML5 is here to turn the web from a web of hacks into a web of applications \u2013 and we are well on the way to this goal. The coming year will be totally and utterly awesome if you are excited about web technologies.\n\nThis year the HTML5 revolution started and there is no stopping it. For the first time all the browser vendors are rallying together to make a technology work. The new browser war is fought over implementation of the HTML5 standard and not over random additions. We live in exciting times.\n\nStarting with a bang\n\nAs with every revolution there is a lot of noise with bangs and explosions, and that\u2019s the stage we\u2019re at right now. HTML5 showcases are often CSS3 showcases, web font playgrounds, or video and canvas examples.\n\nThis is great, as it gets people excited and it gives the media something to show. There is much more to HTML5, though. Let\u2019s take a look at one of the less sexy, but amazingly useful features of HTML5 (it was in the HTML5 specs, but grew at such an alarming rate that it warranted its own spec): storing information on the client-side.\n\nWhy store data on the client-side?\n\nStoring information in people\u2019s browsers affords us a few options that every application should have:\n\n\n\tYou can retain the state of an application \u2013 when the user comes back after closing the browser, everything will be as she left it. That\u2019s how \u2018real\u2019 applications work and this is how the web ones should, too.\n\tYou can cache data \u2013 if something doesn\u2019t change then there is no point in loading it over the Internet if local access is so much faster\n\tYou can store user preferences \u2013 without needing to keep that data on your server at all.\n\n\nIn the past, storing local data wasn\u2019t much fun.\n\nThe pain of hacky browser solutions\n\nIn the past, all we had were cookies. I don\u2019t mean the yummy things you get with your coffee, endorsed by the blue, furry junkie in Sesame Street, but the other, digital ones. Cookies suck \u2013 it isn\u2019t fun to have an unencrypted HTTP overhead on every server request for storing four kilobytes of data in a cryptic format. It was OK for 1994, but really neither an easy nor a beautiful solution for the task of storing data on the client.\n\nThen came a plethora of solutions by different vendors \u2013 from Microsoft\u2019s userdata to Flash\u2019s LSO, and from Silverlight isolated storage to Google\u2019s Gears. If you want to know just how many crazy and convoluted ways there are to store a bit of information, check out Samy\u2019s evercookie.\n\nClearly, we needed an easier and standardised way of storing local data.\n\nKeeping it simple \u2013 local storage\n\nAnd, lo and behold, we have one. The local storage API (or session storage, with the only difference being that session data is lost when the window is closed) is ridiculously easy to use. All you do is call a few methods on the window.localStorage object \u2013 or even just set the properties directly using the square bracket notation:\n\nif('localStorage' in window && window['localStorage'] !== null){\n\tvar store = window.localStorage;\n\n\t// valid, API way\n\t\tstore.setItem(\u2018cow\u2019,\u2018moo\u2019);\n\t\tconsole.log(\n\t\tstore.getItem(\u2018cow\u2019)\n\t); // => \u2018moo\u2019\n\n\t// shorthand, breaks at keys with spaces\n\t\tstore.sheep = \u2018baa\u2019 \n\t\tconsole.log(\n\t\tstore.sheep \n\t); // \u2018baa\u2019\n\n\t// shorthand for all\n\t\tstore[\u2018dog\u2019] = \u2018bark\u2019\n\t\tconsole.log(\n\t\tstore[\u2018dog\u2019]\n\t); // => \u2018bark\u2019\n\n}\n\nBrowser support is actually pretty good: Chrome 4+; Firefox 3.5+; IE8+; Opera 10.5+; Safari 4+; plus iPhone 2.0+; and Android 2.0+. That should cover most of your needs. Of course, you should check for support first (or use a wrapper library like YUI Storage Utility or YUI Storage Lite).\n\nThe data is stored on a per domain basis and you can store up to five megabytes of data in localStorage for each domain.\n\nStrings attached\n\nBy default, localStorage only supports strings as storage formats. You can\u2019t store results of JavaScript computations that are arrays or objects, and every number is stored as a string. This means that long, floating point numbers eat into the available memory much more quickly than if they were stored as numbers.\n\nvar cowdesc = \"the cow is of the bovine ilk, \"+\n\t\t\"one end is for the moo, the \"+\n\t\t\"other for the milk\";\n\nvar cowdef = {\n\tilk\u201cbovine\u201d,\n\tlegs,\n\tudders,\n\tpurposes\n\t\tfront\u201cmoo\u201d,\n\t\tend\u201cmilk\u201d\n\t}\n};\n\nwindow.localStorage.setItem(\u2018describecow\u2019,cowdesc);\nconsole.log(\n\twindow.localStorage.getItem(\u2018describecow\u2019)\n); // => the cow is of the bovine\u2026 \n\nwindow.localStorage.setItem(\u2018definecow\u2019,cowdef);\nconsole.log(\n\twindow.localStorage.getItem(\u2018definecow\u2019)\n); // => [object Object] = bad!\n\nThis limits what you can store quite heavily, which is why it makes sense to use JSON to encode and decode the data you store:\n\nvar cowdef = {\n\t\"ilk\":\"bovine\",\n\t\"legs\":4,\n\t\"udders\":4,\n\t\"purposes\":{\n\t\"front\":\"moo\",\n\t\"end\":\"milk\"\n\t}\n};\n\nwindow.localStorage.setItem(\u2018describecow\u2019,JSON.stringify(cowdef));\nconsole.log(\n\tJSON.parse(\n\t\twindow.localStorage.getItem(\u2018describecow\u2019)\n\t)\n); // => Object { ilk=\u201cbovine\u201d, more\u2026}\n\nYou can also come up with your own formatting solutions like CSV, or pipe | or tilde ~ separated formats, but JSON is very terse and has native browser support.\n\nSome use case examples\n\nThe simplest use of localStorage is, of course, storing some data: the current state of a game; how far through a multi-form sign-up process a user is; and other things we traditionally stored in cookies. Using JSON, though, we can do cooler things.\n\nSpeeding up web service use and avoiding exceeding the quota\n\nA lot of web services only allow you a certain amount of hits per hour or day, and can be very slow. By using localStorage with a time stamp, you can cache results of web services locally and only access them after a certain time to refresh the data.\n\nI used this technique in my An Event Apart 10K entry, World Info, to only load the massive dataset of all the world information once, and allow for much faster subsequent visits to the site. The following screencast shows the difference:\n\n\n\nFor use with YQL (remember last year\u2019s 24 ways entry?), I\u2019ve built a small script called YQL localcache that wraps localStorage around the YQL data call. An example would be the following:\n\nyqlcache.get({\n\tyql: 'select * from flickr.photos.search where text=\"santa\"',\n\tid: 'myphotos',\n\tcacheage: ( 60*60*1000 ),\n\tcallback: function(data) {\n\t\tconsole.log(data);\n\t}\n});\n\nThis loads photos of Santa from Flickr and stores them for an hour in the key myphotos of localStorage. If you call the function at various times, you receive an object back with the YQL results in a data property and a type property which defines where the data came from \u2013 live is live data, cached means it comes from cache, and freshcache indicates that it was called for the first time and a new cache was primed. The cache will work for an hour (60\u00d760\u00d71,000 milliseconds) and then be refreshed. So, instead of hitting the YQL endpoint over and over again, you hit it once per hour.\n\nCaching a full interface\n\nAnother use case I found was to retain the state of a whole interface of an application by caching the innerHTML once it has been rendered. I use this in the Yahoo Firehose search interface, and you can get the full story about local storage and how it is used in this screencast:\n\n\n\nThe stripped down code is incredibly simple (JavaScript with PHP embed):\n\n// test for localStorage support\nif(('localStorage' in window) && window['localStorage'] !== null){\n\nvar f = document.getElementById(\u2018mainform\u2019);\n// test with PHP if the form was sent (the submit button has the name \u201csent\u201d)\n\n\n\t// get the HTML of the form and cache it in the property \u201cstate\u201d\n\tlocalStorage.setItem(\u2018state\u2019,f.innerHTML);\n\n// if the form hasn\u2019t been sent\u2026\n\n\n\t// check if a state property exists and write back the HTML cache\n\tif(\u2018state\u2019 in localStorage){\n\t\tf.innerHTML = localStorage.getItem(\u2018state\u2019); \n\t}\n\n\t\n\n}\n\nOther ideas\n\nIn essence, you can use local storage every time you need to speed up access. For example, you could store image sprites in base-64 encoded datasets instead of loading them from a server. Or you could store CSS and JavaScript libraries on the client. Anything goes \u2013 have a play.\n\nIssues with local and session storage\n\nOf course, not all is rainbows and unicorns with the localStorage API. There are a few niggles that need ironing out. As with anything, this needs people to use the technology and raise issues. Here are some of the problems:\n\n\n\tInadequate information about storage quota \u2013 if you try to add more content to an already full store, you get a QUOTA_EXCEEDED_ERR and that\u2019s it. There\u2019s a great explanation and test suite for localStorage quota available.\n\tLack of automatically expiring storage \u2013 a feature that cookies came with. Pamela Fox has a solution (also available as a demo and source code)\n\tLack of encrypted storage \u2013 right now, everything is stored in readable strings in the browser.\n\n\nBigger, better, faster, more!\n\nAs cool as the local and session storage APIs are, they are not quite ready for extensive adoption \u2013 the storage limits might get in your way, and if you really want to go to town with accessing, filtering and sorting data, real databases are what you\u2019ll need. And, as we live in a world of client-side development, people are moving from heavy server-side databases like MySQL to NoSQL environments.\n\nOn the web, there is also a lot of work going on, with Ian Hickson of Google proposing the Web SQL database, and Nikunj Mehta, Jonas Sicking (Mozilla), Eliot Graff (Microsoft) and Andrei Popescu (Google) taking the idea beyond simply replicating MySQL and instead offering Indexed DB as an even faster alternative.\n\nOn the mobile front, a really important feature is to be able to store data to use when you are offline (mobile coverage and roaming data plans anybody?) and you can use the Offline Webapps API for that.\n\nAs I mentioned at the beginning, we have a very exciting time ahead \u2013 let\u2019s make this web work faster and more reliably by using what browsers offer us. For more on local storage, check out the chapter on Dive into HTML5.", "year": "2010", "author": "Christian Heilmann", "author_slug": "chrisheilmann", "published": "2010-12-06T00:00:00+00:00", "url": "https://24ways.org/2010/html5-local-storage/", "topic": "code"} {"rowid": 235, "title": "Real Animation Using JavaScript, CSS3, and HTML5 Video", "contents": "When I was in school to be a 3-D animator, I read a book called Timing for Animation. Though only 152 pages long, it\u2019s essentially the bible for anyone looking to be a great animator. In fact, Pixar chief creative officer John Lasseter used the first edition as a reference when he was an animator at Walt Disney Studios in the early 1980s.\n\nIn the book, authors John Halas and Harold Whitaker advise:\n\n\n\tTiming is the part of animation which gives meaning to movement. Movement can easily be achieved by drawing the same thing in two different positions and inserting a number of other drawings between the two. The result on the screen will be movement; but it will not be animation.\n\n\nBut that\u2019s exactly what we\u2019re doing with CSS3 and JavaScript: we\u2019re moving elements, not animating them. We\u2019re constantly specifying beginning and end states and allowing the technology to interpolate between the two. And yet, it\u2019s the nuances within those middle frames that create the sense of life we\u2019re looking for.\n\nAs bandwidth increases and browser rendering grows more consistent, we can create interactions in different ways than we\u2019ve been able to before. We\u2019re encountering motion more and more on sites we\u2019d generally label \u2018static.\u2019 However, this motion is mostly just movement, not animation. It\u2019s the manipulation of an element\u2019s properties, most commonly width, height, x- and y-coordinates, and opacity.\n\nSo how do we create real animation?\n\nThe metaphor\n\nIn my experience, animation is most believable when it simulates, exaggerates, or defies the real world. A bowling ball falls differently than a racquetball. They each have different weights and sizes, which affect the way they land, bounce, and impact other objects.\n\nThis is a major reason that JavaScript animation frequently feels mechanical; it doesn\u2019t complete a metaphor. Expanding and collapsing a
feels very different than a opening a door or unfolding a piece of paper, but it often shouldn\u2019t. The interaction itself should tie directly to the art direction of a page.\n\nPhysics\n\nUnderstanding the physics of a situation is key to creating convincing animation, even if your animation seeks to defy conventional physics. Isaac Newton\u2019s first law of motion\u2019s_laws_of_motion states, \u201cEvery body remains in a state of rest or uniform motion (constant velocity) unless it is acted upon by an external unbalanced force.\u201d Once a force acts upon an object, the object\u2019s shape can change accordingly, depending on the strength of the force and the mass of the object. Another nugget of wisdom from Halas and Whitaker:\n\n\n\tAll objects in nature have their own weight, construction, and degree of flexibility, and therefore each behaves in its own individual way when a force acts upon it. This behavior, a combination of position and timing, is the basis of animation. The basic question which an animator is continually asking himself is this: \u201cWhat will happen to this object when a force acts upon it?\u201d And the success of his animation largely depends on how well he answers this question.\n\n\nIn animating with CSS3 and JavaScript, keep physics in mind. How \u2018heavy\u2019 is the element you\u2019re interacting with? What kind of force created the action? A gentle nudge? A forceful shove? These subtleties will add a sense of realism to your animations and make them much more believable to your users.\n\nMisdirection\n\nMagicians often use misdirection to get their audience to focus on one thing rather than another. They fool us into thinking something happened that actually didn\u2019t.\n\nAnimation is the same, especially on a screen. By changing the arrangement of pixels on screen at a fast enough rate, your eyes fool your mind into thinking an object is actually in motion. \n\nAnother important component of misdirecting in animation is the use of multiple objects. Try to recall a cartoon where a character vanishes. More often, the character makes some sort of exaggerated motion (this is called anticipation) then disappears, and a puff a smoke follows. That smoke is an extra element, but it goes a long way into make you believe that character actually disappeared.\n\nVery rarely does a vanishing character\u2019s opacity simply go from one hundred per cent to zero. That\u2019s not believable. So why do we do it with
s?\n\nArmed with the ammunition of metaphors and misdirection, let\u2019s code an example.\n\nShake, rattle, and roll\n\n(These demos require at least a basic understanding of jQuery and CSS3. Run away if your\u2019re afraid, or brush up on CSS animation and resources for learning jQuery. Also, these demos use WebKit-specific features and are best viewed in the latest version of Safari, so performance in other browsers may vary.)\n\nWe often see the design pattern of clicking a link to reveal content. Our \u201cfirst demo\u201d:\u201d/examples/2010/real-animation/demo1/ shows us exactly that. It uses jQuery\u2019s \u201c slideDown()\u201d:http://api.jquery.com/slideDown/ method, as many instances do.\n\nBut what force acted on the
that caused it to open? Did pressing the button unlatch some imaginary hook? Did it activate an unlocking sequence with some gears?\n\nTake 2\n\nOur second demo is more explicit about what happens: the button fell on the
and shook its content loose. Here\u2019s how it\u2019s done. \n\nfunction clickHandler(){\n\t$('#button').addClass('animate');\n\treturn false;\n}\n\nClicking the link adds a class of animate to our button. That class has the following CSS associated with it:\n\n\n\nIn our keyframe definition, we\u2019ve specified from and to states. This is great, because we can be explicit about how an object starts and finishes moving. \n\nWhat\u2019s also extra handy is that these CSS keyframes broadcast events that you can react to with JavaScript. In this example, we\u2019re listening to the webkitAnimationEnd event and opening the
only when the sequence is complete. Here\u2019s that code.\n\nfunction attachAnimationEventHandlers(){\n\tvar wrap = document.getElementById('wrap');\n\twrap.addEventListener('webkitAnimationEnd', function($e) {\n\t\tswitch($e.animationName){\n\t\t\tcase \"ANIMATE\" :\n\t\t\topenMain();\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t}\n\t}, false);\n}\nfunction openMain(){\n\t$('#main .inner').slideDown('slow');\n}\n\n(For more info on handling animation events, check out the documentation at the Safari Reference Library.)\n\nTake 3\n\nThe problem with the previous demo is that the subtleties of timing aren\u2019t evident. It still feels a bit choppy.\n\nFor our third demo, we\u2019ll use percentages instead of keywords so that we can insert as many points as we need to communicate more realistic timing. The percentages allow us to add the keys to well-timed animation: anticipation, hold, release, and reaction. \n\n\n\nTake 4\n\nThe button animation is starting to feel much better, but the reaction of the
opening seems a bit slow.\n\nThis fourth demo uses jQuery\u2019s delay() method to time the opening precisely when we want it. Since we know the button\u2019s animation is one second long and its reaction starts at eighty per cent of that, that puts our delay at 800ms (eighty per cent of one second). However, here\u2019s a little pro tip: let\u2019s start the opening at 750ms instead. The extra fifty milliseconds makes it feel more like the opening is a reaction to the exact hit of the button. Instead of listening for the webkitAnimationEnd event, we can start the opening as soon as the button is clicked, and the movement plays on the specified delay.\n\nfunction clickHandler(){\n\t$('#button').addClass('animate');\n\topenMain();\n\treturn false;\n}\nfunction openMain(){\n\t$('#main .inner').delay(750).slideDown('slow');\n}\n\nTake 5\n\nWe can tweak the timing of that previous animation forever, but that\u2019s probably as close as we\u2019re going to get to realistic animation with CSS and JavaScript. However, for some extra sauce, we could relegate the whole animation in our final demo to a video sequence which includes more nuances and extra elements for misdirection.\n\nHere\u2019s the basis of video replacement. Add a