SlideShare a Scribd company logo
Fabric.js
Bulding a canvas library




       @kangax ✎ BK.js ✎ 2011
Who am I?
                 @kangax




perfectionkills.com        kangax.github.com/es5-compat-table/
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.
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
Canvas



Charts         Games




Editors   Physics simulation
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=
But why get rid of an
 elegant canvas API for
some questionable blob of
    Javascript code?
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);
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);
fabric vs. native
native

 ctx.fillRect(20, 50, 20, 20);




fabric

rect.set(‘left’, 20).set(‘top’, 50);
canvas.renderAll();
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();
But wait, there’s more!
      Object manipulations with mouse




     http://kangax.github.com/fabric.js/test/demo/
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
Supported browsers

• Firefox 2+
• Safari 3+
• Opera 9.64+
• Chrome (all versions should work)
• IE9 (IE7/8 via excanvas)
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);
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');
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);
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
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
                                 ...
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
                                 ...
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
                                 ...
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
                                           ...
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
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
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;
}
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 }) + '>';
  }
});
How fabric works
     SVG parser
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, ... ],
                                                  [ ... ],
                                                  ...
                                              ]
                                          }
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, ... ],
                                                 [ ... ],
                                                 ...
                                             ]
                                         }
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;
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));
};
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.
http://www.w3.org/TR/SVG/
 paths.html#PathDataBNF     Fun with SVG parsing
continued...
are we there yet?
Fun with SVG parsing
Docs
http://kangax.github.com/fabric.js/docs
Unit tests
http://kangax.github.com/fabric.js/test/unit/suite_runner
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
Future plans:
• Smaller footprint (delete Cufon)
• Custom builder
• Better docs
• More complete SVG parsing
• toSVG()
• Pretty website, logo (help!!111)
• Better IE support
These slides online:



http://slideshare.net/kangax
Thank you!
       Questions?
    http://spkr8.com/t/7303




github.com/kangax/fabric.js

@FabricJS




  Follow me @kangax

More Related Content

What's hot

RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)Tracy Lee
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeRamon Ribeiro Rabello
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVICS
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScriptpcnmtutorials
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedVisual Engineering
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsANKUSH CHAVAN
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
Jetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourJetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourMatthew Clarke
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 

What's hot (20)

RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Declarative UIs with Jetpack Compose
Declarative UIs with Jetpack ComposeDeclarative UIs with Jetpack Compose
Declarative UIs with Jetpack Compose
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
React-JS Component Life-cycle Methods
React-JS Component Life-cycle MethodsReact-JS Component Life-cycle Methods
React-JS Component Life-cycle Methods
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Jetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourJetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning Tour
 
IPC with Qt
IPC with QtIPC with Qt
IPC with Qt
 
React Context API
React Context APIReact Context API
React Context API
 

Viewers also liked

Open Source - Hip not Hype
Open Source - Hip not HypeOpen Source - Hip not Hype
Open Source - Hip not HypePriyank Kapadia
 
The Desirability of Connected Products
The Desirability of Connected ProductsThe Desirability of Connected Products
The Desirability of Connected ProductsJ F Grossen
 
towards a global CC license - the affiliate perspective
towards a global CC license - the affiliate perspective towards a global CC license - the affiliate perspective
towards a global CC license - the affiliate perspective Paul Keller
 
Creative Commons Enforcement
Creative Commons EnforcementCreative Commons Enforcement
Creative Commons EnforcementAndres Guadamuz
 
Open Source and Economic Development
Open Source and Economic DevelopmentOpen Source and Economic Development
Open Source and Economic DevelopmentDeborah Bryant
 
Using the CC BY license, Workshop for 2013 OPEN Kick-off
Using the CC BY license, Workshop for 2013 OPEN Kick-offUsing the CC BY license, Workshop for 2013 OPEN Kick-off
Using the CC BY license, Workshop for 2013 OPEN Kick-offJane Park
 
CCL and Database in Korea
CCL and Database in KoreaCCL and Database in Korea
CCL and Database in KoreaJay Yoon
 
Phillips Remix Cycle Pixelodeon 2007
Phillips   Remix Cycle   Pixelodeon 2007Phillips   Remix Cycle   Pixelodeon 2007
Phillips Remix Cycle Pixelodeon 2007Jon Phillips
 
The definition and future of noncommercial
The definition and future of noncommercialThe definition and future of noncommercial
The definition and future of noncommercialMike Linksvayer
 
Saudi Arabia’s National Open Education Strategy, Master Plan & Policy
Saudi Arabia’s National Open Education Strategy, Master Plan & PolicySaudi Arabia’s National Open Education Strategy, Master Plan & Policy
Saudi Arabia’s National Open Education Strategy, Master Plan & PolicyCable Green
 
Creative Commons & Cultural Heritage
Creative Commons & Cultural HeritageCreative Commons & Cultural Heritage
Creative Commons & Cultural HeritageJane Park
 
Hong Kong Startup Ecosystem ToolBox v.1
Hong Kong Startup Ecosystem ToolBox v.1Hong Kong Startup Ecosystem ToolBox v.1
Hong Kong Startup Ecosystem ToolBox v.1WHub
 
