Skip to content

SVG 치트시트

해상도에 독립적인 이미지를 위한 확장 벡터 그래픽.

01

기본 구조

SVG 문서 골격

xmlns 속성은 SVG 네임스페이스를 선언합니다. width/height는 렌더링 크기를 픽셀로 설정합니다. viewBox는 내부 좌표계를 정의합니다. SVG는 독립 .svg 파일이거나 HTML에 인라인으로 포함될 수 있으며, 인라인일 때 XML 선언과 xmlns는 선택 사항입니다.

svg
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     width="200" height="200"
     viewBox="0 0 200 200">
  <!-- SVG content goes here -->
  <rect x="0" y="0" width="200" height="200" fill="#eee"/>
</svg>

HTML에 SVG 포함하기

인라인 SVG는 가장 유연합니다. HTML처럼 CSS로 스타일링하고 JS로 스크립팅할 수 있습니다. <img>와 background-image는 SVG를 정적 이미지로 취급합니다(내부 CSS/JS 없음). <object>는 별도 문서로 로드해 자체 DOM을 가지며 일부 스크립팅을 허용합니다.

svg
<!-- 1. Inline (best for styling and scripting) -->
<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="red"/>
</svg>

<!-- 2. As an image (no CSS/JS interaction) -->
<img src="icon.svg" alt="Icon" width="100" height="100">

<!-- 3. As a background (limited styling) -->
<div style="background: url('icon.svg') no-repeat;"></div>

<!-- 4. Via object/embed (allows scripting) -->
<object data="icon.svg" type="image/svg+xml"></object>

좌표계

SVG는 왼손 좌표계를 씁니다. 원점은 왼쪽 위, X는 오른쪽, Y는 아래입니다. viewBox 속성은 내부 좌표 공간을 정의합니다. SVG는 콘텐츠를 요소의 width/height에 맞게 스케일하므로 200px 요소에 viewBox 0 0 100 100을 쓰면 모든 것이 2배로 렌더링됩니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Origin (0,0) is top-left, like Canvas -->
  <!-- X increases rightward, Y increases downward -->

  <!-- A point at (50, 25) -->
  <circle cx="50" cy="25" r="3" fill="black"/>

  <!-- The viewBox stretches content to fill width/height -->
  <!-- viewBox="minX minY width height" -->
</svg>

<!-- viewBox 0 0 100 100 in a 200x200 element = 2x zoom -->
<svg width="200" height="200" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="50" fill="blue"/>
</svg>

width, height와 단위

사용자 단위(접미사 없음)는 px와 같습니다. 백분율은 부모 기준입니다. 반응형 SVG에는 width/height를 생략하고 viewBox를 설정하세요. SVG가 종횡비를 유지하며 컨테이너에 맞게 스케일됩니다. viewBox가 있으면 height에 'auto'를 써서 비율을 유지할 수 있습니다.

svg
<svg width="200" height="100">
  <!-- Default unit is the user unit (px equivalent) -->
</svg>

<!-- Common units: px, em, %, pt, cm, mm, in -->
<svg width="50%" height="auto" viewBox="0 0 100 100">
  <!-- % is relative to the parent element -->
</svg>

<!-- No width/height + viewBox = fully responsive -->
<svg viewBox="0 0 100 100" style="width:100%;height:auto;">
  <!-- Scales to container, preserves aspect ratio -->
</svg>

네임스페이스와 xlink

SVG 2는 <use>, <image>, <a>에서 직접 href 지원을 도입해 xlink:href를 폐기했습니다. 최신 브라우저는 일반 href를 지원합니다. 아주 오래된 브라우저를 지원해야 할 때만 xlink 네임스페이스를 유지하세요. HTML에 인라인된 SVG에는 xmlns 속성이 엄격히 필요하지 않습니다.

svg
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

  <!-- Modern SVG 2: use href directly -->
  <use href="#icon"/>

  <!-- Legacy SVG 1.1: use xlink:href -->
  <use xlink:href="#icon"/>
</svg>

<!-- In HTML5 inline SVG, the xmlns is optional -->
<!-- But xlink namespace is needed if you use xlink:href -->

주석과 메타데이터

<title>과 <desc>는 스크린 리더가 읽는 접근성 텍스트를 제공하므로 의미 있는 SVG에는 항상 포함하세요. <metadata>는 도구용 구조화 데이터(RDF, Dublin Core)를 담습니다. 주석은 HTML과 같은 <!-- --> 문법을 사용합니다.

svg
<svg width="100" height="100" viewBox="0 0 100 100">
  <!-- This is an XML comment (same as HTML) -->

  <!-- Metadata is hidden from rendering -->
  <metadata>
    <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">My Icon</dc:title>
    </rdf:RDF>
  </metadata>

  <!-- title and desc for accessibility -->
  <title>Shopping Cart Icon</title>
  <desc>A red shopping cart with 3 items</desc>

  <circle cx="50" cy="50" r="40" fill="red"/>
</svg>
02

도형

사각형(rect)

rect는 x, y, width, height가 필요합니다. rx/ry는 둥근 모서리를 만듭니다(rx만 설정하면 ry는 rx를 따름). fill='none'은 내부를 투명하게 만듭니다. stroke-width는 가장자리 중심에 그려지므로 절반이 도형 바깥으로 나갑니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Basic rectangle -->
  <rect x="10" y="10" width="80" height="50" fill="steelblue"/>

  <!-- Rounded corners -->
  <rect x="110" y="10" width="80" height="50"
        rx="10" ry="10" fill="tomato"/>

  <!-- Stroked, no fill -->
  <rect x="10" y="70" width="80" height="20"
        fill="none" stroke="black" stroke-width="2"/>
</svg>

원과 타원

circle은 중심(cx, cy)과 반지름 r로 정의됩니다. ellipse는 늘리기 위해 rx와 ry를 따로 가집니다. 둘 다 cx/cy를 생략하면 0이 기본값입니다. rect와 달리 원/타원은 이미 곡선이라 둥근 모서리를 따로 지정할 수 없습니다.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- circle: cx, cy (center), r (radius) -->
  <circle cx="50" cy="60" r="40" fill="gold"/>

  <!-- ellipse: cx, cy, rx (x radius), ry (y radius) -->
  <ellipse cx="150" cy="60" rx="50" ry="30" fill="mediumpurple"/>

  <!-- Circle as an ellipse (rx == ry) -->
  <ellipse cx="100" cy="20" rx="15" ry="15" fill="black"/>
</svg>

선

line은 두 점을 연결합니다. fill이 없고 stroke만 있습니다. stroke-dasharray는 파선을 만듭니다. 패턴은 'dash-length,gap-length'가 반복됩니다. stroke-linecap(butt, round, square)은 선 끝 모양을 제어합니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- line: x1,y1 (start) to x2,y2 (end) -->
  <line x1="10" y1="10" x2="190" y2="10" stroke="black" stroke-width="2"/>

  <!-- Diagonal line -->
  <line x1="10" y1="90" x2="190" y2="10" stroke="red" stroke-width="3"/>

  <!-- Dashed line -->
  <line x1="10" y1="50" x2="190" y2="50"
        stroke="blue" stroke-width="2" stroke-dasharray="10,5"/>
</svg>

폴리라인과 폴리곤

polyline은 도형을 닫지 않고 연결된 선분을 그립니다(fill은 닫힌 것처럼 적용되지만 끝을 잇는 stroke는 없음). polygon은 마지막 점을 첫 점에 연결해 자동으로 닫습니다. points는 공백이나 쉼표로 구분된 x,y 쌍 목록입니다.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- polyline: open shape (no auto-close) -->
  <polyline points="10,10 50,90 100,10 150,90 190,10"
            fill="none" stroke="green" stroke-width="2"/>

  <!-- polygon: closed shape (auto-connects last to first) -->
  <polygon points="100,10 190,110 10,110"
           fill="lime" stroke="black" stroke-width="1"/>

  <!-- Star (polygon with 10 points) -->
  <polygon points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"
           fill="gold" stroke="orange"/>
</svg>

흔한 도형 속성

fill과 stroke는 두 가지 주요 페인트 속성입니다. opacity는 요소 전체에 영향을 주고 fill-opacity와 stroke-opacity는 독립적으로 작동합니다. stroke-linecap(butt/round/square)은 선 끝을, stroke-linejoin(miter/round/bevel)은 모서리를 다듬습니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="10" y="10" width="80" height="80"
        fill="#3498db"
        fill-opacity="0.5"
        stroke="#2c3e50"
        stroke-width="3"
        stroke-opacity="0.8"
        stroke-dasharray="5,3"
        stroke-linecap="round"
        stroke-linejoin="round"
        opacity="0.9"/>

  <!-- opacity affects the whole element -->
  <!-- fill-opacity/stroke-opacity affect parts independently -->
</svg>

채우기 규칙(evenodd)

fill-rule은 도형의 겹치는 영역을 채우는 방식을 결정합니다. 'nonzero'(기본)는 감기 방향에 따라 채웁니다. 'evenodd'는 홀수 번 둘러싸인 영역을 채워 자기 교차 경로와 동심 다각형에서 고전적인 '도넛 구멍' 효과를 만듭니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Default fill-rule: nonzero -->
  <polygon points="50,10 90,90 10,90 50,30 80,80 20,80"
           fill="red" fill-rule="nonzero"/>

  <!-- fill-rule: evenodd creates holes in overlapping shapes -->
  <polygon points="150,10 190,90 110,90 150,30 180,80 120,80"
           fill="blue" fill-rule="evenodd"/>
</svg>
03

패스

패스 명령 개요

<path> 요소는 가장 강력한 SVG 도형입니다. d 속성에 그리기 명령 문자열이 담깁니다. 대문자 명령은 절대 좌표, 소문자는 현재 펜 위치 기준 상대 좌표를 사용합니다. M, L, C, Q, A, Z가 핵심 명령입니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- The d attribute contains all path commands -->
  <path d="M 10 10 L 190 10 L 100 90 Z" fill="none" stroke="black"/>

  <!-- Uppercase = absolute, lowercase = relative -->
  <!-- M = moveto (lift pen, move) -->
  <!-- L = lineto (draw straight line) -->
  <!-- H = horizontal lineto, V = vertical lineto -->
  <!-- C = cubic bezier, S = smooth cubic -->
  <!-- Q = quadratic bezier, T = smooth quadratic -->
  <!-- A = arc, Z = closepath -->
</svg>

M, L, H, V, Z(선)

M은 그리지 않고 펜을 이동합니다. L은 점까지 선을 긋습니다. H/V는 수평/수직선을 그립니다(좌표 하나). Z는 경로를 시작점으로 닫습니다. 소문자 버전(l, h, v, z)은 좌표를 현재 위치에서의 오프셋으로 해석해 하위 경로를 재사용 가능하게 만듭니다.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- M = moveto, L = lineto, Z = close path -->
  <path d="M 10 10 L 190 10 L 190 110 L 10 110 Z"
        fill="none" stroke="black"/>

  <!-- H = horizontal line, V = vertical line (one coord each) -->
  <path d="M 10 60 H 190" stroke="red"/>

  <!-- Relative commands (lowercase): coords are offsets -->
  <path d="M 10 80 l 30 -20 l 30 20 l 30 -20 l 30 20"
        fill="none" stroke="blue"/>

  <!-- Multiple M's create subpaths (disconnected segments) -->
  <path d="M 10 100 L 50 100 M 100 100 L 150 100" stroke="green"/>
</svg>

C와 S(3차 베지어)

C는 곡선을 당기는 제어점 두 개로 3차 베지어를 그립니다. 첫 제어점(x1,y1)은 시작 접선에, 두 번째(x2,y2)는 끝 접선에 영향을 줍니다. S는 이전 곡선의 두 번째 제어점을 반사해 부드럽게 이어가므로 새 두 번째 제어점과 끝점만 지정하면 됩니다.

svg
<svg width="240" height="120" viewBox="0 0 240 120">
  <!-- C = cubic bezier: two control points + endpoint -->
  <!-- C x1 y1, x2 y2, x y -->
  <path d="M 10 60 C 60 10, 180 110, 230 60"
        fill="none" stroke="red" stroke-width="2"/>

  <!-- S = smooth cubic: control point mirrors the previous -->
  <!-- S x2 y2, x y (first control point is auto-mirrored) -->
  <path d="M 10 100 C 60 50, 100 50, 120 100 S 200 150, 230 100"
        fill="none" stroke="blue" stroke-width="2"/>

  <!-- Multiple cubics in one path -->
  <path d="M 10 20 C 40 0, 70 40, 100 20 C 130 0, 160 40, 190 20"
        fill="none" stroke="green"/>
</svg>

Q와 T(2차 베지어)

Q는 제어점을 두 개 대신 하나만 사용해 C보다 단순하지만 덜 유연합니다. T는 Q의 제어점을 반사해 부드럽게 이어가며 끝점만 필요합니다. 2차 곡선은 제어점 하나로 충분한 글꼴 글리프와 단순 아이콘 경로에 흔합니다.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- Q = quadratic bezier: one control point + endpoint -->
  <!-- Q x1 y1, x y -->
  <path d="M 10 100 Q 100 0, 190 100"
        fill="none" stroke="purple" stroke-width="2"/>

  <!-- T = smooth quadratic: control point auto-mirrored -->
  <path d="M 10 60 Q 50 20, 90 60 T 170 60"
        fill="none" stroke="orange" stroke-width="2"/>

  <!-- Q is simpler than C but less precise — good for curves -->
  <!-- with a single bend, like basic arcs and waves -->
</svg>

A(호)

