旋转对象时Fabricjs图像问题

时间:2018-03-19 04:02:11

标签: fabricjs

需要帮助。旋转图像时,我认为旋转点已更改,但在鼠标上:向上图像被正确剪切到边界框。我不知道为什么但是使用Fabricjs1.7代码工作正常但是当我将它更新为Fabricjs2.2.0时,我开始遇到这个问题。我认为计算有所改变,但我似乎无法弄清楚

这是旋转时的屏幕截图 screen shot 2018-03-19 at 11 34 03 am

下面的屏幕截图是旋转后的图像。 screen shot 2018-03-19 at 11 37 49 am

这是一个有效的jsfiddle link

// Do some initializing stuff
fabric.Object.prototype.set({
  transparentCorners: false,
  cornerColor: 'rgba(102,153,255,0.5)',
  cornerSize: 12,
  padding: 5,
  allowTouchScrolling: false
});

// initialize fabric canvas and assign to global windows object for debug
var canvas = window._canvas = new fabric.Canvas('c');
canvas.setBackgroundColor('#FFCDD2');


// Set bounding box
let boundingBox = new fabric.Rect({
      NUM_FRACTION_DIGITS: 9,
      originX: 'left',
      originY: 'top',
      width: 300,
      height: 400,
      fill: 'rgba(255,255,255,0.3)',
      selectable: false,
      strokeWidth: 1,
      crossOrigin: 'anonymous',
    })
canvas.centerObject(boundingBox)    
canvas.setOverlayImage(boundingBox, canvas.renderAll.bind(canvas))
// END Set bounding box


// Add Image clip to bounding box
fabric.Image.fromURL('https://images.unsplash.com/photo-1498622601663-8277ceda5cb6?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=8e3fd47325de4950e9a709bcb3591dc8&auto=format&fit=crop&w=791&q=80', imgObj => {
  imgObj.set({
    strech : false,
    scaleX: canvas.width / imgObj.width,
    scaleY: canvas.height / imgObj.height,
  })

// Computation for new dimension of the image
let wrh = imgObj.width / imgObj.height;
let newWidth = boundingBox.width;
let newHeight = newWidth / wrh;
if (newHeight > boundingBox.height) {
  newHeight = boundingBox.height;
  newWidth = newHeight * wrh;
}

imgObj.scaleToWidth(newWidth)
imgObj.scaleToHeight(newHeight)
imgObj.clipTo = this.clipToBoundingBox.bind(imgObj, boundingBox)
canvas.centerObject(imgObj)    
canvas.add(imgObj);
})


// Function for Image clipping to bounding box
clipToBoundingBox = function(box, ctx) {
    this.setCoords();
    let clipRect = box
    var scaleXTo1 = (1 / this.scaleX);
    var scaleYTo1 = (1 / this.scaleY);
    ctx.save();

    var ctxLeft = -( this.width / 2 ) + clipRect.strokeWidth;
    var ctxTop = -( this.height / 2 ) + clipRect.strokeWidth;
    var ctxWidth = clipRect.width - clipRect.strokeWidth;
    var ctxHeight = clipRect.height - clipRect.strokeWidth;

    ctx.translate( ctxLeft, ctxTop );

    ctx.rotate(this.angle * -1 * (Math.PI / 180))
    ctx.scale(scaleXTo1, scaleYTo1);
    // ctx.globalCompositeOperation = 'destination-over';
    ctx.beginPath();
    ctx.rect(
        clipRect.left - this.left,
        clipRect.top - this.top,
        clipRect.width,
        clipRect.height
    );
    ctx.closePath();
    ctx.restore();
  }
canvas {
  border: 1px solid #999;
}

button {
  margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.2/fabric.min.js"></script>
<canvas id="c" width="450" height="600"></canvas>

0 个答案:

没有答案