Planning of lutyens' delhi
Planning of lutyens' delhiPlanning of lutyens' delhi
Planning of lutyens' delhiVedika Agrawal
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Made With Creative Commons
Made With Creative CommonsMade With Creative Commons
Made With Creative CommonsPaul_Stacey
 
Creative Commons Certificates
Creative Commons CertificatesCreative Commons Certificates
Creative Commons CertificatesPaul_Stacey
 

Viewers also liked (20)

Open Source - Hip not Hype
Open Source - Hip not HypeOpen Source - Hip not Hype
Open Source - Hip not Hype
 
The Use of Creative Commons Licences in the Ministry of Justice of the Govern...
The Use of Creative Commons Licences in the Ministry of Justice of the Govern...The Use of Creative Commons Licences in the Ministry of Justice of the Govern...
The Use of Creative Commons Licences in the Ministry of Justice of the Govern...
 
The Desirability of Connected Products
The Desirability of Connected ProductsThe Desirability of Connected Products
The Desirability of Connected Products
 
Guide open source-bdef
Guide open source-bdefGuide open source-bdef
Guide open source-bdef
 
towards a global CC license - the affiliate perspective
towards a global CC license - the affiliate perspective towards a global CC license - the affiliate perspective
towards a global CC license - the affiliate perspective
 
Creative Commons Enforcement
Creative Commons EnforcementCreative Commons Enforcement
Creative Commons Enforcement
 
Open Source and Economic Development
Open Source and Economic DevelopmentOpen Source and Economic Development
Open Source and Economic Development
 
Using the CC BY license, Workshop for 2013 OPEN Kick-off
Using the CC BY license, Workshop for 2013 OPEN Kick-offUsing the CC BY license, Workshop for 2013 OPEN Kick-off
Using the CC BY license, Workshop for 2013 OPEN Kick-off
 
CCL and Database in Korea
CCL and Database in KoreaCCL and Database in Korea
CCL and Database in Korea
 
Phillips Remix Cycle Pixelodeon 2007
Phillips   Remix Cycle   Pixelodeon 2007Phillips   Remix Cycle   Pixelodeon 2007
Phillips Remix Cycle Pixelodeon 2007
 
The definition and future of noncommercial
The definition and future of noncommercialThe definition and future of noncommercial
The definition and future of noncommercial
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Open Credential and Radical Openness
 Open Credential  and Radical Openness Open Credential  and Radical Openness
Open Credential and Radical Openness
 
Saudi Arabia’s National Open Education Strategy, Master Plan & Policy
Saudi Arabia’s National Open Education Strategy, Master Plan & PolicySaudi Arabia’s National Open Education Strategy, Master Plan & Policy
Saudi Arabia’s National Open Education Strategy, Master Plan & Policy
 
Creative Commons & Cultural Heritage
Creative Commons & Cultural HeritageCreative Commons & Cultural Heritage
Creative Commons & Cultural Heritage
 
Hong Kong Startup Ecosystem ToolBox v.1
Hong Kong Startup Ecosystem ToolBox v.1Hong Kong Startup Ecosystem ToolBox v.1
Hong Kong Startup Ecosystem ToolBox v.1
 
Planning of lutyens' delhi
Planning of lutyens' delhiPlanning of lutyens' delhi
Planning of lutyens' delhi
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Made With Creative Commons
Made With Creative CommonsMade With Creative Commons
Made With Creative Commons
 
Creative Commons Certificates
Creative Commons CertificatesCreative Commons Certificates
Creative Commons Certificates
 

Similar to Fabric.js — Building a Canvas Library

Building Windows 8 Metro Style casual games using HTML5 and JavaScript
Building Windows 8 Metro Style casual games using HTML5 and JavaScriptBuilding Windows 8 Metro Style casual games using HTML5 and JavaScript
Building Windows 8 Metro Style casual games using HTML5 and JavaScriptDavid Isbitski
 
Html5 Canvas Drawing and Animation
Html5 Canvas Drawing and AnimationHtml5 Canvas Drawing and Animation
Html5 Canvas Drawing and AnimationMindfire Solutions
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebRobin Hawkes
 
asmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docx
asmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docxasmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docx
asmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docxfredharris32
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 CanvasHenry Osborne
 
SVGo: a Go Library for SVG generation
SVGo: a Go Library for SVG generationSVGo: a Go Library for SVG generation
SVGo: a Go Library for SVG generationAnthony Starks
 
2008 Sccc Inheritance
2008 Sccc Inheritance2008 Sccc Inheritance
2008 Sccc Inheritancebergel
 
HTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web GamesHTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web Gameslivedoor
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersAriya Hidayat
 
High Performance Mobile Web Game Development in HTML5
High Performance Mobile Web Game Development in HTML5High Performance Mobile Web Game Development in HTML5
High Performance Mobile Web Game Development in HTML5Sangmin Shim
 
Simulation tools use in Textile product
Simulation tools use in Textile productSimulation tools use in Textile product
Simulation tools use in Textile productHashim Ali
 
