Adobe

decor

Web Platform Team Blog

Making the web awesome

Good-Looking Shapes Gallery

As a modern consumer of media, you rarely crack open a magazine or a pamphlet or anything that would be characterized as “printed”. Let me suggest that you take a walk on the wild side. The next time you are in a doctor’s office, or a supermarket checkout lane, or a library, thumb though a magazine. Most of the layouts you’ll find inside can also be found on the web, but not all of them. Layouts where content hugs the boundaries of illustrations are common in print and rare on the web. One of the reasons non-rectangular contour-hugging layouts are uncommon on the web is that they are difficult to produce.

They are not difficult to produce anymore.

The CSS Shapes specification is now in the final stages of standardization. This feature enables flowing content around geometric shapes (like circles and polygons), as well as around shapes defined by an image’s alpha channel. Shapes make it easy to produce the kinds of layouts you can find in print today, with all the added flexibility and power that modern online media affords. You can use CSS Shapes right now with the latest builds of WebKit and Blink based browsers, like Safari and Chrome.

Development of CSS Shapes has been underway for about two years, and we’ve been regularly heralding its progress here. Many of those reports have focused on the evolution of the spec and implementations, and they’ve included examples that emphasized basics over beauty. This article is an attempt to tilt the balance back towards good-looking. Listed below are simple shapes demos that we think look pretty good. Everyone on Adobe’s CSS Shapes engineering team contributed at least one.

There’s a live CodePen.io version of each demo in the gallery. Click on the demo screenshot or one of the handy links to take a look. You’ll want to view the demos with a browser that supports Shapes and you’ll need to enable CSS Shapes in that browser. For example you can use a nightly build of the Safari browser or you can enable shapes in Chrome or Chrome Canary like this:

  1. Copy and paste chrome://flags/#enable-experimental-web-platform-features into the address bar, then press enter.
  2. Click the ‘Enable’ link within that section.
  3. Click the ‘Relaunch Now’ button at the bottom of the browser window.

A few of the demos use the new Shapes Polyfill and will work in most browsers.

And now, without further ado, please have a look through our good-looking shapes gallery.


Ozma of Oz

ozma-demo-screenshot

This demo reproduces the layout style that opens many of the chapters of the L. Frank Baum books, including Ozma of Oz.  The first page is often dominated by an illustration on the left or right. The chapter’s text conforms to the illustration, but not too tightly. The books were published over 100 years ago and they still look good print.  With CSS Shapes they can still look good on the web.

Top Cap

topcap-demo-screenshot

The conventional “drop-cap” opens a paragraph by enlarging and highlighting the first letter, word or phrase. The drop-cap’s goal is to draw your attention to where you can start reading. This demo delivers the same effect by crowning the entire opening paragraph with a “top cap” that funnels your attention into the article. In both cases, what’s going on is a segue from a graphic element to the text.

Violator

monsters-demo-screenshot

A violator is small element that “violates” rectangular text layout by encroaching on a corner or a small part of an edge. This layout idiom is common in short-form magazines and product packaging. That “new and improved” banner which blazes through the corner of thousands of consumer products (whether or not they are new or improved) – it’s a violator.

Column Interest

columns-demo-screenshot

When a print magazine feels the need to incorporate some column layout melodrama, they often reach for this idiom. The shape spans a pair of columns, which creates visual interest in the middle of the page. Without it you’d be faced with a wall of attention sapping text and more than likely turn the page.

Caption

Screenshot of the wine jug caption demo.

The old-school approach for including a caption with an image is to put the caption text alongside or below the image. Putting a caption on top of an image requires a little more finesse, since you have to ensure that the text doesn’t obscure anything important and that the text is rendered in a way that preserves readability.  The result can be relatively attractive.

This photograph was taken by Zoltan Horvath who has pointed out that I’ve combined a quote about tea with a picture of a ceremonial wine jug.  I apologize for briefly breaching that beverage boundary. It’s just a demo.

Paging

Screenshot of the paging demo.

