Excalidraw Diagram Generator
GitHubOfficialFirst committed by jun-shiromizuDistributed by GitHub
- Skill
- Content generator
- Design and creative
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Excalidraw Diagram Generator transforms natural language prompts into valid .excalidraw JSON files. It supports a wide variety of diagram types including flowcharts, mind maps, system architectures, and sequence diagrams. The skill provides a structured workflow to extract entities and relationships, map them to appropriate shapes, and format the output for direct use in the Excalidraw application. It also includes advanced capabilities for managing icon libraries and automating complex layouts via Python scripts.
What it does
- Converts natural language descriptions into .excalidraw JSON files.
- Supports multiple diagram types: flowcharts, mind maps, architecture, and ER diagrams.
- Provides guidelines for element placement, color schemes, and font usage.
- Includes Python scripts to automate icon integration and arrow connections.
- Offers strategies for managing complex diagrams by breaking them into smaller parts.
- Validates output against Excalidraw's JSON schema requirements.
When to use it
- When you need to visualize a process, workflow, or system architecture.
- When you want to create a mind map for brainstorming or concept organization.
- When you need to generate a diagram file that can be opened and edited in Excalidraw.
- When you require a consistent, programmatic way to generate visual documentation.
Advantages
- Eliminates manual drawing time for standard diagrams.
- Ensures consistent styling and formatting across generated diagrams.
- Supports professional icon libraries for specialized architecture diagrams.
- Automates complex coordinate calculations through provided Python scripts.
- Reduces token usage by offloading icon data handling to local scripts.
Usage examples
- “Create a flowchart for user registration”
- Generates a .excalidraw file containing rectangles for steps like 'Enter email' and 'Verify email' connected by arrows.
- “Diagram the relationship between User, Post, and Comment entities”
- Produces an ER-style diagram showing the entities and their logical connections.
- “Mind map about machine learning concepts”
- Creates a radial-style mind map with a central topic and branches for supervised, unsupervised, and reinforcement learning.
- “Create an AWS architecture diagram with Internet Gateway, VPC, and EC2”
- Generates a structured architecture diagram using professional icons and clear flow connections.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/github/excalidraw-diagram-generator/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip excalidraw-diagram-generator.zip -d .agents/skills
Documentation by jun-shiromizu
Excalidraw Diagram Generator
A skill for generating Excalidraw-format diagrams from natural language descriptions. This skill helps create visual representations of processes, systems, relationships, and ideas without manual drawing.
When to Use This Skill
Use this skill when users request:
"Create a diagram showing..."
"Make a flowchart for..."
"Visualize the process of..."
"Draw the system architecture of..."
"Generate a mind map about..."
"Create an Excalidraw file for..."
"Show the relationship between..."
"Diagram the workflow of..."
Supported diagram types:
📊 Flowcharts: Sequential processes, workflows, decision trees
🔗 Relationship Diagrams: Entity relationships, system components, dependencies
🧠 Mind Maps: Concept hierarchies, brainstorming results, topic organization
🏗️ Architecture Diagrams: System design, module interactions, data flow
📈 Data Flow Diagrams (DFD): Data flow visualization, data transformation processes
🏊 Business Flow (Swimlane): Cross-functional workflows, actor-based process flows
📦 Class Diagrams: Object-oriented design, class structures and relationships
🔄 Sequence Diagrams: Object interactions over time, message flows
🗃️ ER Diagrams: Database entity relationships, data models
Prerequisites
Clear description of what should be visualized
Identification of key entities, steps, or concepts
Understanding of relationships or flow between elements
Step-by-Step Workflow
Step 1: Understand the Request
Analyze the user's description to determine:
Diagram type (flowchart, relationship, mind map, architecture)
Key elements (entities, steps, concepts)
Relationships (flow, connections, hierarchy)
Complexity (number of elements)
Step 2: Choose the Appropriate Diagram Type
| User Intent | Diagram Type | Example Keywords |
|---|---|---|
| Process flow, steps, procedures | Flowchart | "workflow", "process", "steps", "procedure" |
| Connections, dependencies, associations | Relationship Diagram | "relationship", "connections", "dependencies", "structure" |
| Concept hierarchy, brainstorming | Mind Map | "mind map", "concepts", "ideas", "breakdown" |
| System design, components | Architecture Diagram | "architecture", "system", "components", "modules" |
| Data flow, transformation processes | Data Flow Diagram (DFD) | "data flow", "data processing", "data transformation" |
| Cross-functional processes, actor responsibilities | Business Flow (Swimlane) | "business process", "swimlane", "actors", "responsibilities" |
| Object-oriented design, class structures | Class Diagram | "class", "inheritance", "OOP", "object model" |
| Interaction sequences, message flows | Sequence Diagram | "sequence", "interaction", "messages", "timeline" |
| Database design, entity relationships | ER Diagram | "database", "entity", "relationship", "data model" |
Step 3: Extract Structured Information
For Flowcharts:
List of sequential steps
Decision points (if any)
Start and end points
For Relationship Diagrams:
Entities/nodes (name + optional description)
Relationships between entities (from → to, with label)
For Mind Maps:
Central topic
Main branches (3-6 recommended)
Sub-topics for each branch (optional)
For Data Flow Diagrams (DFD):
Data sources and destinations (external entities)
Processes (data transformations)
Data stores (databases, files)
Data flows (arrows showing data movement from left-to-right or from top-left to bottom-right)
Important: Do not represent process order, only data flow
For Business Flow (Swimlane):
Actors/roles (departments, systems, people) - displayed as header columns
Process lanes (vertical lanes under each actor)
Process boxes (activities within each lane)
Flow arrows (connecting process boxes, including cross-lane handoffs)
For Class Diagrams:
Classes with names
Attributes with visibility (+, -, #)
Methods with visibility and parameters
Relationships: inheritance (solid line + white triangle), implementation (dashed line + white triangle), association (solid line), dependency (dashed line), aggregation (solid line + white diamond), composition (solid line + filled diamond)
Multiplicity notations (1, 0..1, 1..*, *)
For Sequence Diagrams:
Objects/actors (arranged horizontally at top)
Lifelines (vertical lines from each object)
Messages (horizontal arrows between lifelines)
Synchronous messages (solid arrow), asynchronous messages (dashed arrow)
Return values (dashed arrows)
Activation boxes (rectangles on lifelines during execution)
Time flows from top to bottom
For ER Diagrams:
Entities (rectangles with entity names)
Attributes (listed inside entities)
Primary keys (underlined or marked with PK)
Foreign keys (marked with FK)
Relationships (lines connecting entities)
Cardinality: 1:1 (one-to-one), 1:N (one-to-many), N:M (many-to-many)
Junction/associative entities for many-to-many relationships (dashed rectangles)
Step 4: Generate the Excalidraw JSON
Create the .excalidraw file with appropriate elements:
Available element types:
rectangle: Boxes for entities, steps, conceptsellipse: Alternative shapes for emphasisdiamond: Decision pointsarrow: Directional connectionstext: Labels and annotations
Key properties to set:
Position:
x,ycoordinatesSize:
width,heightStyle:
strokeColor,backgroundColor,fillStyleFont:
fontFamily: 5(Excalifont - required for all text elements)Text: Embedded text for labels
Connections:
pointsarray for arrows
Important: All text elements must use fontFamily: 5 (Excalifont) for consistent visual appearance.
Step 5: Format the Output
Structure the complete Excalidraw file:
{
"type": "excalidraw",
"version": 2,
"source": "https://excalidraw.com",
"elements": [
// Array of diagram elements
],
"appState": {
"viewBackgroundColor": "#ffffff",
"gridSize": 20
},
"files": {}
}Step 6: Save and Provide Instructions
Save as
<descriptive-name>.excalidrawInform user how to open:
Visit https://excalidraw.com
Click "Open" or drag-and-drop the file
Or use Excalidraw VS Code extension
Best Practices
Element Count Guidelines
| Diagram Type | Recommended Count | Maximum |
|---|---|---|
| Flowchart steps | 3-10 | 15 |
| Relationship entities | 3-8 | 12 |
| Mind map branches | 4-6 | 8 |
| Mind map sub-topics per branch | 2-4 | 6 |
Layout Tips
Start positions: Center important elements, use consistent spacing
Spacing:
Horizontal gap: 200-300px between elements
Vertical gap: 100-150px between rows
Colors: Use consistent color scheme
Primary elements: Light blue (
#a5d8ff)Secondary elements: Light green (
#b2f2bb)Important/Central: Yellow (
#ffd43b)Alerts/Warnings: Light red (
#ffc9c9)
Text sizing: 16-24px for readability
Font: Always use
fontFamily: 5(Excalifont) for all text elementsArrow style: Use straight arrows for simple flows, curved for complex relationships
Complexity Management
If user request has too many elements:
Suggest breaking into multiple diagrams
Focus on main elements first
Offer to create detailed sub-diagrams
Example response:
"Your request includes 15 components. For clarity, I recommend:
1. High-level architecture diagram (6 main components)
2. Detailed diagram for each subsystem
Would you like me to start with the high-level view?"Example Prompts and Responses
Example 1: Simple Flowchart
User: "Create a flowchart for user registration"
Agent generates:
Extract steps: "Enter email" → "Verify email" → "Set password" → "Complete"
Create flowchart with 4 rectangles + 3 arrows
Save as
user-registration-flow.excalidraw
Example 2: Relationship Diagram
User: "Diagram the relationship between User, Post, and Comment entities"
Agent generates:
Entities: User, Post, Comment
Relationships: User → Post ("creates"), User → Comment ("writes"), Post → Comment ("contains")
Save as
user-content-relationships.excalidraw
Example 3: Mind Map
User: "Mind map about machine learning concepts"
Agent generates:
Center: "Machine Learning"
Branches: Supervised Learning, Unsupervised Learning, Reinforcement Learning, Deep Learning
Sub-topics under each branch
Save as
machine-learning-mindmap.excalidraw
Troubleshooting
| Issue | Solution |
|---|---|
| Elements overlap | Increase spacing between coordinates |
| Text doesn't fit in boxes | Increase box width or reduce font size |
| Too many elements | Break into multiple diagrams |
| Unclear layout | Use grid layout (rows/columns) or radial layout (mind maps) |
| Colors inconsistent | Define color palette upfront based on element types |
Advanced Techniques
Grid Layout (for Relationship Diagrams)
const columns = Math.ceil(Math.sqrt(entityCount));
const x = startX + (index % columns) * horizontalGap;
const y = startY + Math.floor(index / columns) * verticalGap;Radial Layout (for Mind Maps)
const angle = (2 * Math.PI * index) / branchCount;
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);Auto-generated IDs
Use timestamp + random string for unique IDs:
const id = Date.now().toString(36) + Math.random().toString(36).substr(2);Output Format
Always provide:
✅ Complete
.excalidrawJSON file📊 Summary of what was created
📝 Element count
💡 Instructions for opening/editing
Example summary:
Created: user-workflow.excalidraw
Type: Flowchart
Elements: 7 rectangles, 6 arrows, 1 title text
Total: 14 elements
To view:
1. Visit https://excalidraw.com
2. Drag and drop user-workflow.excalidraw
3. Or use File → Open in Excalidraw VS Code extensionValidation Checklist
Before delivering the diagram:
[ ] All elements have unique IDs
[ ] Coordinates prevent overlapping
[ ] Text is readable (font size 16+)
[ ] All text elements use
fontFamily: 5(Excalifont)[ ] Arrows connect logically
[ ] Colors follow consistent scheme
[ ] File is valid JSON
[ ] Element count is reasonable (<20 for clarity)
Icon Libraries (Optional Enhancement)
For specialized diagrams (e.g., AWS/GCP/Azure architecture diagrams), you can use pre-made icon libraries from Excalidraw. This provides professional, standardized icons instead of basic shapes.
When User Requests Icons
If user asks for AWS/cloud architecture diagrams or mentions wanting to use specific icons:
Check if library exists: Look for
libraries/<library-name>/reference.mdIf library exists: Proceed to use icons (see AI Assistant Workflow below)
If library does NOT exist: Respond with setup instructions:
To use [AWS/GCP/Azure/etc.] architecture icons, please follow these steps: 1. Visit https://libraries.excalidraw.com/ 2. Search for "[AWS Architecture Icons/etc.]" and download the .excalidrawlib file 3. Create directory: skills/excalidraw-diagram-generator/libraries/[icon-set-name]/ 4. Place the downloaded file in that directory 5. Run the splitter script: python skills/excalidraw-diagram-generator/scripts/split-excalidraw-library.py skills/excalidraw-diagram-generator/libraries/[icon-set-name]/ This will split the library into individual icon files for efficient use. After setup is complete, I can create your diagram using the actual AWS/cloud icons. Alternatively, I can create the diagram now using simple shapes (rectangles, ellipses) which you can later replace with icons manually in Excalidraw.
User Setup Instructions (Detailed)
Step 1: Create Library Directory
mkdir -p skills/excalidraw-diagram-generator/libraries/aws-architecture-iconsStep 2: Download Library
Search for your desired icon set (e.g., "AWS Architecture Icons")
Click download to get the
.excalidrawlibfileExample categories (availability varies; confirm on the site):
Cloud service icons
UI/Material icons
Flowchart symbols
Step 3: Place Library File
Rename the downloaded file to match the directory name (e.g.,
aws-architecture-icons.excalidrawlib)Move it to the directory created in Step 1
Step 4: Run Splitter Script
python skills/excalidraw-diagram-generator/scripts/split-excalidraw-library.py skills/excalidraw-diagram-generator/libraries/aws-architecture-icons/Step 5: Verify Setup After running the script, verify the following structure exists:
skills/excalidraw-diagram-generator/libraries/aws-architecture-icons/
aws-architecture-icons.excalidrawlib (original)
reference.md (generated - icon lookup table)
icons/ (generated - individual icon files)
API-Gateway.json
CloudFront.json
EC2.json
Lambda.json
RDS.json
S3.json
...AI Assistant Workflow
When icon libraries are available in libraries/:
RECOMMENDED APPROACH: Use Python Scripts (Efficient & Reliable)
The repository includes Python scripts that handle icon integration automatically:
Create base diagram structure:
Create
.excalidrawfile with basic layout (title, boxes, regions)This establishes the canvas and overall structure
Add icons using Python script:
python skills/excalidraw-diagram-generator/scripts/add-icon-to-diagram.py \ <diagram-path> <icon-name> <x> <y> [--label "Text"] [--library-path PATH]Edit via
.excalidraw.editis enabled by default to avoid overwrite issues; pass--no-use-edit-suffixto disable.
Examples:
# Add EC2 icon at position (400, 300) with label python scripts/add-icon-to-diagram.py diagram.excalidraw EC2 400 300 --label "Web Server" # Add VPC icon at position (200, 150) python scripts/add-icon-to-diagram.py diagram.excalidraw VPC 200 150 # Add icon from different library python scripts/add-icon-to-diagram.py diagram.excalidraw Compute-Engine 500 200 \ --library-path libraries/gcp-icons --label "API Server"Add connecting arrows:
python skills/excalidraw-diagram-generator/scripts/add-arrow.py \ <diagram-path> <from-x> <from-y> <to-x> <to-y> [--label "Text"] [--style solid|dashed|dotted] [--color HEX]Edit via
.excalidraw.editis enabled by default to avoid overwrite issues; pass--no-use-edit-suffixto disable.
Examples:
# Simple arrow from (300, 250) to (500, 300) python scripts/add-arrow.py diagram.excalidraw 300 250 500 300 # Arrow with label python scripts/add-arrow.py diagram.excalidraw 300 250 500 300 --label "HTTPS" # Dashed arrow with custom color python scripts/add-arrow.py diagram.excalidraw 400 350 600 400 --style dashed --color "#7950f2"Workflow summary:
# Step 1: Create base diagram with title and structure # (Create .excalidraw file with initial elements) # Step 2: Add icons with labels python scripts/add-icon-to-diagram.py my-diagram.excalidraw "Internet-gateway" 200 150 --label "Internet Gateway" python scripts/add-icon-to-diagram.py my-diagram.excalidraw VPC 250 250 python scripts/add-icon-to-diagram.py my-diagram.excalidraw ELB 350 300 --label "Load Balancer" python scripts/add-icon-to-diagram.py my-diagram.excalidraw EC2 450 350 --label "EC2 Instance" python scripts/add-icon-to-diagram.py my-diagram.excalidraw RDS 550 400 --label "Database" # Step 3: Add connecting arrows python scripts/add-arrow.py my-diagram.excalidraw 250 200 300 250 # Internet → VPC python scripts/add-arrow.py my-diagram.excalidraw 300 300 400 300 # VPC → ELB python scripts/add-arrow.py my-diagram.excalidraw 400 330 500 350 # ELB → EC2 python scripts/add-arrow.py my-diagram.excalidraw 500 380 600 400 # EC2 → RDS
Benefits of Python Script Approach:
✅ No token consumption: Icon JSON data (200-1000 lines each) never enters AI context
✅ Accurate transformations: Coordinate calculations handled deterministically
✅ ID management: Automatic UUID generation prevents conflicts
✅ Reliable: No risk of coordinate miscalculation or ID collision
✅ Fast: Direct file manipulation, no parsing overhead
✅ Reusable: Works with any Excalidraw library you provide
ALTERNATIVE: Manual Icon Integration (Not Recommended)
Only use this if Python scripts are unavailable:
Check for libraries:
List directory: skills/excalidraw-diagram-generator/libraries/ Look for subdirectories containing reference.md filesRead reference.md:
Open: libraries/<library-name>/reference.md This is lightweight (typically <300 lines) and lists all available iconsFind relevant icons:
Search the reference.md table for icon names matching diagram needs Example: For AWS diagram with EC2, S3, Lambda → Find "EC2", "S3", "Lambda" in tableLoad specific icon data (WARNING: Large files):
Read ONLY the needed icon files: - libraries/aws-architecture-icons/icons/EC2.json (200-300 lines) - libraries/aws-architecture-icons/icons/S3.json (200-300 lines) - libraries/aws-architecture-icons/icons/Lambda.json (200-300 lines) Note: Each icon file is 200-1000 lines - this consumes significant tokensExtract and transform elements:
Each icon JSON contains an "elements" array Calculate bounding box (min_x, min_y, max_x, max_y) Apply offset to all x/y coordinates Generate new unique IDs for all elements Update groupIds references Copy transformed elements into your diagramPosition icons and add connections:
Adjust x/y coordinates to position icons correctly in the diagram Update IDs to ensure uniqueness across diagram Add connecting arrows and labels as needed
Manual Integration Challenges:
⚠️ High token consumption (200-1000 lines per icon × number of icons)
⚠️ Complex coordinate transformation calculations
⚠️ Risk of ID collision if not handled carefully
⚠️ Time-consuming for diagrams with many icons
Example: Creating AWS Diagram with Icons
Request: "Create an AWS architecture diagram with Internet Gateway, VPC, ELB, EC2, and RDS"
Recommended Workflow (using Python scripts): Request: "Create an AWS architecture diagram with Internet Gateway, VPC, ELB, EC2, and RDS"
Recommended Workflow (using Python scripts):
# Step 1: Create base diagram file with title
# Create my-aws-diagram.excalidraw with basic structure (title, etc.)
# Step 2: Check icon availability
# Read: libraries/aws-architecture-icons/reference.md
# Confirm icons exist: Internet-gateway, VPC, ELB, EC2, RDS
# Step 3: Add icons with Python script
python scripts/add-icon-to-diagram.py my-aws-diagram.excalidraw "Internet-gateway" 150 100 --label "Internet Gateway"
python scripts/add-icon-to-diagram.py my-aws-diagram.excalidraw VPC 200 200
python scripts/add-icon-to-diagram.py my-aws-diagram.excalidraw ELB 350 250 --label "Load Balancer"
python scripts/add-icon-to-diagram.py my-aws-diagram.excalidraw EC2 500 300 --label "Web Server"
python scripts/add-icon-to-diagram.py my-aws-diagram.excalidraw RDS 650 350 --label "Database"
# Step 4: Add connecting arrows
python scripts/add-arrow.py my-aws-diagram.excalidraw 200 150 250 200 # Internet → VPC
python scripts/add-arrow.py my-aws-diagram.excalidraw 265 230 350 250 # VPC → ELB
python scripts/add-arrow.py my-aws-diagram.excalidraw 415 280 500 300 # ELB → EC2
python scripts/add-arrow.py my-aws-diagram.excalidraw 565 330 650 350 --label "SQL" --style dashed
# Result: Complete diagram with professional AWS icons, labels, and connectionsBenefits:
No manual coordinate calculation
No token consumption for icon data
Deterministic, reliable results
Easy to iterate and adjust positions
Alternative Workflow (manual, if scripts unavailable):
Check:
libraries/aws-architecture-icons/reference.mdexists → YesRead reference.md → Find entries for Internet-gateway, VPC, ELB, EC2, RDS
Load:
icons/Internet-gateway.json(298 lines)icons/VPC.json(550 lines)icons/ELB.json(363 lines)icons/EC2.json(231 lines)icons/RDS.json(similar size) Total: ~2000+ lines of JSON to process
Extract elements from each JSON
Calculate bounding boxes and offsets for each icon
Transform all coordinates (x, y) for positioning
Generate unique IDs for all elements
Add arrows showing data flow
Add text labels
Generate final
.excalidrawfile
Challenges with manual approach:
High token consumption (~2000-5000 lines)
Complex coordinate math
Risk of ID conflicts
Supported Icon Libraries (Examples — verify availability)
This workflow works with any valid
.excalidrawlibfile you provide.Examples of library categories you may find on https://libraries.excalidraw.com/:
Cloud service icons
Kubernetes / infrastructure icons
UI / Material icons
Flowchart / diagram symbols
Network diagram icons
Availability and naming can change; verify exact library names on the site before use.
Fallback: No Icons Available
If no icon libraries are set up:
Create diagrams using basic shapes (rectangles, ellipses, arrows)
Use color coding and text labels to distinguish components
Inform user they can add icons later or set up libraries for future diagrams
The diagram will still be functional and clear, just less visually polished
References
See bundled references for:
references/excalidraw-schema.md- Complete Excalidraw JSON schemareferences/element-types.md- Detailed element type specificationstemplates/flowchart-template.excalidraw- Basic flowchart startertemplates/relationship-template.excalidraw- Relationship diagram startertemplates/mindmap-template.excalidraw- Mind map startertemplates/business-flow-swimlane-template.excalidraw- Business flow swimlane startertemplates/class-diagram-template.excalidraw- Class diagram startertemplates/data-flow-diagram-template.excalidraw- Data flow diagram startertemplates/er-diagram-template.excalidraw- Entity-relationship diagram startertemplates/sequence-diagram-template.excalidraw- Sequence diagram starterscripts/add-icon-to-diagram.py- Add icons from Excalidraw libraries to diagramsscripts/add-arrow.py- Add arrows (connections) between elements in diagramsscripts/split-excalidraw-library.py- Tool to split.excalidrawlibfilesscripts/README.md- Documentation for library toolsscripts/.gitignore- Prevents local Python artifacts from being committed
Limitations
Complex curves are simplified to straight/basic curved lines
Hand-drawn roughness is set to default (1)
No embedded images support in auto-generation
Maximum recommended elements: 20 per diagram
No automatic collision detection (use spacing guidelines)
Future Enhancements
Potential improvements:
Auto-layout optimization algorithms
Import from Mermaid/PlantUML syntax
Template library expansion
Interactive editing after generation
Files
- ATTRIBUTION.mdAdded by AutoGineer899 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md23.8 KiB
- references/element-types.md8.5 KiB
- references/excalidraw-schema.md8.2 KiB
- scripts/.gitignore484 B
- scripts/README.md6.4 KiB
- scripts/add-arrow.pyScript9.7 KiB
- scripts/add-icon-to-diagram.pyScript13.2 KiB
- scripts/split-excalidraw-library.pyScript5.4 KiB
- templates/business-flow-swimlane-template.excalidraw7.6 KiB
- templates/class-diagram-template.excalidraw12.6 KiB
- templates/data-flow-diagram-template.excalidraw6.3 KiB
- templates/er-diagram-template.excalidraw15.1 KiB
- templates/flowchart-template.excalidraw4.0 KiB
- templates/mindmap-template.excalidraw5.3 KiB
- templates/relationship-template.excalidraw3.2 KiB
- templates/sequence-diagram-template.excalidraw11.4 KiB
scripts/add-arrow.py
#!/usr/bin/env python3
"""
Add arrows (connections) between elements in Excalidraw diagrams.
Usage:
python add-arrow.py <diagram_path> <from_x> <from_y> <to_x> <to_y> [OPTIONS]
Options:
--style {solid|dashed|dotted} Arrow line style (default: solid)
--color HEX Arrow color (default: #1e1e1e)
--label TEXT Add text label on the arrow
--use-edit-suffix Edit via .excalidraw.edit to avoid editor overwrite issues (enabled by default; use --no-use-edit-suffix to disable)
Examples:
python add-arrow.py diagram.excalidraw 300 200 500 300
python add-arrow.py diagram.excalidraw 300 200 500 300 --label "HTTP"
python add-arrow.py diagram.excalidraw 300 200 500 300 --style dashed --color "#7950f2"
python add-arrow.py diagram.excalidraw 300 200 500 300 --use-edit-suffix
"""
import json
import sys
import uuid
from pathlib import Path
from typing import Dict, Any
def generate_unique_id() -> str:
"""Generate a unique ID for Excalidraw elements."""
return str(uuid.uuid4()).replace('-', '')[:16]
def prepare_edit_path(diagram_path: Path, use_edit_suffix: bool) -> tuple[Path, Path | None]:
"""
Prepare a safe edit path to avoid editor overwrite issues.
Returns:
(work_path, final_path)
- work_path: file path to read/write during edit
- final_path: file path to rename back to (or None if not used)
"""
if not use_edit_suffix:
return diagram_path, None
if diagram_path.suffix != ".excalidraw":
return diagram_path, None
edit_path = diagram_path.with_suffix(diagram_path.suffix + ".edit")
if diagram_path.exists():
if edit_path.exists():
raise FileExistsError(f"Edit file already exists: {edit_path}")
diagram_path.rename(edit_path)
return edit_path, diagram_path
def finalize_edit_path(work_path: Path, final_path: Path | None) -> None:
"""Finalize edit by renaming .edit back to .excalidraw if needed."""
if final_path is None:
return
if final_path.exists():
final_path.unlink()
work_path.rename(final_path)
def create_arrow(
from_x: float,
from_y: float,
to_x: float,
to_y: float,
style: str = "solid",
color: str = "#1e1e1e",
label: str = None
) -> list:
"""
Create an arrow element.
Args:
from_x: Starting X coordinate
from_y: Starting Y coordinate
to_x: Ending X coordinate
to_y: Ending Y coordinate
style: Line style (solid, dashed, dotted)
color: Arrow color
label: Optional text label on the arrow
Returns:
List of elements (arrow and optional label)
"""
elements = []
# Arrow element
arrow = {
"id": generate_unique_id(),
"type": "arrow",
"x": from_x,
"y": from_y,
"width": to_x - from_x,
"height": to_y - from_y,
"angle": 0,
"strokeColor": color,
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": style,
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": None,
"index": "a0",
"roundness": {
"type": 2
},
"seed": 1000000000 + hash(f"{from_x}{from_y}{to_x}{to_y}") % 1000000000,
"version": 1,
"versionNonce": 2000000000 + hash(f"{from_x}{from_y}{to_x}{to_y}") % 1000000000,
"isDeleted": False,
"boundElements": [],
"updated": 1738195200000,
"link": None,
"locked": False,
"points": [
[0, 0],
[to_x - from_x, to_y - from_y]
],
"startBinding": None,
"endBinding": None,
"startArrowhead": None,
"endArrowhead": "arrow",
"lastCommittedPoint": None
}
elements.append(arrow)
# Optional label
if label:
mid_x = (from_x + to_x) / 2 - (len(label) * 5)
mid_y = (from_y + to_y) / 2 - 10
label_element = {
"id": generate_unique_id(),
"type": "text",
"x": mid_x,
"y": mid_y,
"width": len(label) * 10,
"height": 20,
"angle": 0,
"strokeColor": color,
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": "solid",
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": None,
"index": "a0",
"roundness": None,
"seed": 1000000000 + hash(label) % 1000000000,
"version": 1,
"versionNonce": 2000000000 + hash(label) % 1000000000,
"isDeleted": False,
"boundElements": [],
"updated": 1738195200000,
"link": None,
"locked": False,
"text": label,
"fontSize": 14,
"fontFamily": 5,
"textAlign": "center",
"verticalAlign": "top",
"containerId": None,
"originalText": label,
"autoResize": True,
"lineHeight": 1.25
}
elements.append(label_element)
return elements
def add_arrow_to_diagram(
diagram_path: Path,
from_x: float,
from_y: float,
to_x: float,
to_y: float,
style: str = "solid",
color: str = "#1e1e1e",
label: str = None
) -> None:
"""
Add an arrow to an Excalidraw diagram.
Args:
diagram_path: Path to the Excalidraw diagram file
from_x: Starting X coordinate
from_y: Starting Y coordinate
to_x: Ending X coordinate
to_y: Ending Y coordinate
style: Line style (solid, dashed, dotted)
color: Arrow color
label: Optional text label
"""
print(f"Creating arrow from ({from_x}, {from_y}) to ({to_x}, {to_y})")
arrow_elements = create_arrow(from_x, from_y, to_x, to_y, style, color, label)
if label:
print(f" With label: '{label}'")
# Load diagram
print(f"Loading diagram: {diagram_path}")
with open(diagram_path, 'r', encoding='utf-8') as f:
diagram = json.load(f)
# Add arrow elements
if 'elements' not in diagram:
diagram['elements'] = []
original_count = len(diagram['elements'])
diagram['elements'].extend(arrow_elements)
print(f" Added {len(arrow_elements)} elements (total: {original_count} -> {len(diagram['elements'])})")
# Save diagram
print(f"Saving diagram")
with open(diagram_path, 'w', encoding='utf-8') as f:
json.dump(diagram, f, indent=2, ensure_ascii=False)
print(f"✓ Successfully added arrow to diagram")
def main():
"""Main entry point."""
if hasattr(sys.stdout, "reconfigure"):
# Ensure consistent UTF-8 output on Windows consoles.
sys.stdout.reconfigure(encoding="utf-8")
if len(sys.argv) < 6:
print("Usage: python add-arrow.py <diagram_path> <from_x> <from_y> <to_x> <to_y> [OPTIONS]")
print("\nOptions:")
print(" --style {solid|dashed|dotted} Line style (default: solid)")
print(" --color HEX Color (default: #1e1e1e)")
print(" --label TEXT Text label on arrow")
print(" --use-edit-suffix Edit via .excalidraw.edit to avoid editor overwrite issues (enabled by default; use --no-use-edit-suffix to disable)")
print("\nExamples:")
print(" python add-arrow.py diagram.excalidraw 300 200 500 300")
print(" python add-arrow.py diagram.excalidraw 300 200 500 300 --label 'HTTP'")
sys.exit(1)
diagram_path = Path(sys.argv[1])
from_x = float(sys.argv[2])
from_y = float(sys.argv[3])
to_x = float(sys.argv[4])
to_y = float(sys.argv[5])
# Parse optional arguments
style = "solid"
color = "#1e1e1e"
label = None
# Default: use edit suffix to avoid editor overwrite issues
use_edit_suffix = True
i = 6
while i < len(sys.argv):
if sys.argv[i] == '--style':
if i + 1 < len(sys.argv):
style = sys.argv[i + 1]
if style not in ['solid', 'dashed', 'dotted']:
print(f"Error: Invalid style '{style}'. Must be: solid, dashed, or dotted")
sys.exit(1)
i += 2
else:
print("Error: --style requires an argument")
sys.exit(1)
elif sys.argv[i] == '--color':
if i + 1 < len(sys.argv):
color = sys.argv[i + 1]
i += 2
else:
print("Error: --color requires an argument")
sys.exit(1)
elif sys.argv[i] == '--label':
if i + 1 < len(sys.argv):
label = sys.argv[i + 1]
i += 2
else:
print("Error: --label requires a text argument")
sys.exit(1)
elif sys.argv[i] == '--use-edit-suffix':
use_edit_suffix = True
i += 1
elif sys.argv[i] == '--no-use-edit-suffix':
use_edit_suffix = False
i += 1
else:
print(f"Error: Unknown option: {sys.argv[i]}")
sys.exit(1)
# Validate inputs
if not diagram_path.exists():
print(f"Error: Diagram file not found: {diagram_path}")
sys.exit(1)
try:
work_path, final_path = prepare_edit_path(diagram_path, use_edit_suffix)
add_arrow_to_diagram(work_path, from_x, from_y, to_x, to_y, style, color, label)
finalize_edit_path(work_path, final_path)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == '__main__':
main()
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
jun-shiromizu
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/excalidraw-diagram-generator · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- jun-shiromizu, SEPURI-SAI-KRISHNA, brainit-consulting
AutoGineer is not affiliated with or endorsed by jun-shiromizu or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download excalidraw-diagram-generator.zip