2017-06-20 359 views
0

关于使用Fabric.js 1.7.3,裁剪图像时我注意到了一个奇怪的现象。从本质上讲,我已经设置了图像中的clipTo方法在图像的中心只显示一个小广场:Fabric.js:裁剪后的选择框图像

The image's selection box still takes up the original size rather than the cropped size

然而,问题是图像的选择框仍然采用了原来的大小,而比裁剪的大小。当点击图片时,我会希望角落紧挨着图片的边缘;同样,只有当我点击裁剪图片时才能激活选择。

一个可能的解决方案包括将图像的裁剪部分导出为base64,删除旧图像并添加裁剪版本。然而,这是不切实际的,感觉像是过度杀伤。有没有一种方法可以简单地调整选择框来尊重裁剪的尺寸?

+0

请包括迄今为止完成的工作。 – Observer

回答

1

要建立在AndreaBogazzi的答案,这是我在我重写_render方法完整的解决方案。每当我创建一个图像,我添加了一个“sizeMode”属性,它告诉_render究竟是如何把它漆成:

fabric.Image.prototype._render = function(ctx, noTransform) { 
    /* This is the default behavior. I haven't modified anything in this part. */ 
    let x, y, imageMargins = this._findMargins(), elementToDraw; 

    x = (noTransform ? this.left : -this.width/2); 
    y = (noTransform ? this.top : -this.height/2); 

    if (this.meetOrSlice === 'slice') { 
     ctx.beginPath(); 
     ctx.rect(x, y, this.width, this.height); 
     ctx.clip(); 
    } 

    if (this.isMoving === false && this.resizeFilters.length && this._needsResize()) { 
     this._lastScaleX = this.scaleX; 
     this._lastScaleY = this.scaleY; 
     elementToDraw = this.applyFilters(null, this.resizeFilters, this._filteredEl 
      || this._originalElement, true); 
    } 
    else { 
     elementToDraw = this._element; 
    } 

    /* My changes begin here. */ 
    if (elementToDraw && elementToDraw.naturalHeight > 0) { 
     if (this.sizeMode === BadgingImageSizeMode.CenterImage) { 
      drawCenterImage.apply(this, [ctx, elementToDraw, imageMargins, x, y]); 
     } else { 
      // Default _render behavior 
      ctx.drawImage(elementToDraw, 
       x + imageMargins.marginX, 
       y + imageMargins.marginY, 
       imageMargins.width, 
       imageMargins.height); 
     } 
    } 

    /* And they finish here. */ 
    this._stroke(ctx); 
    this._renderStroke(ctx); 
}; 

我已经定义了drawCenterImage功能是在这里:

const drawCenterImage = function(ctx, elementToDraw, imageMargins, x, y) { 
    const sx = (elementToDraw.naturalWidth - this.width)/2; 
    const sy = (elementToDraw.naturalHeight - this.height)/2; 
    ctx.drawImage(elementToDraw, 
     sx, 
     sy, 
     imageMargins.width, 
     imageMargins.height, 
     x + imageMargins.marginX, 
     y + imageMargins.marginY, 
     imageMargins.width, 
     imageMargins.height); 
}; 

这枚对图像进行居中处理(正如我原来的问题),对ctx.drawImage的不同调用将导致不同的效果。 Here is the documentation for the drawImage method

1

fabricjs中实际上没有cropTo方法。

有一个clipTo方法,其行为如您所述。

裁剪不是基本的fabricjs功能。使用2.0版本可能会更容易,但现在获得它的唯一方法是对render方法进行子类化并完全由您自己完成。

  • 使用ctx.drawImage(this._element,sx,sy,sw,sh,dx,dy,dw,dh)公式。
  • 十个分量自己inforamtion的作物被SX,SY,SW代表,SH
+0

谢谢!并道歉 - 我写了“cropTo”而不是“clipTo”;我显然是指第二个。我已经编辑了我的问题来反映这一点。 – unpollito