With a layout like this, one could simple let the content wrap and around the shape on the right and then expand into the usual rectangle.  In this demo the content is served up a paragraph at a time, in response to the left and right arrow keys.

Note also: yes in fact the mate gourd is perched on exactly the same windowsill as the previous demo. Zoltan and Pope Francis are among the many fans of yerba mate tea.

Ersatz shape-inside

Screenshot of the ersatz shape-inside demo.

Originally the CSS Shapes spec included shape-inside as well as shape-outside. Sadly, shape-inside was promoted to “Level 2″ of the spec and isn’t available in the current implementations. Fortunately for shape insiders everywhere, it’s still sometimes possible to mimic shape-inside with an adjacent pair of carefully designed shape-outside floats. This demo is a nice example of that, where the text appears inside a bowl of oatmeal.

Animation

animation-demo-screeenshot

This is an animated demo, so to appreciate it you’ll really need to take a look at the live version. It is an example of using an animated shape to draw the user’s attention to a particular message.  Of course one must use this approach with restraint, since an animated loop on a web page doesn’t just gently tug at the user’s attention. It drags at their attention like a tractor beam.

Performance

performance-demo-screenshot

Advertisements are intended to grab the user’s attention and a second or two of animation will do that. In this demo a series of transition motions have been strung together into a tiny performance that will temporarily get the reader’s attention. The highlight of the performance is – of course – the text snapping into the robot’s contour for the finale. Try and imagine a soundtrack that punctuates the action with some whirring and clanking noises, it’s even better that way.

CSS Shapes Polyfill

The CSS Shapes feature is coming soon to a browser near you. The specification has reached Candidate Recommendation and implementations are maturing in the experimental builds of WebKit and Blink. In addition to brushing up on CSS Shapes over at A List Apart or here on the Adobe Web Platform Blog, you may also want to start thinking about browser compatibility. Even after these features become available in release versions of Chrome and Safari (fingers crossed for soon), they will not yet be available in other browsers.

The CSS Shapes Polyfill is one method of achieving consistent behavior across browsers. It is a bit of JavaScript that checks to see if a browser supports CSS Shapes; if not, it approximates the behavior with a series of floats. There are simpler approaches to compatibility, such as gracefully falling back to old float behavior, or using feature detection like Modernizr to tweak styles based on shapes support. However, the polyfill allows you to use shapes, even in non-supporting browsers, and utilizes native implementations where possible.

The Basics

See the Pen CSS Shapes Polyfill Demo by Adobe Web Platform (@adobe) on CodePen.

Using the polyfill is incredibly easy. All you have to do is:

  1. Download the script from GitHub. You’ll want shapes-polyfill.js or shapes-polyfill.min.js (the minified version).
  2. Include the script in your page.
  3. Add shape-outside and shape-margin styles in linked stylesheets or <style> elements.

Example

In order to use the polyfill, the key pieces are the CSS to add the shape styles:

.shape {
    float: left;
    -webkit-shape-outside: circle(50%); /* only prefix currently supported */
    shape-outside: circle(50%);
    shape-margin: 1em;
}

and the html markup it is applied to, along with the polyfill script itself:

<div class='shape'></div>
This text will wrap around the circular contour to the left.
<script src='shapes-polyfill.js'></script>

If you are interested in seeing the full context for this code, I have created a working example.

Caveats

The polyfill will work best in simple shapes cases, and there are some limitations you may run into.

  • Shape styles must be set inside style elements or linked stylesheets. The polyfill does not monitor inline styles that are set via the style attribute.
  • The script recomputes layout only in response to a window resize event. If other events (like style changes) should cause relayout, you will have to force a layout using the ShapesPolyfill.teardown() and ShapesPolyfill.run() methods (see the documentation).
  • shape-outside: url() values respect CORS, so you should load images from the same domain as the page, or from a server that supplies the appropriate CORS headers.
  • The polyfill does not yet support shapes on stacked floats.

