Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Controlling Border Width Scaling in Fabric.js

Tech 2

In Fabric.js, scaling an object tyipcally scales all its visual properties, including its border (stroke) width. This behavior can be undesirable when you need to maintain a consistent border thickness regardless of the object's size. The library provides the strokeUniform property to control this.

Set the strokeUniform property to true on an object to decouple its stroke width from its scale transformations. When the object is scaled, the stroke will retain the pixel width defined by strokeWidth.

const canvasElement = document.getElementById('canvas');
const fabricCanvas = new fabric.Canvas(canvasElement);

const rectangle = new fabric.Rect({
  left: 100,
  top: 100,
  width: 150,
  height: 100,
  fill: 'lightblue',
  stroke: 'navy',
  strokeWidth: 8,
  strokeUniform: true // Border width remains fixed during scaling
});

fabricCanvas.add(rectangle);

In this example, the rectangle's border is initially 8 pixels wide. Scaling the rectangle up or down will not change this border width; it will stay at 8 pixels.

The default value of strokeUniform is false. When left as false, the stroke width scales proportionally with the object, becoming thicker when enlarged and thinner when shrunk.

Limitation with Text Objects

A notable limitation is that the strokeUniform property does not affect fabric.Text objects or its subclasses like fabric.Textbox. For text elements, the stroke width will always scale with the object.

const sampleText = new fabric.Text('Sample Text', {
  left: 50,
  top: 50,
  fontSize: 40,
  fill: 'coral',
  stroke: 'darkred',
  strokeWidth: 3,
  strokeUniform: true // This setting has no effect on text objects
});

fabricCanvas.add(sampleText);
// Scaling this text will also scale its stroke width.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.