0

是否可以使用fabric js屏蔽两个图像?

例如:我有一个彩色的形状(心)。我有另一个图像,我想将它掩盖在心脏上,以便新图像仅显示为心脏。我可以移动第二张上传的图像并调整大小以获得该心脏所需的区域。

这两个图像都是用户上传的图像,而不是使用织物创建的矩形或正方形之一,并且像此处的 jsfiddle 示例中那样拖动和调整图像大小。

http://jsfiddle.net/Jagi/efmbrm4v/1/

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

var clippingRect = new fabric.Rect({
    left: 0,
    top: 0,
    width: 100,
    height: 100,
    fill: 'transparent',
    opacity: 1
});
canvas.add(clippingRect);

function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        var img = new Image();
        img.onload = function () {

            var instanceWidth, instanceHeight;

            instanceWidth = img.width;
            instanceHeight = img.height;

            var imgInstance = new fabric.Image(img, {
                width: instanceWidth,
                height: instanceHeight,
                top: (canvas.getHeight() / 2 - instanceHeight / 2),
                left: (canvas.getWidth() / 2 - instanceWidth / 2),
                originX: 'left',
                originY: 'top'
            });
            canvas.add(imgInstance);
            imgInstance.clipTo = function (ctx) {
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.rect(
    100, 100,
    200, 200
  );
  ctx.restore();
            };
            canvas.renderAll();
        };
        img.src = event.target.result;
    };
    reader.readAsDataURL(e.target.files[0]);
}

我正是需要这个,但有两个自定义图像(用户上传的图像)。

4

1 回答 1

0

也许这个伪示例将为您提供如何使用路径添加遮罩的指针,而不仅仅是矩形。

//adding main image and mask
fabric.Image.fromURL(IMAGE_URL_HERE, function(pic) {
  canvas.add(pic);
  //positioning image, if needed
  pic.centerH().setCoords();

  //adding path, may be a heart or any other in your case
  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');

//positioning path, if needed
path.set({
  originX: 'center',
  originY: 'center',
});

//masking img with path
pic.set({
  clipTo: function(ctx) {
    path.render(ctx);
  }
});

  canvas.renderAll();
});

完整的演示(虽然只是另一种情况):http: //jsfiddle.net/mqL55m0f/2/

于 2016-02-01T19:58:54.183 回答