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

How to create a camera2
How to create a camera2How to create a camera2
How to create a camera2
Booch Lin
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
MicroPyramid .
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
Sunil Yadav
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JS
Naga Harish M
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
Thanh Tuong
 
Android Chromium Rendering Pipeline
Android Chromium Rendering PipelineAndroid Chromium Rendering Pipeline
Android Chromium Rendering PipelineHyungwook Lee
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
Bethmi Gunasekara
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
Tariqul islam
 
Magento 2 Declarative Schema
Magento 2 Declarative SchemaMagento 2 Declarative Schema
Magento 2 Declarative Schema
atishgoswami
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Shopware PWA - a technical overview of
Shopware PWA - a technical overview ofShopware PWA - a technical overview of
Shopware PWA - a technical overview of
Sander Mangel
 
HikCentral supports Access Control & Attendance Solutions
HikCentral supports Access Control & Attendance SolutionsHikCentral supports Access Control & Attendance Solutions
HikCentral supports Access Control & Attendance Solutions
Hikvision Europe B.V.
 
Reactjs
Reactjs Reactjs
Reactjs
Neha Sharma
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Chris Richardson
 
React js basics
React js basicsReact js basics
React js basics
Maulik Shah
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
Hermann Hueck
 
WebXR - Introduction and Workshop
WebXR - Introduction and WorkshopWebXR - Introduction and Workshop
WebXR - Introduction and Workshop
Timmy Kokke
 

What's hot (20)

20 códigos de eclipse
20 códigos de eclipse20 códigos de eclipse
20 códigos de eclipse
 
How to create a camera2
How to create a camera2How to create a camera2
How to create a camera2
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JS
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Android Chromium Rendering Pipeline
Android Chromium Rendering PipelineAndroid Chromium Rendering Pipeline
Android Chromium Rendering Pipeline
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Magento 2 Declarative Schema
Magento 2 Declarative SchemaMagento 2 Declarative Schema
Magento 2 Declarative Schema
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Shopware PWA - a technical overview of
Shopware PWA - a technical overview ofShopware PWA - a technical overview of
Shopware PWA - a technical overview of
 
HikCentral supports Access Control & Attendance Solutions
HikCentral supports Access Control & Attendance SolutionsHikCentral supports Access Control & Attendance Solutions
HikCentral supports Access Control & Attendance Solutions
 
Reactjs
Reactjs Reactjs
Reactjs
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
React js basics
React js basicsReact js basics
React js basics
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
WebXR - Introduction and Workshop
WebXR - Introduction and WorkshopWebXR - Introduction and Workshop
WebXR - Introduction and Workshop
 

Viewers also liked

Open Source - Hip not Hype
Open Source - Hip not HypeOpen Source - Hip not Hype
Open Source - Hip not Hype
Priyank Kapadia
 
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...
Departament de Justícia. Generalitat de Catalunya.
 
The Desirability of Connected Products
The Desirability of Connected ProductsThe Desirability of Connected Products
The Desirability of Connected Products
J F Grossen
 
Guide open source-bdef
Guide open source-bdefGuide open source-bdef
Guide open source-bdef
Syntec Numérique
 
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 Enforcement
Andres Guadamuz
 
Open Source and Economic Development
Open Source and Economic DevelopmentOpen Source and Economic Development
Open Source and Economic Development
Deborah 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-off
Jane Park
 
CCL and Database in Korea
CCL and Database in KoreaCCL and Database in Korea
CCL and Database in Korea
Jay Yoon
 
Phillips Remix Cycle Pixelodeon 2007
Phillips   Remix Cycle   Pixelodeon 2007Phillips   Remix Cycle   Pixelodeon 2007
Phillips Remix Cycle Pixelodeon 2007
Jon 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
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
David Lindkvist
 
Open Credential and Radical Openness
 Open Credential  and Radical Openness Open Credential  and Radical Openness
Open Credential and Radical Openness
Open Education Global (OEGlobal)
 
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
Cable Green
 
Creative Commons & Cultural Heritage
Creative Commons & Cultural HeritageCreative Commons & Cultural Heritage
Creative Commons & Cultural Heritage
Jane 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.1
WHub
 
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 Commons
Paul_Stacey
 
Creative Commons Certificates
Creative Commons CertificatesCreative Commons Certificates
Creative Commons Certificates
Paul_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
 
Intro to HTML5 Canvas
Intro to HTML5 CanvasIntro to HTML5 Canvas
Intro to HTML5 Canvas
Juho Vepsäläinen
 
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
Robin 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.docx
fredharris32
 
Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
Henry Osborne
 
SVGo workshop
SVGo workshopSVGo workshop
SVGo workshop
Anthony Starks
 
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
Anthony Starks
 
2008 Sccc Inheritance
2008 Sccc Inheritance2008 Sccc Inheritance
2008 Sccc Inheritance
bergel
 
HTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web GamesHTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web Games
livedoor
 
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 HTML5
Sangmin Shim
 
Simulation tools use in Textile product
Simulation tools use in Textile productSimulation tools use in Textile product
Simulation tools use in Textile product
Hashim 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 BabylonJS
HansRontheWeb
 
Raphael
RaphaelRaphael
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

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 

Recently uploaded (20)

Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 

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