0
# SVG Components and Graphics
1
2
Comprehensive SVG element generation system for creating scalable vector graphics, charts, diagrams, and interactive visualizations.
3
4
## Capabilities
5
6
### SVG Root Element
7
8
Create SVG container elements with automatic namespace handling and viewport configuration.
9
10
```python { .api }
11
def Svg(*args, viewBox=None, h=None, w=None, height=None, width=None, xmlns="http://www.w3.org/2000/svg", **kwargs):
12
"""
13
SVG root element with automatic xmlns namespace.
14
15
Creates the main SVG container with proper namespace declaration
16
and optional viewport configuration.
17
18
Args:
19
*args: Child SVG elements
20
viewBox: Viewport definition (e.g., "0 0 100 100")
21
h: Height (alternative to height)
22
w: Width (alternative to width)
23
height: SVG height
24
width: SVG width
25
xmlns: XML namespace (automatically set)
26
**kwargs: Additional SVG attributes
27
28
Returns:
29
SVG root element with namespace and configuration
30
"""
31
32
def ft_svg(tag: str, *c, transform=None, opacity=None, clip=None, mask=None, filter=None, **kwargs):
33
"""
34
Create SVG element with SVG-specific attributes.
35
36
Enhanced SVG element creation with support for SVG-specific
37
attributes like transforms, clipping, and filters.
38
39
Args:
40
tag: SVG element tag name
41
*c: Child content
42
transform: SVG transform attribute
43
opacity: Element opacity (0-1)
44
clip: Clipping path reference
45
mask: Mask reference
46
filter: Filter reference
47
**kwargs: Additional SVG attributes
48
49
Returns:
50
SVG element with processed attributes
51
"""
52
```
53
54
### Basic SVG Shapes
55
56
Fundamental geometric shapes for building SVG graphics.
57
58
```python { .api }
59
def Rect(width, height, x=0, y=0, fill=None, stroke=None, stroke_width=None, rx=None, ry=None, **kwargs):
60
"""
61
SVG rectangle element.
62
63
Args:
64
width: Rectangle width
65
height: Rectangle height
66
x: X coordinate of top-left corner
67
y: Y coordinate of top-left corner
68
fill: Fill color
69
stroke: Stroke color
70
stroke_width: Stroke width
71
rx: X-axis corner radius
72
ry: Y-axis corner radius
73
**kwargs: Additional attributes
74
75
Returns:
76
SVG rect element
77
"""
78
79
def Circle(r, cx=0, cy=0, fill=None, stroke=None, stroke_width=None, **kwargs):
80
"""
81
SVG circle element.
82
83
Args:
84
r: Circle radius
85
cx: Center X coordinate
86
cy: Center Y coordinate
87
fill: Fill color
88
stroke: Stroke color
89
stroke_width: Stroke width
90
**kwargs: Additional attributes
91
92
Returns:
93
SVG circle element
94
"""
95
96
def Ellipse(rx, ry, cx=0, cy=0, fill=None, stroke=None, stroke_width=None, **kwargs):
97
"""
98
SVG ellipse element.
99
100
Args:
101
rx: X-axis radius
102
ry: Y-axis radius
103
cx: Center X coordinate
104
cy: Center Y coordinate
105
fill: Fill color
106
stroke: Stroke color
107
stroke_width: Stroke width
108
**kwargs: Additional attributes
109
110
Returns:
111
SVG ellipse element
112
"""
113
114
def Line(x1, y1, x2=0, y2=0, stroke='black', w=None, stroke_width=1, **kwargs):
115
"""
116
SVG line element.
117
118
Args:
119
x1: Starting X coordinate
120
y1: Starting Y coordinate
121
x2: Ending X coordinate
122
y2: Ending Y coordinate
123
stroke: Line color
124
w: Line width (alternative to stroke_width)
125
stroke_width: Line width
126
**kwargs: Additional attributes
127
128
Returns:
129
SVG line element
130
"""
131
```
132
133
### Complex Shapes and Paths
134
135
Advanced shape elements for complex graphics and custom paths.
136
137
```python { .api }
138
def Polyline(*args, points=None, fill=None, stroke=None, stroke_width=None, **kwargs):
139
"""
140
SVG polyline element for connected line segments.
141
142
Args:
143
*args: Point coordinates as individual arguments
144
points: Points as string or list (e.g., "0,0 10,10 20,0")
145
fill: Fill color
146
stroke: Stroke color
147
stroke_width: Stroke width
148
**kwargs: Additional attributes
149
150
Returns:
151
SVG polyline element
152
"""
153
154
def Polygon(*args, points=None, fill=None, stroke=None, stroke_width=None, **kwargs):
155
"""
156
SVG polygon element for closed shapes.
157
158
Args:
159
*args: Point coordinates as individual arguments
160
points: Points as string or list
161
fill: Fill color
162
stroke: Stroke color
163
stroke_width: Stroke width
164
**kwargs: Additional attributes
165
166
Returns:
167
SVG polygon element
168
"""
169
170
class PathFT:
171
"""Advanced path builder for complex SVG paths."""
172
173
def __init__(self):
174
"""Initialize path builder."""
175
176
def M(self, x, y):
177
"""Move to absolute position."""
178
179
def L(self, x, y):
180
"""Line to absolute position."""
181
182
def C(self, x1, y1, x2, y2, x, y):
183
"""Cubic Bézier curve."""
184
185
def Z(self):
186
"""Close path."""
187
188
def Path(d='', fill=None, stroke=None, stroke_width=None, **kwargs):
189
"""
190
SVG path element for complex shapes.
191
192
Args:
193
d: Path data string (SVG path commands)
194
fill: Fill color
195
stroke: Stroke color
196
stroke_width: Stroke width
197
**kwargs: Additional attributes
198
199
Returns:
200
SVG path element
201
"""
202
```
203
204
### Text and Typography
205
206
SVG text elements with advanced typography features.
207
208
```python { .api }
209
def Text(*args, x=0, y=0, font_family=None, font_size=None, fill=None, text_anchor=None, **kwargs):
210
"""
211
SVG text element.
212
213
Args:
214
*args: Text content
215
x: X coordinate
216
y: Y coordinate
217
font_family: Font family name
218
font_size: Font size
219
fill: Text color
220
text_anchor: Text alignment (start, middle, end)
221
**kwargs: Additional text attributes
222
223
Returns:
224
SVG text element
225
"""
226
```
227
228
### Grouping and Organization
229
230
Elements for organizing and structuring complex SVG graphics.
231
232
```python { .api }
233
def G(*args, **kwargs):
234
"""
235
SVG group element for organizing related elements.
236
237
Args:
238
*args: Child SVG elements
239
**kwargs: Group attributes (transform, etc.)
240
241
Returns:
242
SVG g (group) element
243
"""
244
245
def Defs(*args, **kwargs):
246
"""
247
SVG definitions element for reusable components.
248
249
Args:
250
*args: Definition elements (gradients, patterns, etc.)
251
**kwargs: Additional attributes
252
253
Returns:
254
SVG defs element
255
"""
256
257
def Use(href=None, x=0, y=0, **kwargs):
258
"""
259
SVG use element for referencing defined elements.
260
261
Args:
262
href: Reference to defined element (e.g., "#myElement")
263
x: X coordinate offset
264
y: Y coordinate offset
265
**kwargs: Additional attributes
266
267
Returns:
268
SVG use element
269
"""
270
271
def Symbol(*args, viewBox=None, **kwargs):
272
"""
273
SVG symbol element for reusable graphics.
274
275
Args:
276
*args: Symbol content
277
viewBox: Symbol viewport
278
**kwargs: Additional attributes
279
280
Returns:
281
SVG symbol element
282
"""
283
```
284
285
### Gradients and Patterns
286
287
Advanced fill and stroke options using gradients and patterns.
288
289
```python { .api }
290
def LinearGradient(*args, id=None, x1=None, y1=None, x2=None, y2=None, **kwargs):
291
"""
292
SVG linear gradient definition.
293
294
Args:
295
*args: Gradient stops
296
id: Gradient identifier for referencing
297
x1: Starting X coordinate (0-1 or percentage)
298
y1: Starting Y coordinate (0-1 or percentage)
299
x2: Ending X coordinate (0-1 or percentage)
300
y2: Ending Y coordinate (0-1 or percentage)
301
**kwargs: Additional gradient attributes
302
303
Returns:
304
SVG linearGradient element
305
"""
306
307
def RadialGradient(*args, id=None, cx=None, cy=None, r=None, **kwargs):
308
"""
309
SVG radial gradient definition.
310
311
Args:
312
*args: Gradient stops
313
id: Gradient identifier
314
cx: Center X coordinate
315
cy: Center Y coordinate
316
r: Gradient radius
317
**kwargs: Additional gradient attributes
318
319
Returns:
320
SVG radialGradient element
321
"""
322
323
def Stop(offset, stop_color=None, stop_opacity=None, **kwargs):
324
"""
325
SVG gradient stop.
326
327
Args:
328
offset: Stop position (0-1 or percentage)
329
stop_color: Stop color
330
stop_opacity: Stop opacity
331
**kwargs: Additional stop attributes
332
333
Returns:
334
SVG stop element
335
"""
336
337
def Pattern(*args, id=None, width=None, height=None, patternUnits=None, **kwargs):
338
"""
339
SVG pattern definition for complex fills.
340
341
Args:
342
*args: Pattern content
343
id: Pattern identifier
344
width: Pattern width
345
height: Pattern height
346
patternUnits: Pattern coordinate system
347
**kwargs: Additional pattern attributes
348
349
Returns:
350
SVG pattern element
351
"""
352
```
353
354
### Transform Utilities
355
356
Utility functions for SVG transformations.
357
358
```python { .api }
359
def transformd(translate=None, scale=None, rotate=None, skewX=None, skewY=None, matrix=None):
360
"""
361
Transform dictionary to SVG transform string.
362
363
Converts transform parameters to SVG transform attribute string.
364
365
Args:
366
translate: Translation (x, y) tuple
367
scale: Scale factor or (x, y) tuple
368
rotate: Rotation angle in degrees
369
skewX: X-axis skew angle
370
skewY: Y-axis skew angle
371
matrix: Transform matrix (a, b, c, d, e, f)
372
373
Returns:
374
str: SVG transform attribute string
375
"""
376
```
377
378
### HTMX Integration
379
380
SVG elements with HTMX support for dynamic graphics.
381
382
```python { .api }
383
def SvgOob(*args, **kwargs):
384
"""
385
SVG out-of-band update for HTMX.
386
387
Args:
388
*args: SVG content for out-of-band update
389
**kwargs: Update attributes
390
391
Returns:
392
SVG element with HTMX out-of-band attributes
393
"""
394
395
def SvgInb(*args, **kwargs):
396
"""
397
SVG inline update for HTMX.
398
399
Args:
400
*args: SVG content for inline update
401
**kwargs: Update attributes
402
403
Returns:
404
SVG element with HTMX inline attributes
405
"""
406
```
407
408
## Usage Examples
409
410
### Basic SVG Graphics
411
412
```python
413
from fasthtml.common import *
414
415
app, rt = fast_app()
416
417
@rt('/svg-demo')
418
def svg_demo():
419
return Titled("SVG Graphics Demo",
420
Container(
421
H1("SVG Components"),
422
423
# Basic shapes
424
Div(
425
H2("Basic Shapes"),
426
Svg(
427
Rect(width="100", height="60", x="10", y="10",
428
fill="lightblue", stroke="navy", stroke_width="2"),
429
Circle(r="30", cx="80", cy="80",
430
fill="lightcoral", stroke="darkred", stroke_width="2"),
431
Ellipse(rx="40", ry="20", cx="150", cy="50",
432
fill="lightgreen", stroke="darkgreen", stroke_width="2"),
433
Line(x1="10", y1="120", x2="180", y2="120",
434
stroke="purple", stroke_width="3"),
435
viewBox="0 0 200 140",
436
width="400",
437
height="280"
438
)
439
),
440
441
# Text and typography
442
Div(
443
H2("SVG Text"),
444
Svg(
445
Text("Hello SVG!", x="10", y="30",
446
font_family="Arial", font_size="20", fill="darkblue"),
447
Text("Centered Text", x="100", y="60",
448
text_anchor="middle", font_size="16", fill="red"),
449
Text("Right Aligned", x="190", y="90",
450
text_anchor="end", font_size="14", fill="green"),
451
viewBox="0 0 200 100",
452
width="400",
453
height="200"
454
)
455
)
456
)
457
)
458
```
459
460
### Complex Shapes and Paths
461
462
```python
463
from fasthtml.common import *
464
465
app, rt = fast_app()
466
467
@rt('/svg-complex')
468
def svg_complex():
469
return Titled("Complex SVG Shapes",
470
Container(
471
H1("Advanced SVG Graphics"),
472
473
# Polygons and polylines
474
Div(
475
H2("Polygons and Polylines"),
476
Svg(
477
Polygon(points="50,10 90,90 10,90",
478
fill="orange", stroke="darkorange", stroke_width="2"),
479
Polyline(points="110,10 150,50 190,10 230,50 270,10",
480
fill="none", stroke="blue", stroke_width="3"),
481
viewBox="0 0 280 100",
482
width="560",
483
height="200"
484
)
485
),
486
487
# Custom paths
488
Div(
489
H2("Custom Paths"),
490
Svg(
491
Path(d="M10,50 Q50,10 90,50 T170,50",
492
fill="none", stroke="purple", stroke_width="3"),
493
Path(d="M10,80 C10,80 50,40 90,80 S170,120 210,80",
494
fill="none", stroke="darkgreen", stroke_width="2"),
495
Path(d="M10,110 L50,110 L30,140 Z",
496
fill="red", stroke="darkred", stroke_width="2"),
497
viewBox="0 0 220 150",
498
width="440",
499
height="300"
500
)
501
)
502
)
503
)
504
```
505
506
### Interactive SVG with HTMX
507
508
```python
509
from fasthtml.common import *
510
511
app, rt = fast_app()
512
513
@rt('/svg-interactive')
514
def svg_interactive():
515
return Titled("Interactive SVG",
516
Container(
517
H1("Interactive SVG Graphics"),
518
519
# Interactive shapes
520
Div(
521
H2("Click the shapes to change them"),
522
Svg(
523
Circle(
524
r="30", cx="60", cy="60",
525
fill="lightblue", stroke="navy", stroke_width="2",
526
hx_post="/svg/change-circle",
527
hx_target="#interactive-svg",
528
hx_swap="innerHTML",
529
style="cursor: pointer;"
530
),
531
Rect(
532
width="60", height="40", x="120", y="40",
533
fill="lightcoral", stroke="darkred", stroke_width="2",
534
hx_post="/svg/change-rect",
535
hx_target="#interactive-svg",
536
hx_swap="innerHTML",
537
style="cursor: pointer;"
538
),
539
id="interactive-svg",
540
viewBox="0 0 220 120",
541
width="440",
542
height="240"
543
)
544
),
545
546
# Dynamic chart
547
Div(
548
H2("Dynamic Chart"),
549
Button(
550
"Update Chart",
551
hx_post="/svg/update-chart",
552
hx_target="#chart-svg",
553
hx_swap="innerHTML"
554
),
555
Svg(id="chart-svg",
556
*[Rect(
557
width="20", height=f"{20 + i * 10}",
558
x=f"{30 + i * 30}", y=f"{100 - (20 + i * 10)}",
559
fill="steelblue", stroke="navy", stroke_width="1"
560
) for i in range(5)],
561
viewBox="0 0 200 120",
562
width="400",
563
height="240"
564
)
565
)
566
)
567
)
568
569
@rt('/svg/change-circle', methods=['POST'])
570
def change_circle():
571
import random
572
colors = ['lightblue', 'lightcoral', 'lightgreen', 'lightyellow', 'lightpink']
573
color = random.choice(colors)
574
radius = random.randint(20, 40)
575
576
return [
577
Circle(
578
r=str(radius), cx="60", cy="60",
579
fill=color, stroke="navy", stroke_width="2",
580
hx_post="/svg/change-circle",
581
hx_target="#interactive-svg",
582
hx_swap="innerHTML",
583
style="cursor: pointer;"
584
),
585
Rect(
586
width="60", height="40", x="120", y="40",
587
fill="lightcoral", stroke="darkred", stroke_width="2",
588
hx_post="/svg/change-rect",
589
hx_target="#interactive-svg",
590
hx_swap="innerHTML",
591
style="cursor: pointer;"
592
)
593
]
594
595
@rt('/svg/change-rect', methods=['POST'])
596
def change_rect():
597
import random
598
colors = ['lightcoral', 'lightblue', 'lightgreen', 'lightyellow', 'lightpink']
599
color = random.choice(colors)
600
width = random.randint(40, 80)
601
height = random.randint(30, 50)
602
603
return [
604
Circle(
605
r="30", cx="60", cy="60",
606
fill="lightblue", stroke="navy", stroke_width="2",
607
hx_post="/svg/change-circle",
608
hx_target="#interactive-svg",
609
hx_swap="innerHTML",
610
style="cursor: pointer;"
611
),
612
Rect(
613
width=str(width), height=str(height), x="120", y="40",
614
fill=color, stroke="darkred", stroke_width="2",
615
hx_post="/svg/change-rect",
616
hx_target="#interactive-svg",
617
hx_swap="innerHTML",
618
style="cursor: pointer;"
619
)
620
]
621
622
@rt('/svg/update-chart', methods=['POST'])
623
def update_chart():
624
import random
625
data = [random.randint(10, 80) for _ in range(5)]
626
627
return [
628
Rect(
629
width="20", height=str(height),
630
x=str(30 + i * 30), y=str(100 - height),
631
fill="steelblue", stroke="navy", stroke_width="1"
632
) for i, height in enumerate(data)
633
]
634
```
635
636
### Gradients and Advanced Styling
637
638
```python
639
from fasthtml.common import *
640
641
app, rt = fast_app()
642
643
@rt('/svg-gradients')
644
def svg_gradients():
645
return Titled("SVG Gradients and Patterns",
646
Container(
647
H1("Advanced SVG Styling"),
648
649
# Linear gradients
650
Div(
651
H2("Linear Gradients"),
652
Svg(
653
Defs(
654
LinearGradient(
655
Stop(offset="0%", stop_color="red"),
656
Stop(offset="50%", stop_color="yellow"),
657
Stop(offset="100%", stop_color="blue"),
658
id="linear1",
659
x1="0%", y1="0%", x2="100%", y2="0%"
660
),
661
LinearGradient(
662
Stop(offset="0%", stop_color="purple"),
663
Stop(offset="100%", stop_color="pink"),
664
id="linear2",
665
x1="0%", y1="0%", x2="0%", y2="100%"
666
)
667
),
668
Rect(width="100", height="60", x="10", y="10",
669
fill="url(#linear1)", stroke="black", stroke_width="2"),
670
Circle(r="30", cx="150", cy="40",
671
fill="url(#linear2)", stroke="black", stroke_width="2"),
672
viewBox="0 0 200 80",
673
width="400",
674
height="160"
675
)
676
),
677
678
# Radial gradients
679
Div(
680
H2("Radial Gradients"),
681
Svg(
682
Defs(
683
RadialGradient(
684
Stop(offset="0%", stop_color="white"),
685
Stop(offset="50%", stop_color="orange"),
686
Stop(offset="100%", stop_color="red"),
687
id="radial1",
688
cx="50%", cy="50%", r="50%"
689
)
690
),
691
Circle(r="40", cx="100", cy="50",
692
fill="url(#radial1)", stroke="darkred", stroke_width="3"),
693
viewBox="0 0 200 100",
694
width="400",
695
height="200"
696
)
697
)
698
)
699
)
700
```
701
702
### Data Visualization
703
704
```python
705
from fasthtml.common import *
706
707
app, rt = fast_app()
708
709
@rt('/svg-charts')
710
def svg_charts():
711
# Sample data
712
data = [30, 45, 60, 35, 50, 40, 55]
713
labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
714
715
# Create bar chart
716
chart_width = 300
717
chart_height = 200
718
bar_width = chart_width / len(data)
719
max_value = max(data)
720
721
bars = []
722
text_labels = []
723
724
for i, (value, label) in enumerate(zip(data, labels)):
725
bar_height = (value / max_value) * (chart_height - 40)
726
x = i * bar_width + 10
727
y = chart_height - bar_height - 20
728
729
bars.append(
730
Rect(
731
width=str(bar_width - 2), height=str(bar_height),
732
x=str(x), y=str(y),
733
fill="steelblue", stroke="navy", stroke_width="1"
734
)
735
)
736
737
text_labels.extend([
738
Text(str(value), x=str(x + bar_width/2), y=str(y - 5),
739
text_anchor="middle", font_size="12", fill="black"),
740
Text(label, x=str(x + bar_width/2), y=str(chart_height - 5),
741
text_anchor="middle", font_size="10", fill="gray")
742
])
743
744
return Titled("SVG Data Visualization",
745
Container(
746
H1("Data Charts with SVG"),
747
748
Div(
749
H2("Weekly Sales Chart"),
750
Svg(
751
*bars,
752
*text_labels,
753
# Y-axis
754
Line(x1="5", y1="20", x2="5", y2=str(chart_height - 20),
755
stroke="black", stroke_width="2"),
756
# X-axis
757
Line(x1="5", y1=str(chart_height - 20), x2=str(chart_width + 10), y2=str(chart_height - 20),
758
stroke="black", stroke_width="2"),
759
viewBox=f"0 0 {chart_width + 20} {chart_height + 10}",
760
width=str((chart_width + 20) * 2),
761
height=str((chart_height + 10) * 2)
762
)
763
)
764
)
765
)
766
```