Fabric.js:如何将滤镜应用于整个画布?

时间:2013-04-12 15:42:43

标签: javascript svg fabricjs

虽然我已经看到了几种将滤镜应用于图像的方法,但我还没有看到任何将布料滤镜应用于整个画布的方法。

图像滤镜功能的示例 来自http://fabricjs.com/fabric-intro-part-2/

fabric.Image.fromURL('pug.jpg', 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
  canvas.add(img);
});

我想传递整个canvas元素和里面的所有形状,并将过滤器应用于所有。

我是否需要展平画布,将其转换为图像,然后应用滤镜?用户可以在展平和应用之后进行更改,然后必须将画布分离回“图层”,以便用户可以继续编辑。

GreyScale过滤器的文档。 http://fabricjs.com/docs/symbols/fabric.Image.filters.Grayscale.html

1 个答案:

答案 0 :(得分:1)

结束必须将画布转换为图像,然后从html中的隐藏图像添加它。

标记中的

<img class="test-image" src="" style="display:none;" />

var addFilterToCanvas = function (name) {

    // remove controls on filter click, have to do it before it creates the image to
    // get rid of shape controls
    canvas.deactivateAll()

    var overlayImageUrl = canvas.toDataURL('png');
    $('.test-image').attr('src', overlayImageUrl);
    var filterImageUrl = $('.test-image').attr('src');


            fabric.Image.fromURL(filterImageUrl, function(img) {

            // add filter
            switch (name) {
                case 'Grayscale':
                    img.filters.push(new fabric.Image.filters.Grayscale());
                break;
                case 'Sepia':
                    img.filters.push(new fabric.Image.filters.Sepia());
                break;
                case 'Sepia2':
                    img.filters.push(new fabric.Image.filters.Sepia2());
                break;
                case 'Invert':
                    img.filters.push(new fabric.Image.filters.Invert());
                break;
            }

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

                // center image 
                img.top = canvas.getHeight() / 2;
                img.left = canvas.getWidth() / 2;

                // add image onto canvas
                canvas.add(img);
            });

        // remove controls on after filter applied to get rid of
        // new image resize controls
        canvas.deactivateAll().renderAll();

}