A는 타원 호를 그립니다. rx, ry는 반지름이고 x-rotation은 타원을 기울입니다. large-arc-flag(0/1)는 두 점 사이의 짧은 호 또는 긴 호를 고르고, sweep-flag(0/1)는 반시계 또는 시계 방향을 고릅니다. 호는 까다로워서 많은 디자이너가 예측 가능한 C 곡선을 대신 사용합니다.

svg
<svg width="200" height="150" viewBox="0 0 200 150">
  <!-- A rx ry, x-rotation, large-arc-flag, sweep-flag, x y -->
  <path d="M 10 75 A 60 60, 0, 0, 1, 130 75"
        fill="none" stroke="red" stroke-width="2"/>

  <!-- large-arc-flag: 0 = small arc, 1 = large arc -->
  <!-- sweep-flag: 0 = counterclockwise, 1 = clockwise -->

  <!-- Large arc (the long way around) -->
  <path d="M 10 75 A 60 60, 0, 1, 1, 130 75"
        fill="none" stroke="blue" stroke-width="2"/>

  <!-- Elliptical arc (rx != ry) -->
  <path d="M 10 120 A 80 30, 0, 0, 0, 170 120"
        fill="none" stroke="green" stroke-width="2"/>
</svg>

실용 패스 예제

실제 아이콘은 M, L, C, Z를 조합해 모양을 그립니다. 하트는 부드러운 곡선을 위해 3차 베지어를 사용합니다. 체크 표시는 둥근 선 끝을 가진 세 점일 뿐입니다. 말풍선은 사각형에 H/V 선을, 꼬리에 L 명령을 섞습니다. 단순하게 시작해 제어점을 다듬으세요.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <!-- Heart shape -->
  <path d="M 100 30
           C 70 0, 20 20, 20 60
           C 20 90, 60 110, 100 120
           C 140 110, 180 90, 180 60
           C 180 20, 130 0, 100 30 Z"
        fill="red"/>

  <!-- Checkmark -->
  <path d="M 20 60 L 50 90 L 100 20"
        fill="none" stroke="green" stroke-width="6"
        stroke-linecap="round" stroke-linejoin="round"/>

  <!-- Speech bubble (combines lines and curves) -->
  <path d="M 20 20 H 180 V 80 H 60 L 40 100 L 45 80 H 20 Z"
        fill="lightblue" stroke="navy"/>
</svg>
04

텍스트

기본 텍스트

y 좌표는 기본적으로 위쪽이 아니라 텍스트 기준선을 가리킵니다. text-anchor(start/middle/end)는 x 기준 수평 정렬을, dominant-baseline(auto/middle/hanging/...)은 수직 정렬을 제어합니다. 둘 다 텍스트를 가운데 정렬하는 데 필수입니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <text x="10" y="50" font-family="Arial" font-size="24"
        fill="black">Hello SVG!</text>

  <!-- x, y sets the baseline position (y is the text baseline) -->
  <!-- Use dominant-baseline to change the vertical anchor -->
  <text x="100" y="50" font-size="20" fill="blue"
        text-anchor="middle" dominant-baseline="middle">Centered</text>
</svg>

텍스트 스타일링

SVG 텍스트는 대부분의 CSS 글꼴 속성을 속성으로 지원합니다. font-family는 표준 글꼴 스택을 받습니다. 텍스트에 stroke를 쓰면 외곽선을 그리므로 fill을 가리지 않도록 작은 stroke-width를 사용하세요. letter-spacing과 word-spacing은 CSS처럼 동작합니다.

svg
<svg width="300" height="120" viewBox="0 0 300 120">
  <text x="10" y="30"
        font-family="Georgia, serif"
        font-size="28"
        font-weight="bold"
        font-style="italic"
        fill="darkblue"
        stroke="navy"
        stroke-width="0.5"
        text-decoration="underline"
        letter-spacing="2">Styled Text</text>

  <!-- font-family uses CSS font stacks -->
  <!-- font-weight: normal, bold, 100-900 -->
  <!-- font-style: normal, italic, oblique -->
</svg>

tspan(하위 텍스트)

<tspan>은 HTML의 <span>처럼 텍스트 일부를 다르게 스타일링하거나 배치합니다. dx/dy는 이전 문자 기준 오프셋이고 절대 x/y는 새 위치로 이동합니다(줄바꿈에는 원래 x 값과 dy 사용). SVG에서 여러 줄 텍스트를 만드는 방법이 tspan입니다.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <text x="10" y="50" font-size="20" fill="black">
    <tspan font-weight="bold" fill="red">Bold red</tspan>
    <tspan dx="10" font-style="italic">italic</tspan>
    <tspan x="10" dy="30">New line via dy</tspan>
    <tspan dx="10" font-size="14">smaller</tspan>
  </text>

  <!-- dx/dy: relative offset from previous position -->
  <!-- x/y: absolute position (useful for line breaks) -->
</svg>

경로 위의 텍스트

<textPath>는 어떤 path 요소를 따라서도 텍스트를 렌더링합니다. href(최신)나 xlink:href(레거시)로 경로를 id로 참조하세요. startOffset(길이 또는 백분율)은 경로를 따라 텍스트 위치를 정합니다. 호, 원, 사용자 정의 도형에 곡선 라벨을 붙이는 표준 기법입니다.

svg
<svg width="300" height="150" viewBox="0 0 300 150">
  <!-- Define a path (can be invisible) -->
  <defs>
    <path id="curve" d="M 20 100 Q 150 0, 280 100" fill="none"/>
  </defs>

  <!-- Text follows the path via xlink:href / href -->
  <text font-size="20" fill="purple">
    <textPath href="#curve">Text along a curved path!</textPath>
  </text>

  <!-- startOffset shifts where the text begins on the path -->
  <text font-size="14" fill="gray">
    <textPath href="#curve" startOffset="50%" text-anchor="middle">
      Centered on path
    </textPath>
  </text>
</svg>

쓰기 모드와 방향

writing-mode='tb'는 텍스트를 위에서 아래로 흐르게 합니다(동아시아 타이포그래피에서 흔함). direction='rtl'은 오른쪽에서 왼쪽 문자 순서를 뒤집습니다. 임의 회전에는 transform 속성을 사용하세요. rotate(angle, cx, cy)는 점 (cx, cy)를 중심으로 회전합니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- Vertical text (top-to-bottom) -->
  <text x="50" y="20" writing-mode="tb" font-size="20">Vertical</text>

  <!-- Right-to-left text -->
  <text x="190" y="100" direction="rtl" font-size="20"
        text-anchor="end">RTL text</text>

  <!-- Rotated text (via transform) -->
  <text x="100" y="100" font-size="20"
        transform="rotate(45, 100, 100)">Rotated 45°</text>
</svg>

텍스트 접근성

SVG 텍스트는 기본적으로 선택 가능하고 접근 가능하지만 장식용 SVG에는 <title>과 <desc>를 넣어야 합니다. UI 요소로 쓰는 인라인 SVG에는 role='img'와 aria-label을 추가해 스크린 리더가 의미를 알리게 하세요. 필수 정보를 SVG 텍스트에만 넣지 마세요. HTML 텍스트가 더 접근성이 좋습니다.

svg
<svg width="200" height="80" viewBox="0 0 200 80">
  <title>Error Icon</title>
  <desc>A red circle with a white exclamation mark</desc>

  <!-- role and aria-label for screen readers -->
  <text role="img" aria-label="Error: 3 items need attention"
        x="100" y="45" text-anchor="middle"
        font-size="24" fill="red">! Error</text>
</svg>
05

그라디언트

선형 그라디언트

linearGradient는 선을 따라 색을 전환합니다. x1/y1에서 x2/y2가 방향을 정의합니다(0% 0%에서 100% 0%는 왼쪽에서 오른쪽). <stop> 요소는 색상 지점을 정의하고 offset은 0-100% 또는 0-1입니다. fill='url(#id)'로 그라디언트를 참조하세요. 그라디언트는 <defs> 안에 있어야 합니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" stop-color="red"/>
      <stop offset="50%" stop-color="yellow"/>
      <stop offset="100%" stop-color="green"/>
    </linearGradient>
  </defs>

  <rect x="10" y="10" width="180" height="80" fill="url(#grad1)"/>
</svg>

방사형 그라디언트

radialGradient는 중심점에서 방사합니다. cx/cy는 중심, r은 반지름입니다. fx/fy는 초점(0% 색이 시작하는 곳)으로, 이를 오프셋하면 방향성 조명 효과가 생깁니다. 기본값: cx/cy 50%, r 50%, fx/fy는 cx/cy를 따름.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <radialGradient id="grad2" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%" stop-color="white"/>
      <stop offset="50%" stop-color="orange"/>
      <stop offset="100%" stop-color="darkred"/>
    </radialGradient>
  </defs>

  <circle cx="100" cy="100" r="90" fill="url(#grad2)"/>
</svg>

그라디언트 단위와 확산

gradientUnits='objectBoundingBox'(기본)는 좌표를 각 도형 기준(0-1)으로 만들어 같은 그라디언트가 어떤 요소에도 맞습니다. 'userSpaceOnUse'는 절대 SVG 좌표를 사용해 그라디언트가 문서에 위치하므로 여러 도형에 걸쳐 그라디언트를 정렬할 때 유용합니다.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- objectBoundingBox (default): coords are 0-1 relative to the shape -->
    <linearGradient id="g1" x1="0" y1="0" x2="1" y2="0">
      <stop offset="0" stop-color="blue"/>
      <stop offset="1" stop-color="cyan"/>
    </linearGradient>

    <!-- userSpaceOnUse: coords are in the SVG's user units -->
    <linearGradient id="g2" x1="0" y1="0" x2="200" y2="0"
                    gradientUnits="userSpaceOnUse">
      <stop offset="0" stop-color="red"/>
      <stop offset="1" stop-color="yellow"/>
    </linearGradient>

    <!-- spreadMethod: pad (default), reflect, repeat -->
    <linearGradient id="g3" x1="0" y1="0" x2="0.3" y2="0"
                    spreadMethod="repeat">
      <stop offset="0" stop-color="green"/>
      <stop offset="1" stop-color="lime"/>
    </linearGradient>
  </defs>
  <rect width="100" height="100" x="0" fill="url(#g1)"/>
  <rect width="100" height="100" x="100" fill="url(#g2)"/>
  <rect width="100" height="100" x="200" fill="url(#g3)"/>
</svg>

스톱 투명도와 여러 스톱

각 스톱은 투명도 전환을 위한 stop-opacity(0-1)를 가질 수 있습니다. 복잡한 색상 램프에는 많은 스톱을 조합하세요. 이 일몰 그라디언트는 위쪽의 투명한 파랑에서 아래쪽의 불투명한 진한 빨강으로 페이드됩니다. 대기 배경에 흔한 기법입니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <linearGradient id="sunset" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="deepskyblue" stop-opacity="0"/>
      <stop offset="40%" stop-color="orange" stop-opacity="0.8"/>
      <stop offset="70%" stop-color="orangered"/>
      <stop offset="100%" stop-color="darkred"/>
    </linearGradient>
  </defs>
  <rect width="200" height="200" fill="url(#sunset)"/>
</svg>

그라디언트 재사용

<defs>에 그라디언트를 한 번 정의하고 fill='url(#id)'로 여러 도형에서 참조하세요. href로 기존 그라디언트에서 새 그라디언트를 파생하고 일부 속성(방향 등)만 덮어쓸 수 있습니다. SVG를 DRY하게 유지하고 파일 크기를 줄입니다.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- A reusable gradient -->
    <linearGradient id="metal" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="#eee"/>
      <stop offset="50%" stop-color="#999"/>
      <stop offset="100%" stop-color="#333"/>
    </linearGradient>

    <!-- Gradient referencing another via href -->
    <linearGradient id="metal-horizontal" href="#metal"
                    x1="0" y1="0" x2="1" y2="0"/>
  </defs>

  <!-- Same gradient on multiple shapes -->
  <rect x="10" y="10" width="80" height="80" fill="url(#metal)"/>
  <circle cx="150" cy="50" r="40" fill="url(#metal)"/>
  <rect x="210" y="10" width="80" height="80" fill="url(#metal-horizontal)"/>
</svg>
06

패턴

기본 패턴

<pattern>은 반복 그래픽을 타일링합니다. 패턴의 자식이 타일 하나를 정의하고 width/height가 타일 크기를 설정합니다. patternUnits='userSpaceOnUse'(권장)는 타일 크기를 채우는 도형과 무관한 SVG 사용자 단위로 지정합니다. fill='url(#id)'로 참조하세요.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <pattern id="dots" x="0" y="0" width="20" height="20"
             patternUnits="userSpaceOnUse">
      <circle cx="10" cy="10" r="3" fill="steelblue"/>
    </pattern>
  </defs>

  <rect width="200" height="200" fill="url(#dots)"/>
</svg>

패턴 단위

patternUnits='objectBoundingBox'(기본)는 타일 크기를 도형의 비율로 지정하므로 패턴이 각 도형에 맞게 스케일됩니다. 'userSpaceOnUse'는 절대 단위를 써서 크기와 무관하게 도형 간에 일관된 패턴을 만듭니다. 실제 패턴은 대부분 userSpaceOnUse를 사용합니다.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- objectBoundingBox (default): tile size is relative to shape -->
    <!-- 0.1 = 10% of the shape's width/height -->
    <pattern id="p1" width="0.1" height="0.1">
      <rect width="10" height="10" fill="red" opacity="0.5"/>
    </pattern>

    <!-- userSpaceOnUse: tile size is in SVG units -->
    <pattern id="p2" width="20" height="20"
             patternUnits="userSpaceOnUse">
      <rect width="10" height="10" fill="blue" opacity="0.5"/>
    </pattern>
  </defs>

  <rect width="150" height="100" fill="url(#p1)"/>
  <rect x="150" width="150" height="100" fill="url(#p2)"/>
