Skip to main content

Affinity SDK — Complete Learning Tutorial


What this tutorial is​

This is a structured tutorial for learning the Affinity by Canva JavaScript SDK — the scripting system that lets you automate Affinity application using JavaScript running directly inside the application.

The tutorial covers the SDK from the ground up: the execution model, the document structure, the command system, visual properties, text, dialogs, export, AI operations, layer effects, async patterns, pixel processing, and typography. It is built from direct inspection of the SDK source code and the official test suite, and every example script has been verified against a running Affinity installation.


Official SDK documentation​

The official Affinity SDK documentation lives at https://sdk.affinity.studio/. This tutorial is built from direct inspection of the SDK source code, but the SDK evolves — new modules, commands, and examples ship with Affinity updates. Make it a habit to check the official documentation alongside this tutorial for the latest API reference; when in doubt, the official docs are the canonical source.


What is the Affinity SDK​

The Affinity SDK is a JavaScript scripting environment embedded inside Affinity by Canva. Scripts run in a sandboxed JS engine that has direct access to the open document — its layers, nodes, text, fills, geometry, and pixel data — through a set of native modules.

It is not a browser API. It is not Node.js. It is a purpose-built environment with its own rules:

  • Modules are loaded with require('/module-name.js') — not npm. ES imports are also supported when you enable the "Run as module" option under the Cog button in the script editor
  • Scripts run on their own thread, separate from the application's main thread, to avoid UI lock-up. But the separation isn't absolute — a script that triggers many UI updates still loads the main thread. Within a script, commands execute synchronously
  • All document modifications go through a command system that integrates with Affinity's undo stack
  • The only output mechanism available to scripts is console.log(), viewed in the script console
  • Scripts are restricted to reading and writing files on the Desktop or to folders you grant access to

Within those constraints, scripts can do a remarkable amount: read and modify any property of any layer, apply fills and effects, manipulate text, export assets in any format, call external APIs via the network module, drive Affinity's AI features, and process images pixel by pixel.


Who this tutorial is for​

This tutorial assumes you can read and write JavaScript — loops, functions, objects, and basic async patterns. You do not need experience with Node.js, browser APIs, or any specific JavaScript framework. SDK scripting is different from all of them, and this tutorial treats it on its own terms.

You do not need any prior experience with Affinity's scripting panel. Lesson 01 covers everything you need to get your first script running.

This tutorial also assumes you are familiar with Affinity by Canva — how to open documents, work with layers, use the export persona, and navigate the UI. The tutorial teaches SDK scripting, not the application itself. If you are new to Affinity, start with the official Affinity tutorials first. Bottom line: if you're unfamiliar with what Affinity by Canva can do, you'll have a hard time automating it.


What you will be able to build​

By the end of this tutorial you will be able to write scripts that:

  • Iterate every layer in a document, identify node types, and read or modify their properties
  • Apply fills, strokes, gradients, and effects to any node or set of nodes in a single undoable command
  • Read, replace, and style text in any text frame using the Story API
  • Present native dialogs that collect input from the user and drive the rest of the script
  • Export every artboard as named files, write JSON manifests, and POST results to an external API
  • Generate images from text prompts, remove backgrounds, and chain AI operations with export pipelines
  • Process every pixel of a raster layer to implement custom image filters and analysis tools
  • Enumerate installed fonts, detect missing typefaces, and substitute them programmatically
  • Write async pipelines that chain execute, export, and save operations with proper error handling

How the tutorial is structured​

The tutorial is organised into five phases, each building on the last. Within each phase, lessons are ordered so that earlier lessons are prerequisites for later ones. The phase and lesson READMEs tell you exactly what they depend on. Phase 5 is a reference collection of official example scripts rather than lessons.

affinity-sdk-tutorial/
├── phase-1-foundations/ Lessons 01–03
│ ├── 01-environment-setup/
│ ├── 02-app-and-document/
│ └── 03-node-model/
├── phase-2-core-api/ Lessons 04–06
│ ├── 04-command-pattern/
│ ├── 05-fills-and-strokes/
│ └── 06-geometry/
├── phase-3-tools/ Lessons 07–10
│ ├── 07-text-and-story/
│ ├── 08-dialog-ui/
│ ├── 09-export-and-files/
│ └── 10-text-threading/
└── phase-4-advanced/ Lessons 11–18
├── 11-ai-commands/
├── 12-layer-effects/
├── 13-pro-patterns/
├── 14-special-modules/
├── 15-pixel-processing/
├── 16-fonts-and-typography/
├── 17-raster-adjustments/
└── 18-align-distribute/
└── phase-5-official-examples/ Official Affinity SDK example scripts (34 files)
└── examples/

Each lesson folder contains:

  • README.md — a full explanation of the concepts, the correct API patterns, the common failure modes, and a key gotchas section that documents the non-obvious behaviours that cost time to discover independently
  • examples/ — runnable .js scripts that you paste directly into Affinity's script panel. Every example is self-contained and includes comments explaining the non-obvious parts

