JavaScript & Graphical Output

(Canvas / PDF / + More)

Presented by LB Corney / @lb_corney

Graphics, Why?

  • Graphic presentation is intuitive to the user.
  • In the form of graphs and charts, they provide a means for analyzing a wide variety of numerical facts via points, lines, areas or other shapes and symbols.
  • In the form of pictures, they can tell a story, engage the user on an emotional level.
  • Graphic presentation can simplify complicated concepts, and contribute to a more balanced understanding of a problem.
  • Dynamic effects.. Animation, modeling, games.

Graphic Tools in Browser with HTML5

  • Document Object Model (DOM)
  • Scalable Vector Graphics (SVG)
  • Canvas ( <canvas/> )
  • <video/> (and <audio/> )
  • WebGL and OpenGL low-level 3D graphics APIs

Document Object Model

You can do a lot of 2D graphics 'tricks' here, using Cascasding Style Sheets (CSS). You can do animations, and paint style creations. You can move <div> s around the DOM to place things where you want them to go.

Document Object Model


DOM Continued...

#rectangleBox { width: 300px; height: 200px; background-color: #0000ff; color: white; position: relative; }
#circle { width: 160px; height: 160px; background: green; -moz-border-radius: 80px; -webkit-border-radius: 80px; border-radius: 80px; position:
absolute; left: 70px; top: 20px; }
#textBox { position: absolute; left: 50px; top: 50px; font-size: 30px; }
#line { border-bottom: 5px solid red; -webkit-transform: translateY(130px) translateX(5px) rotate(-26deg); width: 275px; }
#line2 { border-bottom:	5px solid red; -webkit-transform: translateY(100px) translateX(5px) rotate(-26deg); width: 275px; }

Scalable Vector Graphics (SVG)

SVG is concerned with the shapes of things.

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation.





Canvas elements are concerned with pixels.

The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low level, procedural model that updates a bitmap.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = " #0000ff";  // was red
ctx.fillRect(0, 0, 300, 200);
ctx.fillStyle = "#00FF00";
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 80;

Canvas Continued...

ctx.lineWidth = 5;
ctx.strokeStyle = "red";
ctx.moveTo(25, 155);
ctx.lineTo(275, 30);

ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "green"; // "#00FF00";

Compare 2D graphic concepts (DOM / SVG / Canvas)

You can build graphs, animations, games, and image composition with all three techniques (kinda, sorta).

Comparison of all three techniques

DOM and SVG output is very similiar in functioning... (SVG for serious work) For next portion of discussion, I'm going to be comparing SVG to Canvas.

Compare 2D - Factor: JavaScript

SVG elements can be displayed on a static site, without JavaScript.

For Canvas, all elements must be modeled via JavaScript. If JavaScript is turned off in the users browser, then the canvas element fails.

Compare 2D - Factor: Static Display / Ease of Use

For simple elements, like static displays, SVG (with its xml style) is pretty easy to use. In use, its similiar to CSS.

Canvas displays must be programmed via JavaScript, and it requires more coding.

Compare 2D - Factor: Text

For graphical output with lots of shape controls (like text) SVG will outperform canvas every time. Items scale very well. Although canvas does support custom .ttf fonts, they may not scale or animate well on all devices.

Compare 2D - Factor: Dynamic Animation

You can move, scale, change elements dynamically in SVG. You can also control Z-index, dynamically.

In Canvas, you can there's no way to alter existing drawings. If you want to update the Canvas image, you have to erase it, and then redraw it. Have a nice day.

Compare 2D - Factor: Speed

On larger displays / higher resolution displays, canvas tends to slow as you have a lot more pixels to populate on refresh.

With SVG and CSS/DOM entries, the more objects you have in the DOM, the more performance degrades.

Canvas Benchmark

SVG D3 Stress Test

Compare 2D - Factor: Event Handlers

SVG images are defined in XML. As a result, every SVG element is appended to the DOM and can be manipulated using a combination of JavaScript and CSS. Moreover, you can attach an event handlers directly to a SVG element or update its properties based on another document event.

Canvas, on the other hand, is a simple graphics API. It draws pixels very well and nothing more. There are ways to 'fake' event handlers via mouse positions, but that takes more work.

Compare 2D - Factor: Libraries / Other Support API's

SVG: Ton of stuff here, including graphing tools like D3.js (which uses SVG and CSS for its output). There are also many tools (e.g. Raphaël ) which bring vector art to SVG.