In addition to the above limitations, the polyfill also has a performance cost. Because of the computation required, layout using the polyfill is roughly an order of magnitude slower (10-20x depending on shape) than layout utilizing a native shapes implementation. The polyfill is also another resource that must be loaded into your page. You should weigh these performance costs when deciding whether the polyfill is the optimal approach for shapes browser compatibility on your site.

Further Tinkering

The source code is available on GitHub, and includes documentation for customizing how the polyfill runs. Please let us know if you have any feedback. You can do so through GitHub issues, here on the blog, or via twitter @adobeweb.

Posted in Shapes | Comments Off

CSS Shapes feature testing is available in Modernizr production builds!

Modernizr is a JavaScript library that detects HTML and CSS features in the user’s browser. I have developed feature-testing support in Modernizr for CSS Shapes. I am writing this post to proudly announce that support for CSS Shapes is now available in Modernizr 2.8.1 production builds. It will also be included in future Modernizr releases.

Modernizr-2-Logo-vertical-medium

Why should you do feature testing?

As CSS Shapes support is knocking on the door of release in stable browser versions, I want to encourage you to get a head start using the feature. Until it is widely supported, you might want to have a fallback in place or display a notice to users with browsers that don’t yet support the feature. Modernizr is a good tool to enable this feature detection.

How we can test for the shapes support?

Let’s take a look at the following examples:

The most important part of the first example is the if-condition that checks for “Modernizr.shapes” and decides to show an informational message if shapes support is not detected.

You can also also specify custom CSS selectors for cases when Shapes support is detected. Modernizr adds the ‘shapes’ class to the html root tag if shapes are supported, and the ‘no-shapes’ class if not. If you want to know more about how Modernizr works, please check out the documentation.

The key point of the second example is the .shapes prefix before the h1 selector, which applies the custom style to every h1 tags only if the support is detected.

How do you get Modernizr with CSS Shapes support?

  1. Open modernizr.org and go to the Download section.
  2. Check the box for CSS Shapes under Non-core detects.
  3. Check the box for Modernizr.testAllProps() under Extensibility.
  4. Generate and Download the code.
  5. Include the generated Modernizer.js in your HTML file.
  6. Now you can use Modernizr.shapes in JavaScript or .shapes in CSS anywhere in your page.

Modernizr is a powerful tool for testing HTML and CSS feature support. I encourage you to use it if you’re experimenting with the latest and greatest web features.

Let us know what you think here or on Twitter @adobeweb or @ZoltanWebKit!

Adobe Web Platform Goes to the 2014 WebKit Contributors’ Meeting

Last week, Apple hosted the 2014 WebKit Contributors’ Meeting at their campus in Cupertino. As usual it was an unconference-style event, with session scheduling happening on the morning of the first day. While much of the session content was very specific to WebKit implementation, there were topics covered that are interesting to the wider web community. This post is a roundup of some of these topics from the sessions that Adobe Web Platform Team members attended.

CSS Custom Properties for Cascading Variables

Alan Stearns suggested a session on planning a new implementation of CSS Custom Properties for Cascading Variables. While implementations of this spec have been attempted in WebKit in the past, they never got past the experimental stage. Despite this, there is still much interest in implementing this feature. In addition, the current version of the spec has addressed many of the issues that WebKit contributors had previously expressed. We talked about a possible issue with using variables in custom property values, which Alan is investigating. More detail is available in the notes from the Custom Properties session.

CSS Regions

Andrei Bucur presented the current state of the CSS Regions implementation in WebKit. The presentation was well received and well attended. Notably, this was one of the few sessions with enough interest that it had a time slot all to itself.

While CSS Regions shipped last year in iOS 7 and Safari 6.1 and 7, the implementation in WebKit hasn’t been standing still. Andrei mentioned the following short list of changes in WebKit since the last Safari release:

  • correct painting of fragments and overflow
  • scrollable regions
  • accelerated content inside regions
  • position: fixed elements
  • the regionoversetchange event
  • better selection
  • better WebInspector integration
  • and more…

