我已经从 fabric js 创建了 svg。在创建卡片时,我使用以下代码将文本对齐应用于对象:
activeObj.set({
textAlign : 'center',
});
canvas.renderAll();
所以我的 svg 如下所示:
https://codepen.io/dhavalsisodiya/pen/BrRbRG
现在,当我用原始值更改我的 {company_address} 地址变量时,该文本应该居中对齐,但事实并非如此。
https://codepen.io/dhavalsisodiya/pen/VXbRzy
然后我手动修改了 SVG,我添加text-anchor="middle"
了 SVG 的 tspan 标签(这是我的变量的放置)
https://codepen.io/dhavalsisodiya/pen/ZxKPab
添加后,我的文本出现在 SVG 的中心。
那么有没有办法使用fabric js来做到这一点,所以text-anchor="middle"
当我应用文本对齐时它包含?
我也应用了 textAnchor,但它没有转换为 svg。
感谢@AndreaBogazzi,我能够使用以下方法解决它:
我已经修改了结构 js 文件,如下所示:
增加了'text-anchor="' + this.textAnchor + '" ',
在_wrapSVGTextAndBg: function(markup, textAndBg) {
作为@AndreaBogazzi建议。
/**
* @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;
}
});
通过进行上述更改,现在即使我修改了文本,我的变量也会保持中间状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句