Back to Lit

04

packages/lit-dev-content/site/tutorials/content/svg-templates/04.md

latest2.7 KB
Original Source

This section of the tutorial covers the basics of the <pattern> element in SVG including how to:

  • Define a <pattern> element
  • Apply a <pattern> as a fill

Learn

In SVG, the <pattern> element visually repeats children across a 2D plane.

The patternUnits property defines the relative coordinate geometry used to paint a pattern. Setting patternUnits to userSpaceOnUse makes geometry relative to the user space. In this case, user space is the DOM.

ts
const helloPattern = svg`
  <pattern patternUnits="userSpaceOnUse">
    ${createTile()}
  </pattern>
`;

The <pattern> element can be given an id and referenced as a fill in other SVG elements as shown in the example below:

ts
const helloPattern = svg`
  <pattern
    id="hello-pattern"
    patternUnits="userSpaceOnUse">
    ${createTile()}
  </pattern>
`;

const helloPatternFill = svg`
  <rect fill="url(#hello-pattern)" width="200" height="200"></rect>
`;

Apply

Create a function called createRepeatPattern that returns a pattern element. Call createTile inside a <pattern> element. Give the <pattern> an id of repeat-pattern.

Provide pattern attributes like height and width to define how a tiles are painted. The example below creates a 200px square tile with a vertical and horizontal offset of -10. The pattern is painted using geometry defined by userSpaceOnUse.

ts
const createRepeatPattern = () => svg`
  <pattern
    id="repeat-pattern"
    x="-10"
    y="-10"
    width="200"
    height="200"
    patternUnits="userSpaceOnUse">
    ${createTile()}
  </pattern>
`;

Place createRepeatPattern inside the <defs> element in render to make #repeat-pattern available to other elements.

ts
render() {
  return html`
    <svg height="100%" width="100%">
      <defs>
        ...
        ${createRepeatPattern()}
      </defs>
    </svg>
  `;
}

Add two <rect> elements to the render method in repeat-pattern. One rect will be a solid white background. The other rect will have a fill referencing the <pattern> element by #repeat-pattern. Then remove the call to createTile from render.

ts
render() {
  return html`
    <svg height="100%" width="100%">
      ...
      <rect height="100%" width="100%" fill="#ffffff"></rect>
      <rect height="100%" width="100%" fill="url(#repeat-pattern)"></rect>
    </svg>
  `;
}

After completing this section, you'll be ready to learn how style and theme SVG with CSS.