SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
fabric.js
Building a canvas library




       Warsaw   2011
who is kangax?
     kangax.com
who is kangax?

perfectionkills.com                 ES5 compat tables


                      fabric.js


                      Common Feature Tests
                                              PrototypeJS

HTML minifier                                  DOMLint
Game Plan

History
Why fabric?
How it works. Features.
Canvas libraries
Future plans
History
 printio.ru
History
 printio.ru



        All Javascript, no Flash
        Free drawing
        Vectors & images
        Performance
Canvas vs SVG
Why fabric?
 Canvas API sucks is too low level

There was an excruciating need for
     interactive object model
       for canvas element
Why fabric?
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);
Why fabric?
native

 var canvasEl = document.getElementById('canvas');
 var ctx = canvasEl.getContext('2d');
 ctx.strokeStyle = '';
 ctx.fillStyle = 'red';
 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);
Why fabric?
native

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




fabric
rect.set(‘left’, 20).set(‘top’, 50);
canvas.renderAll();
Why fabric?
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();
Demo




http://kangax.github.com/fabric.js/test/demo
Under the hood
Upper <canvas>
Group selection




                                   Lower <canvas>
                                     All objects
Under the hood
                                   fabric.Circle
   fabric.Rect                               render()
        render()




fabric.Element
      renderAll()
                          fabric.Triangle
                                  render()
Under the hood
                                        fabric.Circle
    fabric.Rect                                   render()
          render()




fabric.Element                 fabric.Triangle
       renderAll()
                                       render()
Under the hood
     Root “class”. 2D objects           Concrete “subclasses”


fabric.Object                   fabric.Line
                                fabric.Circle
                                fabric.Triangle
                                fabric.Ellipse
              Container
                                fabric.Rect
fabric.Element                  fabric.Polyline
                                fabric.Polygon
                                fabric.Group                    fabric.Color
                                fabric.Text                     fabric.Point
                                fabric.Image                    fabric.Intersection
                                fabric.Path
Under the hood
                                clone
                                cloneAsImage
     Root “class”. 2D objects   complexity      Inherited by all subclasses
                                get
fabric.Object                   getCenter
                                getWidth
                                getElement
                                getHeight
                                intersectsWithObject
                                isActive
                                isType
                                scale
                                scaleToHeight
                                scaleToWidth
                                set
                                setActive
                                setElement
                                straighten
                                toDataURL
                                toJSON
                                toGrayscale
                                ...
Features — Animation
                      fxCenterObjectV: function (...) {
fabric.util.animate     ...

                          fabric.util.animate({

                            startValue: object.get('top'),
                            endValue: this.getCenter().top,

                            duration: this.FX_DURATION,

                            onChange: function(value) {
                               object.set('top', value);
                               _this.renderAll();
                               onChange();
fxCenterObjectV             },
                            onComplete: function() {
fxCenterObjectH                object.setCoords();
                               onComplete();
fxStraightenObject          }
                          });

fxRemove                  ...
                      }
...
Features — Animation
Or just use new, fancy window.requestAnimationFrame

                        (function animate() {
                          canvas.forEachObject(function(obj) {
                            obj.left += (obj.movingLeft ? -1 : 1);
                            obj.top += 1;
                            if (obj.left > 900 || obj.top > 500) {
                              canvas.remove(obj);
                            }
                            else {
                              obj.setAngle(obj.getAngle() + 2);
                            }
                          });
                          canvas.renderAll();
                          window.requestAnimationFrame(animate);
                        })();
Features — Events
object:scaled
object:selected          fabric.util.observeEvent('object:moved', function(e) {

object:moved               var activeObject = e.memo.target;

                           console.log(activeObject.left, activeObject.top);

group:modified           });

group:selected
before:group:destroyed
after:group:destroyed


mouse:up


selection:cleared              Will be made more consistent!
path:created
Features — Text
fontsize
                     var myText = new fabric.Text('Hello world', {
font weight
                      fontfamily: 'delicious'
fontfamily
                     });
fontStyle
                     canvas.add(myText);


textDecoration
textShadow


lineHeight
backgroundColor


strokeStyle                Will be made more consistent!
strokeWidth
Features — Text
Multiline support




                    text aligning coming soon
Features — Text
Multiline support
Relies on Cufon.js




http://kangax.github.com/jstests/canvas_fillText_test
Features — Text
       Multiline support
       Relies on Cufon.js
       Renders using any
       OTF, TTF, etc. font



Each font is a JS file with glyph definitions
Features — SVG Parser

  Q:   How to render SVG shapes on canvas?
       A:   Transform them to fabric objects.
Features — SVG Parser



<path d="M-122.304 84.285C-122.304            {
84.285 -122.203 86.179 -123.027      Step 1       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, ... ],
                                                      [ ... ],
                                                      ...
                                                  ]
                                              }