Andrei’s slides outlining the state of CSS Regions also contain a roadmap for the feature’s future in WebKit as well as a nice demo of the fix to fragment and overflow handling. If you are following the progress of CSS Regions in WebKit, the slides are definitely worth a look. (As of this writing, the Regions demo in the slides only works in Safari and WebKit Nightly.)

CSS Shapes

Zoltan Horvath, Bear Travis, and I covered the current state of CSS Shapes in WebKit. We are almost done implementing the functionality in Level 1 of the CSS Shapes Specification (which is itself a Candidate Recommendation, the last step before becoming an official W3C standard). The discussion in this session was very positive. We received good feedback on use cases for shape-outside and even talked a bit about the possibilities for when shape-inside is revisited as part of CSS Shapes Level 2. While I don’t have any slides or demos to share at the moment, we will soon be publishing a blog post to bring everyone up to date on the latest in CSS Shapes. So watch this space for more!

Subpixel Layout

This session was mostly about implementation. However, Zalan Bujtas drew an interesting distinction between subpixel layout and subpixel painting. Subpixel layout allows for better space utilization when laying out elements on the page, as boxes can be sized and positioned more precisely using fractional units. Subpixel painting allows for better utilization of high DPI displays by actually drawing elements on the screen using fractional CSS pixels (For example: on a 2x “Retina” display, half of a CSS pixel is one device pixel). Subpixel painting allows for much cleaner lines and smoother animations on high DPI displays when combined with subpixel layout. While subpixel layout is currently implemented in WebKit, subpixel painting is currently a work in progress.

Web Inspector

The Web Inspector is full of shiny new features. The front-end continues to shift to a new design, while the back-end gets cleaned up to remove cruft. The architecture for custom visual property editors is in place and will hopefully enable quick and intuitive editing of gradients, transforms, and animations in the future. Other goodies include new breakpoint actions (like value logging), a redesigned timeline, and IndexedDB debugging support. The Web Inspector still has room for new features, and you can always check out the #webkit-inspector channel on freenode IRC for the latest and greatest.

Web Components

The Web Components set of features continues to gather interest from the browser community. Web Components is made up of four different features: HTML Components, HTML Imports, Shadow DOM, and HTML Templates. The general gist of the talk was that the Web Components concepts are desirable, but there are concerns that the features’ complexity may make implementation difficult. The main concerns seemed to center around performance and encapsulation with Shadow DOM, and will hopefully be addressed with a prototype implementation of the feature (in the works). You can also take a look at the slides from the Web Components session.

CSS Grid Layout

The WebKit implementation of the CSS Grid Layout specification is relatively advanced. After learning in this session that the only way to test out Grid Layout in WebKit was to make a custom build with it enabled, session attendees concluded that it should be turned on by default in the WebKit Nightlies. So in the near future, experimenting with Grid Layout in WebKit should be as easy as installing a nightly build.

More?

As I mentioned earlier, this was just a high-level overview of a few of the topics at this year’s WebKit Contributors’ Meeting. Notes and slides for some of the topics not mentioned here are available on the 2014 WebKit Meeting page in the wiki. The WebKit project is always welcoming new contributors, so if you happen to see a topic on that wiki page that interests you, feel free to get in touch with the community and see how you can get involved.

Acknowledgements

This post would not have been possible without the notes and editing assistance of my colleagues on the Adobe Web Platform Team that attended the meeting along with me: Alan Stearns, Andrei Bucur, Bear Travis, and Zoltan Horvath.

Add a caption to an image — if you can

So you want to add a caption to an image. As Hans points out in his latest blog post, Captioneering, it’s a technique as old as images and captions. But even with HTML5 figure and figcaption tags, replicating some basic captioning is not straightforward. There are tricks to implementing traditional print captions and now-next-new ways of captioning for the web. Hans talks about different techniques, how to implement them and what to avoid. And while Hans calls out various complications, somehow the reader walks away with a clearer picture — with captions!

CSS Shapes Editor for Brackets

CSS Shapes open a lot of design possibilities with the ability to wrap content inside and around custom paths.

