This section of the tutorial covers the basics of using SVG with Lit including how to:

Learn

Permalink to “Learn”

In pattern making, an element refers to the smallest piece of a pattern that cannot be derived from other parts of the pattern.

The element in this demo will be a single piece of text. We can create text in SVG and Lit with SVG templates as demonstrated below.

const helloSVG = svg`<text>Hello, SVG!</text>`;

In Lit, an SVG template must be the child of an <svg> element. The <svg> element must be contained inside an HTML template. An implementation of these requirements is demonstrated by the following example.

const helloHTML = html`
<svg>
${svg`<text>Hello, SVG!</text>`}
</svg>
`;

Apply

Permalink to “Apply”

Create a function called createElement that generates a <text> element with configurable display text using a Lit SVG template. Add text-specfic styling attributes to the <text> element.

const createElement = (chars: string): SVGTemplateResult => svg`
<text
dominant-baseline="hanging"
font-family="monospace"
font-size="24px">
${chars}
</text>
`;
const createElement = (chars) => svg`
<text
dominant-baseline="hanging"
font-family="monospace"
font-size="24px">
${chars}
</text>
`;

Call createElement in the render() function of a repeat-pattern component similar to the example below.

@customElement('repeat-pattern')
export class RepeatPattern extends LitElement {
render() {
return html`
<svg height="100%" width="100%">
${createElement("lit")}
</svg>
`;
}
}
import { LitElement } from "lit";

export class RepeatPattern extends LitElement {
render() {
return html`
<svg height="100%" width="100%">
${createElement("lit")}
</svg>
`;
}
}
customElements.define('repeat-pattern', RepeatPattern);

Finally, create a reactive property called chars so that text rendered can be configured by consumers of repeat-pattern.

@customElement('repeat-pattern')
export class RepeatPattern extends LitElement {
@property({type: String}) chars = "lit";
render() {
return html`
<svg height="100%" width="100%">
${createElement(this.chars)}
</svg>
`;
}
}
export class RepeatPattern extends LitElement {
static properties = {
chars: {type: String},
};

constructor() {
super();
this.chars = 'lit';
}

render() {
return html`
<svg height="100%" width="100%">
${createElement(this.chars)}
</svg>
`;
}
}
customElements.define('repeat-pattern', RepeatPattern);

After completing this section, you'll be ready to learn how to create reusable structures in SVG in the next chapter.