</svg>

줄무늬와 체커보드

patternTransform은 전체 패턴을 회전, 스케일, 기울입니다. 줄무늬는 타일 절반을 한 색, 나머지 절반을 다른 색으로 채운 뒤 회전하세요. 체커보드는 타일당 사각형 네 개(또는 L자 쌍 두 개)를 사용합니다. 이런 패턴은 다이어그램과 텍스처에 흔합니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- Diagonal stripes -->
    <pattern id="stripes" width="20" height="20"
             patternUnits="userSpaceOnUse"
             patternTransform="rotate(45)">
      <rect width="20" height="10" fill="gold"/>
      <rect y="10" width="20" height="10" fill="black"/>
    </pattern>

    <!-- Checkerboard -->
    <pattern id="checker" width="40" height="40"
             patternUnits="userSpaceOnUse">
      <rect width="40" height="40" fill="white"/>
      <rect width="20" height="20" fill="black"/>
      <rect x="20" y="20" width="20" height="20" fill="black"/>
    </pattern>
  </defs>

  <rect width="100" height="200" fill="url(#stripes)"/>
  <rect x="100" width="100" height="200" fill="url(#checker)"/>
</svg>

패턴 콘텐츠 단위

patternContentUnits는 패턴 자식 요소의 좌표계(타일 크기가 아님)를 제어합니다. 'objectBoundingBox'는 자식 좌표를 도형의 비율로 만들어 패턴 세부가 각 도형에 비례해 스케일되게 할 때 유용합니다. 드물지만 강력합니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- patternContentUnits: how the pattern's children are measured -->
    <!-- userSpaceOnUse (default): children use SVG units -->
    <!-- objectBoundingBox: children are relative to the shape -->
    <pattern id="pb" width="0.25" height="0.25"
             patternContentUnits="objectBoundingBox">
      <circle cx="0.125" cy="0.125" r="0.05" fill="green"/>
    </pattern>
  </defs>

  <!-- The dots scale with each shape's bounding box -->
  <rect width="100" height="100" fill="url(#pb)"/>
  <rect x="100" width="100" height="200" fill="url(#pb)"/>
</svg>

중첩 패턴

패턴은 그라디언트, 다른 패턴, 기타 SVG 콘텐츠를 담을 수 있습니다. 이 격자 패턴은 각 셀을 은은한 그라디언트로 채우고 위에 격자 선을 그립니다. 중첩으로 복잡한 텍스처를 만들 수 있습니다. 타일이 너무 작으면 성능 문제가 생길 수 있으니 크기를 적절히 유지하세요.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- A pattern can reference another pattern or gradient -->
    <pattern id="grid" width="40" height="40"
             patternUnits="userSpaceOnUse">
      <rect width="40" height="40" fill="url(#cellGrad)"/>
      <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#ccc"/>
    </pattern>

    <linearGradient id="cellGrad">
      <stop offset="0" stop-color="#f0f8ff"/>
      <stop offset="1" stop-color="#e0e0ff"/>
    </linearGradient>
  </defs>

  <rect width="200" height="200" fill="url(#grid)"/>
</svg>
07

변환

이동

translate(tx, ty)는 요소를 tx, ty만큼 이동합니다. ty를 생략하면 0입니다. 변환은 요소의 좌표계에 적용되므로 x/y 속성은 이동된 원점 기준입니다. CSS 변환(style 경유)은 최신 브라우저의 인라인 SVG에서 동작하고 CSS 전환으로 애니메이션할 수 있습니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- Original -->
  <rect x="10" y="10" width="40" height="40" fill="red"/>

  <!-- Translated 80px right -->
  <rect x="10" y="10" width="40" height="40" fill="blue"
        transform="translate(80, 0)"/>

  <!-- translate with one arg moves only horizontally -->
  <rect x="10" y="10" width="40" height="40" fill="green"
        transform="translate(0, 50)"/>

  <!-- Equivalent in CSS (for inline SVG in HTML) -->
  <rect x="10" y="10" width="40" height="40" fill="orange"
        style="transform: translate(150px, 0);"/>
</svg>

회전

rotate(angle, cx, cy)는 점 (cx, cy)를 중심으로 angle도 회전합니다. cx/cy가 없으면 원점 (0,0)을 중심으로 회전하는데 보통 원하는 동작이 아닙니다. 양수는 시계 방향, 음수는 반시계 방향입니다. 요소를 제자리에서 회전하려면 항상 중심을 지정하세요.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <rect x="50" y="50" width="100" height="20" fill="red"/>

  <!-- rotate(angle) around origin (0,0) -->
  <rect x="50" y="50" width="100" height="20" fill="blue"
        transform="rotate(45)"/>

  <!-- rotate(angle, cx, cy) around point (cx, cy) -->
  <rect x="50" y="50" width="100" height="20" fill="green"
        transform="rotate(45, 100, 60)"/>

  <!-- Negative angles rotate counterclockwise -->
  <rect x="50" y="50" width="100" height="20" fill="orange"
        transform="rotate(-30, 100, 60)"/>
</svg>

스케일과 기울이기

scale(sx, sy)는 크기를 배수로 늘립니다. 인자 하나면 양 축을 동일하게 스케일합니다. 스케일은 stroke-width와 위치에도 영향을 줍니다. skewX/skewY는 축을 따라 각도만큼 기울입니다. 모든 변환은 원점 (0,0) 기준이므로 x=100의 도형을 스케일하면 위치도 이동합니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- Original square -->
  <rect x="10" y="10" width="50" height="50" fill="red"/>

  <!-- scale(2): 2x in both dimensions -->
  <rect x="10" y="10" width="50" height="50" fill="blue"
        transform="scale(2)"/>

  <!-- scale(sx, sy): different x and y scaling -->
  <rect x="10" y="10" width="50" height="50" fill="green"
        transform="scale(1, 2)"/>

  <!-- skewX / skewY: shear the shape -->
  <rect x="10" y="10" width="50" height="50" fill="orange"
        transform="skewX(30)"/>
</svg>

행렬 변환

matrix(a,b,c,d,e,f)는 모든 변환의 기저 형식입니다. a,d는 스케일, b,c는 기울이기, e,f는 이동입니다. 대부분의 개발자는 가독성을 위해 이름 있는 변환(translate, rotate 등)을 쓰지만 matrix는 도구가 출력하는 형식이며 변환 결합이나 파싱에 유용합니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- transform="matrix(a, b, c, d, e, f)" -->
  <!-- Represents: [a c e] [b d f] [0 0 1] -->
  <!-- New x = a*x + c*y + e -->
  <!-- New y = b*x + d*y + f -->

  <!-- Identity (no change) -->
  <rect width="50" height="50" fill="red" transform="matrix(1,0,0,1,0,0)"/>

  <!-- Translate (100, 50) -->
  <rect width="50" height="50" fill="blue" transform="matrix(1,0,0,1,100,50)"/>

  <!-- Scale 2x and translate -->
  <rect width="50" height="50" fill="green" transform="matrix(2,0,0,2,50,0)"/>
</svg>

변환 결합

속성의 여러 변환은 오른쪽에서 왼쪽으로 적용됩니다(가장 오른쪽이 먼저). 따라서 'translate(100,100) rotate(45)'는 도형을 자기 원점에서 먼저 회전한 뒤 이동하며 보통 원하는 동작입니다. transform-origin을 쓰는 CSS 변환이 인라인 SVG에서 더 직관적인 경우가 많습니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- Multiple transforms apply right-to-left -->
  <rect x="0" y="0" width="40" height="40" fill="red"
        transform="translate(100, 100) rotate(45) scale(2)"/>

  <!-- This means: scale, then rotate, then translate -->
  <!-- Order matters! rotate then translate != translate then rotate -->

  <!-- transform-origin via CSS (for inline SVG) -->
  <rect x="80" y="80" width="40" height="40" fill="blue"
        style="transform: rotate(45deg); transform-origin: center;"/>

  <!-- transform-origin: center, 50% 50%, or explicit coords -->
</svg>

transform-origin(CSS)

CSS로 SVG를 애니메이션할 때 transform-origin(SVG 사용자 단위)과 transform-box(요소 경계 상자는 fill-box, SVG 캔버스는 view-box)를 명시하세요. 이것이 없으면 회전이 요소가 아니라 SVG 원점을 중심으로 일어납니다. CSS 애니메이션과 전환은 인라인 SVG에서 동작합니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <style>
    .gear {
      transform-origin: 100px 100px;  /* SVG user units */
      transform-box: fill-box;        /* or view-box */
      animation: spin 4s linear infinite;
    }
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
  </style>

  <circle class="gear" cx="100" cy="100" r="50" fill="orange"/>
  <circle cx="100" cy="100" r="10" fill="black"/>
</svg>
08

그룹(g)

기본 그룹화

<g>는 요소를 묶어 속성(fill, stroke, transform 등)을 공유하고 하나의 단위로 조작하게 합니다. 자식은 그룹의 표현 속성을 상속합니다. 복잡한 SVG를 정리하고 여러 도형에 한 번에 변환을 적용하는 데 필수입니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <g fill="steelblue" stroke="navy" stroke-width="2">
    <!-- Children inherit the group's attributes -->
    <circle cx="60" cy="60" r="30"/>
    <rect x="100" y="30" width="60" height="60" rx="5"/>
    <path d="M 30 150 L 100 110 L 170 150 Z"/>
  </g>

  <!-- Without g, you'd repeat fill/stroke on each element -->
</svg>

그룹 변환

<g>의 transform은 자식에게 새 좌표계를 만듭니다. 재사용 가능한 컴포넌트를 만드는 핵심입니다. (0,0)을 기준으로 디자인한 뒤 translate로 그룹 전체를 배치하세요. 자식 좌표는 그룹의 변환된 원점 기준입니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <!-- A transform on a group applies to all children -->
  <g transform="translate(100, 100) rotate(45)">
    <rect x="-30" y="-30" width="60" height="60" fill="red"/>
    <circle cx="0" cy="0" r="15" fill="white"/>
  </g>

  <!-- The group defines its own coordinate system -->
  <!-- Children use coords relative to the group's origin -->
  <g transform="translate(50, 150)">
    <text x="0" y="0">Origin here</text>
    <circle cx="0" cy="-20" r="5"/>
  </g>
</svg>

중첩 그룹

그룹은 임의 깊이로 중첩될 수 있습니다. 각 중첩 변환이 누적되어 가장 안쪽 요소가 모든 상위 변환의 순차적 영향을 받습니다. 계층적 장면(회전하는 팔, 움직이는 손이 있는 캐릭터 등)을 만드는 방법입니다. 성능을 위해 중첩을 적절히 유지하세요.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <g transform="translate(100, 100)">  <!-- outer group -->
    <g transform="scale(0.5)">          <!-- inner group -->
      <circle r="80" fill="blue"/>
      <g transform="translate(40, 0)">  <!-- innermost -->
        <circle r="20" fill="white"/>
      </g>
    </g>
  </g>

  <!-- Transforms compound: the innermost circle is -->
  <!-- translated, scaled, and translated again -->
</svg>

그룹 ID와 참조

그룹에 id를 부여하고 <use href='#id'>로 참조해 복제하세요. SVG 스프라이트와 재사용 컴포넌트의 기반입니다. 그룹은 <defs>에 두어 직접 렌더링하지 않고 서로 다른 변환으로 여러 번 인스턴스화할 수 있습니다. <use>에서 속성을 덮어쓰는 것은 제한적입니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <g id="star">
      <polygon points="50,5 61,38 95,38 67,58 78,90 50,70 22,90 33,58 5,38 39,38"
               fill="gold" stroke="orange"/>
    </g>
  </defs>

  <!-- Reference the group with <use> -->
  <use href="#star" transform="translate(0, 0) scale(0.5)"/>
  <use href="#star" transform="translate(100, 0) scale(0.5)"/>
  <use href="#star" transform="translate(0, 50) scale(0.3)"/>
</svg>

조건부 그룹

id가 있는 그룹은 CSS(hover, active 상태)와 JavaScript 이벤트 처리의 완벽한 연결점입니다. <g>를 컴포넌트처럼 다루세요. 도형을 묶고 id를 부여한 뒤 하나의 단위로 상호작용합니다. 그룹의 이벤트 리스너는 모든 자식의 이벤트를 잡습니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- <g> can have ids for CSS targeting and JS selection -->
  <g id="button" class="interactive" data-action="save">
    <rect width="80" height="30" rx="5" fill="steelblue"/>
    <text x="40" y="20" text-anchor="middle" fill="white">Save</text>
  </g>

  <style>
    #button:hover rect { fill: royalblue; }
    #button { cursor: pointer; }
  </style>

  <script>
    document.getElementById("button").addEventListener("click", save);
  </script>
</svg>

그룹 vs 심볼

<symbol>은 재사용 아이콘 전용입니다. 직접 렌더링되지 않고 자체 viewBox를 가져 <use>가 독립적으로 크기를 조정할 수 있습니다. <defs>의 <g>도 동작하지만 viewBox 기능이 없습니다. 아이콘 시스템에는 스케일과 종횡비를 자동 처리하는 <symbol>을 권장하세요.

