Hi I'm quite new with fabric.js.
I need to convert my image to a pure black and white image. So I want to have just pure black (#000000) and white (#ffffff) in my picture (not grayscale!)
Does somebody know's how I can do that with fabric.js?
I use fabric.js (Version 1.7.16) with angular2.
Feel free to ask if I forgot to write some important information :)
I tried it with a "workaround". First to make it grayscaled, then remove all the white parts and at the end add a Tint-Filter to make the rest black. With that i don't really have the white parts but when I use a White background i looks like.
this.imageObject.filters[4] = new fabric.Image.filters.Grayscale();
this.imageObject.filters[5] = new fabric.Image.filters.RemoveWhite({
threshold: this.removeWhiteThreshold.toString(),
distance: 40
});
this.imageObject.filters[6] = new fabric.Image.filters.Tint({
color: '#000000',
opacity: 1
});
this.imageObject.applyFilters(this.canvas.renderAll.bind(this.canvas));
It works but I hope there are some better solutions...
Filters are now supported on the current stable version, read the filters docs
If you want to convert your image to pure black / white you will need to use the BlackWhite
filter:
Example provided in the docs:
var filter = new fabric.Image.filters.BlackWhite();
object.filters.push(filter);
object.applyFilters();
However, using this filter will not be enough to convert the image to only black and white tones as you may expect, some minor gray tones can persist depending on the original contrast and colors of the image, check the demo example.
If you really need only white (#FFF) and black (#000) tones, a combination of this filters should do the work: BlackWhite
, Contrast
, Grayscale
// Main filter
var bw = new fabric.Image.filters.BlackWhite();
object.filters.push(bw);
// Remove minor gray tones ( #000, #FFF only )
var gs = new fabric.Image.filters.Grayscale();
object.filters.push(gs);
// Set contrast to max value
var contrast = new fabric.Image.filters.Contrast({ contrast: 1});
object.filters.push(contrast);
// Don forget to apply the filters
object.applyFilters();
Deprecated answer
Image Filters fabricjs 2.0 beta
The blackWithe
filter is supported in version 2.0 (beta)
// manually initialize 2 filter backend to give ability to switch:
var webglBackend = new fabric.WebglFilterBackend();
var canvas2dBackend = new fabric.Canvas2dFilterBackend()
fabric.filterBackend = webglBackend;
// Your code...
this.imageObject.filters[0] = new fabric.Image.filters.blackWhite()