Tuesday, July 28th, 2009
Weston Ruter has created a very cool library that enables CSS gradients on non-WebKit browsers (at least, a subset). Incredibly cool:
CSS Gradients via Canvas provides a subset of WebKit’s CSS Gradients proposal for browsers that implement the HTML5
To use, just include css-gradients-via-canvas.js (12KB) anywhere on the page (see examples below). Unlike WebKit, this implementation does not currently allow gradients to be used for border images, list bullets, or generated content. The script employs
document.querySelectorAll()—it has no external dependencies if this function is implemented; otherwise, it looks for the presence of jQuery, Prototype, or Sizzle to provide selector-querying functionality.
The implementation works in Firefox 2/3+ and Opera 9.64 (at least). Safari and Chrome have native support for CSS Gradients since they use WebKit, as already mentiond.
This implementation does not work in Internet Explorer since IE does not support Canvas, although IE8 does support the
data:URI scheme, which is a prerequisite (see support detection method). When/if Gears’s Canvas API fully implements the HTML5 canvas specification, then this implementation should be tweakable to work in IE8. In the mean time, rudimentary gradients may be achieved in IE by means of its non-standard gradient filter.
CSS Gradients via Canvas works by parsing all stylesheets upon page load (
DOMContentLoaded), and searches for all instances of CSS gradients being used as background images. The source code for the external stylesheets is loaded via
XMLHttpRequest—ensure that they are cached by serving them with a far-future Expires header to avoid extra HTTP traffic.
The CSS selector associated with the gradient background image property is used to query all elements on the page; for each of the selected elements, a canvas is created of the same size as the element’s dimensions, and the specified gradients are drawn onto that canvas. Thereafter, the gradient image is retrieved via
canvas.toDataURL()and this data is supplied as the
background-imagefor the element.
An aside. I only just noticed the Gears Canvas API. It doesn’t quite do what you think….. I always wanted to implement Canvas in Gears. It is also strange that Gears is so under the radar at Google these days. One blog post per year?. I guess all of the work is going into Chrome / WebKit itself.
Posted by Dion Almaer at 6:00 am