Reputation: 38842
In Raphael.js, if I have an text element:
var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
I would like to use CSS to style this text, I successfully CSS it by
($(t.node)).css('font-size', 18);
BUT, what if I define the css code in an external CSS file? How can I specifically define the css for my text element?
I tried in javascript:
($(t.node)).addClass('my-text');
in my.css:
.my-text {
font-size: 18
}
But it does not work at all, because the jQuery.addClass() is not working in Raphael..any ideas of how to style Raphael elements by using an external CSS file??
Upvotes: 3
Views: 4652
Reputation: 6004
Raphael adds a bunch of inline font styles automatically. After calling Paper.text()
to get your textElement
use this function
function removeInlineFontStyles(textElement) {
textElement.node.style.font = null;
textElement.node.attributes.removeNamedItem('font-family');
textElement.node.attributes.removeNamedItem('font-size');
return textElement;
}
Then your css classes will be able to do their thing
Upvotes: 0
Reputation: 2392
The trick is to reset the "font"-Attribute.
Raphael sets a "font"-Attribute to the text node. That will override your CSS settings. For me this works:
var txt = paper.text(10, 10, "Big Test Text").attr({"font": ""});
txt.node.setAttribute('class', 'my-text');
And in my CSS:
.my-text {
font-size: 5em;
}
To exactly see whats happening, see raphael.js, line 6923 and 558 (Version 2.1.0)
Upvotes: 0
Reputation: 2786
You can use vanilla js to add a class like so:
var paper = Raphael(10, 50, 320, 200);
var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!");
(t.node.className ? t.node.className.baseVal = 'mytext' : t.node.setAttribute('class', 'mytext'));
However, please be aware that Raphael places in-line style which will override your class, but you can use things like !important
to force it.
Note this is not suggested as you should be drawing the svg with the correct properties to start with, I would recommend using "factory" approach that generates your different svg parts with properties setup already.
Example (tested in Chrome 13.0.772): jsfiddle
Upvotes: 5
Reputation:
There seem some differences that doesn't make it possible to apply external css to raphäel text. I recommend you use http://glazman.org/JSCSSP/ to read and parse your external css and apply the rules to your text. A bit more complicated but acceptable.
I also tested with Raphäel 2.0 and it doesn't work. Anyway - I recommend trying out the new library. It has some awesome additions: https://github.com/DmitryBaranovskiy/raphael/tree/2.0
Hope that helps.
Upvotes: 1