[DevoxxFR2013] Animate Your HTML5 Pages: A Comprehensive Tour of Animation Techniques in HTML5
Lecturer
Martin Gorner is passionate about science, technology, coding, and algorithms. He graduated from Mines Paris Tech and spent early years in ST Microelectronics’ computer architecture group. For 11 years, he shaped the eBook market via Mobipocket, which became Amazon Kindle’s software core. Joining Google Developer Relations in 2011, he focuses on entrepreneurship outreach.
Abstract
Martin Gorner’s lecture surveys HTML5’s four animation technologies: CSS3 and SVG for declarative approaches, Canvas and WebGL for programmatic ones. Through live demonstrations and explanations, he elucidates their strengths, limitations, and applications, emphasizing fluidity for user interfaces akin to mobile apps. The presentation, itself HTML5-based, covers transitions, transformations, and shaders, offering practical insights for enhancing web experiences.
Declarative Animations with CSS3: Simplicity and Power
Gorner introduces CSS3 as straightforward: the ‘transition’ property interpolates between states when a CSS value changes. A JavaScript snippet swaps classes (‘begin’ to ‘end’), shifting position and rotation; specifying ‘transition: 1s’ yields smooth 60fps animation.
For continuous loops, ‘animation’ references a ‘@keyframes’ block defining CSS at percentages (0%, 10%, etc.). Over 3 seconds, it interpolates, applying left shifts, scales, and rotations.
Animatable properties include border thickness, opacity (for fades), and geometric transformations via ‘transform’: rotate, scale, skew (distorting axes). Default easing provides appealing velocity profiles; ‘ease-in-out’ accelerates/decelerates naturally.
Prefixes (e.g., -webkit-) are needed for non-standardized specs; tools like prefixfree.js or SASS automate this. CSS3 suits simple, event-triggered or looping effects but lacks complex paths or programmatic control.
Enhancing Vector Graphics: SVG’s Declarative Animation Capabilities
SVG, for vector drawings, supports declarative animations via tags. Paths define curves; animations alter attributes like ‘d’ for shapes or ‘transform’ for motion.
Keyframes in SVG mirror CSS but embed in elements. Motion follows paths with , rotating optionally. Colors animate via ; groups allow collective effects.
SMIL timing enables sequencing: ‘begin’ offsets, ‘dur’ durations, ‘repeatCount’ loops. Events trigger via ‘begin=”element.click”‘. Interactivity shines: JavaScript manipulates attributes for dynamic changes.
SVG excels in scalable graphics with paths, gradients, and masks but remains declarative, limiting real-time computations. Browser support is strong, though IE lags.
<svg width="400" height="200">
<circle cx="50" cy="50" r="40" fill="red">
<animate attributeName="cx" from="50" to="350" dur="2s" repeatCount="indefinite"/>
</circle>
</svg>
This code animates a circle horizontally, illustrating SVG’s embeddability in HTML5.
Programmatic 2D Animations: Canvas for Frame-by-Frame Control
Canvas offers a bitmap context for JavaScript drawing. ‘requestAnimationFrame’ schedules redraws at 60fps, clearing and repainting each frame.
Basic shapes (rectangles, paths) fill or stroke; images draw via ‘drawImage’. For physics, libraries like Box2D simulate collisions, as in a bouncing ball demo.
Compositing modes (e.g., ‘source-over’) layer effects; shadows add depth. Text renders with fonts; patterns tile images.
Canvas suits games or simulations needing calculations per frame, like particle systems. However, it’s bitmap-based, losing scalability, and requires redrawing everything each frame, taxing performance for complex scenes.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(x, y, 50, 50); // Draw moving rectangle
x += 1; // Update position
requestAnimationFrame(animate);
}
animate();
This snippet moves a rectangle, demonstrating frame updates.
Diving into 3D: WebGL’s Programmatic Power with Shaders
WebGL, on Canvas’s ‘webgl’ context, leverages GPU via OpenGL ES. Setup involves shaders: vertex (positioning) and fragment (coloring) in GLSL.
A simple triangle requires vertex buffers, shader compilation, and drawing with ‘drawArrays’. Matrices handle transformations; perspective projection creates 3D illusions.
Textures map images; lighting (Lambert, Phong) computes via normals. Techniques like normal mapping simulate bumps; environment mapping fakes reflections using cube maps.
Libraries like three.js abstract complexities: ‘new THREE.Mesh’ creates objects with materials. Demos show textured, illuminated models without writing shaders.
WebGL enables high-performance 3D, ideal for visualizations or games, but demands graphics knowledge. Browser support grows, though mobile varies.
const gl = canvas.getContext('webgl');
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, `
attribute vec4 position;
void main() {
gl_Position = position;
}
`);
gl.compileShader(vertexShader);
// Similar for fragment shader, then link program
This initializes a vertex shader, foundational for WebGL.
Choosing the Right Tool: Contexts and Implications for Web Development
Gorner compares: CSS3 for simple declarative effects; SVG for vector precision and interactivity; Canvas for 2D programmatic needs; WebGL for immersive 3D.
Mobile apps set expectations for fluid UIs; HTML5 meets this sans plugins. Prefixes persist but tools mitigate. Performance favors GPU-accelerated methods.
Workshops on AppSpot cover CSS3, Canvas with Box2D, and WebGL, enabling hands-on learning.
In summary, HTML5’s animations enhance intuitiveness, with choices suiting project scales and requirements.