However, creating the actual shapes used to be a cumbersome process. You’d use an image authoring tool to create paths, export them, maybe adjust them to conform to CSS shapes syntax, import them into your stylesheet, then check in the browser to see how the result interacts with content on the page. Even minor adjustments become too painful to do with this workflow. A better approach was needed.

CSS Shapes are meant to be used in the browser. Why not create them there?

shapes-polygon

Today, we are announcing the release of the CSS Shapes Editor extension for Brackets. It is a tool which you use to edit, scale and transform CSS Shapes values right in the browser when using the LivePreview mode in Brackets. Authoring shapes this way gives you instant visual feedback for your changes, so you get to see how the shapes interact with other elements on the page.

Head over to the Brackets blog to find out how to get the CSS Shapes Editor extension.

We are also making it easy for web developers inspect CSS Shapes with the Webkit WebInspector. You can see the shape outline by hovering your mouse over the element which uses it.

webinspector-shapes

April 2014 Extensible Web Summit

Last week, W3C TAG (Technical Architecture Group) held an “Extensible Web Summit” hosted by the PhoneGap team at the Adobe offices in San Francisco. The summit brought together TAG members, people from the Extensible Web Community Group, browser implementers, JavaScript library authors, and web developers to talk about the future of the web platform. I believe the consensus of the people who participated was that the TAG should host more summits like these on a regular basis.

The conversations at the summit were informed by the Extensible Web Manifesto, which lays out a few ideas on how to add new features to the web. What makes the most sense to me in the manifesto is the idea of exposing lower-level capabilities that high-level features can be built upon. It’s an easy trap to build constrained high-level features that can’t be extended past a narrow set of use cases. It’s somewhat harder — but more rewarding — to find lower-level primitives that expose the inner workings of a feature and allow for extensions to new use cases.

The summit was organized barcamp style, with topics suggested by the attendees. A list of sessions with links to the conversation minutes can be found on the summit’s Lanyrd site. Topics ranged over the whole web stack, from exploring the levels below the browser through how web applications get packaged.

In the introductory talks, Tab Atkins from Google acknowledged that CSS is one of the least-extensible parts of the web stack. If a CSS declaration isn’t understood, it generally gets thrown out with no way to retrieve the information. This makes it difficult to write JavaScript libraries that extend CSS capabilities, as you have to reconstruct all the CSS parsing and cascading you require.

Custom properties help with some of these problems. Once they are widely supported, CSS polyfills can avoid re-inventing CSS parsing and cascading. The summit had a session on what else might be useful for extending CSS. One of the suggestions was some way for script to hook in to when styles change — perhaps something like a style mutation observer.

We have DOM MutationObservers to watch for DOM changes. But style changes aren’t exposed in this way:  if a script needs to react to a style change, all sorts of hacks are needed to find out when something changed and what that change might be. A standardized style mutation observer would be a big help for these problems.

So one result of the extensible Web Summit is renewed interest in exposing style changes. There’s already a thread on www-style following up on the summit session, and I’m planning on pushing forward on the idea as much as I can. If you are interested, please join the discussion there.

And if you find anything else interesting in the summit notes, please follow up on the topics that interest you. Part of the Extensible Web Manifesto is about getting more feedback from web developers in choosing how we move the web forward. Hopefully we can have more events like this summit where we can draw upon ideas from a larger and larger set of people who want to make the web awesome.

Bear talks about filters on CSS-Tricks

Some time ago, we got a facelift at our Baker-Hamilton building in San Francisco. For a while, all of the conference rooms were floor-to-ceiling clear glass. The masses were horrified to think that we’d be on display during meetings, like goldfish in a goldfish bowl. So when the frosted glass was applied to the windows, it was the “talk of the town,” as they say. As all good memes do, it spread: before we knew it, several folks had said, “We should really do something around frosted-glass effect in web design.” About that time, Chris Coyier invited Bear Travis to write a guest article on CSS-Tricks. The subject that came to mind? Frosting Glass with CSS Filters. Hmmm…

20140407_133412_688

