Javascript Raphael JS 和文本定位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2124763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Raphael JS and Text positioning?
提问by RadiantHex
I'm trying to position text within the SVG canvas, by supplying x, y coordinates
我试图通过提供x、y 坐标在 SVG 画布中定位文本
var t = paper.text(50, 50, "Rapha?l\nkicks\nbutt!");
but does not position the text like all other objects...
但不会像所有其他对象一样定位文本......
x, y coordinates specify the centerof the object! Not the "left and top most"pixel!
x,y坐标指定对象的中心!不是“最左边和最顶部”的像素!
I would like to "left align"the text along a line, same as standard HTML.
我想沿一条线“左对齐”文本,与标准 HTML 相同。
Help would be very much appreciated.
非常感谢帮助。
采纳答案by RadiantHex
Resolved!
解决!
By using the following
通过使用以下
paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30);
it now aligns text on the left.
它现在在左侧对齐文本。
回答by Dasha Salo
Text-anchor property for text method is set to 'middle' by default.
默认情况下,文本方法的文本锚属性设置为“中间”。
If you want to left align it then change text-anchor in attributes for the object:
如果要左对齐它,请更改对象属性中的文本锚点:
var t = paper.text(50, 50, "Rapha?l\nkicks\nbutt!").attr({'text-anchor': 'start'});
回答by Jimmy Chandra
I know you didn't say you need to vertical align it to top, but if you want to use paper.text instead of paper.print... and would like to vertical align to be top.
我知道你没有说你需要将它垂直对齐到顶部,但是如果你想使用 paper.text 而不是 paper.print ... 并且想要垂直对齐到顶部。
Try this:
尝试这个:
function alignTop(t) {
var b = t.getBBox();
var h = Math.abs(b.y2) - Math.abs(b.y) + 1;
t.attr({
'y': b.y + h
});
}
And just pass the Raphael text object to it. It will top align it for you. and just call that function
只需将 Raphael 文本对象传递给它。它将为您顶部对齐。只需调用该函数
回答by ciga
Following code works well in IE , Chrome (Firefox not tested):
以下代码在 IE 、Chrome 中运行良好(Firefox 未测试):
var t = paper.text(50, 50, "Rapha?l\nkicks\nbutt!"),
b = t._getBBox();
t.translate(-b.width/2,-b.height/2);
Explanation:
解释:
in Raphael , text is centered around your given x & y by default, you can set left align with:
在 Raphael 中,默认情况下文本以给定的 x & y 为中心,您可以将左对齐设置为:
t.attr({'text-anchor':'start'})
but you have no attribute to set it top align. I firstly tried :
但是您没有将其设置为顶部对齐的属性。我首先尝试:
var b=t.getBBox();
but it returned NaN in IE, so I turned to:
但它在 IE 中返回 NaN,所以我转向:
var b=t._getBBox();
_getBBox() is undocumented but used internally by Raphael itself , and it works!
_getBBox() 未记录但由 Raphael 本身在内部使用,并且它有效!
Hope it helps.
希望能帮助到你。

