Friday, 15 May 2015

SVG with RaphaelJS - Working with Text in RaphaelJS


Welcome to this section of the weekly series SVG with RaphaelJS. Creating text in RaphaelJS involves the use of the text() function. Extra attributes of a text string are the anchor position of a text string.

By default, RaphaelJS assigns the anchor position of a text string to the middle. But the other attributes are start and end.

We are going to write out a piece of text using different anchor positions 3 times to explain this concept. The code to do this is given below.

$(function(){ var paper = Raphael('container', 500, 500);
var text1 = paper.text(200, 100, "Raphaël")
.attr({ "fill": "#F00", "font-size": "40", "text-anchor": "start" });
var text2 = paper.text(200, 200, "Raphaël")
.attr({ "fill": "#F00", "font-size": "40", "text-anchor": "middle" });
var text3 = paper.text(200, 300, "Raphaël")
.attr({ "fill": "#F00", "font-size": "40", "text-anchor": "end" });
});

This code produces the image shown below. You can view it online here or get the full code from the GitHub repository for this course.


From the above diagram, you can see that choosing your anchor point affects how the text is displayed. Using the line at x = 200 as a guide, we see that when the text-anchor is at the start, the text starts from the line. When it is placed at its default position (middle), the text is displayed at the centre and when the text-anchor is at the end, the displayed text stops at the line.

That is all for this week on SVG with RaphaelJS. Next week we will look at using RaphaelJS with other JavaScript libraries.

2 comments:

  1. So what about if am working on path on a map and i want to give separate fill colors to the regions how will i do that?

    ReplyDelete
  2. What i mean is this, i want to see a different region to be fill with red and other regions to be filled with different colors how will i do that

    ReplyDelete