Trimantra Software Solution Trimantra Software Solution - 1 year ago 467
Javascript Question

FabricJS CurvedText object (extended) is not getting displayed on updating spacing and text properties

I have updated fabric CurvedText extension because of our requirement is something different. I want to set auto spacing between characters as it covers full circle. I got solutions after updating code in fabric CurvedText extension. While I am changing text of the object (on keyup event of textbox), I recalculate spacing and setting that spacing and text via setText and set("spacing", val) properties. In some situations, I can not see object on canvas but I can see pointer of the object on canvas mouse hover effect.

Remove characters from the textbox in this snippet and object will be hide after you will remove some characters.
Same thing happens when I add characters in the textbox.

Updated curved text extension.

var radius = 100;
var circum = Math.floor(2 * Math.PI * radius);
var spacing = 0;
var fontFamily = 'Arial';
var fontSize = 30;

var text;
var lineHeight = 1;
var topa = 100;
var left = 200;

var char = 0;
var textWidth = 0;

var obj;
var canvas, ctx;

$(document).ready(function () {

canvas = new fabric.Canvas('c');
ctx = canvas.getContext("2d");

text = $('#uppertext').val();


var upperText = new fabric.CurvedText(text, {
radius: radius,
top: topa,
left: left,
fontFamily: fontFamily,
fontSize: fontSize,
lineHeight: lineHeight,
spacing: spacing,
originX: 'center',
hasControls: true,
hasBorders: true,
selectable: true,
textAlign: 'center'

$('#uppertext').on('keyup', function () {
text = $('#uppertext').val();

if (spacingOperation())

function spacingOperation() {
textWidth = getTotalTextWidth();
spacing = 0;
textWidth = getTotalTextWidth();
var diff = Math.ceil(circum - textWidth);
spacing = Math.ceil(diff / char);
return true;

function getTotalTextWidth()
ctx.font = fontSize + 'px ' + fontFamily;
char = text.length;
txtWidth = Math.ceil(ctx.measureText(text).width + (spacing * char));
return txtWidth;

function setObjects() {
obj = canvas.getActiveObject();

function setProps() {
obj.set('spacing', spacing);

<!DOCTYPE html>
<script src=""></script>
<script src=""></script>
<script src=""></script>
<div class="row">
<div class="row canvas-container" style="width: 50%; float: left;">
<canvas id="c" width="400" height="400" style="border:1px dotted #000;"></canvas>
<div class="row" style="float: left; width: 50%; height: 150px;">
Upper Text : <input type="text" id="uppertext" value="UTXXXXXXXXXXXXXUTXXXXXaaaaaaaawwwwwwwwwXXXXXXXXUTXXXXXXXXXXXXXUTXXXXXXXXXXXXX" />

Answer Source

I have looked into you code and changed one line in fabric curvedtext extension from ctx = new fabric.Canvas('c').getContext('2d'); to ctx = fabric.util.createCanvasElement().getContext('2d'); and it is working perfectly fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download