October 1, 2008 Visual Programming with Javascript (John Resig)
The Canvas element
- 2d drawing layer, in which you can draw using javascript
- embedded in web pages, looks & behaves like an img
- Mozilla proposing adding a full OpenGL API for 3d rendering (*!!!)
- can draw paths, certain built-in shapes, etc.
- drawing is NOT vector, it’s pure raster; like programming in Microsoft Paint using OpenGL
- much faster than SVG
- can be used for drawing dynamic charts
- in jQuery, flot charting library uses it
- can style on fill and stroke, supports color with opacity
- can load an image into a canvas element and then draw other stuff on top of it
- scale, translate, rotate work like in Processing; operation acts on the entire canvas as a whole
- like Processing, rotation is around 0,0 unless stacked with translate
Browser Support for Canvas
- browser support: native in Firefox, Safari, Opera
- library called exCanvas, by Google, brings canvas support into IE
- exCanvas recreates everything canvas using VML; Resig sez: “actually pretty fast”
- with exCanvas, the canvas element actually has better browser support than SVG
Animation with Canvas
- have to do it all from scratch
- use a javascript interval, change properties like position
- remember: once you draw something to a canvas, it’s there; no access to remove old objects
- have to draw over something to clear it from view
- trick: can draw over with partial opacity to create a motion tail
- canvas is fast enough that this is usually okay
- all mouse interaction is based on pure mouse position/pixel detection
Embedding/Extending Canvas
- can embed a canvas into another canvas
- will be able to embed video (Firefox 3.1)
- can embed a webpage in Firefox (using a Firefox extension)
- can extract data from canvas, convert to another format (didn’t say much about how)
- smaller canvases are better
- text/fonts is part of the spec, browsers are starting to adapt, text is in FF3 now
Processing.js
(* Processing is awesome btw, and this is very exciting!)
- Resig ported processing to javascript using the canvas element
- resulting awesomeness
- 2 stages of implementation: language conversion (Processing to js) and implementation of the Processing API
- converts Processing to javascript at load time
- can embed Processing code in script type=”application/processing” (browser will ignore if they don’t recognize the type), and pass to processing object
- or, can get the processing object on a canvas and then use that in more of a javascript API-like fashion, calling on individual Processing methods throughout your javascript code