在 fabricjs 上实现 ClipTo 函数 canvas

Implementing ClipTo function on fabricjs canvas

如果我在 canvas 最初加载时对 SVG 进行硬编码,我可以将我的 canvas 剪辑成一个形状。现在我正在尝试使用点击功能来做到这一点。挑战在于,由于所有内容都已加载,当我单击它并加载剪辑功能时,它会清除我的 canvas 并只留下形状和背景。我正在寻找有关如何实现它的想法。我只知道如何在 new fabric.canvas 函数中加载 opts。我怀疑我必须获取当前的 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);

});

您应该在您的应用程序中只初始化 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();

});