Search code examples
htmlcanvasfabricjs

Canvas - FabricJS - Separate stroke from text edge


I am trying to use FabricJS and Canvas to create a text with stroke on it.

I am able to add stroke to text but i want to separate the text from the stroke, like put a margin on the text and then draw the stroke on the outside of the margin.

I have searched and search and cant find anything.

Any advice?

im wondering if there isnt a way to do this with current libraries, is there a way that i can tap into the scripting that creates the and set the start point +x and +y and do that for the whole time it is drawing around the text.

Any guidance would be greatly appreciated.

canvas = new fabric.Canvas('myc');

var text = new fabric.Text('Test', {
    left: 25,
    top: 25,
    stroke: '#000',
    strokeWidth: 3,
    fill: '#fff',
    fontSize: 75,
    strokeOffset: 5   <--- i need something like this
});
canvas.add(text);

<canvas id="myc"></canvas>

The result would look something like this... enter image description here


Solution

  • You cannot really separate the stroke from the fill. What you can do is this:

    1) Modify the text render function of fabricjs invert the stroke and fill order.

    2) modify the text stroke function to stroke 2 times: 2a) stroke with a strokeWidth of strokeWidth + strokeOffset with color "red" 2b) stroke with a strokeWidth of strokeOffset with backgroundColor ( not sure if you can use transparent to overwrite it)

    3) filling with color will make that effect.

    Note: Maybe using globalCompositeOperation in XOR mode, you can even make it transparent.