SVG リソースの使用

SVG リソースをコンポーネントに追加するには、2 つの方法があります。1 つは SVG リソースをコンポーネントの HTML テンプレートに直接追加する方法。もう 1 つは SVG リソースを静的リソースとしてアップロードしてから、コンポーネントの JavaScript ファイルにインポートする方法です。

SVG (Scalable Vector Graphics) は、直線、曲線、図形、テキストを定義できる、XML ベースの画像形式です。次に、赤の長方形、緑の円、「SVG」という白のテキストを含むファイルの例を示します。

1<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
2    <rect width="100%" height="100%" fill="red"></rect>
3    <circle cx="150" cy="100" r="80" fill="green"></circle>
4    <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
5</svg>

このように、各図形には、どのような図形か (たとえば、rect は長方形)、サイズ、色を記述するタグがあります。

SVG リソースを HTML テンプレートに直接追加する 

HTML テンプレートに SVG リソースを含めるには、他の要素と同様に <template> タグでリソースを囲みます。

1<template>
2    <svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
3        <rect width="100%" height="100%" fill="red"></rect>
4        <circle cx="150" cy="100" r="80" fill="green"></circle>
5        <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
6    </svg>
7</template>

SVG リソースを静的リソースとしてインポートする 

  1. SVG ファイルで、id 属性を <svg> タグに追加します。

    1<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg" id="logo">
    2    <rect width="100%" height="100%" fill="red"></rect>
    3    <circle cx="150" cy="100" r="80" fill="green"></circle>
    4    <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
    5</svg>
  2. SVG リソースを静的リソースとして組織にアップロードします。

  3. コンポーネントの JavaScript ファイルで、静的リソースをインポートします。静的リソースへの参照をその id と連結する項目を定義します。

    1// myComponent.js
    2import { LightningElement } from "lwc";
    3import SVG_LOGO from "@salesforce/resourceUrl/logo";
    4
    5export default class myComponent extends LightningElement {
    6  svgURL = `${SVG_LOGO}#logo`;
    7}
  4. SVG の <use> 要素を使用して、HTML テンプレートの項目を参照します。

    1<!-- myComponent.html -->
    2 <template>
    3   <svg xmlns="http://www.w3.org/2000/svg" width="300" height="200">
    4     ;
    5     <use href={svgURL}></use>
    6   </svg>
    7 </template>

サポートされる SVG タグ 

Lightning Web コンポーネントは、SVG タグの制限付きリストをサポートします。

  • <svg>
  • <a>
  • <altglyph>
  • <altglyphdef>
  • <altglyphitem>
  • <animatecolor>
  • <animatemotion>
  • <animatetransform>
  • <audio>
  • <canvas>
  • <circle>
  • <defs>
  • <desc>
  • <ellipse>
  • <filter>
  • <font>
  • <g>
  • <glyph>
  • <glyphref>
  • <hkern>
  • <image>
  • <line>
  • <lineargradient>
  • <marker>
  • <mask>
  • <mpath>
  • <path>
  • <pattern>
  • <polygon>
  • <polyline>
  • <radialgradient>
  • <rect>
  • <stop>
  • <switch>
  • <symbol>
  • <text>
  • <title>
  • <tref>
  • <tspan>
  • <video>
  • <view>
  • <vkern>
  • <use>

関連トピック

The Japanese Summer '24 guide is now live

日本語の Summer '24 ガイドが公開されました! 「Component Reference (コンポーネントリファレンス)」は、以前と同様にコンポーネントライブラリにあります。