以 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.