Nahid Hossain

Nahid Hossain

Web Application & Software Developer

Lesson 1 – Text in SVG

Websites with lots of pictures are slow. If your website takes more than a few seconds, you will lose your visitors. Who wants to wait in this age of Internet? We want everything instantly.

The good news is that you can redefine your site’s performance using SVG images. Read this blog post to get a basic idea about the SVG image format: An introduction to SVG format.

Your first SVG code

 

The <svg> element is used to define an SVG image. The “height” and “width” attributes define the height and width of the SVG images.

Example:

<!doctype html>
<html>
    <head></head>
    <body>
        <svg height="40" width="300">
            <text x="0" y="20">Hello</text>
        </svg>
    </body>
</html>

Output

 

Hello

 

The <text> element

The <text> element defines a text. You can customize the text using the attributes of the <text> element. The following example defines the text “Hello”.

Example:

<svg height="40" width="300">
    <text x="0" y="20">Hello</text>
</svg>

Output

 

Hello

 

Positioning the text

Use the “x” and “y” attributes of the <text> element to set the SVG image on a particular position of the screen.

Example:

<svg height="300" width="300">
    <text x="200" y="200">Hello</text>
</svg>


Output:

Hello

Styling the text

 

You can style the text in two ways – using CSS and using attributes.

The below example shows how to style a text using CSS.

Example:

<svg height="200" width="300">
    <text x="0" y="100" fill="blue" font-size="30px">Hello</text>
</svg>

Output:

Hello

The below example shows how to style a text using attributes.

Example:

<svg height="200" width="300">
    <text x="0" y="100" fill="blue" font-size="30px">Hello</text>
</svg>

Output:

Hello

Sub-portions of a <text> element

You can divide a <text> element into multiple sub-portions using the <tspan> element. This kind of arrangement of text will be useful when you will want to set different attribute values for different sub-portions of the text.

Each <tspan> element is a sub-portion or child of the <text> element.

Example:

<svg height="100" width="300">
    <text x="0" y="30" font-weight="bold">Games:
        <tspan x="12" y="55" font-weight="normal">Cricket.</tspan>
        <tspan x="12" y="75" font-weight="normal">Football.</tspan>
    </text>
</svg>

Output:

Games: Cricket. Football.

Making rotations

The “transform” attribute of the <text> element lets you rotate a text using the “rotate” transform definition.

Example:

<svg height="100" width="300">
    <text x="50" y="50" fill="green" font-size="30px" transform="rotate(40 10,70)">Hello</text>
</svg>


Output:

Hello

This lesson explained the basics concepts of text in SVG. In the next lesson, you will learn about drawing shapes.

 

 

Leave A Comment

Your email address will not be published. Required fields are marked *