Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabricjs How to scale object but keep the border (stroke) width fixed

Tags:

fabricjs

I'm developing a diagram tool based on fabricjs. Our tool has our own collection of shape, which is svg based. My problem is when I scale the object, the border (stroke) scale as well. My question is: How can I scale the object but keep the stroke width fixed. Please check the attachments.
small version

scaled version

Thank you very much!

like image 545
trongd Avatar asked Sep 17 '16 15:09

trongd


1 Answers

I have found what feels like an even better solution, works really well with SVG paths.

You can override fabricjs' _renderStroke method and add ctx.scale(1 / this.scaleX, 1 / this.scaleY); before ctx.stroke(); as shown below.

fabric.Object.prototype._renderStroke = function(ctx) {
    if (!this.stroke || this.strokeWidth === 0) {
        return;
    }
    if (this.shadow && !this.shadow.affectStroke) {
        this._removeShadow(ctx);
    }
    ctx.save();
    ctx.scale(1 / this.scaleX, 1 / this.scaleY);
    this._setLineDash(ctx, this.strokeDashArray, this._renderDashedStroke);
    this._applyPatternGradientTransform(ctx, this.stroke);
    ctx.stroke();
    ctx.restore();
};

You may also need to override fabric.Object.prototype._getTransformedDimensions to adjust the bounding box to account for the difference in size.

Also a more complete implementation would probably add a fabric object property to conditionally control this change for both overridden methods.

like image 91
byoungb Avatar answered Oct 13 '22 18:10

byoungb