0


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

像这个视频这样的预期结果:
比例照片

这是我的代码:

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];函数中的解决方法;请注意,上下文原点位于对象的中心点(不是左/上角)

4

0 回答 0