Raphael js文本定位:将文本居中放置在一个圆圈中
我正在使用 Raphael js 绘制带圆圈的数字。问题是每个数字都有不同的宽度/高度,因此使用一组坐标将文本居中是行不通的。 IE、FF 和 safari 之间的文本显示不同。是否有一种动态方法来查找数字的高度/宽度并相应地将其居中?
这是我的测试页面:
http://jesserosenfield.com/fluid/test.html
和我的代码:
function drawcircle(div, text) {
var paper = Raphael(div, 26, 26); //<<
var circle = paper.circle(13, 13, 10.5);
circle.attr("stroke", "#f1f1f1");
circle.attr("stroke-width", 2);
var text = paper.text(12, 13, text); //<<
text.attr({'font-size': 15, 'font-family': 'FranklinGothicFSCondensed-1, FranklinGothicFSCondensed-2'});
text.attr("fill", "#f1f1f1");
}
window.onload = function () {
drawcircle("c1", "1");
drawcircle("c2", "2");
drawcircle("c3", "3");
};
非常感谢!
I am using Raphael js to draw circled numbers. The problem is that each number has a different width/height so using one set of coordinates to center the text isn't working. The text displays differently between IE, FF, and safari. Is there a dynamic way to find the height/width of the number and center it accordingly?
Here is my test page:
http://jesserosenfield.com/fluid/test.html
and my code:
function drawcircle(div, text) {
var paper = Raphael(div, 26, 26); //<<
var circle = paper.circle(13, 13, 10.5);
circle.attr("stroke", "#f1f1f1");
circle.attr("stroke-width", 2);
var text = paper.text(12, 13, text); //<<
text.attr({'font-size': 15, 'font-family': 'FranklinGothicFSCondensed-1, FranklinGothicFSCondensed-2'});
text.attr("fill", "#f1f1f1");
}
window.onload = function () {
drawcircle("c1", "1");
drawcircle("c2", "2");
drawcircle("c3", "3");
};
Thanks very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(答案重写):Raphael.js 默认情况下水平和垂直居中文本节点。
这里的“居中”意味着 paper.text() 方法的 x, y 参数期望文本边界框的中心。
因此,只需指定与圆相同的 x、y 值即可产生所需的结果:
(jsFiddle)
相关源代码:
(Answer rewritten): Raphael.js centers text nodes both horizontally and vertically by default.
"Centering" here means that the x, y argument of paper.text() method expects the center of the text's bounding box.
So, just specifying the same x, y value as the circle should produce the desired result:
(jsFiddle)
Relevant source code:
也许这个:
Maybe this:
使用此属性:
'text-anchor':'start'
:Use this attribute:
'text-anchor':'start'
:精确旋转文本示例(在页面的右侧列中列出,或 < a href="https://gist.github.com/265480" rel="nofollow">github 中的此处),讨论将文本放在精确的位置,以及像往常一样,制作所需的额外步骤IE 中一切正常。
它确实找到了文本的边界框;我想按照 Jan 的建议,将文本移动边界框的一半是很简单的。
The Rotating Text Exactly example (listed in the right-hand column of the page, or here in github), discusses putting text in a precise position, along with, as usual, extra steps required to make things work in IE.
It does find a bounding box for the text; I imagine it is straightforward to move the text by half the bounding box as Jan suggested.