I'm trying to write a Django template tag that will generate a number inside a circle as an inline svg.
The math is pretty straight-forward (except for the fudge-factor in real_fontsize
-- I'm thinking it has to do with numerals being shorter than the tallest character..?)
@register.inclusion_tag('numcircle.html')
def numcircle(n, size=36, border=4, color='white', background="black", **kw):
"""Draw a circle with a number inside.
"""
kw['padding'] = kw.get('padding', 2)
kw['num'] = n
kw['size'] = size
kw['border'] = border
kw['center'] = size / 2
kw['radius'] = (size / 2) - border
kw['color'] = color
kw['background'] = background
kw['fontsize'] = size - (2 * (border + kw['padding']))
real_fontsize = kw['fontsize'] * (0.8 if kw['fontsize'] > 25 else 1)
kw['ypos'] = kw['center'] + real_fontsize / 2 - kw['border'] + kw.get('yadjust', 0)
kw['xpos'] = kw.get('xpos', size / 2)
return kw
template:
<svg width="{{ size }}" height="{{ size }}" viewBox="0 0 {{ size }} {{ size }}">
<circle cx="{{ center }}"
cy="{{ center }}"
r="{{ radius }}"
stroke="{{ color }}"
stroke-width="{{ border }}"
fill="{{ background }}"/>
<text font-size="{{ fontsize }}"
fill="{{ color }}"
font-family="Verdana"
text-anchor="middle"
alignment-baseline="baseline"
x="{{ xpos }}"
y="{{ ypos }}">{{ num }}</text>
</svg>
it produces an svg that renders very nicely in all browsers I have tested, except the native iPad browser, where the number is flush with the bottom of the circle (and not in the center)..
<svg width="44" height="44" viewBox="0 0 44 44">
<circle cx="22"
cy="22"
r="20"
stroke="white"
stroke-width="2"
fill="#21435F"/>
<text font-size="36"
fill="white"
font-family="Verdana"
text-anchor="middle"
alignment-baseline="baseline"
x="22"
y="34.4">1</text>
</svg>
Is there any way to work around this issue in a cross-browser (IE9+) fashion?
jsfiddle: http://jsfiddle.net/onLyh6bm/
(using alignment-baseline: middle
doesn't seem to align in the middle in any browser..: http://jsfiddle.net/68oamxdo/1/)
You can't really rely on the alignment-baseline
property. Support for it is pretty spotty at best.
Even when it is supported, alignment-baseline: middle
doesn't really vertically centre the characters. There is, in fact, no way to do it accurately and reliably.
You can centre horizontally with text-anchor="middle"
, which is supported everywhere.
IMO, the best you can do in the vertical case, is the solution I propose in this answer: https://stackoverflow.com/a/19273331/1292848
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments