Reputation: 53
I'd like to figure out what are the units of lineHeight
and charSpacing
properties in fabric.js and how they are calculated.
In the documentation I couldn't find my answer or maybe I don't understand how it works exactly.
lineHeight :
http://fabricjs.com/docs/fabric.Text.html#lineHeight
charSpacing:
http://fabricjs.com/docs/fabric.Text.html#charSpacing
Upvotes: 5
Views: 1348
Reputation: 4998
Fabric's lineHeight corresponds to CSS line-height
's unitless value, which means it's a multiplier of the text's font size. The actual formula fabric.js uses to calculate line's height (in text.getHeightOfLine()
method) is
maxHeight * this.lineHeight * this._fontSizeMult
where:
maxHeight
is the font size of the largest character in the given line;
_fontSizeMult
is a constant text line proportion to font size (in pixels) that equals 1.13
by default. Fabric.js uses _fontSizeMult
multiplier to leave a little bit of extra room for underline and overline. So you might need to divide text.lineHeight
by fabric.Text.prototype._fontSizeMult
for this value to be consistent between fabric.js and CSS.
Fabric's charSpacing corresponds to CSS letter-spacing
's em
units divided by 1000. I.e. a fabric.Text
with charSpacing = 500
will look more or less the same as a text with letter-spacing: .5em;
.
Here's a comparison of fabric.js text (black) and HTML text (red):
const canvas = new fabric.StaticCanvas('c')
canvas.add(new fabric.Text('text\ntext', {
fontSize: 20,
left: 0,
top: 8,
lineHeight: 2 / fabric.Text.prototype._fontSizeMult
}))
canvas.add(new fabric.Text('text', {
fontSize: 20,
left: 0,
top: 80,
charSpacing: 500
}))
.row {
display: flex;
flex-direction: row;
}
.col {
display: flex;
flex-direction: column;
}
.text {
font-size: 20px;
color: red;
}
.text1 {
line-height: 2;
}
.text2 {
letter-spacing: .5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.6.0/fabric.js"></script>
<div class="row">
<div class="col">
<canvas id="c" width="80" height="100"></canvas>
<span class="text text2">text</span>
</div>
<div class="col text text1">
<span>text</span>
<span>text</span>
</div>
</div>
Upvotes: 10