Fabric.js resize stroke on scaling
Customisation of fabric.js to resize an interactive fabric.Object by adjusting its height and width rather than simply scaling it (which distorts the stroke width).
by vstefani
HTML
<canvas id="canvas" class="canvas" ></canvas>
CSS
.canvas {
border: 1px solid Black;
}
TypeScript
var canvas = new fabric.Canvas('canvas');
canvas.setWidth(500);
canvas.setHeight(500);
var myText = new fabric.Textbox("Some text", {
width: 100,
height: 100,
top: 100,
left: 100,
fontSize: 20,
textAlign: 'center',
fontFamily: 'Arial',
padding: 2,
});
canvas.add(myText);
let lastHeight: number;
const updateTextSize = () => {
const controlPoint = myText.__corner;
if (controlPoint && controlPoint !== 'mr' && controlPoint !== 'ml') {
lastHeight = myText.height * myText.scaleY;
}
myText.set({
height: lastHeight || myText.height,
scaleY: 1,
});
};
myText.on('scaling', updateTextSize);
myText.on('editing:entered', updateTextSize);
myText.on('text:changed', updateTextSize);