Phase overview​

PhaseWhat it coversLessons
1 — FoundationsThe execution model, document entry point, and node tree. Everything else depends on this.1–3
2 — Core APIThe command system, fills, strokes, geometry, and transforms. This is where scripts start making changes.4–6
3 — ToolsText automation, dialog UI, file export, and HTTP networking. This is where scripts become useful to other people.7–10
4 — AdvancedAI commands, layer effects, raster adjustments, async pipelines, pixel processing, typography, and align/distribute. The full capability of the SDK.11–18
5 — Official examplesVerbatim example scripts shipped by the Affinity team — best-practice references across layout, geometry, paths, text, strokes, selection, raster, dialogs, and logging.reference

How to use this tutorial​

Read the README before running the examples. Each lesson README explains the concepts, the gotchas, and the argument orders before you encounter them in code. The examples will make more sense — and fail less often — if you understand the model first.

Keep CHEAT-SHEET.md open while coding. It is a single-page reference covering the patterns, argument orders, and critical rules that come up in almost every session. The critical rules table at the bottom is particularly worth memorising — it documents the SDK behaviours that produce silent failures rather than helpful error messages.

Run the examples on a real document. Most examples require an open document and a selection. Start with a simple document — a few shapes on a single page — until you understand how a script interacts with it. Move to more complex documents once the patterns are clear. I would encourage you to type all the examples yourself. Don't just copy-paste. The muscle memory you will gain will serve you well in the future.

Work through phases in order, but not necessarily every lesson. Phases 1 and 2 are prerequisites for everything. Within Phase 3 and 4, individual lessons are largely independent — if you need text automation now, go to Lesson 07. If you need pixel processing, go to Lesson 14. Come back to the others when you need them.

Use SDK-EXPOSURE-MAP.md as a reference. It documents the full API surface — every module, every class, every method — in one place. When you need something the lessons don't cover, start there.


The three rules everything else builds on​

1. require('/module.js') — not ./module The SDK has its own module registry. Paths start with /. There is no npm, no ES modules, no node_modules. If a require call silently returns undefined, the module path is wrong.

2. console.log() is your only output Scripts don't return values to the UI. Everything you want to see must be logged. View the output in Affinity's script console panel.

3. All document changes go through doc.executeCommand() Never mutate nodes directly. Build a command object and execute it. This is what gives you undo/redo integration, and it is also what gives the command system its ability to batch multiple changes into a single undoable step via CompoundCommandBuilder.


Running a script​

  1. Open a document in Affinity by Canva
  2. Open the Script Editor: go to Window → Scripting → Script Editor, or switch to the Scripting Studio for a full range of scripting panels
  3. Paste/type a script into the editor
  4. Click Run — output appears in the console below the editor

For scripts that require a selection, select the relevant objects before clicking Run.


SDK module reference​

ModuleKey exports
/applicationapp — version, platform, Desktop path
/documentDocument, DocumentPromises, DocumentPreset, DocumentHistory, DocumentSnapshot, FileExportOptions, FileExportArea, NewDocumentOptions, LoadDocumentOptions
/commandsDocumentCommand, CompoundCommandBuilder, AddChildNodesCommandBuilder
/nodesAll node classes — ShapeNode, TextNode, RasterNode, etc.
/selectionsSelection, TextSelection
/coloursRGBA8, Colour, ColourProfile
/fillsFillDescriptor, SolidFill, GradientFill, HatchFill, BitmapFill, NoFill
/linestyleLineStyle, LineStyleMask, LineType
/geometryTransform, CurveBuilder, PolyCurve, Bezier
/shapesShape definitions and parameters
/dialogDialog, all control types, DialogResult
/storybuilderStoryBuilder — construct text content programmatically
/storydeltaStoryDelta — describe text formatting changes
/glyphattsCharacter-level formatting attributes
/paragraphattsParagraph-level formatting attributes
/pixelaccessorPixelReaderWriterRGBA8 and all other pixel accessor classes
/rasterobjectBitmap, PixelBuffer, NodeRenderingEngine, RasterFormat
/fontsFont, FontFamily, FontWeight, FontWidth
/fsFile — Desktop read/write only
/networkHttpRequest, RequestMethod
/timerssetTimeout(delay, callback), setInterval(delay, callback)
/bufferBuffer — raw binary data
/unitsUnitType, UnitValueConverter

For the complete API surface including all methods and argument signatures, see SDK-EXPOSURE-MAP.md. The official SDK documentation at https://sdk.affinity.studio/ is the canonical reference — check it for the latest additions and changes.


Supporting files​

FilePurpose
SDK-PRIMER.mdAI project starter — correct patterns, broken APIs, non-obvious behaviours. Read this before writing any code in a new session.
CHEAT-SHEET.mdOne-page quick reference — keep this open while coding
SDK-EXPOSURE-MAP.mdFull API surface inventory — modules, classes, methods