Successfully reported this slideshow.

Fabric.js — Building a Canvas Library

16

Share

Upcoming SlideShare
Fabricjs ppt
Fabricjs ppt
Loading in …3
×
1 of 42
1 of 42

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

Fabric.js — Building a Canvas Library

  1. 1. Fabric.js Bulding a canvas library @kangax ✎ BK.js ✎ 2011
  2. 2. Who am I? @kangax perfectionkills.com kangax.github.com/es5-compat-table/
  3. 3. fabric.js Fabric.js is a framework that makes it easy to work with HTML5 canvas element. It is an interactive object model on top of canvas element. It is also an SVG-to-canvas parser.
  4. 4. t ian Canvas? -co m pl WHATWG says: “The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.” http://www.whatwg.org/specs/web-apps/current-work/ multipage/the-canvas-element.html#the-canvas-element
  5. 5. Canvas Charts Games Editors Physics simulation
  6. 6. How canvas works document.getElementById(‘canvas’).getContext(‘2d’) CanvasRenderingContext2D • clearRect() • arc() • fillRect() • drawImage() • createImageData() • arcTo() • strokeRect() • bezierCurveTo() • putImageData() • getImageData() • clip() • closePath() • restore() • fill() • save() • strokeText() • lineTo() • fillText() • moveTo() • rotate() • measureText() • quadraticCurveTo() • scale() • rect() • transform() • stroke() • translate() • strokeStyle= • fillStyle=
  7. 7. But why get rid of an elegant canvas API for some questionable blob of Javascript code?
  8. 8. fabric vs. native native var canvasEl = document.getElementById('canvas'); var ctx = canvasEl.getContext('2d'); ctx.strokeStyle = ''; ctx.fillStyle = 'red'; ctx.fillRect(100, 100, 20, 20); fabric var canvas = new fabric.Element('canvas'); var rect = new fabric.Rect({ top: 100, left: 100, fill: 'red', width: 20, height: 20 }); canvas.add(rect);
  9. 9. fabric vs. native native var canvasEl = document.getElementById('canvas'); var ctx = canvasEl.getContext('2d'); ctx.strokeStyle = ''; ctx.fillStyle = 'red'; because we all love radians ctx.save(); ctx.translate(100, 100); ctx.rotate(Math.PI / 180 * 45); ctx.fillRect(-10, -10, 20, 20); ctx.restore(); fabric var canvas = new fabric.Element('canvas'); var rect = new fabric.Rect({ top: 100, left: 100, fill: 'red', width: 20, height: 20, angle: 45 }); canvas.add(rect);
  10. 10. fabric vs. native native ctx.fillRect(20, 50, 20, 20); fabric rect.set(‘left’, 20).set(‘top’, 50); canvas.renderAll();
  11. 11. fabric vs. native native ctx.fillRect(20, 50, 20, 20); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillRect(20, 50, 20, 20); fabric rect.set(‘left’, 20).set(‘top’, 50); canvas.renderAll();
  12. 12. But wait, there’s more! Object manipulations with mouse http://kangax.github.com/fabric.js/test/demo/
  13. 13. Goals • Unit tested (1000+ tests at the moment) • Modular (~20 small "classes") • Cross-browser (degrades gracefully) • Fast • Encapsulated in one object • No browser sniffing • ES5 strict mode -ready
  14. 14. Supported browsers • Firefox 2+ • Safari 3+ • Opera 9.64+ • Chrome (all versions should work) • IE9 (IE7/8 via excanvas)
  15. 15. How fabric works “Hello world” example var canvas = new fabric.Element('canvas'); var text = new fabric.Text('hello world', { fontfamily: 'delicious_500' }); canvas.add(text);
  16. 16. How fabric works “Hello world” example var canvas = new fabric.Element('canvas'); var text = new fabric.Text('hello world', { fontfamily: 'delicious_500' }); canvas.add(text); text.setText('trololololo') .set('left', 100) .set('top', 100) .set('fontfamily', 'comic_sans');
  17. 17. How fabric works “Hello world” example var canvas = new fabric.Element('canvas'); var text = new fabric.Text('hello world', { fontfamily: 'delicious_500' }); canvas.add(text); text.setText('trololololo') .set('left', 100) .set('top', 100) .set('fontfamily', 'comic_sans'); canvas.remove(text);
  18. 18. How fabric works “Class” hierarchy fabric.Object fabric.util.* fabric.Element fabric.Line fabric.Circle fabric.Triangle fabric.parseAttributes fabric.Ellipse fabric.parseElements fabric.Rect fabric.parseStyleAttribute fabric.Polyline fabric.parsePointsAttribute fabric.Polygon fabric.Group fabric.Text fabric.Image fabric.Color fabric.Path fabric.PathGroup fabric.Point fabric.Intersection
  19. 19. How fabric works “Class” hierarchy fabric.Object clone cloneAsImage complexity get fabric.Line getCenter fabric.Circle getWidth fabric.Triangle getHeight intersectsWithObject fabric.Ellipse isActive fabric.Rect isType fabric.Polyline scale scaleToHeight fabric.Polygon scaleToWidth fabric.Group set fabric.Text setActive straighten fabric.Image toDataURL fabric.Path toJSON ...
  20. 20. How fabric works “Class” hierarchy clone fabric.Object cloneAsImage complexity get getCenter fabric.Line getRadiusX fabric.Circle getRadiusY fabric.Triangle getWidth getHeight fabric.Ellipse intersectsWithObject fabric.Rect isActive fabric.Polyline isType scale fabric.Polygon scaleToHeight fabric.Group scaleToWidth fabric.Text set setActive fabric.Image straighten fabric.Path toDataURL toJSON ...
  21. 21. How fabric works “Class” hierarchy clone fabric.Object cloneAsImage complexity get getCenter fabric.Line getWidth getElement fabric.Circle getHeight fabric.Triangle intersectsWithObject fabric.Ellipse isActive isType fabric.Rect scale fabric.Polyline scaleToHeight fabric.Polygon scaleToWidth set fabric.Group setActive fabric.Text setElement fabric.Image straighten toDataURL fabric.Path toJSON toGrayscale ...
  22. 22. How fabric works fabric.Element add bringForward fabric.Element bringToFront centerObjectH centerObjectV clear clone Main drawing area complexity containsPoint deactivateAll - Wraps <canvas> element getActiveObject - Renders fabric.* objects added to it getCenter - Provides mouse-based selection getHeight getWidth - Dispatches events getObjects insertAt isEmpty item loadFromJSON loadSVGFromURL remove renderAll ...
  23. 23. How fabric works fabric.Element render() fabric.Rect.prototype.render render() fabric.Path.prototype.render render() render() fabric.Image.prototype.render fabric.Circle.prototype.render
  24. 24. How fabric works Drawing a frame 1. clear entire canvas 2. for each object in canvas 2a. object.render() render() render() fabric.Rect.prototype.render fabric.Path.prototype.render render() render() fabric.Image.prototype.render fabric.Circle.prototype.render
  25. 25. How fabric works Prototypal inheritance function createClass() { var parent = null, based on properties = slice.call(arguments, 0); Prototype.js if (typeof properties[0] === 'function') { parent = properties.shift(); } function klass() { this.initialize.apply(this, arguments); } klass.superclass = parent; klass.subclasses = [ ]; if (parent) { subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } for (var i = 0, length = properties.length; i < length; i++) { addMethods(klass, properties[i]); } if (!klass.prototype.initialize) { klass.prototype.initialize = emptyFunction; } klass.prototype.constructor = klass; return klass; }
  26. 26. How fabric works Prototypal inheritance fabric.Path = fabric.util.createClass( fabric.Object, { type: 'path', initialize: function(path, options) { options = options || { }; ... }, render: function() { ... }, toString: function() { return '#<fabric.Path (' + this.complexity() + '): ' + JSON.stringify({ top: this.top, left: this.left }) + '>'; } });
  27. 27. How fabric works SVG parser
  28. 28. How fabric works SVG parser <path d="M-122.304 84.285C-122.304 { 84.285 -122.203 86.179 -123.027 path: [ 86.16C-123.851 86.141 -140.305 [ "M", -122.304, 84.285 ], 38.066 -160.833 40.309C-160.833 [ "C", -122.304, 84.285, 40.309 -143.05 32.956 -122.304 -122.203, 86.179, 84.285z" /> -123.027, 86.16 ], [ "C", -123.851, ... ], [ ... ], ... ] }
  29. 29. How fabric works SVG parser { path: [ [ "M", -122.304, 84.285 ], [ "C", -122.304, 84.285, Instance of fabric.Path -122.203, 86.179, [[Prototype]] == fabric.Path.prototype -123.027, 86.16 ], [ "C", -123.851, ... ], [ ... ], ... ] }
  30. 30. How fabric works SVG parser fabric.Path.prototype.render (line 173) case 'C': // bezierCurveTo, absolute x = current[5]; { y = current[6]; path: [ controlX = current[3]; [ "M", -122.304, 84.285 ], controlY = current[4]; [ "C", -122.304, 84.285, ctx.bezierCurveTo( -122.203, 86.179, current[1] + l, current[2] + t, -123.027, 86.16 ], controlX + l, [ "C", -123.851, ... ], controlY + t, [ ... ], x + l, ... y + t ] ); } break;
  31. 31. How fabric works SVG parser Static fromElement method on all constructors fabric.Line.fromElement = function(element, options) { var parsedAttributes = fabric.parseAttributes(element, fabric.Line.ATTRIBUTE_NAMES); var points = [ parsedAttributes.x1 || 0, parsedAttributes.y1 || 0, parsedAttributes.x2 || 0, parsedAttributes.y2 || 0 ]; return new fabric.Line(points, extend(parsedAttributes, options)); };
  32. 32. How fabric works SVG parser Static fromElement method on all constructors fabric.Path.fromElement = function(element, options) { var parsedAttributes = fabric.parseAttributes(element, fabric.Path.ATTRIBUTE_NAMES); return new fabric.Path(parsedAttributes.d, extend(parsedAttributes, options)); }; Ditto for fabric.Rect, fabric.Circle, etc.
  33. 33. http://www.w3.org/TR/SVG/ paths.html#PathDataBNF Fun with SVG parsing
  34. 34. continued...
  35. 35. are we there yet?
  36. 36. Fun with SVG parsing
  37. 37. Docs http://kangax.github.com/fabric.js/docs
  38. 38. Unit tests http://kangax.github.com/fabric.js/test/unit/suite_runner
  39. 39. Benchmarks http://kangax.github.com/fabric.js/test/ raphael_vs_fabric/simple_shapes http://kangax.github.com/fabric.js/test/ raphael_vs_fabric/complex_shape
  40. 40. Future plans: • Smaller footprint (delete Cufon) • Custom builder • Better docs • More complete SVG parsing • toSVG() • Pretty website, logo (help!!111) • Better IE support
  41. 41. These slides online: http://slideshare.net/kangax
  42. 42. Thank you! Questions? http://spkr8.com/t/7303 github.com/kangax/fabric.js @FabricJS Follow me @kangax

Editor's Notes

  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Fabric provides state. Object oriented approach. Different paradigm.\n
  • Demo time.\n
  • \n
  • More complete IE support to come in the future\n
  • \n
  • Note the chaining.\n
  • Note the chaining.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Exclude images, parser, text.\nMore tutorials.\nSupport gradients.\n
  • \n
  • \n
  • ×