如何在FabricJS中缩放ClipTo区域?

时间:2019-01-11 07:58:13

标签: html5-canvas fabricjs fabricjs2


我有一个矩形,可以使用ClipPath制作Image的视口,并且我希望在用户缩放覆盖矩形以制作蒙版时在Image的clipTo中缩放区域。

像此视频一样的预期结果:
scale photo

这是我的代码:

var canvas;

var canvasObject = document.getElementById("editorCanvas");

// set canvas equal size with div
$(canvasObject).width($("#canvasContainer").width());
$(canvasObject).height($("#canvasContainer").height());

canvas = new fabric.Canvas('editorCanvas', {
  backgroundColor: 'white',
  selectionLineWidth: 2,
  width: $("#canvasContainer").width(),
  height: $("#canvasContainer").height()
});

var newImage = new fabric.Image();
canvas.add(newImage);

newImage.setSrc('https://futushigame.firebaseapp.com/photo-small.jpg', function(img) {

  img.top = 50;
  img.left = 50;
  img.selectable = false;

  var rect = new fabric.Rect({
    width: img.width * 0.5,
    height: img.height * 0.5,
    left: img.left + 10,
    top: img.top + 10,
    // fill: 'transparent'
    fill: 'blue',
    opacity: 0.2,
    lockMovementX: true,
    lockMovementY: true
  });
  rect.setControlsVisibility({
    mb: false,
    ml: false,
    mr: false,
    mt: false
  });

  canvas.add(rect);

  img.clipTo = function(ctx) {
    img.scaleX = rect.scaleX;
    img.scaleY = rect.scaleY;

    var rectWidth = rect.width;
    var rectHeight = rect.height;

    var localPoint = img.toLocalPoint(new fabric.Point(rect.left, rect.top));
    ctx.rect(-img.width / 2 + localPoint.x, -img.height / 2 + localPoint.y, rectWidth, rectHeight);
  }

  rect.on('scaling', objectScale);
  // rect.on('moving', objectMoving);

  img.set('dirty', true);
  canvas.renderAll();
  setObjectCoords();

});

setObjectCoords();

function objectScale(otp) {
  if (otp.transform.action == "scale") {

  }
  console.log('scaling' + otp);
}

function setObjectCoords() {
  canvas.forEachObject(function(object) {
    object.setCoords();
  });
}
#canvasContainer {
  width: 100%;
  height: 100vh;
  background-color: gray;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script>

<div id="canvasContainer">
  <canvas id="editorCanvas"></canvas>
</div>

谢谢!

clipTo:function
确定对象裁剪的函数(上下文作为第一个参数传递)。如果您使用代码压缩,则可以缩小/忽略ctx参数,您应该在函数中将其用作解决方法var ctx = arguments[0];;请注意,上下文原点位于对象的中心点(不是左/上角)

0 个答案:

没有答案