Curved text in Fabric.js elements

Related searches

How can I apply "HTML5 Canvas Text Along Arc Path" in context of Fabric.js element?

http://www.html5canvastutorials.com/labs/html5-canvas-text-along-arc-path/ using above link we can show curved text , how can i achieve this in fabric.js ??

JS fiddle :: http://jsfiddle.net/E5vnU/

      function drawTextAlongArc(context, str, centerX, centerY, radius, angle) {
    var len = str.length, s;
    context.save();
    context.translate(centerX, centerY);
    context.rotate(-1 * angle / 2);
    context.rotate(-1 * (angle / len) / 2);
    for(var n = 0; n < len; n++) {
      context.rotate(angle / len);
      context.save();
      context.translate(0, -1 * radius);
      s = str[n];
      context.fillText(s, 0, 0);
      context.restore();
    }
    context.restore();
  }
  var canvas = document.getElementById('myCanvas'), 
    context = canvas.getContext('2d'),
    centerX = canvas.width / 2,
    centerY = canvas.height - 30,
    angle = Math.PI * 0.8,
    radius = 150;

  context.font = '30pt Calibri';
  context.textAlign = 'center';
  context.fillStyle = 'blue';
  context.strokeStyle = 'blue';
  context.lineWidth = 4;
  drawTextAlongArc(context, 'Text along arc path', centerX, centerY, radius, angle);

  // draw circle underneath text
  context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
  context.stroke();

I just finished implementing curved text.

https://github.com/EffEPi/fabric.curvedText

You can use it like any other fabric.Text object.

