Skip to content Skip to sidebar Skip to footer

How To Implement Black And White Filter To A Document

How can I use fabricjs or any other JavaScript library to apply black and white filter to a document to get the following results? input image: expected result: input image: exp

Solution 1:

Here is a solution:http://jsfiddle.net/qasLmxvh/1/

var canvas = new fabric.Canvas('c');

$('.select_image').change(function (e) {
        loadImage(e.target.files[0]);
    });
    is_grayscale = true;
functionloadImage(src) {

    if (!src.type.match(/image.*/)) {
        console.log("The dropped file is not an image: ", src.type);
        return;
    }

    let reader = newFileReader();
    reader.onload = function (e) {
        let imgObj = newImage();
        imgObj.src = e.target.result;
        imgObj.onload = function () {
        let scale = 300 / Math.max(imgObj.naturalWidth, imgObj.naturalHeight);
            let img = new fabric.Image(imgObj, {
                left: 10,
                top: 10,
                scaleX: scale,
                scaleY: scale
            });
            canvas.add(img);
               toGrey();
               img.diry=1;
            canvas.renderAll();
            
            
        };
    };
    reader.readAsDataURL(src);
}
functiontoGrey() {
    let grayscale = new fabric.Image.filters.Grayscale();
    canvas.getObjects().forEach(function (t) {
      if (t.hasOwnProperty('filters')) {
        if (is_grayscale) {
          t.filters.push(grayscale);
        } else {
          t.filters.length = 0;
        }
        t.applyFilters(canvas.renderAll.bind(canvas));
      } elseif (t.hasOwnProperty('fill')) {
        let color_sum = t.fill
        .match(/\d+,\d+,\d+/)[0]
        .split(',')
        .map((i) =>parseInt(i))
        .reduce((a, b) => a + b, 0);

        let gray = color_sum / 3;

        t.setColor(to_rgba({r: gray, g: gray, b: gray, a: 1}));
      }
    });
    applyFilter(1, new f.Contrast({
      contrast: 255
    }));
    canvas.renderAll();
}
functionapplyFilter(index, filter) {
  var obj = canvas.getObjects()[0];
  obj.filters[index] = filter;
  obj.applyFilters(canvas.renderAll.bind(canvas));
}

var f = fabric.Image.filters;

document.getElementById("input").onchange = function() {
  applyFilter(1, new f.Contrast({
    contrast: parseInt(document.getElementById("input").value,10)
  }));
};

Basically I applied a grayscale effect and after this a contrast effect. enter image description here

Post a Comment for "How To Implement Black And White Filter To A Document"