Search code examples
javascriptcssraphaelfont-face

How to style JavaScript created text using CSS's @font-face


I'm trying to create a page which uses java script to get data via PHP and then display it using a custom font declared in a CSS style sheet. The entire page should use one custom font which I have declared in the main CSS file using @font-face like so:

@font-face {
    font-family: 'bauhaus';
    src: url('fonts/Bauhaus.woff') format('woff'),
    font-weight: normal;
    font-style: normal; }

My HTML file looks like this:

<html>  
<head> 
    <script type="text/javascript" src="resources/raphael-min.js"></script>  
    <script type="text/javascript" src="resources/index.js"></script> 
    <link href="Main.css" rel="stylesheet" type="text/css">
    <style type="text/css">  
        #canvas_container {  
            width: 100%;  
            border: 1px solid #aaa; 
            font-family:'bauhaus', "Times New Roman", Times, serif;
        }  
    </style>  
</head>  
<body>  
    <div id="canvas_container">FONTTEST</div>  
</body>  
</html>  

Within the index.js I can create text objects using Raphaeljs' syntax like so:

var txt = paper.text(150, 590, 'Test123').attr({'font-family': bauhaus, 'font-size':'70', fill:'#000'});

If I do it like that no 'Test123' text appears at all (I assume because it can't find or use the style 'bauhaus') and if I remove the font-family attribute it shows me text using the browser's default style which in my case is Arial. The 'FONTTEST' text on the other hand is displayed correctly using the correct @font-face Font.

Now my question is how to automatically have text created by Raphaeljs (or other Javascript libraries) follow the style declared by the CSS statements? I like using custom fonts but I can't find a proper solution on how to easily use the stylized text with Javascript.

Thanks for your help!


Solution

  • Well, after a bit of searching through Raphael's code I found it automatically sets its own font style (Arial) on all its text elements. I don't think that really makes sense, especially since I couldn't figure out on how to override it with a CSS '@font-face' font, but ok. My solution was to simply delete the automatic setting of the font attribute in Raphael's source code.

    For anyone interested, it's in the part where theText is declared. Just delete the font: availableAttrs.font bit in res.attrsand everything will obey the CSS style you want.