Canvas: Tools like Fabric.js (provides interactive object model on top of canvas element.) KineticJS (enabling canvas interactivity for desktop and mobile applications.) jsPDF (creating graphic output in scale on physical paper).

Compare 2D - Factor: Decision Time!

  • What am I trying to achieve?
  • Available tutorials?
  • Key libraries and support tools?

Why am I talking on this topic?

Mechanism Design

Remember our "Why Graphics?" slide? Here's a graphic presentation that is intuitive to the user.

Human Powered Mechanical Walker Project

Creating this site is what got me interested in all things canvas .

Canvas Code Examples

Drop a dot / drag it...

This is a tester for mouse events within canvas.

Canvas Code Example

Theory of CAD, Curved Lines

Graphic presentation can simplify complicated concepts, and contribute to a more balanced understanding of a problem.

Canvas Code Example, Tube Notcher

TubeNotcher Pattern Creation Tool

This web page creates custom paper templates to aid folks in manufacturing awesome things without a lot of investment costs. (Makers Faire or generic fabrication folks? Custom Motorcycle / Bicycle Frames? Vehicle customizers?) Tools I'm using: canvas, jsPDF, HTML2canvas, and Descriptive Geometry.

Lessons Learned, Tidbits of JS

  • User Interface for complicated single page? Best way to manage things? (This UI stuff is hard!)
    Ans: jQuery Tabs for navigation.
  • Best way to display four graphic elements on same page? iframes vs multiple canvas?
    Ans: For this one, iframes worked great!

More Lessons Learned...

  • Array (& object) type variables are passed to the function by reference.
  • Primitive type variables (like a string or a number) are passed to the function by value.
  • Too many global variables in not a good thing.

More Lessons Learned...

How to call a function from an array? Ans:
var btn = [			// array of button objects.
{x: 70, y: 300, display: "Display", action: functionDisplay },
{x: 310, y: 300, display: "Reset", action: functionReset }

// After a canvas mouse click occurs, check all buttons
for (var i = 0; i < btn.length; i++) {
  if (... test x, y locations... was mouse over this button?... ) {
    console.log("Button #" + (i + 1) + " has been clicked!!");
    btn[i].action(); // execute button function

function functionDisplay() {...}
function functionReset() {...}

More Lessons Learned..

  • How to send a parameter to an iframe? Ans:
    // and later within the JS code...
    var result =
  • How to format numbers in JavaScript? Ans:
  • On the Tubenotcher project there is a whole lot of code. How can I organize things better? Ans: JavaScript design patterns.


  • Sometimes its okay to use an older API.
  • Descriptive Geometry = the representation of three-dimensional objects in two dimensions, important for engineering, architecture, design and art.
  • Reference: Albrecht Dürer, Underweysung der Messung Mit dem Zirckel..., Nuremberg, 1525 A.D.

More Lessons Learned..

Canvas width, height huh? CSS or attribute? What's an attribute really?

// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width  = 400;
canvas.height = 300;  = '800px'; = '600px';

More Lessons Learned...

  • Overlapping div's over canvas elements was difficult. jQuery Dialog Boxes were MUCH EASIER.
  • There are a whole lot of similiarities porting java code over to JS.
  • Discretization vs parameterization (Aren't StackOverflow arguments fun?)
Whenever you see a function within another function, the inner function has access to the scope in the outer function. This is called Lexical Scope or Closure - also referred to as Static Scope. The easiest way to demonstrate that:

// Scope A var
myFunction = function () {
  // Scope B
  var name = 'Todd';
  // defined in Scope B
  var myOtherFunction = function () {
	// Scope C: `name` is accessible here!
This issue came up with the question "Where do I place click handlers?" Should they be located within the HTML? Ans: Anywhere will work, but the scope needs to match, and html JS is global.
  • How to set a default value for a parameter to a js function
  • The Math.sign() function returns the sign of a number, indicating whether the number is positive, negative or zero. Use with sine wave to generate a square wave.
  • CloudFlare and JS minify (er, no, not really) CloudFlare removes comments and whitespace, doesn't change variable names, doesn't work if jslint has errors (use strict)


Is this code perfect? Certainly not, but, remember,

if every pork chop was perfect, we wouldn't have hot dogs.

Reveal.JS presenter tool & documentation