svg
<svg width="0" height="0" viewBox="0 0 0 0">
  <!-- <g> in <defs>: original is hidden, use can instantiate -->
  <defs>
    <g id="icon-g">
      <rect width="20" height="20" fill="red"/>
    </g>
  </defs>

  <!-- <symbol> is like <g> but supports viewBox and is never rendered -->
  <symbol id="icon-s" viewBox="0 0 20 20">
    <rect width="20" height="20" fill="blue"/>
  </symbol>

  <!-- Use with explicit size (symbol scales to fit) -->
  <use href="#icon-g" x="0" y="0"/>
  <use href="#icon-s" x="40" y="0" width="40" height="40"/>
</svg>
09

Use / Symbol / Defs

defs 요소

<defs>는 참조되기 전까지 그려지지 않는 재사용 정의를 담습니다: 그라디언트, 패턴, 필터, 클립 경로, 마스크, 심볼, 그룹. defs에 두면 렌더링 출력이 깔끔해지고 의도가 드러납니다. defs 밖의 것은 즉시 렌더링됩니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <!-- Anything in defs is defined but NOT rendered -->
    <linearGradient id="myGrad">
      <stop offset="0" stop-color="red"/>
      <stop offset="1" stop-color="blue"/>
    </linearGradient>

    <pattern id="myPattern" width="20" height="20">
      <circle cx="10" cy="10" r="5" fill="url(#myGrad)"/>
    </pattern>

    <g id="myShape">
      <rect width="40" height="40" rx="5"/>
    </g>
  </defs>

  <!-- Reference and render them -->
  <rect width="100" height="100" fill="url(#myPattern)"/>
  <use href="#myShape" x="120" y="30" fill="green"/>
</svg>

use 요소

<use>는 정의된 요소(g, symbol 또는 모든 도형)를 복제해 렌더링합니다. x/y는 인스턴스 위치입니다. <use>의 fill/stroke는 원본이 지정하지 않은 경우에만(CSS 상속) 덮어씁니다. transform은 인스턴스에 적용됩니다. SVG 스프라이트가 동작하는 방식입니다.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <g id="cloud">
      <circle cx="30" cy="50" r="20" fill="white"/>
      <circle cx="50" cy="45" r="25" fill="white"/>
      <circle cx="75" cy="50" r="20" fill="white"/>
    </g>
  </defs>

  <!-- Basic use -->
  <use href="#cloud"/>

  <!-- Positioned and styled -->
  <use href="#cloud" x="120" y="0" fill="lightgray"/>
  <use href="#cloud" x="200" y="10" transform="scale(0.5)" fill="silver"/>
</svg>

symbol 요소

<symbol>은 자체 viewBox를 가진 재사용 그래픽을 정의합니다. <g>와 달리 직접 렌더링되지 않고 <use> 요소 크기에 맞게 스케일됩니다. fill='currentColor'를 쓰면 소비자가 CSS color로 색을 지정할 수 있습니다. SVG 아이콘 시스템의 표준 패턴입니다.

svg
<!-- In a hidden sprite file or <defs> -->
<svg width="0" height="0" style="position:absolute">
  <symbol id="heart" viewBox="0 0 32 32">
    <path d="M16 28 C 4 18, 4 8, 12 8 C 14 8, 16 10, 16 12
             C 16 10, 18 8, 20 8 C 28 8, 28 18, 16 28 Z"
          fill="currentColor"/>
  </symbol>

  <symbol id="star" viewBox="0 0 32 32">
    <polygon points="16,2 20,12 31,12 22,19 25,30 16,23 7,30 10,19 1,12 12,12"
             fill="currentColor"/>
  </symbol>
</svg>

<!-- Usage: size with width/height, color with CSS -->
<svg width="24" height="24"><use href="#heart"/></svg>
<svg width="48" height="48"><use href="#star" style="color: gold"/></svg>

외부 SVG 참조

<use>는 href='file.svg#id'로 외부 SVG 파일의 심볼을 참조할 수 있습니다. 하지만 브라우저 지원이 일관되지 않고(IE 없음, CORS 제한) file://에서 깨집니다. 신뢰할 수 있는 방법은 HTML 맨 위에 숨겨진 SVG 스프라이트를 인라인하고 같은 문서 안의 심볼을 참조하는 것입니다.

svg
<!-- Reference a symbol in an external .svg file -->
<svg width="24" height="24">
  <use href="icons.svg#heart"/>
</svg>

<!-- The external file (icons.svg) would contain: -->
<!-- <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> -->
<!--   <symbol id="heart" viewBox="0 0 32 32">...</symbol> -->
<!-- </svg> -->

<!-- Note: external references have limited browser support -->
<!-- and don't work with file:// protocol. Inline is more reliable. -->
<!-- For production, inline the sprite at the top of your HTML body. -->

Use 속성 덮어쓰기

원본 도형이 표현 속성(fill 등)을 생략하면 <use>가 이를 설정할 수 있고 인스턴스가 값을 상속합니다. 원본이 fill을 지정하면 use의 fill은 무시됩니다(표현 속성이 CSS 상속을 이김). 사용자 정의 가능한 심볼을 만들려면 덮어쓸 속성을 원본에서 생략하세요.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- Shape without explicit fill — inherits from use -->
    <circle id="ball" cx="20" cy="20" r="15"/>
  </defs>

  <!-- Each use can set its own fill -->
  <use href="#ball" fill="red"/>
  <use href="#ball" x="50" fill="green"/>
  <use href="#ball" x="100" fill="blue" stroke="black" stroke-width="2"/>
</svg>

심볼 중첩과 스프라이트

SVG 아이콘의 운영 패턴입니다. 문서 맨 위에 모든 아이콘을 <symbol>로 담은 숨겨진 스프라이트 SVG 하나를 두고 <use>로 어디서나 렌더링합니다. currentColor는 아이콘이 텍스트 색을 상속하게 합니다. 크기는 CSS가 제어합니다. 스프라이트는 첫 로드 후 캐시되어 모든 페이지에서 빠릅니다.

svg
<!-- A complete inline SVG sprite system -->
<svg style="display:none" aria-hidden="true">
  <symbol id="icon-home" viewBox="0 0 24 24">
    <path d="M12 3 L2 12 H5 V21 H10 V14 H14 V21 H19 V12 H22 Z"/>
  </symbol>
  <symbol id="icon-search" viewBox="0 0 24 24">
    <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
    <line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
  </symbol>
</svg>

<!-- Reference anywhere in HTML -->
<svg class="icon"><use href="#icon-home"/></svg>
<svg class="icon"><use href="#icon-search"/></svg>

<style>
  .icon { width: 24px; height: 24px; fill: currentColor; }
</style>
10

필터

필터 기초

<filter>는 그래픽을 처리하는 하나 이상의 필터 기본 요소(fe* 요소)를 담습니다. in='SourceGraphic'은 요소 자체의 렌더링을 받습니다. filter='url(#id)'로 적용하세요. 필터는 비쌀 수 있으므로 큰 배경이 아니라 작은 요소에 드물게 사용하세요.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <defs>
    <filter id="blur1">
      <!-- feGaussianBlur: stdDeviation is the blur radius -->
      <feGaussianBlur in="SourceGraphic" stdDeviation="3"/>
    </filter>
  </defs>

  <!-- Without filter -->
  <text x="10" y="30" font-size="24" fill="red">Sharp</text>

  <!-- With filter -->
  <text x="10" y="70" font-size="24" fill="red"
        filter="url(#blur1)">Blurred</text>
</svg>

드롭 섀도

드롭 섀도는 feOffset(이동), feGaussianBlur(부드럽게), feFlood(색), feComposite(그림자에 색 적용), feMerge(원본 아래에 그림자 레이어)를 결합합니다. 필터의 x/y/width/height(기본 -10%에서 110%)를 늘리지 않으면 그림자가 잘립니다.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <defs>
    <filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
      <!-- Offset the source -->
      <feOffset in="SourceAlpha" dx="4" dy="4" result="offset"/>
      <!-- Blur the offset copy -->
      <feGaussianBlur in="offset" stdDeviation="3" result="blur"/>
      <!-- Color the shadow -->
      <feFlood flood-color="black" flood-opacity="0.5" result="color"/>
      <feComposite in="color" in2="blur" operator="in" result="shadow"/>
      <!-- Put shadow under the original -->
      <feMerge>
        <feMergeNode in="shadow"/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
  </defs>

  <rect x="20" y="20" width="80" height="60" fill="white"
        filter="url(#shadow)"/>
</svg>

간단한 드롭 섀도(CSS)

인라인 SVG의 간단한 그림자에는 CSS filter: drop-shadow()가 SVG 필터를 만드는 것보다 훨씬 간단합니다. box-shadow와 달리 경계 상자가 아니라 도형의 실제 윤곽을 따릅니다. CSS로 표현할 수 없는 복잡한 다단계 효과에만 SVG 필터를 사용하세요.

svg
<!-- Modern browsers: use CSS filter instead of SVG filter -->
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="50" y="20" width="100" height="60" fill="white"
        style="filter: drop-shadow(4px 4px 4px rgba(0,0,0,0.5));"/>
</svg>

<!-- In CSS -->
<style>
  .shadowed { filter: drop-shadow(0 0 10px rgba(0,0,0,0.3)); }
</style>

<!-- CSS drop-shadow follows the shape's alpha, unlike box-shadow -->
<!-- which only shadows the bounding box -->

색상 행렬

feColorMatrix는 5x4 행렬로 색을 변환합니다(RGBA 입력, RGBA 출력). type='saturate'에 0-1 값을 주면 채도를 낮추고, type='hueRotate'는 색상을 도 단위로 회전하며, type='luminanceToAlpha'는 밝기를 알파로 변환합니다. 그레이스케일, 세피아, SVG 콘텐츠 색상 조정에 유용합니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <defs>
    <!-- Convert to grayscale -->
    <filter id="grayscale">
      <feColorMatrix type="matrix"
        values="0.33 0.33 0.33 0 0
                0.33 0.33 0.33 0 0
                0.33 0.33 0.33 0 0
                0    0    0    1 0"/>
    </filter>

    <!-- Built-in saturation -->
    <filter id="desaturate">
      <feColorMatrix type="saturate" values="0"/>
    </filter>
  </defs>

  <image href="photo.jpg" width="100" height="100" filter="url(#grayscale)"/>
  <image href="photo.jpg" x="100" width="100" height="100" filter="url(#desaturate)"/>
</svg>

조명 효과

feSpecularLighting과 feDiffuseLighting은 2D 도형의 높이 맵(알파에서 파생)에 3D 조명을 시뮬레이션합니다. surfaceScale은 깊이를 제어하고 조명 요소(fePointLight, feDistantLight, feSpotLight)가 방향을 정합니다. feComposite와 결합하면 엠보스, 베벨, 3D 텍스트 효과를 얻습니다.

svg
<svg width="200" height="120" viewBox="0 0 200 120">
  <defs>
    <filter id="emboss">
      <!-- Create a height map from the alpha -->
      <feGaussianBlur in="SourceAlpha" stdDeviation="2" result="blur"/>
      <!-- Lighting from upper-left -->
      <feSpecularLighting in="blur" surfaceScale="5"
                          specularConstant="0.8" specularExponent="20"
                          lighting-color="white" result="spec">
        <fePointLight x="-50" y="-50" z="200"/>
      </feSpecularLighting>
      <feComposite in="spec" in2="SourceGraphic"
                   operator="in" result="lit"/>
      <feComposite in="SourceGraphic" in2="lit" operator="arithmetic"
                   k1="0" k2="1" k3="1" k4="0"/>
    </filter>
  </defs>

  <text x="10" y="70" font-size="48" font-weight="bold"
        fill="gray" filter="url(#emboss)">3D</text>
</svg>

터뷸런스(텍스처)

feTurbulence는 절차적 노이즈(fractal 또는 turbulence 타입)를 생성하므로 스태틱, 구름, 물, 종이 질감 같은 텍스처에 유용합니다. baseFrequency는 스케일을 제어합니다(0.5는 미세, 0.05는 구름). numOctaves는 속도를 희생해 세부를 추가합니다. feColorMatrix나 feDisplacementMap과 결합하세요.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- feTurbulence generates Perlin noise -->
    <filter id="noise" x="0" y="0" width="100%" height="100%">
      <feTurbulence type="fractalNoise" baseFrequency="0.65"
                    numOctaves="3" stitchTiles="stitch"/>
      <feColorMatrix type="matrix"
        values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.1 0"/>
    </filter>
  </defs>

  <rect width="200" height="200" fill="steelblue"/>
  <rect width="200" height="200" filter="url(#noise)"/>

  <!-- type: "fractalNoise" or "turbulence" -->
  <!-- baseFrequency: lower = larger blobs, higher = finer grain -->
  <!-- numOctaves: more = more detail (slower) -->
</svg>
11

클리핑과 마스킹

클립 경로

