기본 구조
SVG 문서 골격
xmlns 속성은 SVG 네임스페이스를 선언합니다. width/height는 렌더링 크기를 픽셀로 설정합니다. viewBox는 내부 좌표계를 정의합니다. SVG는 독립 .svg 파일이거나 HTML에 인라인으로 포함될 수 있으며, 인라인일 때 XML 선언과 xmlns는 선택 사항입니다.
<?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을 가지며 일부 스크립팅을 허용합니다.
<!-- 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 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 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 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 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>도형
사각형(rect)
rect는 x, y, width, height가 필요합니다. rx/ry는 둥근 모서리를 만듭니다(rx만 설정하면 ry는 rx를 따름). fill='none'은 내부를 투명하게 만듭니다. stroke-width는 가장자리 중심에 그려지므로 절반이 도형 바깥으로 나갑니다.
<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 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 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 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 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 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>패스
패스 명령 개요
<path> 요소는 가장 강력한 SVG 도형입 니다. d 속성에 그리기 명령 문자열이 담깁니다. 대문자 명령은 절대 좌표, 소문자는 현재 펜 위치 기준 상대 좌표를 사용합니다. M, L, C, Q, A, Z가 핵심 명령입니다.
<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 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 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 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 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 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>텍스트
기본 텍스트
y 좌표는 기본적으로 위쪽이 아니라 텍스트 기준선을 가리킵니다. text-anchor(start/middle/end)는 x 기준 수평 정렬을, dominant-baseline(auto/middle/hanging/...)은 수직 정렬을 제어합니다. 둘 다 텍스트를 가운데 정렬하는 데 필수입니다.
<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 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 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 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 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 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>그라디언트
선형 그라디언트
linearGradient는 선을 따라 색을 전환합니다. x1/y1에서 x2/y2가 방향을 정의합니다(0% 0%에서 100% 0%는 왼쪽에서 오른쪽). <stop> 요소는 색상 지점을 정의하고 offset은 0-100% 또는 0-1입니다. fill='url(#id)'로 그라디언트를 참조하세요. 그라디언트는 <defs> 안에 있어야 합니다.
<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 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 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 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 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>패턴
기본 패턴
<pattern>은 반복 그래픽을 타일링합니다. 패턴의 자식이 타일 하나를 정의하고 width/height가 타일 크기를 설정합니다. patternUnits='userSpaceOnUse'(권장)는 타일 크기를 채우는 도형과 무관한 SVG 사용자 단위로 지정합니다. fill='url(#id)'로 참조하세요.
<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 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 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 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 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>변환
이동
translate(tx, ty)는 요소를 tx, ty만큼 이동합니다. ty를 생략하면 0입니다. 변환은 요소의 좌표계에 적용되므로 x/y 속성은 이동된 원점 기준입니다. CSS 변환(style 경유)은 최신 브라우저의 인라인 SVG에서 동작하고 CSS 전환으로 애니메이션할 수 있습니다.
<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 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 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 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 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 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>그룹(g)
기본 그룹화
<g>는 요소를 묶어 속성(fill, stroke, transform 등)을 공유하고 하나의 단위로 조작하게 합니다. 자식은 그룹의 표현 속성을 상속합니다. 복잡한 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 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 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 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 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 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>Use / Symbol / Defs
defs 요소
<defs>는 참조되기 전까지 그려지지 않는 재사용 정의를 담습니다: 그라디언트, 패턴, 필터, 클립 경로, 마스크, 심볼, 그룹. defs에 두면 렌더링 출력이 깔끔해지고 의도가 드러납니다. defs 밖의 것은 즉시 렌더링됩니다.
<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 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 아이콘 시스템의 표준 패턴입니다.
<!-- 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 스프라이트를 인라인하고 같은 문서 안의 심볼을 참조하는 것입니다.
<!-- 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 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가 제어합니다. 스프라이트는 첫 로드 후 캐시되어 모든 페이지에서 빠릅니다.
<!-- 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>필터
필터 기초
<filter>는 그래픽을 처리하는 하나 이상의 필터 기본 요소(fe* 요소)를 담습니다. in='SourceGraphic'은 요소 자체의 렌더링을 받습니다. filter='url(#id)'로 적용하세요. 필터는 비쌀 수 있으므로 큰 배경이 아니라 작은 요소에 드물게 사용하세요.
<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 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 필터를 사용하세요.
<!-- 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 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 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 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>클리핑과 마스킹
클립 경로
clipPath는 단단한 경계를 정의합니다. 안쪽 픽셀은 보이고 바깥은 숨겨집니다. 클립 도형 자체는 그려지지 않습니다. clip-path가 url(#id)로 참조합니다. 클리핑은 이진(안/밖)이므로 부드러운 전환에는 마스크를 사용하세요. 텍스트를 클립 경로로 쓰면 고전적인 '텍스트 안의 이미지' 효과가 생깁니다.
<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 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 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 마스킹도 지원합니다.
<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 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>애니메이션(SMIL)
animate(기본)
<animate>는 속성을 시간에 따라 전환합니다. attributeName은 대상, from/to는 범위, dur는 지속 시간, repeatCount='indefinite'는 영구 반복입니다. SMIL 애니메이션은 선언적이라 JS가 필요 없고 IE를 제외한 대부분의 브라우저에서 동작합니다. 애니메이션은 대상 요소의 자식으로 둡니다.
<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 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 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 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 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 불가)과 경로 기반 모션에 여전히 유용합니다.