Fill 目前不是图像的公认属性。造成这种情况的一个原因是,在不透明的图像后面绘制纯色会导致该颜色沿图像边缘出现。由于图像类继承了 Object 类的默认填充颜色rgb(0,0,0)(黑色),这意味着每个图像都会有这样的轮廓,除非手动将填充颜色更改为transparent。
但是,如果您确实希望您的图像尊重 fill 属性,您可以通过简单地覆盖 Image 类的 _renderFill 方法来做到这一点。只需确保将不需要背景颜色的任何图像的填充设置为transparent。
fabric.Image.prototype._renderFill = function(ctx) {
var elementToDraw = this._element;
if (!elementToDraw) {
return;
}
var scaleX = this._filterScalingX, scaleY = this._filterScalingY,
w = this.width, h = this.height, min = Math.min, max = Math.max,
// crop values cannot be lesser than 0.
cropX = max(this.cropX, 0), cropY = max(this.cropY, 0),
elWidth = elementToDraw.naturalWidth || elementToDraw.width,
elHeight = elementToDraw.naturalHeight || elementToDraw.height,
sX = cropX * scaleX,
sY = cropY * scaleY,
// the width height cannot exceed element width/height, starting from the crop offset.
sW = min(w * scaleX, elWidth - sX),
sH = min(h * scaleY, elHeight - sY),
x = -w / 2, y = -h / 2,
maxDestW = min(w, elWidth / scaleX - cropX),
maxDestH = min(h, elHeight / scaleY - cropY);
//fill override start
ctx.beginPath();
ctx.rect(x, y, sW, sH);
ctx.fill();
//fill override end
elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);
};