在fabricjs canvas上实现ClipTo函数

时间:2016-02-05 05:39:29

标签: javascript canvas svg fabricjs

如果我在画布最初加载时硬编码SVG,我可以将画布剪切成形状。现在我尝试使用单击功能执行此操作。挑战在于,因为一切都已加载,当我点击它并加载剪切功能时,它会清除我的画布并留下形状和背景。我正在寻找有关如何实现这一点的想法。我只知道如何在opts new函数中加载fabric.canvas。我怀疑我必须获取当前的画布数据,然后将opts参数应用于它,但我不确定最好的方法。这是我的代码:

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

$('#shape').on('click', function(){

var clipPath = new fabric.Path("M161.469,0.007 C161.469,0.007 214.694,96.481 214.694,96.481 C214.694,96.481 322.948,117.266 322.948,117.266 C322.948,117.266 247.591,197.675 247.591,197.675 C247.591,197.675 261.269,306.993 261.269,306.993 C261.269,306.993 161.469,260.209 161.469,260.209 C161.469,260.209 61.667,306.993 61.667,306.993 C61.667,306.993 75.346,197.675 75.346,197.675 C75.346,197.675 -0.010,117.266 -0.010,117.266 C-0.010,117.266 108.242,96.481 108.242,96.481 C108.242,96.481 161.469,0.007 161.469,0.007", ),    

opts = {
  controlsAboveOverlay: true,
  backgroundColor: 'rgb(255,255,255)',
  clipTo: function (ctx) {
    if (typeof backgroundColor !== 'undefined') {
      ctx.fillStyle = backgroundColor;
      ctx.fillRect(0, 0, 900, 900);
    }
    clipPath.render(ctx);
  }
}
    //obviously this is not going to work
    var reloadShape = JSON.stringify(canvas); 
    canvas.loadFromJSON(reloadShape);
    new fabric.Canvas('imageCanvas', opts);

});

1 个答案:

答案 0 :(得分:1)

您应该在应用程序中初始化一次canvas,否则您将丢失它的内容。

稍后当您选择剪切路径时,请创建并指定clipTo函数。 如果不需要任何其他处理,你也可以只做

canvas.clipTo = clipPath._render;

不创建新功能。

//do this once on your application:
var opts = {
  controlsAboveOverlay: true,
  backgroundColor: 'rgb(255,255,255)',
},
canvas = new fabric.Canvas('imageCanvas', opts);

$('#shape').on('click', function(){

var clipPath = new fabric.Path("M161.469,0.007 C161.469,0.007 214.694,96.481 214.694,96.481 C214.694,96.481 322.948,117.266 322.948,117.266 C322.948,117.266 247.591,197.675 247.591,197.675 C247.591,197.675 261.269,306.993 261.269,306.993 C261.269,306.993 161.469,260.209 161.469,260.209 C161.469,260.209 61.667,306.993 61.667,306.993 C61.667,306.993 75.346,197.675 75.346,197.675 C75.346,197.675 -0.010,117.266 -0.010,117.266 C-0.010,117.266 108.242,96.481 108.242,96.481 C108.242,96.481 161.469,0.007 161.469,0.007", );

  canvas.clipTo = function (ctx) {
    if (typeof backgroundColor !== 'undefined') {
      ctx.fillStyle = backgroundColor;
      ctx.fillRect(0, 0, 900, 900);

    //for clipping _render would be enough.
    // but .render() will allow you to position the path where you want with top and left
    clipPath.render(ctx);
  }
  // display new canvas clipped.
  canvas.renderAll();

});