fabric.js在对象内部裁剪路径

时间:2016-01-30 07:48:46

标签: javascript canvas crop fabricjs

enter image description here

您好。我在上面的图像上有一个例子,我尝试使用fabric.js重新定位它。问题是我不能在里面裁剪。谷歌搜索并没有帮助我。我有一个小提琴我的尝试。

var cropCanvas = new fabric.Canvas('crop', {
  backgroundColor: '#000',
});

fabric.Image.fromURL('https://dl.dropboxusercontent.com/u/17055521/face2.jpg', function(pic){

  var rect = new fabric.Rect({
    left: 0,
    top: 0,
    fill: '#000',
    opacity: 0.79,
    width: cropCanvas.width,
    height: cropCanvas.height,
    selectable: false,
    evented : false
  });

  pic.set({
    selectable: false,
    evented : false
  });

  cropCanvas.add(pic);
  cropCanvas.add(rect);
  pic.centerH().setCoords();

  var path = new fabric.Path('M1.398,84.129c3.305,20.461,9.73,50.635,13.591,67.385c2.354,10.212,12.549,23.734,18.51,30.02c4.923,5.191,27.513,23.343,38.34,27.589c18.604,7.295,33.984,4.187,46.012-8.306c12.028-12.493,25.595-34.78,27.954-43.994c2.587-10.105,5.065-26.842,4.313-37.243c-1.036-14.316-14.224-69.332-16.806-79.55c-4.48-17.735-26.246-48.821-80.609-37.668C-1.66,13.514-1.879,63.844,1.398,84.129z');

  path.set({
    originX: 'center',
    originY: 'center',
  });

  rect.set({
    clipTo: function(ctx) {
      path.render(ctx);
    }
  });

  cropCanvas.renderAll();
});

http://jsfiddle.net/codefucker/mqL55m0f/

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您应该将cropTo应用于pic对象,而不是代码中的rect。像这样:

pic.set({
    clipTo: function(ctx) {
      path.render(ctx);
    }
  }); 

点击此处查看更新的小提琴:http://jsfiddle.net/mqL55m0f/1/

<强> UPD

为了获得完全相同的效果 - 您可以添加两次相同的图像,不透明度为0.5。 在这里查看新的小提琴:http://jsfiddle.net/mqL55m0f/2/

//1 - adding bg image
fabric.Image.fromURL(imgURL, function(picBg) {
  picBg.set({
    selectable: false,
    evented: false,
    opacity: 0.6
  });
  cropCanvas.add(picBg);
  picBg.centerH().setCoords();


  //2 - adding main image and mask

  /* here goes all other code */

});