Denis Potschien August 26th, 2014

HTML5 Canvas: Drawing Made Simpler with Fabric.js

Drawing with the HTML element Canvas doesn't leave much to be desired. Complex shapes and animations are possible, the feature set is quite impressive. Yet we need to combine several methods when it comes to e.g. create a shape, rotate it and fill it with a color. The JavaScript library Fabric.js simplifies the possibilities Canvas has to offer and adds functionality to het work done faster. Animations and interactions are created and applied in next to no time. fabricjs

Fabric.js: One Single Method Suffices

Once we have added Fabric.js to the head of our HTML document and created a Canvas element, we are closest to creating our first shape. To do so we insert a new Fabric.js object and attach it to the Canvas. In our example we use the element with the ID „fabricjs“. Per „fabric.Canvas()“ we can add options to further customize the Canvas. We could for example define the background color that way.
var OwnCanvas = new fabric.Canvas("fabricjs", {
  backgroundColor: "seashell"
});
Afterwards we are able to to draw multiple shapes and forms as well as texts.
var OwnRect = new fabric.Rect({
  left: 75,
  top: 25,
  fill: "saddlebrown",
  stroke: "yellowgreen",
  strokeWidth: 3,
  width: 100,
  height: 200,
  angle: 20,
  shadow: "black 3px 3px 6px"
});
In our example we use „fabric.Rect()“ to create a rectangle. All other values such as position, size, color, rotation or shadow are defined via parameters. You know that with Canvas solely things would not be that easy. We'd have to use several methods instead. Color and shadow are declared just like we are used to from CSS. Accordingly, color values can be in „rgb()“ or „rgba()“. fabricjs_beispiel1 Our First Rectangle All the individual properties can be changed later using „set()“.
OwnRect.set({
  angle: -20,
});
In the above example we adjust the angle of our rectangle. The last method named „add()“ actually draws the shape to the canvas.
OwnCanvas.add(OwnRect);

Drag & Drop & More: Shapes Are Interactive by Nature

All the shapes created using „fabric.Canvas()“ are interactive by default. We can drag and drop, scale and rotate them with the mouse or touch gestures. Click any given shape and you'll notice the anchor points that will become visible. If you want to change the looks of these anchors simply use „set()“:
OwnRect.set({
  borderColor: "royalblue",
  cornerColor: "midnightblue",
  cornerSize: 10
});
In some cases you'd probably not want the shapes to be interactive. Using the method „fabric.StaticCanvas()“ will make sure that no interactions are possible.
var OwnCanv = new fabric.StaticCanvas("fabricjs");
Thanks to its own events Fabric.js is able to react upon the manipulation of any given shape..
OwnRect.on("modified", function() {
  OwnRect.set({
    fill: "red"
  })
});
In the example we assign the event „modified“. It will be started each time the shape gets moved, rotated or scaled. If you don't want to react on all of these actions, Fabric.js offers individual events such as „rotating“ or „scaling“ to react only to specific actions. fabricjs_beispiel2 Rectangle with Anchors to Move, Scale and Rotate Fabric.js is also able to perform more classical events such as „moving“ and „mouseup“. The method „get()“ enables us to query certain values of any shape. This is useful to determine a certain kind of manipulation.
OwnRect.on("rotating", function() {
 value = OwnRect.get("angle");
});
In this example „get()“ will query the most recent angle of our shape after each rotation.

Animations in a Twinkling

The „animate()“ method of Fabric.js provides an absolutely simple way to put shapes to motion. Determine the property you want changed and optionally add a handful of parameters to define the length and type of the desired animation.
OwnRect.animate("angle", 45, {
  onChange: OwnCanv.renderAll.bind(OwnCanv),
  duration: 1000,
  easing: fabric.util.ease.easeInElastic
});
This example uses „animate()“ to rotate the rectangle to 45 degrees. Never forget „onChange“ as it cares for actually drawing the shape to the canvas during the animation. Forget and no animation will happen. The other parameters „duration“ and „easing“ are optional. They care for length and type of your animation. Fabric.js has its own easing functions to control different motion sequences. Instead of adding an absolute value - the angle in our example - we could also choose to work with relative values. Instead of rotating to 45 degrees, we could also rotate it through 45 degrees.
OwnRect.animate("angle", "+=45", {
  …
});
In this example we rotate the rectangle through 45 degree. Make sure to always enter relative values in quotes.

Free-style Drawing on the Canvas

The simple parameter „isDrawingMode“ enables free-style drawing. The user is now able to use his mouse to draw random shapes on the canvas.
var OwnCanv = new fabric.Canvas("fabricjs", {
  isDrawingMode: 1
});
The visible brush is customizable.
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 10
In this example we customize color and thickness of the brush using „freeDrawingBrush“.

Larger Feature Set and Browser Support

What I presented you today is only a fairly small sub-set of what Fabric.js is able to offer. There are more powerful features such as an SVG parser that takes SVGs and draws them on the canvas. Converting from canvas to SVG is also possible as is the support for mobile devices via touch gestures. Fabric.js is very well documented and a large number of demos get you going in no time. A variety of benchmarks and tests enables you to find out which browser supports which features and how they perform. Fabric.js runs on all current browsers. Even the INternet Explorer is fully supported from version 9 up. For versions 6 to 8 „excanvas“ is used to mimic HTML5 Canvas on older browsers. That way we are able to use at least some of the features in these ancient browsers. The library is published under the terms of the MIT licence. Fabric.js is free for private and commercial use. (dpe)

Denis Potschien

Denis works as a freelance web designer since 2005.

4 comments

  1. This is so fun! I really enjoyed your demo, I really wish I had a use for this now. It would be nice for some presentations but it would also be fun for a kid site. Thanks for sharing!

  2. Does a person have to use colour names or would one have the full hex range? It seems awfully horrible having to remember the name in this day and age with the range used.

  3. Awesome!! I must use it for designing some of my websites. It’s really a source of fun and a great help for the creation of funny sites. :)

Leave a Reply

Your email address will not be published. Required fields are marked *