fabric.js: Curved Text - JSFiddle, TextCurved object for fabric.js. 5. * @author Arjan Haverkamp (av01d). 6. * @ date January 2018. 7. */. 8. . 9. fabric.TextCurved = fabric.util.createClass(fabric. Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.

Here's my implementation of curved text (text drawn along a circular path). https://jsfiddle.net/av01d/4p0syzw3/

(function(fabric) {

/*
 * CurvedText object for fabric.js
 * @author Arjan Haverkamp (av01d)
 * @date January 2018
 */

fabric.CurvedText = fabric.util.createClass(fabric.Object, {
   type: 'curved-text',
   diameter: 250,
   kerning: 0,
   text: '',
   flipped: false,
   fill: '#000',
   fontFamily: 'Times New Roman',
   fontSize: 24, // in px
   fontWeight: 'normal',
   fontStyle: '', // "normal", "italic" or "oblique".
    cacheProperties: fabric.Object.prototype.cacheProperties.concat('diameter', 'kerning', 'flipped', 'fill', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'strokeStyle', 'strokeWidth'),
   strokeStyle: null,
   strokeWidth: 0,

   initialize: function(text, options) {
      options || (options = {});
      this.text = text;

      this.callSuper('initialize', options);
      this.set('lockUniScaling', true);

      // Draw curved text here initially too, while we need to know the width and height.
      var canvas = this.getCircularText();
      this.cropCanvas(canvas);
      this.set('width', canvas.width);
      this.set('height', canvas.height);
   },

   _getFontDeclaration: function()
   {
      return [
         // node-canvas needs "weight style", while browsers need "style weight"
         (fabric.isLikelyNode ? this.fontWeight : this.fontStyle),
         (fabric.isLikelyNode ? this.fontStyle : this.fontWeight),
         this.fontSize + 'px',
         (fabric.isLikelyNode ? ('"' + this.fontFamily + '"') : this.fontFamily)
      ].join(' ');
   },

   cropCanvas: function(canvas)
   {
      var ctx = canvas.getContext('2d'),
         w = canvas.width,
         h = canvas.height,
         pix = {x:[], y:[]}, n,
         imageData = ctx.getImageData(0,0,w,h),
         fn = function(a,b) { return a-b };

      for (var y = 0; y < h; y++) {
         for (var x = 0; x < w; x++) {
            if (imageData.data[((y * w + x) * 4)+3] > 0) {
               pix.x.push(x);
               pix.y.push(y);
            }
         }
      }
      pix.x.sort(fn);
      pix.y.sort(fn);
      n = pix.x.length-1;

      w = pix.x[n] - pix.x[0];
      h = pix.y[n] - pix.y[0];
      var cut = ctx.getImageData(pix.x[0], pix.y[0], w, h);

      canvas.width = w;
      canvas.height = h;
      ctx.putImageData(cut, 0, 0);
   },

   // Source: http://jsfiddle.net/rbdszxjv/
   getCircularText: function()
   {
      var text = this.text,
         diameter = this.diameter,
         flipped = this.flipped,
         kerning = this.kerning,
         fill = this.fill,
         inwardFacing = true,
         startAngle = 0,
         canvas = fabric.util.createCanvasElement(),
         ctx = canvas.getContext('2d'),
         cw, // character-width
         x, // iterator
         clockwise = -1; // draw clockwise for aligned right. Else Anticlockwise

      if (flipped) {
         startAngle = 180;
         inwardFacing = false;
      }

      startAngle *= Math.PI / 180; // convert to radians

      // Calc heigt of text in selected font:
      var d = document.createElement('div');
      d.style.fontFamily = this.fontFamily;
      d.style.fontSize = this.fontSize + 'px';
      d.style.fontWeight = this.fontWeight;
      d.style.fontStyle = this.fontStyle;
      d.textContent = text;
      document.body.appendChild(d);
      var textHeight = d.offsetHeight;
      document.body.removeChild(d);

      canvas.width = canvas.height = diameter;
      ctx.font = this._getFontDeclaration();

      // Reverse letters for center inward.
      if (inwardFacing) { text = text.split('').reverse().join('') };

      // Setup letters and positioning
      ctx.translate(diameter / 2, diameter / 2); // Move to center
      startAngle += (Math.PI * !inwardFacing); // Rotate 180 if outward
      ctx.textBaseline = 'middle'; // Ensure we draw in exact center
      ctx.textAlign = 'center'; // Ensure we draw in exact center

      // rotate 50% of total angle for center alignment
      for (x = 0; x < text.length; x++) {
         cw = ctx.measureText(text[x]).width;
         startAngle += ((cw + (x == text.length-1 ? 0 : kerning)) / (diameter / 2 - textHeight)) / 2 * -clockwise;
      }

      // Phew... now rotate into final start position
      ctx.rotate(startAngle);

      // Now for the fun bit: draw, rotate, and repeat
      for (x = 0; x < text.length; x++) {
         cw = ctx.measureText(text[x]).width; // half letter
         // rotate half letter
         ctx.rotate((cw/2) / (diameter / 2 - textHeight) * clockwise);
         // draw the character at "top" or "bottom"
         // depending on inward or outward facing

         // Stroke
         if (this.strokeStyle && this.strokeWidth) {
            ctx.strokeStyle = this.strokeStyle;
            ctx.lineWidth = this.strokeWidth;
            ctx.miterLimit = 2;
            ctx.strokeText(text[x], 0, (inwardFacing ? 1 : -1) * (0 - diameter / 2 + textHeight / 2));
         }

         // Actual text
         ctx.fillStyle = fill;
         ctx.fillText(text[x], 0, (inwardFacing ? 1 : -1) * (0 - diameter / 2 + textHeight / 2));

         ctx.rotate((cw/2 + kerning) / (diameter / 2 - textHeight) * clockwise); // rotate half letter
      }
      return canvas;
   },

   _set: function(key, value) {
      switch(key) {
         case 'scaleX':
            this.fontSize *= value;
            this.diameter *= value;
            this.width *= value;
            this.scaleX = 1;
            if (this.width < 1) { this.width = 1; }
            break;

         case 'scaleY':
            this.height *= value;
            this.scaleY = 1;
            if (this.height < 1) { this.height = 1; }
            break;

         default:
            this.callSuper('_set', key, value);
            break;
      }
   },

   _render: function(ctx)
   {
      var canvas = this.getCircularText();
      this.cropCanvas(canvas);

      this.set('width', canvas.width);
      this.set('height', canvas.height);

      ctx.drawImage(canvas, -this.width / 2, -this.height / 2, this.width, this.height);

      this.setCoords();
   },

   toObject: function(propertiesToInclude) {
      return this.callSuper('toObject', ['text', 'diameter', 'kerning', 'flipped', 'fill', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'strokeStyle', 'strokeWidth'].concat(propertiesToInclude));
   }
});

fabric.CurvedText.fromObject = function(object, callback, forceAsync) {
   return fabric.Object._fromObject('CurvedText', object, callback, forceAsync, 'curved-text');
};

})(typeof fabric !== 'undefined' ? fabric : require('fabric').fabric);

Curve Text Feature [$200] � Issue #729 � fabricjs/fabric.js � GitHub, Or is the challenge to get curved text in the canvas with object controls? On Mon, Jul 1, 2013 at 9:20 AM, dean555 notifications@github.com� Curved text for fabric.js. Contribute to imomin/fabric.curvedText development by creating an account on GitHub.

I have also implemented curved text,

Take a look over here,

https://github.com/swabha1/Path_Text_V0.2.git

Actually it is path text it render text on path input given whether it is circle, line, arc, rectangle, etc.

Quadratic Curve, <canvas id="c" width="400" height="200"></canvas><br/>. 2. <input type="text" id ="text" value="CurvedText" /><br>. 3. Reverse : <input type="checkbox"� How to set opacity of a text canvas using Fabric.js ? How to Create a Curve Text using CSS3/Canvas ? How to disable the modification of text canvas using Fabric.js ? How to add underline to canvas-type text using Fabric.js ? How to remove controls of a text canvas using Fabric.js ? How to add stroke width of text canvas using Fabric.js ? How to

That's cool answer by Fabrizio I think this too may help someone. one can try Arctext.js for doing this

http://tympanus.net/Development/Arctext/

fabric curved text, Canvas('c'); // Create a text object. // Does not display it-the canvas doesn't // know about it yet. var hi = new fabric.Text('hello, world. Allows you to create curved text - extension to fabric.js - EffEPi/fabric.curvedText

Create valley text (text with curve) in Fabric.js, Curving text using Canvas: The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images. This is a relatively easier method to curve text using a bit of JavaScript for manipulating the canvas element and styling it.

Do you like fabricJS? If you want it continue running and you do not mind tech related ads, please allow this website in your adblocker. ️ Thank You!

For functionalities on keyDown Map a special key to a function of the instance/prototype If you need different behaviour for ESC or TAB or arrows, you have to change this map setting the name of a function that you build on the fabric.Itext or your prototype. the map change will affect all Instances unless you need for only some text Instances in that case you have to clone this object and

Comments
  • This may be what you are looking for <jsfiddle.net/NHs8t> This is not my code, I got it from Github discussions page, check this out..
  • @PrasannaAarthi i am trying to update fiddle jsfiddle.net/NHs8t/7 to add more than one text and if object selcetd change text of selected object otherwise add new text . but need little help on this
  • i am trying to change colour of curved text using spectrum plugin . coluor change reflects only if i change radius and spacing.what could be problrm , in fiddle attaching code for spectrum change jsfiddle.net/qpJTz/18
  • currently only works with SET, I am looking into figuring out what the problem is, if you post the code to the github site I can look more into it
  • i checked ur plugin .. this is design to set radius ,spacing and more . but can you plz update it to set fill colour??
  • Do you want the example to do so ? It is already supported, in fact all the properties that you can apply to text will also apply to the curvedText as long as you use set. In your case, for fill color use curvedText.setFill('#EFEFEF');
  • if i try to change color it only reflect after changing radius and spacing ,After adding some changes in your plugin _dimensionAffectingProps['fill'] = true; it reflects on as soon as coloured change .. will give u snippts on github very soon
  • Can you please tell me how to use tosvg() function for this curvedText. As it gives me undefined function
  • It's not implemented. I don't know SVG well enough to make this happen.
  • Is there any plan to support newer fabric.js versions like 1.7.x or 2.x?