Raphael JavaScript Library
Raphael JavaScript LibraryRaphael JavaScript Library
Raphael JavaScript LibraryLearningTech
 
A practical intro to BabylonJS
A practical intro to BabylonJSA practical intro to BabylonJS
A practical intro to BabylonJSHansRontheWeb
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive GraphicsBlazing Cloud
 

Similar to Fabric.js — Building a Canvas Library (20)

Building Windows 8 Metro Style casual games using HTML5 and JavaScript
Building Windows 8 Metro Style casual games using HTML5 and JavaScriptBuilding Windows 8 Metro Style casual games using HTML5 and JavaScript
Building Windows 8 Metro Style casual games using HTML5 and JavaScript
 
Html5 Canvas Drawing and Animation
Html5 Canvas Drawing and AnimationHtml5 Canvas Drawing and Animation
Html5 Canvas Drawing and Animation
 
Intro to HTML5 Canvas
Intro to HTML5 CanvasIntro to HTML5 Canvas
Intro to HTML5 Canvas
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the Web
 
asmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docx
asmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docxasmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docx
asmt7~$sc_210_-_assignment_7_fall_15.docasmt7cosc_210_-_as.docx
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
SVGo workshop
SVGo workshopSVGo workshop
SVGo workshop
 
SVGo: a Go Library for SVG generation
SVGo: a Go Library for SVG generationSVGo: a Go Library for SVG generation
SVGo: a Go Library for SVG generation
 
2008 Sccc Inheritance
2008 Sccc Inheritance2008 Sccc Inheritance
2008 Sccc Inheritance
 
HTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web GamesHTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web Games
 
canvas_1.pptx
canvas_1.pptxcanvas_1.pptx
canvas_1.pptx
 
jQuery
jQueryjQuery
jQuery
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile Browsers
 
High Performance Mobile Web Game Development in HTML5
High Performance Mobile Web Game Development in HTML5High Performance Mobile Web Game Development in HTML5
High Performance Mobile Web Game Development in HTML5
 
Simulation tools use in Textile product
Simulation tools use in Textile productSimulation tools use in Textile product
Simulation tools use in Textile product
 
Raphael JavaScript Library
Raphael JavaScript LibraryRaphael JavaScript Library
Raphael JavaScript Library
 
A practical intro to BabylonJS
A practical intro to BabylonJSA practical intro to BabylonJS
A practical intro to BabylonJS
 
Raphael
RaphaelRaphael
Raphael
 
HTML 5_Canvas
HTML 5_CanvasHTML 5_Canvas
HTML 5_Canvas
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 

Recently uploaded

Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...CzechDreamin
 
Transforming The New York Times: Empowering Evolution through UX
Transforming The New York Times: Empowering Evolution through UXTransforming The New York Times: Empowering Evolution through UX
Transforming The New York Times: Empowering Evolution through UXUXDXConf
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101vincent683379
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessUXDXConf
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
Motion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in TechnologyMotion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in TechnologyUXDXConf
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Boni Yeamin
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 

Recently uploaded (20)

Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Transforming The New York Times: Empowering Evolution through UX
Transforming The New York Times: Empowering Evolution through UXTransforming The New York Times: Empowering Evolution through UX
Transforming The New York Times: Empowering Evolution through UX
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Motion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in TechnologyMotion for AI: Creating Empathy in Technology
Motion for AI: Creating Empathy in Technology
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

Fabric.js — Building a Canvas Library

  • 1. Fabric.js Bulding a canvas library @kangax ✎ BK.js ✎ 2011
  • 2. Who am I? @kangax perfectionkills.com kangax.github.com/es5-compat-table/
  • 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. 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. Canvas Charts Games Editors Physics simulation
  • 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. But why get rid of an elegant canvas API for some questionable blob of Javascript code?
  • 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. 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. fabric vs. native native ctx.fillRect(20, 50, 20, 20); fabric rect.set(‘left’, 20).set(‘top’, 50); canvas.renderAll();
  • 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. But wait, there’s more! Object manipulations with mouse http://kangax.github.com/fabric.js/test/demo/
  • 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. Supported browsers • Firefox 2+ • Safari 3+ • Opera 9.64+ • Chrome (all versions should work) • IE9 (IE7/8 via excanvas)
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. How fabric works SVG parser
  • 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. 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. 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. 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. 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.
  • 35. are we there yet?
  • 36. Fun with SVG parsing
  • 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. Future plans: • Smaller footprint (delete Cufon) • Custom builder • Better docs • More complete SVG parsing • toSVG() • Pretty website, logo (help!!111) • Better IE support
  • 42. Thank you! Questions? http://spkr8.com/t/7303 github.com/kangax/fabric.js @FabricJS Follow me @kangax

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. Fabric provides state. Object oriented approach. Different paradigm.\n
  12. Demo time.\n
  13. \n
  14. More complete IE support to come in the future\n
  15. \n
  16. Note the chaining.\n
  17. Note the chaining.\n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. Exclude images, parser, text.\nMore tutorials.\nSupport gradients.\n
  41. \n
  42. \n