What is a HTML canvas? The HTML canvas element has been around for quite some time and is a versatile tool used to draw graphics directly in a web page.
It serves as a space in the DOM where you can render 2D shapes, images, animations and more to create dynamic visuals such as charts, image manipulation tools, 3D modelling tools, and even game graphics.
Unlike traditional HTML elements, everything displayed in a canvas element is rendered by JavaScript which allows you to update the content dynamically and provides a deeper level of interaction and manipulation than static DOM elements.
What is Fabric.js? Fabric.js is a JavaScript library that aims to simplify the task of working with the HTML5 canvas element by providing an object model for the canvas, as well as an SVG parser, layer of interactivity, as well as a large number of utilities to support complex scenarios and data modelling.
This article will focus on version 5 of the Fabric.js library, however it's worth noting the at the time of writing this, version 6.3.0 just released and is well on it's way to being a stable platform.
And that's it! Now we have a fully functioning Fabric.js canvas that we can manipulate to our needs.
Applications pratiques de Fabric.js
So we have a canvas to use and a world of endless possibilities at our fingertips, but what do we build?
La tâche
The taskTo see the true power of Fabric.js I wanted to revisit a product I created in a previous job which allowed users to view and build a "floorplan" of all the dealers and tables on a Casino floor.
At the time of writing that, the decision was made to use SVG's and leveraging Angular's dynamic component loaders I was able to create a "virtual" infinite floorplan which loaded and unloaded elements from the DOM as they entered and left the view.
This whole process was rather complex and took around 3 months to create.
If I could create something similar using a canvas and Fabric.js in even a fraction of that time, I would consider this a a huge success (spoiler alert; it took me about 3 days).
I decided to build a grid based drawing system which could then be further expanded upon to provide drawing abilities for things like building floorplans, restaurant table layouts, landscaping and drafting mockups, as well as anything else that required a "top-down" view of things.
La mise en place
The setupFirst, lets get some styles going. Note: The .lower-canvas class is a class that Fabric creates, all we want to add to that class is a grid for the background.
The background size will eventually match the grid size we create in the Fabric.js canvas implementation to give a "snap to grid" functionality.
Now that we have that out of the way, lets add some features to the canvas.
Pan & Zoom
Panning is a key part of any grid based drawing system. Zooming is added to provide intuitive navigation.
Grille et snapping
Grid SnappingWe have defined the background for the canvas to be a 50px grid, so lets make the dragging on shapes etc. line up and snap to that grid pattern.
Define the grid size property (in pixels).
Note: Sometimes when scaling an object it can give off some weird behaviour and still needs some further investigation.
Ajout d'éléments sur le canvas
Adding Elements to the CanvasOnce all the controls are set up, we can start adding elements to the canvas. Fabric.js makes the job of adding elements to the canvas very simple, and by default any item that is on the canvas has full manipulation enabled.
Now we can look at adding elements to the canvas, for this example we're going to focus on lines, squares, and textboxes as they act as a good proof of concept for this drawing system.
Lignes
LinesLines provide a little bit of a challenge as too small of a stroke width will make the line impossible to select with a cursor and move.
Soumission et persistance
Loading & SavingWe now have everything we need when it comes to element manipulation which means the next step is being able to persist the data across sessions.
Limitations, Constraints, & IdiosyncrasiesFabric.js is a great library to use and covers a wide range of use cases however it does come with it's own set of unique behaviours.
Fabric & Angular
Fabric & AngularThis was unfortunately one of the more tedious things to decipher. Whilst you can use Fabric with Angular and serve up the application, the build itself will actually fail.
This is due to Fabric.js being built using node specific dependencies (jsdom for example) which Angular does not like. To get around this, Fabric.js also publishes a browser version of each of their package versions which is not mentioned in the docs anywhere and I only found after a lot of exploring.
If you are using Fabric.js with Angular, use the -browser version of their packages. For example if you want to use version 5.3.0, you would instead install 5.3.0-browser
Custom Builds & Touch Support
Custom Builds & Touch SupportThe documentation isn't exactly clear on this from the outset, but in order to enable touch events you need to use what is referred to as a "custom build" of Fabric.js. You can do this from their builder and toggle the specific features you want however this then downloads you a .js file to use in your project.
Since we're already using a package manager for the actual Fabric.js package, it seemed odd that custom builds were handled this way - all I wanted was touch support, odd that it's not included in the default package.
To get around this, the "accepted" answer when researching a solution is to set up a post install script which jumps into the installed Fabric.js directory (in node_modules) and runs a custom build with gestures enabled.
To do this, add this to your scripts section in your package.json file.
"postinstall": "cd node_modules/fabric && npm install && npm run build_with_gestures"
Réflexions finales et Angular JS
Final ThoughtsI'm very impressed with the overall usability and design of the Fabric.js library. A task that previously took me many months now took me only a few days, and adding more and more functionality is relatively easy thanks to the object model that Fabric.js provides.
Qu'est-ce que le framework Angular JS ?
Framework de développement front-end open-source, AngularJS est basé sur le langage Javascript. Il fournit un framework pour le modèle vue-modèle (MVVM) côté client et le modèle vue contrôleur (MVC) disposition fondamentale pour faciliter les étapes de test et de développement. L'adaptation la plus récente des frameworks AngularJS est utilisée comme front-end de la stack MEAN, y compris le framework de développement web Express.js, l'ensemble de données MongoDB et le climat d'exécution du travailleur Node.js.
Il utilise HTML comme langage de programmation de format et permet d'étendre HTML pour interagir avec d'autres segments.
Pourquoi utiliser le framework AngularJS pour les projets de développement web ?
Caractéristiques principales des frameworks AngularJSDirectivesLes directives sont les marqueurs sur les parties du DOM comme les crédits, les composants et les CSS. Elles peuvent être utilisées pour encadrer des étiquettes HTML modifiées qui servent de nouveaux gadgets personnalisés. AngularJS possède des mandats intégrés comme ngModel et ngBind.
Liaison de modèle de donnéesPas besoin de composer divers codes pour lier les informations aux contrôles HTML. Cela peut être fait en ajoutant quelques morceaux de code.
MVC (Modèle-Vue-Contrôleur)Le framework AngularJS est créé sur l'idée notable de MVC (Model-View-Controller). C'est un exemple qui est utilisé sur l'ensemble des applications web contemporaines. Ce plan est développé en séparant la couche d'information, la couche de logique commerciale et la couche d'introduction en segments distincts.
Controller & ScopeCe sont des fonctionnalités très utiles des frameworks AngularJS qui sont liées à une extension particulière. Ce sont les articles qui remarquent le modèle. Ils procèdent comme un ciment entre la vue et le régulateur.
Intégration et extensions
ModèlesCe sont les vues consolidées avec les informations du modèle et du régulateur. Ils peuvent se présenter sous la forme d'un document unique comme index.html ou de perspectives complexes sur une page en utilisant des partiels.
Deep linkingIl nous permet d'encoder l'état de l'application dans l'URL afin qu'elle puisse être efficacement marquée d'un signet. À ce moment-là, l'application peut être rétablie dans un état identique à partir de l'URL.
Model View Whatever (MVW)MVW est un exemple d'isolation d'une application en différentes parties appelées modèle, vue et régulateur, chacune ayant des fonctions diverses. Le groupe AngularJS l'appelle "Model View Whatever".
Quels sont les frameworks AngularJS populaires pour le développement d'applications Web ?
Avec AngularJS, il est beaucoup plus facile de développer des applications Web robustes et modernes. Pour rationaliser les tâches et accroître l'efficacité, il existe plusieurs frameworks front-end pour AngularJS. Ces frameworks offrent de nombreux composants web intégrés et en les utilisant avec AngularJS, les développeurs peuvent rapidement construire une application à partir de zéro en beaucoup moins de temps.
Mobile Angular UI et Ionic, Angular Material, UI Bootstrap, UI Grid, LumX, Supersonic, Radian, Sauve UI, Angular Foundation illustrent des solutions liées à AngularJS et à l'UI.
Rewriting Flash-based games to HTML5 Canvas technology would let us play them on mobile browsers as well. EaselJS, part of CreateJS’s suite, makes drawing on HTML5 Canvas simple. Imagine building custom data visualization with high performance and thousands of elements. Scalable Vector Graphic (SVG) is not the right choice, because it uses DOM elements. Browsers become overwhelmed when, at around 600 DOM elements, initial renderings, re-draws, and animation become expensive operations. This means that Canvas based development needs more attention when it comes to separating elements, and attaching events and behaviors to them. SVG-based coding has one big advantage: SVG has an old specification, and there are a lot of design tools that export SVG assets for use in development, so that cooperation between designers and developers works well. If designer-to-developer workflow is the only reason you would use SVGs, consider extensions for Adobe Illustrator (AI) that generate code from shapes created in AI.