Then again, Jacob just told me that it all started with Arno trying to do a frosted-glass effect on his photos. Where do memes originate?

Enjoy Frosting Glass with CSS Filters.

New canvas features

A number of Canvas 2D features features recently landed in WebKit, Chrome and Firefox. Though they were proposed and drafted some time ago, no one was yet actively working on implementing them and polishing the spec. This was a great opportunity for the Adobe Web platform team to clarify those features and work with the various browser vendors to get them implemented.

Most of these features are cutting edge, so to see the running examples below, you need nightly WebKit, daily Chromium, Opera developer or Firefox Nightly. To turn on experimental canvas features in Chrome or Opera, browse to “chrome://flags“, turn on “Enable experimental canvas features” and relaunch. Firefox has individual flags for each feature. They are accessed by going to “about:config“, clicking on “I’ll be careful, I promise” and setting the flag to true. For this article, turn on turn on “canvas.path.enabled” and “canvas.focusring.enabled“. Most of the time, you need to re-launch for the setting to take effect. For features that are marked as ‘shipping‘, you don’t have to use experimental browsers; the latest version of that browser will do.

Path2D objects

The Path2D object lets you cache drawing commands. Previously, if you had a series of drawing commands, you had to repeat them for each frame of your animation. Using Path2D you can record those calls and play them back quickly. This simplifies your code and could increase the performance of your application dramatically. You can even initialize the path with SVG path data. This is faster and you could even store the path data in an SVG path element that is part of your markup.

Path2D can be constructed with the following interface:

 
  path = new Path2D(); // Creates a new empty Path2D object
  path = new Path2D(path); // Creates a new Path2D object that is a copy
  path = new Path2D(d); // Creates a new path with a string interpreted
                        // as SVG path data

The object also exposes the canvaspathmethods so all the path drawing APIs from canvas – such as lineTo, arc and rect – are available.

Canvas 2D context APIs for Path2D

To actually use this new object, the 2D canvas context was extended with the following API’s:

 
  void fill(Path2D path, optional CanvasFillRule fillRule = &quot;nonzero&quot;);
  void stroke(Path2D path);
  void clip(Path2D path, optional CanvasFillRule fillRule = &quot;nonzero&quot;);
  boolean isPointInPath(Path2D path, double x, double y,
                        optional CanvasFillRule fillRule = &quot;nonzero&quot;);
  boolean isPointInStroke(Path2D path, double x, double y);

These methods use the passed-in path object as opposed to the current default path of the existing APIs. Here’s an example that draws a lot of fish bones:

 
      ctx.save();
      ...
      ctx.translate(-60,-25);
      ctx.fill(p); // fill the path
      ctx.restore();
Check out this Pen!

If you profile this CodePen in Chrome, Safari or Firefox, little time is spent in Javascript. If you use individual draw calls, most of the time is spent running scripts. As a result, the performance is much slower.

This example also shows how you can use SVG as a source of path data:

 
var pathstring = document.getElementById(&quot;p&quot;).attributes.d.value;
var p = new Path2D(pathstring);

This API is enabled on WebKit and Firefox Nightly. It is experimental in Chrome Canary.

ImageData constructors

If you ever use a JavaScript routine or web workers to create a buffer of image data, you know that there was no convenient way to pass that to a canvas putImageData call.

It seems that you should be able to do the following:

 
var buffer = new Uint8ClampedArray(256*256);
... // populate the image data
ctx.putImageData({width: 256, height: 256, data: buffer}, 0,0);

However, because of the way browsers are implemented, you get an exception when executing putImageData. Browsers expect that you pass in a browser created object as opposed to one with the same signature that you created yourself.

The workaround was to call getImageData on a context to create a ‘dummy’ Imagedata object and then update it with your data.

With the new ImageData constructor this is no longer necessary and you can write the following code:

 
var data = new Uint8ClampedArray(256*256);
... // populate the image data
ctx.drawImage(new ImageData(data, 256), 0,0);