Features — SVG Parser



{                                            case 'C': // bezierCurveTo, absolute
    path: [                                    x = current[5];
      [ "M", -122.304, 84.285 ],               y = current[6];
      [ "C", -122.304, 84.285,      Step 2     controlX = current[3];
             -122.203, 86.179,                 controlY = current[4];
                                               ctx.bezierCurveTo(
               -123.027, 86.16 ],                 current[1] + l,
        [ "C", -123.851, ... ],                   current[2] + t,
        [ ... ],                                  controlX + l,
        ...                                       controlY + t,
    ]                                             x + l,
}                                                 y + t
                                               );
                                               break;
Canvas libraries



   http://goo.gl/CCRRT
Canvas libraries




  canvg
   The only other library with (good) SVG parser
   But no object model
Canvas libraries




  burst
   Lots of features but completely abandoned
Canvas libraries




  Unit Tests
   Hard to come across a library that has them
Canvas libraries




    easel.js
    Probably the most active, similar, and
    promising alternative.
    But no unit tests or SVG parser :(
Fabric use cases
                 mouse-based interactions built in


Collages
                           might be overkill for static charts

Basic games
Charts
Basic drawing (paintbrush, diagrams)
Display SVG where unsupported (Android)
What can you build?
     mustachified.com
Future plans

Smaller footprint
Better docs, tutorials
Custom builder
fabric-to-SVG
Touch compatible (iOS)
Smaller footprint

        Fabric 0.2.5                     jQuery 1.6.1

102 KB — minified                 91 KB — minified
 33 KB — minified + compressed    32 KB — minified + compressed



Can do even better – optional json2.js, cufon.js + custom builder
Smaller footprint
          with Cufon                              without cufon.js

 102 KB — minified                            86 KB — minified
  33 KB — minified + compressed               29 KB — minified + compressed




                                                  without json2.js

JSON missing in FF 3, SF 3.2, OP 10.1, IE 7    82 KB — minified
                                              25 KB — minified + compressed
Docs, Tests
                                  1000+ tests ATM




        http://kangax.github.com/fabric.js/docs

http://kangax.github.com/fabric.js/test/unit/suite_runner
Demos, Benchmarks




 http://kangax.github.com/fabric.js/test/
     raphael_vs_fabric/complex_shape


 http://kangax.github.com/fabric.js/demos
Supported browsers

Firefox 2+
Safari 3+ (& Mobile Safari)
Opera 9.64+
Chrome (all versions should work)
IE9+ (IE7 & 8 via excanvas.js)
Thank you!
                   Questions?


             http://spkr8.com/t/7582




github.com/kangax/fabric.js
                  @fabric.js
                  @kangax

Contenu connexe

Tendances

[2019] 딥러닝을 이용한 가상 피팅 룸
[2019] 딥러닝을 이용한 가상 피팅 룸[2019] 딥러닝을 이용한 가상 피팅 룸
[2019] 딥러닝을 이용한 가상 피팅 룸NHN FORWARD
 
AWS Community Day: AWS Fargate on EKS 실전 사용하기
AWS Community Day: AWS Fargate on EKS 실전 사용하기AWS Community Day: AWS Fargate on EKS 실전 사용하기
AWS Community Day: AWS Fargate on EKS 실전 사용하기Chanho Yong
 
Animals in english 3 (Aula de Inglês)
Animals in english 3 (Aula de Inglês)Animals in english 3 (Aula de Inglês)
Animals in english 3 (Aula de Inglês)Adilson P Motta Motta
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강
딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강
딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강Minji Kang
 
[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저
[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저
[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저Amazon Web Services Korea
 
PyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in PracticePyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in PracticeSeomgi Han
 
[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기
[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기
[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기OKKY
 
AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트 :: IoT Convergence Conference 2015
AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트  :: IoT Convergence Conference 2015AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트  :: IoT Convergence Conference 2015
AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트 :: IoT Convergence Conference 2015Amazon Web Services Korea
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryZeeshan Khan
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스
제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스
제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스BOAZ Bigdata
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introductionsandeep54552
 
S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)
S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)
S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)ByeongHyeokYu
 

Tendances (16)

[2019] 딥러닝을 이용한 가상 피팅 룸
[2019] 딥러닝을 이용한 가상 피팅 룸[2019] 딥러닝을 이용한 가상 피팅 룸
[2019] 딥러닝을 이용한 가상 피팅 룸
 
AWS Community Day: AWS Fargate on EKS 실전 사용하기
AWS Community Day: AWS Fargate on EKS 실전 사용하기AWS Community Day: AWS Fargate on EKS 실전 사용하기
AWS Community Day: AWS Fargate on EKS 실전 사용하기
 
Animals in english 3 (Aula de Inglês)
Animals in english 3 (Aula de Inglês)Animals in english 3 (Aula de Inglês)
Animals in english 3 (Aula de Inglês)
 
F strings
F stringsF strings
F strings
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강
딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강
딥러닝을 이용한 사용자 선호도 기반 의상 추천 알고리즘 Ppt 선수강
 
[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저
[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저
[Retail & CPG Day 2019] 유통 고객의 AWS 도입 동향 - 박동국, AWS 어카운트 매니저, 김준성, AWS어카운트 매니저
 
PyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in PracticePyCon KR 2018 Effective Tips for Django ORM in Practice
PyCon KR 2018 Effective Tips for Django ORM in Practice
 
[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기
[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기
[OKKYCON] 박재성 - 의식적인 연습으로 TDD, 리팩토링 연습하기
 
AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트 :: IoT Convergence Conference 2015
AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트  :: IoT Convergence Conference 2015AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트  :: IoT Convergence Conference 2015
AWS IoT 서비스 활용하기- 윤석찬, AWS 테크에반젤리스트 :: IoT Convergence Conference 2015
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스
제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스
제 14회 보아즈(BOAZ) 빅데이터 컨퍼런스 - [카페 어디가?팀] : 카페 및 장소 추천 서비스
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introduction
 
Table and Form HTML&CSS
Table and Form HTML&CSSTable and Form HTML&CSS
Table and Form HTML&CSS
 
S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)
S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)
S05 파크랩 DSLab.1기: 네트워크 분석(Network Analysis)
 

Similaire à Fabric.js @ Falsy Values

Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in SwiftNetguru
 
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
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with MobelloJeong-Geun Kim
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserHoward Lewis Ship
 
WPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationWPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationMohammad Shaker
 
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
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientBin Shao
 
2008 Sccc Inheritance
2008 Sccc Inheritance2008 Sccc Inheritance
2008 Sccc Inheritancebergel
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App DevelopmentKetan Raval
 

Similaire à Fabric.js @ Falsy Values (20)

jQuery
jQueryjQuery
jQuery
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
 
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
 
Building mobile web apps with Mobello
Building mobile web apps with MobelloBuilding mobile web apps with Mobello
Building mobile web apps with Mobello
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
HTML 5_Canvas
HTML 5_CanvasHTML 5_Canvas
HTML 5_Canvas
 
Intro to HTML5 Canvas
Intro to HTML5 CanvasIntro to HTML5 Canvas
Intro to HTML5 Canvas
 
WPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and AnimationWPF L02-Graphics, Binding and Animation
WPF L02-Graphics, Binding and Animation
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
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
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
SVGo workshop
SVGo workshopSVGo workshop
SVGo workshop
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
jQuery
jQueryjQuery
jQuery
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
2008 Sccc Inheritance
2008 Sccc Inheritance2008 Sccc Inheritance
2008 Sccc Inheritance
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
 

Dernier

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Fabric.js @ Falsy Values

  • 1. fabric.js Building a canvas library Warsaw 2011
  • 2. who is kangax? kangax.com
  • 3. who is kangax? perfectionkills.com ES5 compat tables fabric.js Common Feature Tests PrototypeJS HTML minifier DOMLint
  • 4. Game Plan History Why fabric? How it works. Features. Canvas libraries Future plans
  • 6. History printio.ru All Javascript, no Flash Free drawing Vectors & images Performance
  • 8. Why fabric? Canvas API sucks is too low level There was an excruciating need for interactive object model for canvas element
  • 9. Why fabric? 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);
  • 10. Why fabric? native var canvasEl = document.getElementById('canvas'); var ctx = canvasEl.getContext('2d'); ctx.strokeStyle = ''; ctx.fillStyle = 'red'; 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);
  • 11. Why fabric? native ctx.fillRect(20, 50, 20, 20); fabric rect.set(‘left’, 20).set(‘top’, 50); canvas.renderAll();
  • 12. Why fabric? 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();
  • 14. Under the hood Upper <canvas> Group selection Lower <canvas> All objects
  • 15. Under the hood fabric.Circle fabric.Rect render() render() fabric.Element renderAll() fabric.Triangle render()
  • 16. Under the hood fabric.Circle fabric.Rect render() render() fabric.Element fabric.Triangle renderAll() render()
  • 17. Under the hood Root “class”. 2D objects Concrete “subclasses” fabric.Object fabric.Line fabric.Circle fabric.Triangle fabric.Ellipse Container fabric.Rect fabric.Element fabric.Polyline fabric.Polygon fabric.Group fabric.Color fabric.Text fabric.Point fabric.Image fabric.Intersection fabric.Path
  • 18. Under the hood clone cloneAsImage Root “class”. 2D objects complexity Inherited by all subclasses get fabric.Object getCenter getWidth getElement getHeight intersectsWithObject isActive isType scale scaleToHeight scaleToWidth set setActive setElement straighten toDataURL toJSON toGrayscale ...
  • 19. Features — Animation fxCenterObjectV: function (...) { fabric.util.animate ... fabric.util.animate({ startValue: object.get('top'), endValue: this.getCenter().top, duration: this.FX_DURATION, onChange: function(value) { object.set('top', value); _this.renderAll(); onChange(); fxCenterObjectV }, onComplete: function() { fxCenterObjectH object.setCoords(); onComplete(); fxStraightenObject } }); fxRemove ... } ...
  • 20. Features — Animation Or just use new, fancy window.requestAnimationFrame (function animate() { canvas.forEachObject(function(obj) { obj.left += (obj.movingLeft ? -1 : 1); obj.top += 1; if (obj.left > 900 || obj.top > 500) { canvas.remove(obj); } else { obj.setAngle(obj.getAngle() + 2); } }); canvas.renderAll(); window.requestAnimationFrame(animate); })();
  • 21. Features — Events object:scaled object:selected fabric.util.observeEvent('object:moved', function(e) { object:moved var activeObject = e.memo.target; console.log(activeObject.left, activeObject.top); group:modified }); group:selected before:group:destroyed after:group:destroyed mouse:up selection:cleared Will be made more consistent! path:created
  • 22. Features — Text fontsize var myText = new fabric.Text('Hello world', { font weight fontfamily: 'delicious' fontfamily }); fontStyle canvas.add(myText); textDecoration textShadow lineHeight backgroundColor strokeStyle Will be made more consistent! strokeWidth
  • 23. Features — Text Multiline support text aligning coming soon
  • 24. Features — Text Multiline support Relies on Cufon.js http://kangax.github.com/jstests/canvas_fillText_test
  • 25. Features — Text Multiline support Relies on Cufon.js Renders using any OTF, TTF, etc. font Each font is a JS file with glyph definitions
  • 26. Features — SVG Parser Q: How to render SVG shapes on canvas? A: Transform them to fabric objects.
  • 27. Features — SVG Parser <path d="M-122.304 84.285C-122.304 { 84.285 -122.203 86.179 -123.027 Step 1 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, ... ], [ ... ], ... ] }
  • 28. Features — SVG Parser { case 'C': // bezierCurveTo, absolute path: [ x = current[5]; [ "M", -122.304, 84.285 ], y = current[6]; [ "C", -122.304, 84.285, Step 2 controlX = current[3]; -122.203, 86.179, controlY = current[4]; ctx.bezierCurveTo( -123.027, 86.16 ], current[1] + l, [ "C", -123.851, ... ], current[2] + t, [ ... ], controlX + l, ... controlY + t, ] x + l, } y + t ); break;
  • 29. Canvas libraries http://goo.gl/CCRRT
  • 30. Canvas libraries canvg The only other library with (good) SVG parser But no object model
  • 31. Canvas libraries burst Lots of features but completely abandoned
  • 32. Canvas libraries Unit Tests Hard to come across a library that has them
  • 33. Canvas libraries easel.js Probably the most active, similar, and promising alternative. But no unit tests or SVG parser :(
  • 34. Fabric use cases mouse-based interactions built in Collages might be overkill for static charts Basic games Charts Basic drawing (paintbrush, diagrams) Display SVG where unsupported (Android)
  • 35. What can you build? mustachified.com
  • 36. Future plans Smaller footprint Better docs, tutorials Custom builder fabric-to-SVG Touch compatible (iOS)
  • 37. Smaller footprint Fabric 0.2.5 jQuery 1.6.1 102 KB — minified 91 KB — minified 33 KB — minified + compressed 32 KB — minified + compressed Can do even better – optional json2.js, cufon.js + custom builder
  • 38. Smaller footprint with Cufon without cufon.js 102 KB — minified 86 KB — minified 33 KB — minified + compressed 29 KB — minified + compressed without json2.js JSON missing in FF 3, SF 3.2, OP 10.1, IE 7 82 KB — minified 25 KB — minified + compressed
  • 39. Docs, Tests 1000+ tests ATM http://kangax.github.com/fabric.js/docs http://kangax.github.com/fabric.js/test/unit/suite_runner
  • 40. Demos, Benchmarks http://kangax.github.com/fabric.js/test/ raphael_vs_fabric/complex_shape http://kangax.github.com/fabric.js/demos
  • 41. Supported browsers Firefox 2+ Safari 3+ (& Mobile Safari) Opera 9.64+ Chrome (all versions should work) IE9+ (IE7 & 8 via excanvas.js)
  • 42. Thank you! Questions? http://spkr8.com/t/7582 github.com/kangax/fabric.js @fabric.js @kangax