1
---
2
name: image-annotations
3
description: 'Annotate screenshots, diagrams, and images with callout rectangles, arrows, labels, and color-coded highlights using PIL. Includes rules for animated GIF annotations with timing and pacing.'
4
---
5
6
# Image Annotations
7
8
Add visual callouts to any image — screenshots, diagrams, architecture docs, demo frames — using PIL/Pillow. Highlights what changed or what to look at, so reviewers don't have to guess.
9
10
## When to Use This Skill
11
12
Use this skill when you need to:
13
14
- Highlight a specific area in a screenshot for a PR description
15
- Annotate before/after images to show what changed
16
- Add labels and callouts to diagrams or architecture images
17
- Create annotated frames for animated GIF demos
18
19
## Prerequisites
20
21
```bash
22
pip install Pillow -q
23
```
24
25
## Color Rules
26
27
- **Red (`#E63946`)** — only for "bad" / "removed" things (e.g., circling a bug being fixed)
28
- **Yellowish-orange (`#FF9F1C`)** — for neutral highlights ("look here", "new feature", etc.)
29
- Never use red just because it's eye-catching — red = bad/removed
30
31
## Font
32
33
- Use **Ink Free** (`C:/Windows/Fonts/Inkfree.ttf`) for a handwritten look on Windows
34
- On Linux/macOS, fall back to `ImageFont.load_default()`
35
- Size **36** for annotations on ~1400px-wide images
36
- `stroke_width=1` with `stroke_fill=<same color as fill>` — gives body without being too thick
37
- Do NOT use white stroke — looks like a bad glow effect
38
39
## Shapes
40
41
- Prefer **rounded rectangles** over circles/ellipses — less pixelation at edges
42
- `draw.rounded_rectangle([x1, y1, x2, y2], radius=14, outline=color, width=5)`
43
- **Padding 18px** around the target content
44
45
## Reference Snippet
46
47
```python
48
from PIL import Image, ImageDraw, ImageFont
49
50
# Setup
51
font = ImageFont.truetype('C:/Windows/Fonts/Inkfree.ttf', 36) # or load_default()
52
color = '#FF9F1C' # orange for highlights
53
stroke = 5
54
pad = 18
55
56
img = Image.open('screenshot.png')
57
draw = ImageDraw.Draw(img)
58
59
# Rounded rect with padding
60
draw.rounded_rectangle(
61
[x1 - pad, y1 - pad, x2 + pad, y2 + pad],
62
radius=14, outline=color, width=stroke
63
)
64
65
# Leader line (same thickness as rect)
66
draw.line([x2 + pad, cy, x2 + pad + 40, cy - 30], fill=color, width=stroke)
67
68
# Label — same-color stroke for body, NO white stroke
69
draw.text(
70
(x2 + pad + 45, cy - 60), 'label text',
71
fill=color, font=font, stroke_width=1, stroke_fill=color
72
)
73
74
img.save('annotated.png')
75
```
76
77
## Algorithmic Annotation — `annotate.py`
78
79
For images with multiple elements to annotate, use the `annotate.py` module below. Save it next to your script and import from it. It handles automatic label placement without overlapping.
80
81
### Quick start
82
83
```python
84
from annotate import annotate_image
85
86
result = annotate_image(
87
'screenshot.png',
88
[
89
{'elem': (560, 275, 635, 390), 'label': 'button', 'draw_box': True},
90
{'elem': (105, 453, 236, 470), 'label': 'status text'},
91
],
92
debug=True,
93
)
94
result.save('annotated.png')
95
```
96
97
- `elem`: `(x1, y1, x2, y2)` tight bounding box — must be exact pixel coordinates
98
- `label`: text label (supports `\n` for multi-line)
99
- `draw_box`: if `True`, draws a rounded rectangle around the element. If `False` (default), draws a V-arrowhead pointing at the element
100
- `debug`: shows targeting rectangles and candidate heatmap for placement validation
101
102
### Coordinate grid helper
103
104
**Always use `grid_image()` before annotating an unfamiliar image.** Scaled-down previews display images smaller than actual pixel dimensions — the error compounds as you move away from (0,0).
105
106
```python
107
from annotate import grid_image
108
109
grid = grid_image('screenshot.png', step=100)
110
grid.save('grid.png')
111
```
112
113
Then verify with small crops:
114
115
```python
116
from PIL import Image
117
img = Image.open('screenshot.png')
118
crop = img.crop((x1 - 20, y1 - 20, x2 + 20, y2 + 20))
119
crop.save('verify.png')
120
```
121
122
### Algorithm overview
123
124
1. **Ring search**: candidates between MIN_ARROW (25px) and MAX_ARROW (120px) from element edge
125
2. **Contrast scoring**: prefers placements where label text is readable — `abs(avg_brightness - 147) - std * 0.3 - dist * 0.02`
126
3. **Joint resolution**: candidates computed independently, placed greedily (best score first)
127
4. **Hard blocks**: labels cannot overlap any other annotation's element or breathing box
128
5. **Proximity penalty**: labels within 40px of other placed boxes get a score penalty
129
6. **Arrow crossing penalty**: -50 for arrows crossing already-placed arrows
130
131
### Debug mode colors
132
133
| Color | Meaning |
134
|-------|---------|
135
| Cyan | Target element box (elem + padding) |
136
| Gray | Exclusion zone (MIN_ARROW buffer) |
137
| Red→Green | Candidate heatmap (red=bad, green=good) |
138
| Magenta | Chosen label position |
139
| Orange | Final rendered annotation |
140
141
### Arrow styles
142
143
- **`draw_box=True`**: rounded rectangle + straight line to label, no arrowhead
144
- **`draw_box=False`**: V-shaped arrowhead with rounded line caps
145
146
### `annotate.py` — full module
147
148
Save this as `annotate.py` and import from it:
149
150
```python
151
"""
152
Algorithmic screenshot annotation with automatic label placement.
153
154
pip install Pillow numpy
155
Optional for diff_images: pip install scipy
156
"""
157
import math
158
import numpy as np
159
from PIL import Image, ImageDraw, ImageFont
160
161
# --- Defaults ---
162
DEFAULT_FONT = 'C:/Windows/Fonts/Inkfree.ttf'
163
DEFAULT_FONT_SIZE = 32
164
DEFAULT_COLOR = '#FF9F1C'
165
DEFAULT_STROKE = 5
166
MIN_ARROW = 25
167
MAX_ARROW = 120
168
TEXT_PAD = 6
169
BREATH = 18
170
CROSSING_PENALTY = 50
171
PROXIMITY_MARGIN = 40
172
PROXIMITY_PENALTY = 50
173
174
175
def _rect_intersects(a, b):
176
return a[0] < b[2] and a[2] > b[0] and a[1] < b[3] and a[3] > b[1]
177
178
179
def _segments_intersect(p1, p2, p3, p4):
180
def cross(o, a, b):
181
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
182
d1, d2 = cross(p3, p4, p1), cross(p3, p4, p2)
183
d3, d4 = cross(p1, p2, p3), cross(p1, p2, p4)
184
return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and \
185
((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0))
186
187
188
def _line_rect_exit(cx, cy, tx, ty, rect):
189
x1, y1, x2, y2 = rect
190
dx, dy = tx - cx, ty - cy
191
tmin, tmax = 0.0, 1.0
192
for lo, hi, p, d in [(x1, x2, cx, dx), (y1, y2, cy, dy)]:
193
if abs(d) < 1e-9:
194
continue
195
t0, t1 = (lo - p) / d, (hi - p) / d
196
if t0 > t1:
197
t0, t1 = t1, t0
198
tmin, tmax = max(tmin, t0), min(tmax, t1)
199
return (cx + dx * tmax, cy + dy * tmax)
200
201
202
def _rect_gap(a, b):
203
dx = max(a[0] - b[2], b[0] - a[2], 0)
204
dy = max(a[1] - b[3], b[1] - a[3], 0)
205
if dx == 0 and dy == 0:
206
return 0
207
return math.sqrt(dx**2 + dy**2)
208
209
210
def _find_candidates(pixels, W, H, cyan, pw, ph, font):
211
cx, cy = (cyan[0] + cyan[2]) / 2, (cyan[1] + cyan[3]) / 2
212
excl_zone = (cyan[0] - MIN_ARROW, cyan[1] - MIN_ARROW,
213
cyan[2] + MIN_ARROW, cyan[3] + MIN_ARROW)
214
sx1 = max(0, cyan[0] - MAX_ARROW - pw)
215
sy1 = max(0, cyan[1] - MAX_ARROW - ph)
216
sx2 = min(W - pw, cyan[2] + MAX_ARROW)
217
sy2 = min(H - ph, cyan[3] + MAX_ARROW)
218
step_x = max(8, min(pw // 2, MAX_ARROW // 3))
219
step_y = max(8, min(ph // 2, MAX_ARROW // 3))
220
cands = []
221
for px in range(sx1, sx2, step_x):
222
for py in range(sy1, sy2, step_y):
223
pink = (px, py, px + pw, py + ph)
224
if _rect_intersects(pink, excl_zone):
225
continue
226
gl, gr = cyan[0] - pink[2], pink[0] - cyan[2]
227
gt, gb = cyan[1] - pink[3], pink[1] - cyan[3]
228
hd, vd = max(gl, gr, 0), max(gt, gb, 0)
229
ed = math.sqrt(hd**2 + vd**2) if (hd > 0 and vd > 0) else max(hd, vd)
230
if ed > MAX_ARROW:
231
continue
232
region = pixels[py:py + ph, px:px + pw, :3].astype(float)
233
score = abs(np.mean(region) - 147) - np.std(region) * 0.3
234
dist = math.sqrt((px + pw/2 - cx)**2 + (py + ph/2 - cy)**2)
235
score -= dist * 0.02
236
cands.append(((px, py), score))
237
return cands
238
239
240
def _resolve_placements(annots, font):
241
placed = []
242
all_elem_zones = []
243
for ann in annots:
244
all_elem_zones.append(ann['cyan'])
245
if ann.get('draw_box', False):
246
c = ann['cyan']
247
all_elem_zones.append((c[0]-BREATH, c[1]-BREATH, c[2]+BREATH, c[3]+BREATH))
248
for ann in sorted(annots, key=lambda a: -a['best_score']):
249
pw, ph = ann['pw'], ann['ph']
250
cyan = ann['cyan']
251
cx, cy = ann['cyan_center']
252
draw_box = ann.get('draw_box', False)
253
best_pos, best_score = None, -999
254
valid = []
255
for (px, py), score in ann['candidates']:
256
pink = (px, py, px + pw, py + ph)
257
ok = True
258
for ez in all_elem_zones:
259
if ez == cyan:
260
continue
261
if ann.get('draw_box', False):
262
own_viz = (cyan[0]-BREATH, cyan[1]-BREATH, cyan[2]+BREATH, cyan[3]+BREATH)
263
if ez == own_viz:
264
continue
265
if _rect_intersects(pink, ez):
266
ok = False; break
267
if not ok:
268
continue
269
for p_pink, p_excl, p_viz, _ in placed:
270
if _rect_intersects(pink, p_pink) or _rect_intersects(pink, p_excl):
271
ok = False; break
272
if p_viz and _rect_intersects(pink, p_viz):
273
ok = False; break
274
if not ok:
275
continue
276
for p_pink, p_excl, p_viz, _ in placed:
277
for rect in [p_pink, p_excl, p_viz]:
278
if rect is None:
279
continue
280
gap = _rect_gap(pink, rect)
281
if gap < PROXIMITY_MARGIN:
282
score -= PROXIMITY_PENALTY * (1 - gap / PROXIMITY_MARGIN)
283
for ez in all_elem_zones:
284
if ez == cyan:
285
continue
286
gap = _rect_gap(pink, ez)
287
if gap < PROXIMITY_MARGIN:
288
score -= PROXIMITY_PENALTY * (1 - gap / PROXIMITY_MARGIN)
289
tcx, tcy = px + pw/2, py + ph/2
290
cand_start = _line_rect_exit(tcx, tcy, cx, cy, pink)
291
if draw_box:
292
viz = (cyan[0]-BREATH, cyan[1]-BREATH, cyan[2]+BREATH, cyan[3]+BREATH)
293
cand_end = _line_rect_exit(cx, cy, tcx, tcy, viz)
294
else:
295
cand_end = _line_rect_exit(cx, cy, tcx, tcy, cyan)
296
for _, _, _, pa in placed:
297
if pa and _segments_intersect(cand_start, cand_end, pa[0], pa[1]):
298
score -= CROSSING_PENALTY; break
299
valid.append(((px, py), score))
300
if score > best_score:
301
best_score, best_pos = score, (px, py)
302
ann['valid_candidates'] = valid
303
if best_pos is None:
304
ann['pink'] = ann['tpos'] = ann['astart'] = ann['aend'] = ann['viz'] = None
305
continue
306
px, py = best_pos
307
pink = (px, py, px + pw, py + ph)
308
ann['pink'] = pink
309
ann['tpos'] = (px + TEXT_PAD, py + TEXT_PAD)
310
tcx, tcy = px + pw/2, py + ph/2
311
ann['astart'] = _line_rect_exit(tcx, tcy, cx, cy, pink)
312
if draw_box:
313
viz = (cyan[0]-BREATH, cyan[1]-BREATH, cyan[2]+BREATH, cyan[3]+BREATH)
314
ann['viz'] = viz
315
ann['aend'] = _line_rect_exit(cx, cy, tcx, tcy, viz)
316
else:
317
ann['viz'] = None
318
ann['aend'] = _line_rect_exit(cx, cy, tcx, tcy, cyan)
319
placed.append((pink, ann['excl_zone'], ann['viz'], (ann['astart'], ann['aend'])))
320
321
322
def _draw_debug(img, annots, color):
323
overlay = Image.new('RGBA', img.size, (0, 0, 0, 0))
324
od = ImageDraw.Draw(overlay)
325
for ann in annots:
326
cands = ann.get('valid_candidates', ann['candidates'])
327
if not cands:
328
continue
329
pw, ph = ann['pw'], ann['ph']
330
scores = [s for _, s in cands]
331
smin, smax = min(scores), max(scores)
332
rng = smax - smin if smax > smin else 1
333
for (px, py), score in cands:
334
t = (score - smin) / rng
335
if t < 0.5:
336
r_c, g_c, b_c = 220, int(180 * (t * 2)), 0
337
else:
338
r_c, g_c, b_c = int(220 * (1 - (t-0.5)*2)), 200, 0
339
alpha_fill = int(40 + 70 * t)
340
alpha_out = int(80 + 120 * t)
341
od.rectangle((px, py, px + pw, py + ph),
342
fill=(r_c, g_c, b_c, alpha_fill), outline=(r_c, g_c, b_c, alpha_out), width=1)
343
for ann in annots:
344
ez = ann['excl_zone']
345
od.rectangle(ez, fill=(120, 120, 120, 50), outline=(160, 160, 160, 160), width=1)
346
od.rectangle(ann['cyan'], fill=(0, 255, 255, 30), outline=(0, 255, 255, 180), width=2)
347
if ann.get('pink'):
348
od.rectangle(ann['pink'], fill=(255, 0, 255, 50),
349
outline=(255, 0, 255, 180), width=2)
350
return Image.alpha_composite(img, overlay)
351
352
353
def _draw_annotations(img, annots, font, color, stroke_width):
354
draw = ImageDraw.Draw(img)
355
for ann in annots:
356
if ann.get('viz'):
357
draw.rounded_rectangle(ann['viz'], radius=12, outline=color, width=stroke_width)
358
tpos = ann.get('tpos')
359
astart, aend = ann.get('astart'), ann.get('aend')
360
if not (tpos and astart and aend):
361
continue
362
sx, sy = int(astart[0]), int(astart[1])
363
ex, ey = int(aend[0]), int(aend[1])
364
draw.line([(sx, sy), (ex, ey)], fill=color, width=4, joint='curve')
365
r = 2
366
draw.ellipse([(sx-r, sy-r), (sx+r, sy+r)], fill=color)
367
draw.ellipse([(ex-r, ey-r), (ex+r, ey+r)], fill=color)
368
if not ann.get('draw_box', False):
369
angle = math.atan2(ey - sy, ex - sx)
370
al, spread = 18, 0.45
371
ax = ex - al * math.cos(angle - spread)
372
ay = ey - al * math.sin(angle - spread)
373
bx = ex - al * math.cos(angle + spread)
374
by = ey - al * math.sin(angle + spread)
375
draw.line([(int(ax), int(ay)), (ex, ey)], fill=color, width=4)
376
draw.line([(int(bx), int(by)), (ex, ey)], fill=color, width=4)
377
for px_, py_ in [(int(ax), int(ay)), (int(bx), int(by))]:
378
draw.ellipse([(px_-r, py_-r), (px_+r, py_+r)], fill=color)
379
draw.text(tpos, ann['label'], fill=color, font=font,
380
stroke_width=1, stroke_fill=color)
381
return img
382
383
384
def annotate_image(image_path, annotations, *,
385
debug=False,
386
font_path=DEFAULT_FONT,
387
font_size=DEFAULT_FONT_SIZE,
388
color=DEFAULT_COLOR,
389
stroke_width=DEFAULT_STROKE):
390
"""
391
Annotate a screenshot with automatic label placement.
392
393
Args:
394
image_path: path to the input image
395
annotations: list of dicts with keys:
396
- elem: (x1, y1, x2, y2) tight bounding box of element
397
- label: text label string
398
- draw_box: (optional, default False) draw rounded rect around element
399
debug: if True, draw developer rectangles (cyan/pink/gray/heatmap)
400
font_path: path to TTF font file
401
font_size: font size in pixels
402
color: hex color for annotations (default orange #FF9F1C)
403
stroke_width: width of orange highlight box outline
404
405
Returns:
406
PIL.Image with annotations drawn
407
"""
408
font = ImageFont.truetype(font_path, font_size)
409
img = Image.open(image_path).convert('RGBA')
410
pixels = np.array(img)
411
W, H = img.size
412
annots = []
413
for i, spec in enumerate(annotations):
414
eb = spec['elem']
415
em_pad = min(20, max(10, (eb[2] - eb[0]) // 10))
416
cyan = (eb[0] - em_pad, eb[1] - em_pad, eb[2] + em_pad, eb[3] + em_pad)
417
lines = spec['label'].split('\n')
418
tw = max(font.getbbox(line)[2] - font.getbbox(line)[0] for line in lines)
419
bbox = font.getbbox('Ay')
420
line_h = bbox[3] - bbox[1]
421
th = line_h * len(lines) + 4 * (len(lines) - 1)
422
pw, ph = tw + 2 * TEXT_PAD, th + 2 * TEXT_PAD
423
cands = _find_candidates(pixels, W, H, cyan, pw, ph, font)
424
annots.append({
425
'id': i,
426
'label': spec['label'],
427
'draw_box': spec.get('draw_box', False),
428
'cyan': cyan,
429
'cyan_center': ((cyan[0]+cyan[2])/2, (cyan[1]+cyan[3])/2),
430
'excl_zone': (cyan[0]-MIN_ARROW, cyan[1]-MIN_ARROW,
431
cyan[2]+MIN_ARROW, cyan[3]+MIN_ARROW),
432
'pw': pw, 'ph': ph,
433
'candidates': cands,
434
'best_score': max((s for _, s in cands), default=-999),
435
})
436
_resolve_placements(annots, font)
437
annots.sort(key=lambda a: a['id'])
438
if debug:
439
img = _draw_debug(img, annots, color)
440
img = _draw_annotations(img, annots, font, color, stroke_width)
441
return img
442
443
444
def diff_images(before_path, after_path, *, threshold=30, min_pixels=300,
445
dilate=5, debug=False):
446
"""Find changed regions between two screenshots and return cluster boxes.
447
448
Returns (clusters, debug_img_or_None):
449
clusters: list of (x1, y1, x2, y2, pixel_count) sorted largest-first
450
debug_img: if debug=True, PIL Image with heatmap overlay and cluster boxes
451
"""
452
from scipy import ndimage
453
img_a = Image.open(before_path).convert('RGB')
454
img_b = Image.open(after_path).convert('RGB')
455
if img_a.size != img_b.size:
456
raise ValueError(f"Image sizes differ: {img_a.size} vs {img_b.size}")
457
arr_a = np.array(img_a, dtype=np.float32)
458
arr_b = np.array(img_b, dtype=np.float32)
459
W, H = img_a.size
460
diff = np.abs(arr_b - arr_a).max(axis=2)
461
mask = diff > threshold
462
dilated = ndimage.binary_dilation(mask, iterations=dilate)
463
labeled, n_clusters = ndimage.label(dilated)
464
clusters = []
465
for i in range(1, n_clusters + 1):
466
ys, xs = np.where(labeled == i)
467
if len(ys) < min_pixels:
468
continue
469
clusters.append((int(xs.min()), int(ys.min()),
470
int(xs.max()), int(ys.max()), len(ys)))
471
clusters.sort(key=lambda c: -c[4])
472
debug_img = None
473
if debug:
474
overlay = img_b.copy().convert('RGBA')
475
norm = np.clip(diff / 255.0, 0, 1)
476
show_mask = diff > 10
477
r = np.clip((norm * 2) * 255, 0, 255).astype(np.uint8)
478
g = np.clip((1 - np.abs(norm - 0.5) * 2) * 200, 0, 200).astype(np.uint8)
479
b = np.clip((1 - norm) * 255, 0, 255).astype(np.uint8)
480
a = np.where(show_mask, np.clip(norm * 200 + 40, 40, 220).astype(np.uint8), 0)
481
heat = Image.fromarray(np.stack([r, g, b, a], axis=2), 'RGBA')
482
overlay = Image.alpha_composite(overlay, heat)
483
draw = ImageDraw.Draw(overlay)
484
try:
485
font = ImageFont.truetype('C:/Windows/Fonts/consola.ttf', 18)
486
except OSError:
487
font = ImageFont.load_default()
488
for idx, (x1, y1, x2, y2, px_count) in enumerate(clusters):
489
draw.rectangle([x1, y1, x2, y2], outline=(0, 255, 255, 200), width=3)
490
label = f"#{idx+1} {px_count:,}px"
491
bbox = font.getbbox(label)
492
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
493
lx, ly = x1, max(0, y1 - th - 8)
494
draw.rectangle([lx, ly, lx + tw + 8, ly + th + 4], fill=(0, 0, 0, 180))
495
draw.text((lx + 4, ly + 2), label, fill=(0, 255, 255, 255), font=font)
496
debug_img = overlay
497
return clusters, debug_img
498
499
500
def grid_image(image_path, step=100):
501
"""Draw a coordinate grid on an image for precise element location."""
502
img = Image.open(image_path).convert('RGBA')
503
draw = ImageDraw.Draw(img)
504
W, H = img.size
505
try:
506
font = ImageFont.truetype('C:/Windows/Fonts/consola.ttf', 14)
507
except OSError:
508
font = ImageFont.load_default()
509
for x in range(0, W, step):
510
draw.line([(x, 0), (x, H)], fill=(255, 0, 0, 120), width=1)
511
draw.text((x + 2, 2), str(x), fill=(255, 0, 0, 200), font=font)
512
for y in range(0, H, step):
513
draw.line([(0, y), (W, y)], fill=(255, 0, 0, 120), width=1)
514
draw.text((2, y + 2), str(y), fill=(255, 0, 0, 200), font=font)
515
return img
516
```
517
518
## Image Diffing
519
520
Find what changed between two screenshots programmatically. Use as a safety net for subtle changes — when the difference is obvious, annotate directly instead.
521
522
```python
523
from annotate import diff_images
524
525
clusters, debug_img = diff_images(
526
'before.png', 'after.png',
527
threshold=30, # pixel difference floor (0-255)
528
min_pixels=300, # ignore tiny noise clusters
529
dilate=5, # merge nearby changed pixels
530
debug=True, # render heatmap overlay
531
)
532
533
# clusters = [(x1, y1, x2, y2, pixel_count), ...] sorted largest-first
534
if debug_img:
535
debug_img.save('diff-debug.png')
536
537
# Feed clusters into annotate_image:
538
annotations = [
539
{'elem': (x1, y1, x2, y2), 'label': f'Change #{i+1}', 'draw_box': True}
540
for i, (x1, y1, x2, y2, _) in enumerate(clusters[:3])
541
]
542
```
543
544
**Debug heatmap colors:** Blue = small difference, Yellow = medium, Red = large, Cyan boxes = cluster bounding boxes.
545
546
**When to use:** subtle opacity changes, dashed lines, minor color shifts, anti-aliasing differences.
547
**When NOT to use:** any change you can see by eye — annotate directly for better labels.
548
549
## Animated GIF Annotations
550
551
Different from static images — animations have timing, transitions, and competing visual motion.
552
553
### Element highlighting
554
555
1. **Rects for big areas, arrows for small elements** — 500x300px area = rect, 200x25px element = arrow
556
2. **Labels go RIGHT NEXT to what they describe** — short arrow (30-80px), label adjacent. Viewer's eye shouldn't travel more than ~100px
557
3. **Arrow must not cross its own label** — pick the edge closest to the target
558
4. **No bottom bar / subtitle approach** — eyes jump between content and bar. Contextual placement only
559
5. **Hero message gets a bigger font** — main takeaway 64pt+, detail annotations 38pt
560
561
### Timing and pacing
562
563
6. **Fade: 2-frame pop-in at 10fps** — 50% → 100% opacity (0.2s total). Easing curves look bad at low FPS
564
7. **Type → pause → annotate** — during fast action, show NO annotation. Pause, then add it
565
8. **Variable frame duration** — fast during action (100ms), slow during pauses (600-800ms), long hold for hero (500ms)
566
9. **Higher FPS for smooth motion** — 10fps minimum for typing/interaction
567
568
### Pop-in fade implementation
569
570
```python
571
# 2-frame pop-in at 10fps
572
FADE_ALPHAS = [0.50, 1.00]
573
574
for frame_idx in range(total_frames):
575
if annotation_just_changed and local_idx < len(FADE_ALPHAS):
576
alpha = FADE_ALPHAS[local_idx]
577
else:
578
alpha = 1.0
579
# Apply alpha to annotation elements:
580
# - pill background: fill=(r, g, b, int(base_alpha * alpha))
581
# - text: fill=(*color, int(255 * alpha))
582
# - rect outline: outline=(*color, int(255 * alpha))
583
```
584
585
## Guidelines
586
587
1. **All elements same thickness** — rect `width`, line `width`, and visual text weight should feel consistent (~5px)
588
2. Place labels **close to the rect** — short leader line (25-35px)
589
3. Labels can overlap content — the stroke gives enough contrast
590
4. **Show locally first** — verify before uploading to a PR
591
5. **Take screenshots at native 1x, control display size in HTML** — use `<img width="300">` in markdown, never resize with PIL (creates artifacts)
592
6. **Always check `Image.open(path).size` first** — HiDPI screenshots are larger than they appear (150% scaling = 1.5x CSS pixel dimensions)
593
7. **Short labels work better** — wide labels have fewer valid placements. Use 1-3 words when possible
594
8. **Verify with debug=True** — always check the first annotation of a new image with debug mode
595
596
## Limitations
597
598
- Ink Free font is Windows-only; other platforms need a fallback font
599
- PIL text rendering is basic — no rich text, no markdown
600
- Animated GIF annotations require frame-by-frame processing which can be slow for long recordings
601
- Algorithmic placement works best with 2-6 annotations; more than that may produce crowded results
602