如何使用fabric.js添加图像过滤器

时间:2016-04-06 17:56:54

标签: javascript fabricjs

我希望能够将图像过滤器添加到用户本地上传的图像中。本地上传工作正常但图像未转换为灰度。这是我的代码:

$("#file_input").change(function (e) {

    var URL = window.webkitURL || window.URL;
    var url = URL.createObjectURL(e.target.files[0]);
    img = new Image();      
    img.src = url;
    img.onload = function () {
        ctx = document.getElementById('myCanvas').getContext("2d");

    ///
     fabric.Image.fromURL( img.src, function( img ) {

  // add filter
  img.filters.push(new fabric.Image.filters.Grayscale());

  // apply filters and re-render canvas when done
  img.applyFilters(ctx.renderAll.bind(ctx));

  // add image onto canvas
  ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
});
    }

    ///
});

1 个答案:

答案 0 :(得分:5)

我不明白你的代码。但我认为你想要这样的东西..

$("#file_input").change(function (e) {

    var URL = window.webkitURL || window.URL;
    var url = URL.createObjectURL(e.target.files[0]);
    img = new Image();      
    img.src = url;
    img.onload = function () {
        var canvas = new fabric.Canvas("c");

    ///
     fabric.Image.fromURL( img.src, function( img ) {

  // add filter
  img.filters.push(new fabric.Image.filters.Grayscale());

  // apply filters and re-render canvas when done
  img.applyFilters(canvas.renderAll.bind(canvas));

  // add image onto canvas
  img.width = canvas.width;
  img.height = canvas.height;
  canvas.add(img);
});
    }

    ///
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<input type="file" id="file_input"/>
<canvas id="c"></canvas>