ImageData is now also in the global space for web workers. It’s not a transferable object yet like in Internet Explorer 11 so the members of ImageData still have to be transferred individually. This API is available on WebKit and Firefox, and is planned for Chrome.

Opaque canvas

The canvas constructor was extended so you can set its initial color to opaque black.

Because the browser now knows that the backdrop for drawing is always opaque, it can make certain assumptions that speed up drawing of transparent content and images. It also helps performance when the canvas context is drawn into the web page since it can assume the everything underneath the canvas pixels can be removed.

An additional benefit is that the browser can now draw text with sub-pixel anti-aliasing. You can trigger this behavior by passing a JSON object during the canvas context creation:

 
var ctx = canvas.getContext(&quot;2d&quot;, {alpha: false});

Once you create a context for a canvas element, there is no way to change it back from opaque to non-opaque and vice versa.

For example:

Check out this Pen!

This example draws some text in the small canvas on the left (under “Input canvas”) and then enlarges it in the canvas on the right (under “zoomed in”). Note how the anti-aliasing on the text is colored. This is a trick to give your monitor more horizontal resolution. For more info see this Wikipedia article. This feature improves the readability of text, especially on low-DPI devices. You need to take care to match the resolution of the canvas backing with the screen and don’t do transformations on anti-aliased text. Otherwise, you see the colored edges of the glyphs.

This API is shipping in Chrome and Nightly Firefox. In Safari you can trigger this behavior by filling the entire canvas with a constant color right after construction of the 2D context.

Focus rings

This new API gives you the ability to draw a focus region on your canvas context. To use this feature, you need to provide a sub-DOM to the canvas object in your markup. This could something like this:

 
&lt;canvas width=&quot;750&quot; height=&quot;220&quot;&gt;  &lt;input id=&quot;showA&quot; type=&quot;checkbox&quot; /&gt;&lt;/canvas&gt;&lt;label for=&quot;showA&quot;&gt;Show As&lt;/label&gt;
&lt;canvas width=&quot;750&quot; height=&quot;220&quot;&gt;  &lt;input id=&quot;showB&quot; type=&quot;checkbox&quot; /&gt;&lt;/canvas&gt;&lt;label for=&quot;showB&quot;&gt;Show Bs&lt;/label&gt;

The sub-DOM needs to contain elements that can get the focus. These elements (also known as fallback content) should have a pixel representation in the canvas bitmap. When the user uses the tab key, elements in the sub-DOM get the focus. To draw a focus ring for a selectedelement, you use the following API:

 
ctx.beginPath();
ctx.moveTo(...);
ctx.lineto(...);
...; // path around the focus area
ctx.drawFocusIfNeeded(fallbackElement);

drawFocusIfNeeded checks if the element has focus. If it has, it draws a focus ring with the correct style around the path. Here is an example:

 
   context.beginPath();
   context.rect(x-7, y-7, 12 + metrics.width+2, 14);
   if(context.drawFocusIfNeeded) // for older browsers
     context.drawFocusIfNeeded(element);
Check out this Pen!

To try it out, click on one of the checkboxes and notice the focus ring. You can also move the ring by using the Tab key.

To enable this feature in Firefox, turn on “canvas.focusring.enabled” in about:config. This API is also about to land in Chrome as an experimental feature.

Summary

As you can tell, there are a lot of small improvements being made to Canvas 2D. We are also looking into support for hit regions that help you route mouse events and provide accessibility features.

These features are brand new so it’s likely you will find bugs. If so, please tell us about them so we can address them before they ship. Let us know what you think!

5/4/2013 Update 1
- Firefox enabled Path2D by default so no runtime flags are needed
- Mathias Bynens pointed out that the demos are working in Opera Developer as well.

CSS Shapes Level 1 is ready for your feedback!

CSS Shapes Level 1 describes how content can be wrapped around geometric shapes. As of last week, the specification is a candidate recommendation. Also, both Blink and WebKit now have the latest syntax that matches this latest spec. This means the spec draft is stable enough for you to try out the features in your designs and to provide feedback.

To help you get started, here are some resources:

So, try it out and do provide feedback!