Programmatic Drawing with LLMs: Principles and Engineering Practice Without Image Models
This article explores a different approach to AI-generated artwork: instead of calling an image model to produce pixels, a large language model writes a drawing program that a rendering engine executes stroke by stroke on a virtual canvas. It explains how this route differs from diffusion models, how canvas state and brush strokes are represented, how the generate-execute-observe-refine loop works, and which engineering details matter for paths, jitter, paint and canvas simulation, and performance. It also covers artist-persona prompting for style control, practical steps for building such a system, and the approach's known limitations.
1. Introduction: How a Large Model Can “Paint” Without Generating Images
Most mainstream image generation approaches rely on diffusion models: starting from random noise, the model iteratively denoises over multiple steps until it approximates a target image, then outputs the result all at once or in stages. This route is efficient and offers strong semantic understanding, but the process is a black box: the model returns pixels directly, with no interpretable drawing process comparable to what a human painter does.
As large models have become better at code generation and tool calling, a fundamentally different technical route has emerged: the model does not generate pixels; it generates a “drawing program.” Once that program runs, it simulates brush movement, paint wetness, canvas grain, and stroke texture on a virtual canvas, accumulating the image stroke by stroke. If a stroke comes out wrong, the model can inspect the canvas state and cover, darken, or correct it with new strokes.
This is not a matter of swapping a diffusion model for another image model. It reframes drawing as a closed-loop control problem of code generation + state observation + iterative refinement. The approach is closer to how real painting works, and it is well suited to studying the limits of a model’s long-horizon planning, spatial reasoning, error recovery, and style evolution.
This article focuses on that route, covering its principles, key components, workflow design, and engineering considerations, so developers can understand why it works, where it applies, and how to build a programmatic drawing system that never calls an image model.
2. From Pixel Generation to Stroke Generation: Two Routes Compared
To understand the value of programmatic drawing, start with how it differs from diffusion models. Both can “generate images,” but the underlying logic is entirely different.
2.1 Diffusion Models: A One-Shot Mapping from Noise to Image
The core idea of a diffusion model is to learn a denoising process: starting from fully random Gaussian noise, a trained network progressively predicts and removes noise until the target image is recovered. Because training exposes it to massive image-text pairs, the model has strong semantic understanding and can output pixels that match a text prompt directly.
The problems with this route are:
- The process is not interpretable: the model predicts pixels directly, with no human concepts such as “stroke,” “paint,” or “brush direction” in between;
- Errors are hard to fix: if something is drawn wrong, you usually regenerate the image or inpaint a region rather than adding a corrective stroke the way a painter would;
- Style control depends on prompts and post-processing: the model has no stable “artistic personality”; style is jointly determined by the prompt, the seed, and sampling parameters.
2.2 Programmatic Drawing: Treating the Canvas as a Programmable Object
Programmatic drawing inverts the problem: the model outputs code instead of pixels. When the code runs, it calls a dedicated drawing engine that executes strokes on a virtual canvas. Each stroke can be described by:
- Brush type and width;
- Color and paint water content;
- Path point coordinates, pressure curve, and jitter amplitude;
- Whether it blends, covers, or leaves the canvas texture showing.
This makes image generation interpretable, observable, and interruptible. After each stroke, the model can read the current canvas state, judge whether it matches expectations, and decide how to draw the next one. Errors no longer require regeneration; they are corrected with new strokes, which closely mirrors how real painting works.
2.3 Where Each Route Fits
| Dimension | Diffusion model route | Programmatic drawing route |
|---|---|---|
| Output form | Pixels directly | Executable code, then rendered to an image |
| Interpretability | Low; the process is a black box | High; every stroke can be traced and reviewed |
| Error correction | Relies on inpainting or partial regeneration | New strokes naturally cover and correct |
| Style control | Depends on prompts and sampling parameters | Shaped stably via an “artist persona” and engine parameters |
| Compute cost | One inference pass produces an image | Multiple rounds of code generation and rendering; higher cost |
| Use cases | Fast generation, batch production | Studying long-horizon planning, spatial reasoning, controllable drawing |
Programmatic drawing is not meant to replace diffusion models. It is a complementary route: better suited to studying a model’s abilities in continuous decision-making, spatial control, and error recovery, and to applications that need an interpretable drawing process.
3. Core Principles: How the Model Directs a Virtual Brush
Programmatic drawing works because it decomposes drawing into an instruction-sequence problem that models handle well. The model does not need to understand pixels directly; it needs to understand:
- What is currently on the canvas;
- Where the next stroke should go, what shape it should take, and what color it should use;
- What the image will look like after that stroke;
- How to correct it if the result differs from expectations.
These four steps form a closed loop. The model acts as the planner and decision-maker, not as a pixel generator.
3.1 A Programmable Representation of Canvas State
The first requirement is to model the canvas as a data structure the program can read and write. A typical virtual canvas may hold:
- Canvas dimensions and resolution;
- Current pixel or layer content;
- The list of strokes drawn so far;
- Path points, color, width, opacity, and other parameters for each stroke;
- Canvas texture (paper grain, canvas fibers) and paint wetness.
Each time the model produces a stroke, the engine writes it to the canvas and updates the state. On the next decision round, the model reads the current state and judges whether the previous stroke landed correctly.
3.2 The Stroke as the Minimal Execution Unit
In programmatic drawing, the stroke is the smallest execution unit. A stroke typically includes:
- Path: a curve defined by control points that describes the pen tip’s trajectory;
- Color: expressed as a hex value or in a color space;
- Width: the brush diameter, which sets stroke thickness;
- Opacity and flow: simulating paint density and layering;
- Jitter: small perturbations added to path points to mimic the natural unsteadiness of a human hand.
For example, when drawing a bird, the model might output an illustrative instruction like this:
stroke = {"color": "#30346a","width": 90,"points": [(120, 80),(125, 82),(130, 81),],"jitter": 7, # deliberate deviation of about 7 pixels"opacity": 0.85,}canvas.draw(stroke)
This means: draw one stroke with a 90-pixel brush in color #30346a along three slightly wavering path points, with about 7 pixels of jitter. The model adds jitter deliberately, because a human arm cannot draw a perfectly straight line, and perfectly straight strokes look mechanical and unnatural.
3.3 Brush Texture, Paint Wetness, and Canvas Feel
What gives programmatic drawing the feel of a real brush is the engine’s simulation of physical properties. Common dimensions include:
- Brush texture: different brushes (round, flat, fan, dry brush) leave different edges and internal textures;
- Paint wetness: wet paint spreads naturally with soft edges, while dry paint leaves broken streaks and grain;
- Canvas texture: canvas fibers absorb paint, creating subtle relief and color variation;
- Layering: when paint covers paint, the lower layer mixes with the new color, producing natural depth.
These properties keep the result from looking like flat color blocks pasted on a surface, giving it the breathing quality and chance variation of real painting. When planning each stroke, the model is effectively anticipating these physical effects and choosing stroke parameters accordingly.
3.4 Error Observation and Correction
Another advantage is that errors are observable and correctable. After each stroke, the model can read the canvas state and check it against expectations. If something is wrong, it can:
- Cover: paint over the bad area with a color close to the background;
- Darken or lighten: layer a darker or lighter color to fix tonal relationships;
- Repaint: draw a new stroke in a better position;
- Adjust later strokes: leave the finished part alone and rebalance the image through subsequent strokes.
For instance, if the model finds the lines on the bird’s back too thin and messy, it can thicken them, adjust the color, or re-outline the contour in later strokes instead of starting over. This draw-observe-correct cycle is what sets programmatic drawing apart from one-shot image generation.
4. From Nothing to a Finished Picture: The Full Workflow
A complete programmatic drawing system typically involves these stages:
- Task understanding: the model interprets the user’s request (for example, “draw a shopping cart in a parking lot” or “draw a bird at sunrise”);
- Composition planning: the model sketches the image mentally, fixing the subject, composition, light source, and palette;
- Stroke decomposition: the image is broken into a large number of independent stroke instructions;
- Code generation: the stroke instructions are written as an executable Python program;
- Program execution: the drawing engine runs the program and paints stroke by stroke;
- State observation: after each stage, the model reads the canvas state and inspects the image;
- Iterative refinement: strokes are adjusted and errors corrected based on observations;
- Final output: the finished image, along with the code that produced it.
The defining characteristic is that the model does not give an answer in one shot; it completes the work through repeated generate-execute-observe-refine cycles. Each cycle is one interaction between the model and the drawing engine.
5. Key Engineering Details: Strokes, Paths, Jitter, and Canvas Simulation
Making programmatic drawing actually look like painting takes attention to many implementation details.
5.1 Path Generation: From Control Points to Smooth Curves
A stroke path usually consists of control points. To keep lines natural and fluid, curve interpolation algorithms (such as Bézier curves or splines) connect the control points into a smooth trajectory. Too few control points make lines stiff; too many raise computation and become hard for the model to control precisely.
Common practice is to:
- Define the general direction of a stroke with a few control points;
- Add slight jitter between adjacent control points to mimic human instability;
- Adapt control point density to stroke length.
5.2 Jitter and Pressure Curves: Giving Strokes a Human Quality
A human hand cannot draw a perfectly straight line, so programmatic drawing deliberately adds small jitter along the path. A 90-pixel-wide stroke, for example, might add roughly 7 pixels of deviation at each of five path points. This jitter is not noise; it is intentional naturalness.
Pressure curves matter just as much. A real brush changes pressure as it lands, travels, and lifts, producing different thickness and density. By simulating a pressure curve, programmatic drawing can make a stroke thin at the start, thicker along the way, and fading at the end, which is closer to real painting.
5.3 Simulating Paint and Canvas Physics
For realistic texture, the engine needs to simulate paint and canvas behavior. Common techniques include:
- Paint layer stacking: model paint as semi-transparent layers, blending new strokes with old ones by ratio;
- Wet spreading: apply a simple diffusion algorithm to wet paint so edges blur naturally;
- Canvas texture overlay: use noise textures to mimic canvas fibers, giving stroke edges a natural roughness;
- Color space mixing: blend colors in a suitable color space to avoid the dullness of naive RGB mixing.
These simulations do not need physical-grade accuracy, but they must be visually convincing. The model implicitly relies on these rules when planning strokes.
5.4 Large Canvases and Performance Optimization
A single image may require hundreds of thousands or even millions of strokes. If every stroke re-renders the whole canvas, performance quickly becomes the bottleneck. Common optimizations include:
- Layered rendering: split the canvas into layers and redraw only affected ones;
- Incremental updates: repaint only the region a stroke covers;
- Stroke caching: cache drawn strokes as bitmaps and only composite them afterward;
- Batch submission: merge multiple strokes into a single render call.
These optimizations make programmatic drawing practical and lower the model’s iteration cost.
6. Making the Model Think Like a Painter: Artistic Persona and Style Evolution
An interesting pattern in programmatic drawing is that the model gradually develops a relatively stable artistic style. To steer that evolution, some practitioners have the model “play” an artist with a fictional background and a consistent creative style.
For example, you can define a fictional artist persona:
You are a painter who specializes in cool-toned landscapes. You like to laya base with wide brushes and outline with fine brushes, and your scenes oftenfeature thin mist and morning light. Your style is consistent; you do notswitch styles frequently.
The model then plans strokes, generates code, observes the canvas, and adjusts feedback under this persona. Over multiple iterations, it settles into stable preferences for strokes, colors, and composition. The benefits of this mechanism are:
- Controllable style: changing the persona steers the model toward different styles;
- Stable style: the model does not switch styles arbitrarily from stroke to stroke;
- Evolving style: textual feedback can gradually shift the model’s preferences.
Note that this is not about making the model imitate a specific real painter. It uses a persona and a feedback mechanism to let the model form its own creative habits at an abstract level. That avoids the disputes that style imitation can raise and better reflects the model’s own creative ability.
7. Practical Guidance: Building a Programmatic Drawing System
If you want to try programmatic drawing in your own project, this path is a reasonable starting point.
7.1 Choose a Drawing Engine
The drawing engine is the foundation. A usable engine should at least support:
- Brush type and width control;
- Color and opacity settings;
- Path points and curve interpolation;
- Reading and writing canvas state;
- Layered rendering and partial updates;
- Final image export.
If you would rather not build one from scratch, prototype with an existing graphics or drawing library, then replace it with a custom engine over time.
7.2 Design a Clear Stroke Instruction Format
The model’s output must be parsed reliably by the engine. Use a structured, validatable stroke format, for example:
{"stroke_id": 1,"brush": "round","color": "#30346a","width": 90,"opacity": 0.85,"points": [(120, 80), (125, 82), (130, 81)],"jitter": 7,"pressure": [0.2, 0.5, 0.3],}
With a structured format, the engine parses reliably and the model finds it easier to emit valid instructions.
7.3 Control Stroke Count and Iteration Limits
Stroke count and iteration count directly determine cost and quality. The recommendations are:
- Start with simple subjects (a single object, a simple composition);
- Increase stroke count and image complexity gradually;
- Set caps on strokes and iterations to avoid infinite loops;
- Compress the prompt for each iteration so the context does not grow too long.
7.4 Add Canvas Observation and Automated Checks
The model has to “see” the canvas to correct errors. Feed it a thumbnail of the canvas plus statistics for key regions (dominant colors, tonal distribution) so it can judge whether the image matches expectations. For more complex scenes, a simple image similarity or composition check can serve as an auxiliary signal.
7.5 Use General Cloud Capabilities to Reduce Engineering Load
A programmatic drawing system involves substantial compute and storage. When building on the cloud, consider general-purpose cloud capabilities:
- Container platforms: run the drawing engine and batch rendering jobs;
- Object storage: store canvas snapshots, stroke logs, and final artwork;
- Message queues: decouple stroke generation from render execution;
- Logging, monitoring, and alerting: track stroke counts, render latency, and failure rates.
These capabilities involve no vendor-specific interfaces, yet they noticeably improve system stability and observability.
8. Capability Limits and Cautions
Programmatic drawing is interesting but not universal. Its limits should be recognized clearly:
- High cost: multiple rounds of code generation and rendering take longer than a single image generation pass;
- Hard fine-grained control: the model’s control over very fine detail is still limited;
- Style depends on setup: without suitable style guidance, the model tends to produce messy images;
- Complex debugging: stroke instructions, render results, and model intent can diverge;
- Not for every scenario: when fast batch generation is the goal, diffusion models remain the better choice.
Programmatic drawing is therefore better treated as an experimental platform for studying long-horizon planning, spatial reasoning, and controllable drawing, rather than a replacement for conventional image generation.
9. Summary
Drawing with code that simulates a real brush, without calling an image model, shows another possibility for large models: a model does not have to generate pixels directly. By writing code, planning strokes, observing the canvas, and correcting errors, it can complete a piece of work. This turns drawing into a closed-loop control problem of code generation + state observation + iterative refinement, making the process interpretable, traceable, and interruptible.
The takeaway for developers is that a large model’s code generation and tool-calling abilities can be combined into more complex application forms, while stroke modeling, canvas simulation, performance optimization, and observation mechanisms are what turn the idea into a working system. If you want to explore controllable generation, long-horizon planning, or human-AI collaborative creation, programmatic drawing is an interesting and practical direction to pursue.