clipPath는 단단한 경계를 정의합니다. 안쪽 픽셀은 보이고 바깥은 숨겨집니다. 클립 도형 자체는 그려지지 않습니다. clip-path가 url(#id)로 참조합니다. 클리핑은 이진(안/밖)이므로 부드러운 전환에는 마스크를 사용하세요. 텍스트를 클립 경로로 쓰면 고전적인 '텍스트 안의 이미지' 효과가 생깁니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- A clip path: only the inside is visible -->
    <clipPath id="circleClip">
      <circle cx="100" cy="100" r="80"/>
    </clipPath>
  </defs>

  <!-- The image is clipped to the circle -->
  <rect width="200" height="200" fill="steelblue"
        clip-path="url(#circleClip)"/>

  <!-- Any shape can be a clip path -->
  <clipPath id="textClip">
    <text x="100" y="120" font-size="80" text-anchor="middle"
          font-weight="bold">SVG</text>
  </clipPath>
  <rect width="200" height="200" fill="gold" clip-path="url(#textClip)"/>
</svg>

마스크

clip-path(이진)와 달리 마스크는 알파를 지원합니다. 흰 영역은 완전히 보이고 검은 영역은 숨겨지며 회색은 부분 투명입니다. 부드러운 페이드를 위해 그라디언트를 마스크 콘텐츠로 사용하세요. 마스크는 클립 경로보다 무겁지만 부드러운 전환과 사진 효과에 필수입니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <defs>
    <!-- A mask: white = visible, black = hidden, gray = partial -->
    <mask id="fadeMask">
      <linearGradient id="fadeGrad" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stop-color="white"/>
        <stop offset="1" stop-color="black"/>
      </linearGradient>
      <rect width="200" height="200" fill="url(#fadeGrad)"/>
    </mask>
  </defs>

  <!-- The image fades from top to bottom -->
  <rect width="200" height="200" fill="red" mask="url(#fadeMask)"/>
</svg>

클립 경로 단위

clipPathUnits='objectBoundingBox'는 클립 경로를 각 요소의 경계 상자(좌표 0-1)에 맞게 스케일하므로 하나의 클립 경로가 크기가 다른 도형에 동작합니다. 'userSpaceOnUse'(기본)는 절대 SVG 좌표를 사용합니다. 재사용 클립은 대부분 objectBoundingBox를 씁니다.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <defs>
    <!-- userSpaceOnUse (default): clip coords in SVG units -->
    <clipPath id="clip1" clipPathUnits="userSpaceOnUse">
      <rect x="10" y="10" width="50" height="50"/>
    </clipPath>

    <!-- objectBoundingBox: coords are 0-1 relative to the element -->
    <clipPath id="clip2" clipPathUnits="objectBoundingBox">
      <rect x="0.1" y="0.1" width="0.8" height="0.8"/>
    </clipPath>
  </defs>

  <rect width="100" height="100" fill="red" clip-path="url(#clip1)"/>
  <rect x="100" width="100" height="80" fill="blue" clip-path="url(#clip2)"/>
  <rect x="200" width="100" height="60" fill="green" clip-path="url(#clip2)"/>
</svg>

CSS clip-path

CSS clip-path는 SVG 없이 기본 도형(circle, ellipse, polygon, inset)을 직접 지원하고 url(#id)로 SVG clipPath 요소를 참조할 수 있습니다. SVG뿐 아니라 HTML 요소에도 동작합니다. 최신 브라우저는 mask-image를 통한 CSS 마스킹도 지원합니다.

svg
<style>
  /* CSS clip-path works on SVG and HTML elements */
  .circle {
    clip-path: circle(50% at 50% 50%);
  }
  .triangle {
    clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
  }
  /* Reference an SVG clipPath */
  .svg-clip {
    clip-path: url(#myClip);
  }
</style>

<svg width="200" height="100">
  <defs>
    <clipPath id="myClip">
      <circle cx="50" cy="50" r="40"/>
    </clipPath>
  </defs>
  <rect class="svg-clip" width="200" height="100" fill="purple"/>
</svg>

실전: 텍스트 안의 이미지

그라디언트나 이미지를 텍스트에 클리핑하는 것은 인기 있는 디자인 기법입니다. clipPath에 <text> 요소를 넣고 클립된 rect를 그라디언트로 채우면 글자 모양 안에서만 보입니다. <image>로도 동작하므로 잡지 스타일 헤더를 위해 사진을 텍스트 안에 넣을 수 있습니다.

svg
<svg width="400" height="120" viewBox="0 0 400 120">
  <defs>
    <clipPath id="textShape">
      <text x="200" y="90" font-size="80" font-weight="900"
            text-anchor="middle" font-family="Arial">SUMMER</text>
    </clipPath>
  </defs>

  <!-- Background (visible only through the text) -->
  <rect width="400" height="120" fill="black"/>

  <!-- Image clipped to the text shape -->
  <rect width="400" height="120" fill="url(#sunsetGrad)"
        clip-path="url(#textShape)"/>

  <linearGradient id="sunsetGrad" x1="0" y1="0" x2="0" y2="1">
    <stop offset="0" stop-color="#ff6b6b"/>
    <stop offset="0.5" stop-color="#feca57"/>
    <stop offset="1" stop-color="#ff9ff3"/>
  </linearGradient>
</svg>
12

애니메이션(SMIL)

animate(기본)

<animate>는 속성을 시간에 따라 전환합니다. attributeName은 대상, from/to는 범위, dur는 지속 시간, repeatCount='indefinite'는 영구 반복입니다. SMIL 애니메이션은 선언적이라 JS가 필요 없고 IE를 제외한 대부분의 브라우저에서 동작합니다. 애니메이션은 대상 요소의 자식으로 둡니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="0" y="40" width="20" height="20" fill="red">
    <animate attributeName="x"
             from="0" to="180"
             dur="2s"
             repeatCount="indefinite"/>
  </rect>

  <!-- The rect moves from x=0 to x=180 over 2 seconds, forever -->
</svg>

animateTransform

<animateTransform>은 transform 속성을 애니메이션합니다. type은 연산(rotate, scale, translate, skewX, skewY)을 고릅니다. rotate의 from/to는 'angle cx cy'(중심점)입니다. JavaScript 없이 요소를 회전시키는 방법입니다. additive='sum'을 쓰지 않으면 요소당 animateTransform 하나만 실행할 수 있습니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <rect x="80" y="80" width="40" height="40" fill="blue">
    <animateTransform attributeName="transform"
                      type="rotate"
                      from="0 100 100" to="360 100 100"
                      dur="3s"
                      repeatCount="indefinite"/>
  </rect>

  <!-- type can be: rotate, scale, translate, skewX, skewY -->
  <!-- For rotate, the values are "angle cx cy" -->
</svg>

animateMotion

<animateMotion>은 요소를 경로를 따라 이동합니다. <mpath href='#id'>로 경로를 참조하거나 path를 직접 정의하세요. rotate='auto'는 요소가 이동 방향을 향하게 하므로 화살표, 자동차, 캐릭터에 필수입니다. JS 없이 경로 기반 애니메이션을 하는 SVG 방식입니다.

svg
<svg width="200" height="150" viewBox="0 0 200 150">
  <defs>
    <path id="motionPath" d="M 10 75 Q 100 0, 190 75" fill="none"/>
  </defs>

  <!-- A circle follows the path -->
  <circle r="10" fill="red">
    <animateMotion dur="3s" repeatCount="indefinite">
      <mpath href="#motionPath"/>
    </animateMotion>
  </circle>

  <!-- Show the path for reference -->
  <use href="#motionPath" stroke="gray" stroke-width="1"/>

  <!-- rotate="auto" makes the element face the direction of motion -->
  <circle r="5" fill="blue">
    <animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
      <mpath href="#motionPath"/>
    </animateMotion>
  </circle>
</svg>

키프레임과 이징

다단계 애니메이션에는 values(세미콜론 구분), keyTimes(0-1 비율), keySplines(구간별 베지어 이징)를 사용하세요. calcMode='spline'은 이징을 켜고 'linear'가 기본입니다. CSS 키프레임 애니메이션을 순수 SVG로 옮긴 것입니다. 사각형이 부드러운 이징으로 앞뒤로 튑니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect x="0" y="40" width="20" height="20" fill="green">
    <animate attributeName="x"
             values="0; 80; 180; 80; 0"
             keyTimes="0; 0.25; 0.5; 0.75; 1"
             keySplines="0.5 0 0.5 1; 0 0 1 1; 0.5 0 0.5 1; 0 0 1 1"
             calcMode="spline"
             dur="4s"
             repeatCount="indefinite"/>
  </rect>

  <!-- values: the animated values at each keyTime -->
  <!-- keyTimes: 0-1 fractions of dur (semicolon-separated) -->
  <!-- keySplines: cubic-bezier easing between each pair -->
  <!-- calcMode: "discrete", "linear", "paced", or "spline" -->
</svg>

begin, end와 트리거

begin은 시간 오프셋(2s), 이벤트(click, mouseenter), 다른 애니메이션 이벤트 참조(anim1.end, anim1.begin+1s)가 될 수 있습니다. fill='freeze'는 애니메이션 종료 후 최종 값을 유지합니다(없으면 원래대로 돌아감). JavaScript 없이 클릭 트리거와 체인 애니메이션을 가능하게 합니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <!-- begin: when to start (time or event) -->
  <rect x="10" y="10" width="30" height="30" fill="red">
    <animate attributeName="width" from="30" to="100"
             dur="1s" begin="2s" fill="freeze"/>
  </rect>

  <!-- begin on a click event -->
  <rect x="10" y="60" width="30" height="30" fill="blue" id="trigger">
    <animate attributeName="x" from="10" to="150"
             dur="1s" begin="click" fill="freeze"/>
  </rect>

  <!-- begin when another animation ends -->
  <rect x="10" y="80" width="30" height="10" fill="green">
    <animate attributeName="x" from="10" to="150"
             dur="1s" begin="trigger.click+1s" fill="freeze"/>
  </rect>
</svg>

CSS 애니메이션 대안

웹 페이지의 인라인 SVG에는 CSS 애니메이션이 SMIL보다 간단하고 도구 지원도 좋은 경우가 많습니다. transform-origin: center가 SVG 캔버스가 아니라 요소를 가리키도록 transform-box: fill-box를 사용하세요. SMIL은 독립 SVG 파일(CSS 불가)과 경로 기반 모션에 여전히 유용합니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <style>
    .pulse {
      animation: pulse 1.5s ease-in-out infinite;
      transform-origin: center;
      transform-box: fill-box;
    }
    @keyframes pulse {
      0%, 100% { transform: scale(1); opacity: 1; }
      50% { transform: scale(1.2); opacity: 0.7; }
    }
  </style>

  <circle class="pulse" cx="100" cy="50" r="20" fill="red"/>
</svg>

<!-- CSS animations are more maintainable for web pages -->
<!-- SMIL is better for standalone .svg files -->
13

이벤트

마우스 이벤트

SVG 요소는 표준 DOM 이벤트를 지원합니다: click, mouseenter, mouseleave, mousemove, mousedown, mouseup, dblclick. HTML 요소처럼 addEventListener를 사용하세요. 핸들러 안의 'this'는 SVG 요소를 가리킵니다. 반응적으로 속성을 바꾸려면 setAttribute를 사용하세요.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect id="box" x="10" y="10" width="80" height="80" fill="steelblue"/>

  <script>
    var box = document.getElementById("box");
    box.addEventListener("click", function (e) {
      alert("Clicked at " + e.clientX + "," + e.clientY);
    });
    box.addEventListener("mouseenter", function () {
      this.setAttribute("fill", "tomato");
    });
    box.addEventListener("mouseleave", function () {
      this.setAttribute("fill", "steelblue");
    });
  </script>
</svg>

터치 이벤트

SVG는 touchstart, touchmove, touchend를 지원합니다. createSVGPoint와 getScreenCTM().inverse()로 화면 좌표를 SVG 좌표로 변환하세요. SVG가 스케일되거나 반응형일 때 필수입니다. touchstart에서 preventDefault()를 호출하면 스크롤 같은 제스처 간섭을 막습니다.

svg
<svg width="200" height="200" viewBox="0 0 200 200">
  <circle id="touch" cx="100" cy="100" r="30" fill="purple"/>

  <script>
    var circle = document.getElementById("touch");
    circle.addEventListener("touchstart", function (e) {
      e.preventDefault();  // prevent scrolling
      this.setAttribute("fill", "orange");
    });
    circle.addEventListener("touchend", function () {
      this.setAttribute("fill", "purple");
    });
    // touchmove for dragging
    circle.addEventListener("touchmove", function (e) {
      var touch = e.touches[0];
      var pt = svg.createSVGPoint();
      pt.x = touch.clientX; pt.y = touch.clientY;
      var svgP = pt.matrixTransform(svg.getScreenCTM().inverse());
      this.setAttribute("cx", svgP.x);
      this.setAttribute("cy", svgP.y);
    });
  </script>
</svg>

좌표 변환

SVG의 viewBox가 픽셀 크기와 다르면 화면 좌표가 SVG 좌표에 1:1로 매핑되지 않습니다. createSVGPoint + getScreenCTM().inverse()가 viewBox, CSS 스케일, 심지어 상위 요소의 변환까지 고려해 올바르게 변환합니다. 정확한 클릭 감지에 필수입니다.

svg
<svg width="500" height="300" viewBox="0 0 1000 600" id="mysvg">
  <rect width="1000" height="600" fill="lightblue"/>

  <script>
    var svg = document.getElementById("mysvg");
    svg.addEventListener("click", function (e) {
      // Convert screen (clientX/Y) to SVG user coordinates
      var pt = svg.createSVGPoint();
      pt.x = e.clientX;
      pt.y = e.clientY;

      // getScreenCTM maps SVG coords to screen; inverse maps back
      var svgPoint = pt.matrixTransform(
        svg.getScreenCTM().inverse()
      );

      console.log("SVG coords:", svgPoint.x, svgPoint.y);
      // This accounts for viewBox scaling and CSS sizing
    });
  </script>
</svg>

이벤트 위임

이벤트 위임(자식마다 여러 리스너 대신 부모 그룹에 하나)은 더 효율적이고 동적으로 추가된 도형도 자동 처리합니다. e.target은 클릭된 도형이고 e.currentTarget은 리스너가 있는 요소입니다. 도형별 메타데이터를 저장하려면 data-* 속성을 사용하세요.

svg
<svg width="300" height="100" viewBox="0 0 300 100">
  <g id="shapes">
    <circle cx="50" cy="50" r="30" fill="red" data-name="circle1"/>
    <rect x="100" y="20" width="60" height="60" fill="blue" data-name="rect1"/>
    <polygon points="220,20 280,20 250,80" fill="green" data-name="tri1"/>
  </g>

  <script>
    // One listener on the parent group handles all children
    document.getElementById("shapes").addEventListener("click", function (e) {
      var target = e.target;
      var name = target.getAttribute("data-name");
      console.log("Clicked:", name, target.tagName);
      // e.target is the actual shape; e.currentTarget is the group
    });
  </script>
</svg>

드래그 상호작용

고전적인 SVG 드래그 패턴입니다. mousedown은 플래그를 설정하고, mousemove는 변환된 SVG 좌표로 요소 위치를 갱신하며, mouseup은 플래그를 해제합니다. 커서가 도형을 벗어나도 드래그가 계속되도록 mousemove/mouseup을 요소가 아니라 SVG에 붙이세요. SVG 기반 편집기의 기반입니다.

svg
<svg width="400" height="300" viewBox="0 0 400 300" id="canvas">
  <circle id="draggable" cx="200" cy="150" r="30" fill="orange" cursor="grab"/>

  <script>
    var circle = document.getElementById("draggable");
    var svg = document.getElementById("canvas");
    var dragging = false;

    function getSVGPoint(e) {
      var pt = svg.createSVGPoint();
      pt.x = e.clientX; pt.y = e.clientY;
      return pt.matrixTransform(svg.getScreenCTM().inverse());
    }

    circle.addEventListener("mousedown", function () {
      dragging = true;
      this.setAttribute("cursor", "grabbing");
    });
    svg.addEventListener("mousemove", function (e) {
      if (!dragging) return;
      var p = getSVGPoint(e);
      circle.setAttribute("cx", p.x);
      circle.setAttribute("cy", p.y);
    });
    svg.addEventListener("mouseup", function () {
      dragging = false;
      circle.setAttribute("cursor", "grab");
    });
  </script>
</svg>
14

JavaScript DOM

요소 만들기

SVG 요소는 document.createElementNS(namespace, tagName)로 만들어야 합니다. createElement는 SVG에서 동작하지 않습니다(알 수 없는 HTML 요소를 만듦). SVG 네임스페이스는 'http://www.w3.org/2000/svg'입니다. 속성에는 setAttribute를 사용하세요. 동적 SVG 생성의 기반입니다.

svg
<svg id="canvas" width="200" height="200" viewBox="0 0 200 200">
  <script>
    var svg = document.getElementById("canvas");
    var NS = "http://www.w3.org/2000/svg";

    // createElementNS is required for SVG elements
    var circle = document.createElementNS(NS, "circle");
    circle.setAttribute("cx", "100");
    circle.setAttribute("cy", "100");
    circle.setAttribute("r", "50");
    circle.setAttribute("fill", "red");
    svg.appendChild(circle);

    // Create a path
    var path = document.createElementNS(NS, "path");
    path.setAttribute("d", "M 10 10 L 100 100");
    path.setAttribute("stroke", "black");
    svg.appendChild(path);
  </script>
</svg>

요소 수정

SVG 표현 속성(fill, stroke, width 등)에는 setAttribute/getAttribute를 사용하세요. classList는 브라우저 전반에서 안정적으로 동작합니다. style.fill 설정은 CSS 속성으로 매핑되므로 동작합니다. SVG에는 innerHTML을 피하고(브라우저 간 불일치) createElementNS로 DOM을 만드세요.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect id="r" x="10" y="10" width="50" height="50" fill="blue"/>

  <script>
    var r = document.getElementById("r");

    // Change attributes
    r.setAttribute("fill", "red");
    r.setAttribute("width", "80");

    // Get attribute values
    var w = r.getAttribute("width");  // "80"

    // Remove attributes
    r.removeAttribute("fill");

    // Class manipulation (use classList, not className for SVG in some browsers)
    r.classList.add("highlight");
    r.classList.toggle("active");

    // Style (use setAttribute for presentation attributes)
    r.style.fill = "green";  // works via CSS
  </script>
</svg>

기하 읽기

getBBox()는 SVG 사용자 단위의 경계 상자를 반환합니다(변환 무시). getBoundingClientRect()는 모든 변환과 CSS 후의 화면 좌표를 반환합니다. getTotalLength()는 경로/선 길이를, getPointAtLength(d)는 거리 d의 점을 반환하므로 경로 기반 애니메이션과 히트 테스트에 필수입니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <rect id="r" x="10" y="10" width="80" height="50" fill="blue"/>

  <script>
    var r = document.getElementById("r");

    // Get bounding box in SVG user units
    var bbox = r.getBBox();
    console.log(bbox.x, bbox.y, bbox.width, bbox.height);

    // Get bounding box in screen coordinates (after transforms)
    var cbox = r.getBoundingClientRect();
    console.log(cbox.left, cbox.top, cbox.width, cbox.height);

    // Total length of a path or line
    var path = document.querySelector("path");
    var len = path.getTotalLength();
    var point = path.getPointAtLength(len / 2);  // midpoint
  </script>
</svg>

데이터셋과 데이터 속성

SVG 요소는 HTML처럼 data-* 속성과 dataset 속성을 지원합니다. 상호작용 앱에서 도형에 데이터를 연결하는 깔끔한 방법입니다. 시각적 속성을 오염시키지 않고 노드 ID, 라벨, 상태를 저장하세요. element.dataset.key로 읽고 같은 방식으로 설정합니다.

svg
<svg width="200" height="100" viewBox="0 0 200 100">
  <circle cx="50" cy="50" r="20" fill="red"
          data-id="123" data-label="node"/>

  <script>
    var circle = document.querySelector("circle");

    // dataset reads data-* attributes
    console.log(circle.dataset.id);     // "123"
    console.log(circle.dataset.label);  // "node"

    // Set data attributes
    circle.dataset.selected = "true";  // adds data-selected="true"

    // Use for storing state
    circle.dataset.visits = "0";
    circle.dataset.visits = String(+circle.dataset.visits + 1);
  </script>
</svg>

동적 경로 생성

SVG를 동적으로 생성하는 것은 커스텀 차트의 기초입니다. 데이터에서 M/L 명령을 연결해 경로 d 속성을 만들고 createElementNS로 요소를 생성하세요. 차팅 라이브러리 없이 완전한 제어를 제공합니다. 복잡한 시각화에는 이 패턴을 우아하게 감싸는 D3.js를 고려하세요.

svg
<svg width="300" height="150" viewBox="0 0 300 150" id="chart">
  <script>
    var NS = "http://www.w3.org/2000/svg";
    var svg = document.getElementById("chart");
    var data = [10, 50, 30, 80, 45, 90, 25];

    // Build a path string from data points
    var d = "M 0 " + (150 - data[0]);
    for (var i = 1; i < data.length; i++) {
      d += " L " + (i * 40) + " " + (150 - data[i]);
    }

    var path = document.createElementNS(NS, "path");
    path.setAttribute("d", d);
    path.setAttribute("fill", "none");
    path.setAttribute("stroke", "steelblue");
    path.setAttribute("stroke-width", "2");
    svg.appendChild(path);

    // Add dots at each point
    data.forEach(function (val, i) {
      var c = document.createElementNS(NS, "circle");
      c.setAttribute("cx", i * 40);
      c.setAttribute("cy", 150 - val);
      c.setAttribute("r", 3);
      c.setAttribute("fill", "red");
      svg.appendChild(c);
    });
  </script>
</svg>

성능 팁

성능: DocumentFragment로 DOM 삽입을 배치 처리하고(리플로우 한 번), JS 애니메이션에는 requestAnimationFrame(디스플레이 주사율 동기화)을 쓰며, 빡빡한 루프에서 속성 조회를 피하세요(값 캐시). SVG는 수백 요소까지 뛰어나지만 수천 개(입자, 밀집 플롯)에는 Canvas나 WebGL이 더 빠릅니다.

svg
<script>
  // Batch DOM operations with document fragments
  var fragment = document.createDocumentFragment();
  for (var i = 0; i < 1000; i++) {
    var c = document.createElementNS(NS, "circle");
    c.setAttribute("cx", i);
    c.setAttribute("cy", 50);
    c.setAttribute("r", 2);
    fragment.appendChild(c);
  }
  svg.appendChild(fragment);  // one reflow, not 1000

  // Use requestAnimationFrame for animations
  function animate() {
    element.setAttribute("cx", +element.getAttribute("cx") + 1);
    requestAnimationFrame(animate);
  }
  animate();

  // For many elements, consider <canvas> instead (faster)
  // SVG slows down with thousands of nodes due to DOM overhead
</script>
15

반응형 SVG(ViewBox)

viewBox 기초

viewBox='minX minY width height'는 내부 좌표계를 정의합니다. 처음 두 값은 뷰를 이동하고 마지막 두 값은 확대/축소합니다. SVG는 이 영역을 width/height에 맞게 스케일합니다. 따라서 그리기 좌표가 렌더링 크기와 분리되어 100x100이나 1920x1080 박스에 한 번만 그리면 됩니다.

svg
<!-- viewBox="minX minY width height" -->
<svg viewBox="0 0 100 100" width="200" height="200">
  <!-- A circle at center of a 100x100 coordinate system -->
  <circle cx="50" cy="50" r="50" fill="blue"/>
</svg>

<!-- viewBox shifts the visible area -->
<svg viewBox="50 50 50 50" width="200" height="200">
  <!-- Now showing only the bottom-right quadrant -->
  <!-- The same circle, but zoomed in 2x on that corner -->
  <circle cx="50" cy="50" r="50" fill="blue"/>
</svg>

preserveAspectRatio

preserveAspectRatio는 종횡비가 다를 때 viewBox가 요소에 맞는 방식을 제어합니다. 'meet'(기본)은 전체를 맞추고 남는 공간을 레터박스로 둡니다. 'slice'는 전체를 채우고 넘치는 부분을 자릅니다. 'none'은 늘려 왜곡합니다. xMidYMid 부분은 정렬을 제어하며 양 축에 Min/Mid/Max를 씁니다.

svg
<!-- Default: preserve aspect ratio, center, letterbox -->
<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="xMidYMid meet">
  <rect width="100" height="50" fill="blue"/>
</svg>

<!-- "slice": fill entirely, crop overflow -->
<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="xMidYMid slice">
  <rect width="100" height="50" fill="red"/>
</svg>

<!-- "none": stretch to fill (distorts) -->
<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="none">
  <rect width="100" height="50" fill="green"/>
</svg>

완전 반응형 SVG

반응형 SVG: width/height 속성을 생략하고 viewBox를 설정한 뒤 CSS(width: 100%, height: auto)로 크기를 제어하세요. SVG가 종횡비를 유지하며 컨테이너에 맞게 스케일됩니다. display: block은 인라인 SVG의 기준선 간격을 없앱니다. 반응형 레이아웃에서 유동 SVG의 표준 패턴입니다.

svg
<!-- Omit width/height, set viewBox, use CSS to size -->
<svg viewBox="0 0 100 100" style="width: 100%; height: auto; display: block;">
  <circle cx="50" cy="50" r="50" fill="orange"/>
</svg>

<!-- In a container with max-width -->
<div style="max-width: 500px; margin: auto;">
  <svg viewBox="0 0 400 300" style="width: 100%; height: auto;">
    <rect width="400" height="300" fill="steelblue"/>
  </svg>
</div>

중첩 SVG와 overflow

중첩 <svg> 요소는 자체 viewBox와 preserveAspectRatio를 가진 독립 뷰포트를 만듭니다. 고정 종횡비 패널이 있는 차트나 UI 컴포넌트에 강력합니다. overflow='visible'은 콘텐츠가 중첩 뷰포트 밖으로 그려지게 합니다(기본은 hidden). 각 중첩 svg는 콘텐츠를 독립적으로 스케일할 수 있습니다.

svg
<svg width="300" height="200" viewBox="0 0 300 200">
  <!-- Nested SVG creates a new viewport -->
  <svg x="10" y="10" width="100" height="100" viewBox="0 0 50 50">
    <circle cx="25" cy="25" r="25" fill="red"/>
  </svg>

  <!-- overflow="hidden" (default) clips content outside -->
  <svg x="120" y="10" width="100" height="100" viewBox="0 0 50 50"
       overflow="visible">
    <circle cx="25" cy="25" r="30" fill="blue"/>
  </svg>

  <!-- Each nested svg can have its own preserveAspectRatio -->
  <svg x="230" y="10" width="60" height="100" viewBox="0 0 50 50"
       preserveAspectRatio="xMidYMid slice">
    <circle cx="25" cy="25" r="25" fill="green"/>
  </svg>
</svg>

유동 텍스트 크기

viewBox가 있는 SVG 내부의 글꼴 크기는 SVG와 함께 스케일됩니다. 400 너비 viewBox의 20px 글꼴을 800px 너비로 표시하면 40px로 렌더링됩니다. 텍스트를 (SVG가 아닌) 브라우저 뷰포트에 반응하게 하려면 style 속성에 CSS 뷰포트 단위(vw, vh)를 사용하세요. SVG 헤드라인이 유동적으로 스케일되는 방식입니다.

svg
<svg viewBox="0 0 400 100" style="width:100%;height:auto;">
  <style>
    /* Use viewBox units for font-size — scales with the SVG */
    text { font-size: 20px; }
    /* Note: 'px' here means SVG user units, not CSS px */
  </style>

  <text x="200" y="50" text-anchor="middle">Scales with SVG</text>
</svg>

<!-- For truly responsive text relative to viewport, use CSS: -->
<svg viewBox="0 0 400 100" style="width:100%;height:auto;">
  <text x="200" y="50" text-anchor="middle"
        style="font-size: 5vw;">5% of viewport width</text>
</svg>

<!-- Or use container queries / media queries on the SVG element -->

종횡비 제어

컨테이너의 CSS aspect-ratio와 SVG의 width/height 100%를 결합하면 예측 가능한 반응형 동작을 얻습니다. SVG 로드 전에 공간을 예약해 레이아웃 이동(CLS)을 막습니다. viewBox가 종횡비와 일치해야 콘텐츠가 왜곡되지 않습니다. 반응형 SVG 임베드의 현대 모범 사례입니다.

svg
<!-- Use CSS aspect-ratio for consistent sizing -->
<div style="width: 100%; max-width: 600px; aspect-ratio: 16/9;">
  <svg viewBox="0 0 1600 900" style="width:100%;height:100%;">
    <rect width="1600" height="900" fill="black"/>
    <text x="800" y="450" text-anchor="middle" dominant-baseline="middle"
          fill="white" font-size="48">16:9 Container</text>
  </svg>
</div>

<!-- aspect-ratio ensures the container keeps proportions -->
<!-- even before the SVG loads, preventing layout shift -->
16

SVG vs Canvas

렌더링 모델

SVG는 유지 모드입니다. 모든 도형이 DOM 요소라 검사, 스타일링, 재애니메이션이 가능합니다. Canvas는 즉시 모드입니다. 그리기 명령으로 픽셀을 칠하고 도형은 객체로 남지 않습니다. 대화형 UI에는 SVG, 수천 개의 동적 픽셀에는 Canvas가 적합합니다.

svg
<!-- SVG: retained mode (DOM-based) -->
<svg width="200" height="100">
  <circle cx="50" cy="50" r="30" fill="red"/>
  <!-- Each element is a DOM node, accessible via JS -->
</svg>

<!-- Canvas: immediate mode (pixel-based) -->
<canvas id="c" width="200" height="100"></canvas>
<script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.beginPath();
  ctx.arc(50, 50, 30, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.fill();
  // Pixels are drawn; the circle isn't an object anymore
</script>

SVG를 쓸 때

다음에는 SVG를 선택하세요: 해상도 독립 그래픽(아이콘, 로고), 접근성(스크린 리더가 DOM 순회), 상호작용(도형별 이벤트), SEO(텍스트 선택 가능), 적당한 요소 수(수백 개까지). SVG 파일은 텍스트라(gzip이 잘 됨) 디자인 도구에서 편집할 수 있습니다.

svg
<!-- SVG is ideal for:
     - Icons and logos (crisp at any size)
     - Charts with few elements (D3.js)
     - Interactive diagrams (clickable shapes)
     - Illustrations with editable layers
     - Accessibility-required graphics
-->
<svg viewBox="0 0 24 24" width="48" height="48">
  <path d="M12 2 L2 22 H22 Z" fill="triangle"/>
</svg>
<!-- Stays sharp whether displayed at 16px or 1024px -->
<!-- Each part can have its own click handler -->
<!-- Screen readers can access <title> and <desc> -->

Canvas를 쓸 때

다음에는 Canvas를 선택하세요: 많은 요소 수(수천 도형), 프레임별 다시 그리기(게임, 입자), 픽셀 조작(필터, 효과), DOM 접근성이 필요 없을 때. Canvas는 순수 픽셀 처리량이 빠르지만 개별 도형 수준의 접근성이나 상호작용은 만들기 어렵습니다.

svg
<!-- Canvas is ideal for:
     - Games (hundreds of sprites per frame)
     - Particle systems
     - Real-time image processing
     - Heatmaps with thousands of cells
     - Physics simulations
-->
<canvas id="particles" width="800" height="600"></canvas>
<script>
  var ctx = document.getElementById("particles").getContext("2d");
  var particles = [];
  for (var i = 0; i < 5000; i++) {
    particles.push({ x: Math.random()*800, y: Math.random()*600 });
  }
  function draw() {
    ctx.clearRect(0, 0, 800, 600);
    particles.forEach(function (p) {
      ctx.fillRect(p.x, p.y, 2, 2);
    });
    requestAnimationFrame(draw);
  }
  draw();
</script>

성능 비교

SVG 성능은 요소 수가 늘면 저하됩니다. 각 도형이 이벤트 처리, 스타일, 레이아웃을 가진 DOM 노드이기 때문입니다. Canvas는 도형 수와 무관하게 프레임당 일정한 오버헤드를 가집니다. 복잡도에 따라 전환점은 약 500-2000 요소입니다. 정적이거나 가벼운 애니메이션에는 SVG, 밀집한 실시간 장면에는 Canvas를 사용하세요.

svg
<!-- SVG DOM overhead grows with element count -->
<!-- 100 circles: SVG ~0.1ms, Canvas ~0.1ms (both fine) -->
<!-- 1000 circles: SVG ~10ms, Canvas ~1ms (Canvas pulls ahead) -->
<!-- 10000 circles: SVG ~500ms+, Canvas ~10ms (SVG struggles) -->

<!-- SVG advantages:
     - No redraw needed for CSS changes (browser handles it)
     - Hardware-accelerated transforms
     - Only changed elements re-render (incremental)
-->
<!-- Canvas advantages:
     - Constant redraw cost regardless of history
     - No DOM memory overhead per shape
     - Direct pixel access (getImageData, putImageData)
-->

하이브리드 접근

둘을 결합하세요. 밀집하고 자주 다시 그리는 레이어(히트맵, 입자)에는 Canvas, 대화형 UI(툴팁, 선택 핸들, 라벨)에는 SVG를 겹칩니다. SVG 레이어는 선명하고 접근 가능하게 유지되고 Canvas가 무거운 픽셀 작업을 처리합니다. Leaflet 같은 지도 라이브러리와 ECharts 같은 차팅 도구가 쓰는 패턴입니다.

svg
<!-- SVG for UI chrome, Canvas for dense content -->
<div style="position:relative; width:800px; height:600px;">
  <!-- Canvas renders the heatmap (fast for thousands of cells) -->
  <canvas width="800" height="600" style="position:absolute; top:0; left:0;">
  </canvas>

  <!-- SVG overlay for interactive tooltips and selection -->
  <svg width="800" height="600" viewBox="0 0 800 600"
       style="position:absolute; top:0; left:0;">
    <g id="overlay"></g>
  </svg>
</div>

<script>
  // Draw heatmap on canvas (performant)
  // Add hover tooltips as SVG elements (accessible, styled)
</script>

접근성 비교

SVG는 본질적으로 접근성이 좋습니다. DOM을 순회할 수 있고 텍스트가 선택/검색 가능하며 <title>/<desc>가 설명을 제공합니다. Canvas는 추가 작업이 필요합니다. role/aria-label을 추가하고 <canvas> 태그 안에 텍스트 폴백 콘텐츠를 제공해야 합니다. 차트와 데이터 시각화에서 SVG의 접근성은 큰 장점입니다.

svg
<!-- SVG: screen readers traverse the DOM -->
<svg role="img" aria-label="Sales chart showing 20% growth">
  <title>Sales Chart</title>
  <desc>Bar chart with 5 quarters, Q3 highest at $2M</desc>
  <rect .../>  <!-- each bar is a DOM element -->
</svg>
<!-- Text in SVG is selectable and searchable -->

<!-- Canvas: just pixels to a screen reader -->
<canvas role="img" aria-label="Sales chart showing 20% growth">
  <!-- Must provide text fallback inside the canvas tag -->
  Sales chart: Q1 $1M, Q2 $1.3M, Q3 $2M, Q4 $1.8M
</canvas>
<!-- No DOM, no selectable text, harder to make accessible -->
17

SVG 스프라이트

인라인 스프라이트 설정

페이지 맨 위의 숨겨진 SVG 안에 모든 아이콘을 <symbol> 요소로 정의하세요. 각 심볼은 자체 viewBox와 id를 가집니다. 스프라이트는 한 번 로드되어 세션 동안 캐시됩니다. fill/stroke에 currentColor를 쓰면 각 사용처가 주변 텍스트 색을 상속해 테마 적용이 간단해집니다.

svg
<!-- Place this hidden SVG at the top of your HTML body -->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
  <symbol id="icon-home" viewBox="0 0 24 24">
    <path d="M12 3 L2 12 H5 V21 H10 V14 H14 V21 H19 V12 H22 Z"/>
  </symbol>
  <symbol id="icon-user" viewBox="0 0 24 24">
    <circle cx="12" cy="8" r="4"/>
    <path d="M4 21 C 4 16, 8 14, 12 14 C 16 14, 20 16, 20 21 Z"/>
  </symbol>
  <symbol id="icon-search" viewBox="0 0 24 24">
    <circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/>
    <line x1="16" y1="16" x2="21" y2="21" stroke="currentColor" stroke-width="2"/>
  </symbol>
</svg>

스프라이트 아이콘 사용

각 <use>가 아이콘을 인스턴스화합니다. CSS .icon 클래스가 기본 크기를 설정하고 하위 클래스가 변형을 위해 덮어씁니다. 심볼이 fill='currentColor'를 쓰므로 아이콘 색이 CSS color 속성을 따릅니다. 버튼에 color를 설정하면 아이콘도 맞춰집니다. 주요 아이콘 시스템(GitHub, Bootstrap)이 이렇게 동작합니다.

svg
<!-- Reference any icon with <use> -->
<svg class="icon"><use href="#icon-home"/></svg>
<svg class="icon"><use href="#icon-user"/></svg>
<svg class="icon icon-large"><use href="#icon-search"/></svg>

<style>
  .icon {
    width: 24px;
    height: 24px;
    fill: currentColor;  /* inherits text color */
    display: inline-block;
    vertical-align: middle;
  }
  .icon-large { width: 48px; height: 48px; }
</style>

<!-- Color via CSS color (because fill="currentColor") -->
<button style="color: red;">
  <svg class="icon"><use href="#icon-home"/></svg> Home
</button>

외부 파일 스프라이트

외부 스프라이트 참조(href='file.svg#id')는 브라우저 지원이 고르지 않고 CORS 문제가 있습니다. 견고한 방법은 스프라이트 파일을 가져와 body 맨 위에 인라인 HTML로 주입하는 것입니다. HTTP로 캐시되고 어디서나 동작합니다. 많은 빌드 도구(svg-sprite-loader, gulp-svg-sprite)가 이를 자동화합니다.

svg
<!-- icons.svg (a separate file) -->
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
  <symbol id="icon-home" viewBox="0 0 24 24">...</symbol>
</svg>

<!-- Reference external symbols (limited browser support) -->
<svg class="icon"><use href="icons.svg#icon-home"/></svg>

<!-- More reliable: fetch and inject the sprite -->
<script>
  fetch("icons.svg")
    .then(r => r.text())
    .then(text => {
      var div = document.createElement("div");
      div.style.display = "none";
      div.innerHTML = text;
      document.body.insertBefore(div, document.body.firstChild);
    });
</script>

빌드 시 스프라이트 생성

빌드 도구가 스프라이트 생성을 자동화합니다. 개별 .svg 파일을 폴더에 넣으면 도구가 적절한 <symbol> 래퍼와 함께 스프라이트로 연결합니다. svg-sprite-loader(webpack), gulp-svg-sprite, vite-plugin-svg가 인기 있습니다. 개발 중에는 아이콘을 개별 파일로 유지하고 운영용으로 번들합니다.

svg
<!-- Using svg-sprite-loader (webpack) -->
// import all icons in a folder
const req = require.context("./icons", true, /\.svg$/);
req.keys().forEach(req);

// In your component:
<svg class="icon"><use href="#icon-home"/></svg>

<!-- Using gulp-svg-sprite -->
// gulpfile.js
const svgSprite = require("gulp-svg-sprite");
gulp.task("sprite", () =>
  gulp.src("icons/*.svg")
    .pipe(svgSprite({ mode: { symbol: { dest: "." } } }))
    .pipe(gulp.dest("dist"))
);
// Outputs dist/symbol/svg/sprite.symbol.svg

스프라이트 아이콘 접근성

접근성: 아이콘이 순전히 장식용(텍스트 옆)이면 aria-hidden='true'로 표시하세요. 아이콘만으로 의미를 전달하면 <svg>에 role='img'와 aria-label을 추가하세요. 아이콘만 있는 버튼에는 aria-label을 SVG가 아니라 <button>에 두세요. 접근 가능한 이름 없이 아이콘에만 의존하지 마세요.

svg
<!-- Decorative icon (hidden from screen readers) -->
<svg class="icon" aria-hidden="true">
  <use href="#icon-decoration"/>
</svg>

<!-- Meaningful icon (with label) -->
<svg class="icon" role="img" aria-label="Home">
  <use href="#icon-home"/>
</svg>

<!-- Icon button with visible text (icon is decorative) -->
<button>
  <svg class="icon" aria-hidden="true"><use href="#icon-home"/></svg>
  <span>Home</span>
</button>

<!-- Icon-only button (needs aria-label on the button) -->
<button aria-label="Search">
  <svg class="icon" aria-hidden="true"><use href="#icon-search"/></svg>
</button>

투톤과 다색 아이콘

다색 아이콘은 <use> 복제에서 덮어쓸 수 있는 범위가 제한되어 스프라이트로 만들기 까다롭습니다. 투톤 아이콘은 주 색에 currentColor를, 보조 색에 고정 색을 사용하세요. 심볼 내부의 CSS 사용자 정의 속성(변수)을 쓰면 소비자가 특정 부분을 덮어쓸 수 있어 유연한 테마 적용이 가능합니다.

svg
<svg style="display:none">
  <!-- Icon with two fill regions -->
  <symbol id="icon-mail" viewBox="0 0 24 24">
    <rect x="2" y="4" width="20" height="16" rx="2" fill="currentColor"/>
    <path d="M2 6 L12 13 L22 6" fill="white"/>
  </symbol>
</svg>

<!-- Override individual parts via CSS (limited: works if the
     symbol uses currentColor and CSS variables) -->
<svg class="icon" style="color: steelblue;">
  <use href="#icon-mail"/>
</svg>

<!-- For full multi-color control, use CSS custom properties -->
<symbol id="icon-alert" viewBox="0 0 24 24">
  <path fill="var(--icon-bg, currentColor)" d="M12 2 L2 22 H22 Z"/>
  <text x="12" y="18" text-anchor="middle" fill="var(--icon-fg, white)">!</text>
</symbol>

<svg class="icon" style="--icon-bg: red; --icon-fg: yellow;">
  <use href="#icon-alert"/>
</svg>
18

SVG 최적화

SVGO CLI

SVGO는 표준 SVG 최적화 도구입니다. 메타데이터, 주석, 편집기 찌꺼기(Inkscape/Illustrator 네임스페이스), 미사용 defs, 중복 속성을 제거해 보통 파일 크기를 30-60% 줄입니다. 모든 운영 SVG에 실행하세요. --show-plugins로 기능을 확인하고 설정 파일로 특정 최적화를 켜고 끄세요.

svg
# Install SVGO globally
npm install -g svgo

# Optimize a single file (overwrites)
svgo icon.svg

# Optimize to a new file
svgo icon.svg -o icon.min.svg

# Optimize a folder
svgo -f icons/ -o icons/min/

# Show available plugins
svgo --show-plugins

# Use a specific config
svgo --config=svgo.config.js icon.svg

흔한 최적화

SVGO는 XML 선언, 편집기 주석과 네임스페이스(Adobe, Inkscape), 메타데이터, 미사용 xlink, enable-background, xml:space, 중복 fill-rule='nonzero'(기본값)를 제거합니다. 색상 값을 줄이고(#FF0000 → red) 공백을 합치며 패스를 병합합니다. 결과는 의미상 동일하지만 훨씬 작습니다.

svg
<!-- Before optimization (from Illustrator) -->
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.0 -->
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/"
     width="100px" height="100px" viewBox="0 0 100 100"
     enable-background="new 0 0 100 100" xml:space="preserve">
  <metadata>...</metadata>
  <path d="..." fill="#FF0000" fill-rule="nonzero"/>
</svg>

<!-- After SVGO -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <path d="..." fill="red"/>
</svg>

패스 최적화

SVGO는 더 짧으면 절대 좌표를 상대로 바꾸고, 수평/수직선에 L 대신 H/V를 쓰며, 불필요한 소수를 제거하고, 동일한 모양의 패스를 병합합니다. 이런 패스 최적화가 패스 문자열 길이를 절반으로 줄이는 경우가 많습니다. 'convertPath' 플러그인이 처리하며 기본으로 켜져 있습니다.

svg
<!-- SVGO can merge and simplify paths -->
<!-- Before: multiple paths with redundant points -->
<g>
  <path d="M 10 10 L 20 10 L 20 20 L 10 20 Z" fill="red"/>
  <path d="M 10 10 L 20 10 L 20 20 L 10 20 Z" fill="none" stroke="black"/>
</g>

<!-- After: merged into one path with combined commands -->
<path d="M10 10h10v10H10z" fill="red" stroke="black"/>

<!-- Path command shortcuts:
     L 20 10  ->  h 10  (relative horizontal)
     L 10 20  ->  v 10  (relative vertical)
     Z closes the path
-->

그룹화와 상속

공유 속성(fill, stroke, font)을 부모 <g>로 옮겨 자식이 상속하게 하세요. 파일 크기를 줄이고 대량 스타일 변경을 쉽게 합니다. SVGO의 'mergePaths'와 'moveElemsAttrsToGroup' 플러그인이 이를 자동화합니다. SVG를 직접 작성할 때는 처음부터 그룹화하세요. 더 깔끔하고 유지보수하기 쉽습니다.

svg
<!-- Before: repeated attributes on each element -->
<svg viewBox="0 0 100 100">
  <rect x="10" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
  <rect x="40" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
  <rect x="70" y="10" width="20" height="20" fill="red" stroke="black" stroke-width="2"/>
</svg>

<!-- After: group with shared attributes -->
<svg viewBox="0 0 100 100">
  <g fill="red" stroke="black" stroke-width="2">
    <rect x="10" y="10" width="20" height="20"/>
    <rect x="40" y="10" width="20" height="20"/>
    <rect x="70" y="10" width="20" height="20"/>
  </g>
</svg>

Gzip과 전달

SVG는 반복적인 XML 텍스트라 gzip이 70-90% 됩니다. 웹 서버가 image/svg+xml을 gzip이나 brotli로 압축하는지 확인하세요. 전달: 중요(첫 화면) SVG는 인라인해 렌더링 차단 요청을 피하고, 화면 밖 일러스트에는 <img loading='lazy'>를 사용하세요. SVG는 거의 바뀌지 않으므로 적극적으로 캐시하세요.

svg
<!-- SVG is text, so it gzips very well (70-90% reduction) -->
<!-- Ensure your server sends SVG with gzip/brotli compression: -->

<!-- Apache .htaccess -->
AddType image/svg+xml .svg
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>

<!-- Nginx -->
# gzip_types image/svg+xml;

<!-- HTML: use the right loading strategy -->
<img src="hero.svg" loading="lazy" decoding="async">

<!-- For above-the-fold critical SVG, inline it to avoid a request -->
<!-- For below-the-fold, use <img loading="lazy"> to defer -->

SVGO 설정 파일

설정 파일로 SVGO를 사용자 정의합니다. 흔한 조정: viewBox 유지(removeViewBox는 기본 켜짐이므로 반응형이 동작하도록 끄세요), 유동 SVG를 위해 width/height 제거(removeDimensions), 스프라이트용 cleanupIDs 활성화(id 이름 단축). multipass는 가장 작은 출력을 위해 안정될 때까지 최적화를 반복합니다.

svg
// svgo.config.js (SVGO 2+)
module.exports = {
  multipass: true,  // run multiple passes for best result
  js2svg: {
    indent: 2,
    pretty: true,   // readable output (false for minified)
  },
  plugins: [
    { name: "preset-default" },         // sensible defaults
    { name: "removeDimensions", active: true },  // remove width/height (use viewBox)
    { name: "removeViewBox", active: false },    // KEEP viewBox (opposite of default)
    { name: "removeXMLNS", active: false },      // keep xmlns for standalone files
    { name: "cleanupIDs", active: true },        // minify id names
    { name: "mergePaths", active: true },
  ],
};
19

모범 사례

접근성 필수 사항

접근 가능한 SVG: <title>과 <desc>를 추가하고 aria-labelledby로 참조하며, role='img'를 설정해 스크린 리더가 SVG를 이미지로 알리게 하고, focusable='false'를 추가해 IE/Edge 탭 정지 문제를 막으세요. 장식용 SVG는 aria-hidden='true'여야 합니다. 이 관행이 보조 기술에서 SVG를 사용 가능하게 만듭니다.

svg
<!-- 1. Always include <title> and <desc> for meaningful SVGs -->
<svg role="img" aria-labelledby="title-id desc-id">
  <title id="title-id">Annual Revenue Chart</title>
  <desc id="desc-id">A bar chart showing revenue from 2019 to 2023,
    rising from $1M to $5M.</desc>
  <!-- chart content -->
</svg>

<!-- 2. Decorative SVG: hide from screen readers -->
<svg aria-hidden="true" focusable="false">
  <!-- purely visual flourish -->
</svg>

<!-- 3. focusable="false" prevents IE/Edge from making SVG focusable -->
<!-- 4. Use role="img" so screen readers treat SVG as a single image -->

width/height 대신 viewBox

항상 viewBox를 포함하세요. 내부 좌표계를 정의하고 스케일링을 가능하게 합니다. 아이콘은 width/height를 (속성이 아닌) CSS로 설정해 같은 SVG가 어떤 크기에서도 동작하게 하세요. 반응형 그래픽은 width/height를 완전히 생략하고 CSS에 width:100%; height:auto를 쓰세요. SVGO의 removeDimensions 플러그인이 이를 강제합니다.

svg
<!-- GOOD: viewBox makes the SVG scalable -->
<svg viewBox="0 0 24 24" style="width: 24px; height: 24px;">
  <path d="..."/>
</svg>

<!-- BAD: fixed width/height limits scalability -->
<svg width="24" height="24">
  <path d="..."/>
</svg>

<!-- For responsive: omit width/height, size with CSS -->
<svg viewBox="0 0 100 100" style="width:100%;height:auto;">
  <circle cx="50" cy="50" r="50"/>
</svg>

테마용 currentColor

fill='currentColor'(또는 stroke)를 쓰면 아이콘이 주변 텍스트 색을 상속합니다. 테마 적용이 간단해져 부모에 color를 설정하면 모든 아이콘이 맞춰집니다. CSS color 전환으로 hover/active 상태도 가능합니다. 브랜드 로고처럼 의도적으로 고정된 경우가 아니면 재사용 심볼에 색을 하드코딩하지 마세요.

svg
<!-- GOOD: use currentColor so the icon inherits text color -->
<symbol id="icon" viewBox="0 0 24 24">
  <path fill="currentColor" d="..."/>
</symbol>

<!-- Usage: color via CSS -->
<button style="color: tomato;">
  <svg class="icon"><use href="#icon"/></svg> Themed
</button>

<button style="color: steelblue;">
  <svg class="icon"><use href="#icon"/></svg> Also themed
</button>

<!-- BAD: hardcoded colors can't be themed -->
<symbol id="icon">
  <path fill="#333333" d="..."/>  <!-- always gray -->
</symbol>

의미 기반 그룹화

요소를 도형 타입이 아니라 논리적 역할(배경, 축, 데이터, 라벨)과 의미 있는 id로 그룹화하세요. SVG를 유지보수, 스타일링, 스크립팅하기 쉬워져 그룹 전체를 표시/숨김하거나 다시 스타일링할 수 있습니다. 접근성(그룹의 aria-labelledby)과 디버깅에도 도움이 됩니다.

svg
<svg viewBox="0 0 200 200">
  <!-- Group by logical component, not just by shape type -->
  <g id="background">
    <rect width="200" height="200" fill="#f0f0f0"/>
  </g>
  <g id="chart-axis">
    <line x1="20" y1="180" x2="180" y2="180" stroke="black"/>
    <line x1="20" y1="20" x2="20" y2="180" stroke="black"/>
  </g>
  <g id="chart-data" fill="steelblue">
    <rect x="30" y="100" width="20" height="80"/>
    <rect x="60" y="60" width="20" height="120"/>
    <rect x="90" y="80" width="20" height="100"/>
  </g>
  <g id="labels" font-size="10" fill="black">
    <text x="40" y="195" text-anchor="middle">Q1</text>
    <text x="70" y="195" text-anchor="middle">Q2</text>
  </g>
</svg>

과도한 그리기와 복잡도 피하기

오버드로(완전히 가려진 도형 그리기)는 렌더링 시간을 낭비하므로 숨은 요소를 제거하세요. 패스를 단순화하세요. 수백 개의 작은 선분 대신 C/Q 곡선을 쓰고 소수 정밀도를 줄이세요(10.499999 → 10.5). 복잡한 일러스트는 래스터 이미지가 더 작고 빠를지 고려하세요. 브라우저 페인트 프로파일러로 측정하세요.

svg
<!-- BAD: layered shapes that cover each other (overdraw) -->
<g>
  <rect width="100" height="100" fill="red"/>
  <rect width="100" height="100" fill="blue"/>  <!-- covers red -->
  <rect width="100" height="100" fill="green"/> <!-- covers blue -->
</g>
<!-- The red and blue are never visible but still rendered -->

<!-- GOOD: only draw what's visible -->
<rect width="100" height="100" fill="green"/>

<!-- BAD: path with 10,000 points for a simple shape -->
<path d="..."/>  <!-- over-tessellated -->

<!-- GOOD: simplify paths; use curves instead of many line segments -->
<path d="M 10 50 Q 50 10, 90 50"/>  <!-- one curve vs 100 lines -->

테스트와 검증

SVG를 코드처럼 테스트하세요. XML을 검증하고, 브라우저 간 렌더링(Safari는 일부 필터에서 특이점이 있음)을 확인하며, 다양한 크기(16px 아이콘 vs 500px 히어로)에서 테스트하고, 스크린 리더 출력을 검증하며, 파일 크기(아이콘은 2KB 미만 권장)를 확인하세요. CI에서 SVGO를 실행해 최적화되지 않은 SVG가 배포되지 않게 하세요. 작은 테스트가 운영 환경의 놀라움을 막습니다.

svg
<!-- 1. Validate SVG XML -->
<!-- Use the W3C validator: https://validator.w3.org/ -->

<!-- 2. Test in multiple browsers -->
<!-- Chrome, Firefox, Safari, Edge, (IE if required) -->

<!-- 3. Test at different sizes -->
<div style="width: 16px;"><svg>...</svg></div>  <!-- icon -->
<div style="width: 500px;"><svg>...</svg></div> <!-- hero -->

<!-- 4. Test with screen readers (VoiceOver, NVDA) -->

<!-- 5. Check file size after optimization -->
ls -la icon.svg  # should be under 2KB for simple icons

<!-- 6. Verify currentColor theming works -->
<!-- 7. Ensure no hardcoded dimensions block responsiveness -->

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.