SlideShare a Scribd company logo
1 of 42
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

Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Nelson Glauber Leal
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Chapitre 5 classes abstraites et interfaces
Chapitre 5  classes abstraites et interfacesChapitre 5  classes abstraites et interfaces
Chapitre 5 classes abstraites et interfacesAmir Souissi
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring bootAntoine Rey
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Android-Tp1: éléments graphiques de base et intents
Android-Tp1: éléments graphiques de base et intentsAndroid-Tp1: éléments graphiques de base et intents
Android-Tp1: éléments graphiques de base et intentsLilia Sfaxi
 
J'ai fait une app native en React Native
J'ai fait une app native en React NativeJ'ai fait une app native en React Native
J'ai fait une app native en React NativeCocoaHeads France
 
Jetpack Compose beginner.pdf
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdfAayushmaAgrawal
 
How to create a camera2
How to create a camera2How to create a camera2
How to create a camera2Booch Lin
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
 
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...ENSET, Université Hassan II Casablanca
 
Panorama des Technologies mobiles
Panorama des Technologies mobilesPanorama des Technologies mobiles
Panorama des Technologies mobilesAbdoulaye Dieng
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 

What's hot (20)

Input Method Kit
Input Method KitInput Method Kit
Input Method Kit
 
Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021Android Jetpack Compose - Turkey 2021
Android Jetpack Compose - Turkey 2021
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Chapitre 5 classes abstraites et interfaces
Chapitre 5  classes abstraites et interfacesChapitre 5  classes abstraites et interfaces
Chapitre 5 classes abstraites et interfaces
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Android-Tp1: éléments graphiques de base et intents
Android-Tp1: éléments graphiques de base et intentsAndroid-Tp1: éléments graphiques de base et intents
Android-Tp1: éléments graphiques de base et intents
 
J'ai fait une app native en React Native
J'ai fait une app native en React NativeJ'ai fait une app native en React Native
J'ai fait une app native en React Native
 
Jetpack Compose beginner.pdf
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdf
 
Nouveautés de java 8
Nouveautés de java 8Nouveautés de java 8
Nouveautés de java 8
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Introduction à ajax
Introduction à ajaxIntroduction à ajax
Introduction à ajax
 
Introduction à Angular
Introduction à AngularIntroduction à Angular
Introduction à Angular
 
How to create a camera2
How to create a camera2How to create a camera2
How to create a camera2
 
Hibernate
HibernateHibernate
Hibernate
 
Cours JavaScript
Cours JavaScriptCours JavaScript
Cours JavaScript
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
Conférence: Catalyseurs de l'Intelligence Artificielle et Écosystème des Fram...
 
Panorama des Technologies mobiles
Panorama des Technologies mobilesPanorama des Technologies mobiles
Panorama des Technologies mobiles
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 

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

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 

Recently uploaded (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 

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