本文介绍了如何对文档实施黑白滤镜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用fabricjs或任何其他JavaScript库对文档应用黑白过滤器以获得以下结果?

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:

预期结果:

expected result:

推荐答案

以下是解决方案:http://jsfiddle.net/qasLmxvh/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;
function loadImage(src) {

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

    let reader = new FileReader();
    reader.onload = function (e) {
        let imgObj = new Image();
        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);
}
function toGrey() {
    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));
      } else if (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();
}
function applyFilter(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.

这篇关于如何对文档实施黑白滤镜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 21:59