如何在fabric js中使用text-anchor:middle

时间:2018-03-22 12:57:20

标签: javascript svg canvas fabricjs

我已经从fabric js创建了svg。在创建卡片时,我使用以下代码将text-align应用于对象:

activeObj.set({
    textAlign : 'center',
});
canvas.renderAll();

所以我的svg如下所示:

https://codepen.io/dhavalsisodiya/pen/BrRbRG

现在,当我将{company_address}地址变量更改为原始值时,该文本应该对齐居中但不是。

https://codepen.io/dhavalsisodiya/pen/VXbRzy

然后我手动修改了SVG,我在SVG的tspan标签中添加了text-anchor="middle"(这是放置我的变量)

https://codepen.io/dhavalsisodiya/pen/ZxKPab

添加后我的文字出现在SVG的中心。

有没有办法使用结构js,所以当我应用文本对齐时它包含text-anchor="middle"

更新

我也应用了textAnchor,但它没有转换为svg。

Codepen

https://codepen.io/dhavalsisodiya/pen/gvQooL

2 个答案:

答案 0 :(得分:1)

There is no text-anchor support in fabric.js for svgs.

You can make it quite easily maybe...

Take the text class from fabric.js, take the _getSVGLeftTopOffsets method for svg export. This methods return -this.width/2 always. I suppose it could return 0 if textAnchor is middle, and this.width/2 if textAnchor is end, becoming:

/**
 * @private
 */
_getSVGLeftTopOffsets: function() {
  return {
    textLeft: this.textAnchor === 'middle' ? 0 : this.textAnchor === 'start' -this.width / 2 : this.width / 2,
    textTop: -this.height / 2,
    lineTop: this.getHeightOfLine(0)
  };
},

Now take the _wrapSVGTextAndBg method and add the text-anchor property to the svg code:

/**
 * @private
 */
_wrapSVGTextAndBg: function(markup, textAndBg) {
  var noShadow = true, filter = this.getSvgFilter(),
      style = filter === '' ? '' : ' style="' + filter + '"',
      textDecoration = this.getSvgTextDecoration(this);
  markup.push(
    '\t<g ', this.getSvgId(), 'transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '"',
    style, '>\n',
    textAndBg.textBgRects.join(''),
    '\t\t<text xml:space="preserve" ',
    'text-anchor="' + this.textAnchor + '" ',
    (this.fontFamily ? 'font-family="' + this.fontFamily.replace(/"/g, '\'') + '" ' : ''),
    (this.fontSize ? 'font-size="' + this.fontSize + '" ' : ''),
    (this.fontStyle ? 'font-style="' + this.fontStyle + '" ' : ''),
    (this.fontWeight ? 'font-weight="' + this.fontWeight + '" ' : ''),
    (textDecoration ? 'text-decoration="' + textDecoration + '" ' : ''),
    'style="', this.getSvgStyles(noShadow), '"', this.addPaintOrder(), ' >',
    textAndBg.textSpans.join(''),
    '</text>\n',
    '\t</g>\n'
  );
},

at this point add to the text class the default for textAnchor value that should be start

答案 1 :(得分:0)

感谢@AndreaBogazzi,我能够使用以下方法解决它:

我修改了下面的fabric js文件:

@AndreaBogazzi建议在'text-anchor="' + this.textAnchor + '" ',添加_wrapSVGTextAndBg: function(markup, textAndBg) {

/**
 * @private
 */
_wrapSVGTextAndBg: function(markup, textAndBg) {
  var noShadow = true, filter = this.getSvgFilter(),
      style = filter === '' ? '' : ' style="' + filter + '"',
      textDecoration = this.getSvgTextDecoration(this);
  markup.push(
    '\t<g ', this.getSvgId(), 'transform="', this.getSvgTransform(), this.getSvgTransformMatrix(), '"',
    style, '>\n',
    textAndBg.textBgRects.join(''),
    '\t\t<text xml:space="preserve" ',
    'text-anchor="' + this.textAnchor + '" ',
    (this.fontFamily ? 'font-family="' + this.fontFamily.replace(/"/g, '\'') + '" ' : ''),
    (this.fontSize ? 'font-size="' + this.fontSize + '" ' : ''),
    (this.fontStyle ? 'font-style="' + this.fontStyle + '" ' : ''),
    (this.fontWeight ? 'font-weight="' + this.fontWeight + '" ' : ''),
    (textDecoration ? 'text-decoration="' + textDecoration + '" ' : ''),
    'style="', this.getSvgStyles(noShadow), '"', this.addPaintOrder(), ' >',
    textAndBg.textSpans.join(''),
    '</text>\n',
    '\t</g>\n'
  );
},

然后我在下面进行了修改:

_createTextCharSpan: function(_char, styleDecl, left, top) {
  var styleProps = this.getSvgSpanStyles(styleDecl, _char !== _char.trim()),
      fillStyles = styleProps ? 'style="' + styleProps + '"' : '';

    //Addded to support text-anhor middle
    if(this.textAnchor==='middle')
    {
        return [
            '\t\t\t<tspan  ',
            fillStyles, '>',
            fabric.util.string.escapeXml(_char),
            '</tspan>\n'
        ].join('');
    }
    else
    {
        return [
            '\t\t\t<tspan x="', toFixed(left, NUM_FRACTION_DIGITS), '" y="',
            toFixed(top, NUM_FRACTION_DIGITS), '" ',
            fillStyles, '>',
            fabric.util.string.escapeXml(_char),
            '</tspan>\n'
          ].join('');
    }
},

扩展toObjectTo以在json中添加textAnchor,请参见:extend toObject

$('.text_alignment').click(function(){
   var cur_value = $(this).attr('data-action');
    var activeObj = canvas.getActiveObject();
    if (cur_value != '' && activeObj) {
        activeObj.set({
            textAlign : cur_value,
            textAnchor : 'middle'
        });
        //To modify Object
        activeObj.toObject = (function(toObject) {
          return function() {
            return fabric.util.object.extend(toObject.call(this), {
              textAnchor: 'middle'
            });
          };
        })(activeObj.toObject);

        //activeObj.textAnchor  = cur_value;
        canvas.renderAll();
    }
    else
    {
        alert('Please select text');
        return false;
    }
});

通过进行上述更改,即使我修改了文本,现在我的变量也保持中间位置。