SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang) [Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang) Johnny Sung
 
Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용흥배 최
 
Random Thoughts on Paper Implementations [KAIST 2018]
Random Thoughts on Paper Implementations [KAIST 2018]Random Thoughts on Paper Implementations [KAIST 2018]
Random Thoughts on Paper Implementations [KAIST 2018]Taehoon Kim
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IICS
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practicesfloydophone
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.ManojSatishKumar
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVICS
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)Tracy Lee
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_jsMicroPyramid .
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt testDavide Coppola
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesCharles Nutter
 
Javascript under the hood 2
Javascript under the hood 2Javascript under the hood 2
Javascript under the hood 2Thang Tran Duc
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.jsTimur Shemsedinov
 

Was ist angesagt? (20)

[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang) [Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
 
Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용Twitter의 snowflake 소개 및 활용
Twitter의 snowflake 소개 및 활용
 
React hooks
React hooksReact hooks
React hooks
 
Random Thoughts on Paper Implementations [KAIST 2018]
Random Thoughts on Paper Implementations [KAIST 2018]Random Thoughts on Paper Implementations [KAIST 2018]
Random Thoughts on Paper Implementations [KAIST 2018]
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Rethinking Best Practices
Rethinking Best PracticesRethinking Best Practices
Rethinking Best Practices
 
React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.React hooks Episode #1: An introduction.
React hooks Episode #1: An introduction.
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt test
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Javascript under the hood 2
Javascript under the hood 2Javascript under the hood 2
Javascript under the hood 2
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.js
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 

Kürzlich hochgeladen (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

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

Hinweis der Redaktion

  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