Graphics in HTML5




These slides were largely inspired by "SVG for JavaScript developers" and "How to use SVG, Canvas, and WebGL without a Time Machine".

What are graphics?

Raster graphics:
Each pixel is separately defined.

Vector graphics:
Mathematical formulas describe lines and shapes.

What are graphics?

Static
Moving
Interactive

Graphics in HTML


Raster Vector Motion Interactive 2D 3D
Images (GIF, BMP, PNG, JPG)
DOM + JS (Example)
Plugins (Flash, Java, X3D, SVG, VRML)
Browser-specific technologies (IE's VML)

The problems with plugins


  • Require user to do more work
  • Can have sub-par performance
  • Not integrated with rest of website
  • Open up security holes
  • Don't work everywhere

Graphics in HTML5


Raster Vector Motion Interactive 2D 3D
SVG
Canvas
WebGL
CSS3

SVG (Scalable Vector Graphics)

An XML-based vector image format for two-dimensional graphics that has support for interactivity and animation.


SVG: Features

  • Shapes
  • Paths
  • Text/Fonts
  • Fill/Stroke/Colors
  • Gradients/Patterns
  • Clipping/Masking
  • Filters
  • DOM Events
  • Scripting
  • Animation

SVG: Shapes

<circle cx="100" cy="50" r="25" fill="black" />
<rect x="0" y="10" width="100" height="75" fill="red" />
<ellipse cx="90" cy="50" rx="50" ry="45" fill="orange" />
<polygon points="10,5 100,45 100,5 100,100" fill="blue" />

SVG: Text, Transforms, Scripting


SVG: Theme Park Demo

theme park

SVG: Ways of Using

  • Embedded file
  • Inline
  • Scripted
  • Backgrounds in CSS

SVG: Embedded File

caniuse.com: SVG basic

SVG: Inline

caniuse.com: SVG inline

SVG: Scripted (Blobular Demo)

SVG: CSS Background


caniuse.com: SVG in CSS

Ways to embed a clickable SVG logo

SVG: Tools & Libraries

  • SVGweb: cross-browser SVG polyfill
  • RaphaëlJS: cross-browser vector graphics JS library
  • gRaphael: SVG-based charting library
  • WijMo: UI widgets and charts
Animated Chart Demo

Canvas

An HTML tag that creates a blank canvas for JavaScript to draw onto.

Canvas: Space Noodles Demo

Canvas

  • Define an element on HTML
    <canvas id="myDrawing" width="500" height="500"></canvas>
  • Get it with JavaScript
    var canvas = document.getElementById("myDrawing");

Context

  • All the draw methods are executed here
    var context = canvas.getContext("2d");

Basic Shapes

  • Draws a rectangle using the current fill style
    fillRect(x, y, width, height);
  • Draws the outline of a rectangle using the current stroke style
    strokeRect(x, y, width, height);
  • Clears all pixels within the given rectangle
    clearRect(x, y, width, height);

Lines and Paths

  • Creates a new subpath at the given point
    moveTo(x, y);
  • Draws a straight line from the previous point
    lineTo(x, y);
  • Adds a new closed rectangular subpath
    rect(x, y, width, height);
  • Adds a subpath along the circumference of the described circle, with the angles defined
    arc(x, y, radius, startAngle, endAngle, counterclockwise);

Lines and Paths

  • Resets the current path
    beginPath();
  • Closes the current subpath and starts a new one
    closePath();
  • Fiils the subpaths with the current fill style
    fill();
  • Outlines the subpaths with the current stroke style
    stroke();

Rectangular Smiley

Circle Smiley

DeviantArt Demo

Animation

  • Animation is nothing more than redrawing the screen at a rate that the human eye doesn't notice
  • The old way:
    var FPS = 60;
    setInterval(function() { 
      redrawCanvas(); // your function here
    }, 1000 / FPS);
  • This new API tells the browser exactly when the next frame is drawn.
  • window.requestAnimationFrame(function() {
      redrawCanvas(); // your function here
    });

Canvas: Snake Demo

Canvas: Wormz Demo

drawImage

See MDN: Using Images

MontageMaker Demo

Canvas: Libraries & Tools

caniuse.com: Canvas

WebGL

  • 3D in the browser and without plugins
  • GPU Processing, directly on the video card
  • It uses the <canvas> tag but with another context
<canvas id="myDrawing" width="500" height="500">
var canvas = document.getElementById("myDrawing"); 
context = canvas.getContext("experimental-webgl");

But most people use the ThreeJS library...

ThreeJS: Renderers

Create a WebGLRenderer

var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(document.body.clientWidth, 
        document.body.clientHeight);

Put it on the DOM

document.body.appendChild(renderer.domElement);

Set some color

renderer.setClearColorHex(0xFFFFFF, 1.0);
renderer.clear();
Demo

ThreeJS: Cameras

Create a Camera

var camera = new THREE.PerspectiveCamera(45, width/height, 1, 10000);
camera.position.z = 300;

Make a Scene with a Cube

var scene = new THREE.Scene();
var cube =  new THREE.Mesh(new THREE.CubeGeometry(50,50,50),
       new THREE.MeshBasicMaterial({color: 0x1fd230}));
scene.add(cube);

And render the Scene from the Camera

renderer.render(scene, camera);
Demo

ThreeJS: Animation

function animate(t) {
  // spin the camera in a circle
  camera.position.x = Math.sin(t/1000)*300;
  camera.position.y = 150;
  camera.position.z = Math.cos(t/1000)*300;
  // you need to update lookAt every frame
  camera.lookAt(scene.position);
  // renderer automatically clears unless autoClear = false
  renderer.render(scene, camera);
  window.requestAnimationFrame(animate, renderer.domElement);
};

animate(new Date().getTime());
      
Demo

ThreeJS: Demos

WebGL: Libraries & Tools

  • Three.JS: JS abstraction library for 3d in the browser
  • JSArToolkit: Augmented reality in JS
  • JebGL: Java fallback for WebGL
  • CWebGL: Canvas fallback for WebGL
  • VoxelJS: Toolkit for Voxel based games like Minecraft.

CSS 3D Transforms

CSS lets you specify keyframes, animations, and transitions for styles.

#tardis {
  animation-name: disappear;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-iteration-count: 1;
  animation-delay: 2s;
}

@keyframes disappear {
  from { opacity: 1; }
  to { opacity: 0; }
}

Spinning tardis demo

caniuse.com: CSS 3d transforms

Graphics in HTML5


Raster Vector Motion Interactive 2D 3D
SVG
Canvas
WebGL
CSS3

When to use which? Depends on performance, features, interactivity, and target browsers.