Prompt Engineering for Code-Generated Images and Video: A Practical Guide
This article explains how to write effective prompts for generating images and video entirely in code. It introduces a four-part prompt structure, shows how to make visual descriptions measurable, and focuses on the technical constraints—pure functions of time, fixed random seeds, and closed loops—that make output reproducible. Two reusable templates and a three-point acceptance checklist are included.
1. The Problem Is the Prompt, Not the Model
Generating an image or video directly with code is fundamentally different from describing a picture in natural language. The output is not pixels but a program that must run, be debugged, and be reproduced frame by frame. That changes the job of the prompt: instead of an aesthetic description, it becomes a simplified engineering contract.
Most people start these prompts with the scene: “aurora,” “fjord,” “snow,” followed by a few words about mood. The result is that the model picks its own implementation path—some build a 3D scene, some write shaders, some rely on heavy bitmap textures, and some simply return a static image with a few displacement transforms. The output may look right, but the code structure is messy, problems are hard to locate, and a seamless loop is not guaranteed.
An even more common failure is the “one-shot” attempt. First-pass code almost always has defects: misaligned periodic terms cause a jump at the loop point, unseeded randomness makes the scene different on every refresh, and time accumulated as state makes it impossible to jump to an arbitrary second. Writing the prompt as verifiable engineering requirements turns rework from a rewrite into a minor adjustment.
2. A Four-Part Prompt Structure
A reliable approach is to split the prompt into four sections in a fixed order: tools and runtime, scene description, technical constraints, and delivery criteria.
The first section declares the tool to remove ambiguity about the implementation path. For example, state “implement with the browser canvas 2D drawing API, single file, no external assets, no network requests.” Once the tool is fixed, the model will not pull in a build chain, dependency packages, or external images.
The second section is the scene description, layered as subject, composition, color, and detail density, rather than piling aesthetic adjectives into one long sentence.
The third section specifies the tech stack and mathematical constraints—the part most often overlooked in pure-code generation and the one that most determines success.
The fourth section sets delivery criteria: render a short sample for confirmation first, then the full piece; also require a written note stating which effects are simulated and which are not implemented.
Illustrative template:
[Tools] Implement with the browser canvas 2D drawing API, single file; no external images, fonts, or network requests.[Scene] Subject: ...; Composition: ...; Color: ...; Detail density: natural-history documentary night scene.[Technical] The frame is a pure function of time t, expose a seek(t) function, keep no cross-frame state;pseudo-random values use a fixed seed; all periods divide the total duration, last frame matches first frame.[Delivery] Render a 5-second sample for confirmation first, then the full piece; attach a one-page note marking simulated and unimplemented items.
3. Make the Scene Description Measurable
“High detail density” is not executable. An executable version breaks density into concrete objects and orders of magnitude: vertical fiber structure inside the light bands, water reflections that change in sync with the bands, star points that stay fixed and do not twinkle, layered snow on the banks. Each item can be checked and fixed on its own.
Color needs constraints on relationships, not just names: green dominant, edges transitioning to pale purple, only one warm light source in the whole frame. Once the warm accent is defined as the only one, the model must keep everything else cool, and the composition holds together naturally.
Also state prohibitions explicitly: no text or watermarks, no recognizable landmarks, no reproduction of any specific photograph. Limit style references to “borrow only the texture of long exposure and the warm-cool contrast,” keeping style constraints at the texture level rather than the composition or subject level.
4. Technical Constraints Are the Core of Reproducibility
The three most common defects in pure-code animation can all be eliminated in advance with constraints.
The first is state drift. If each frame accumulates on top of the previous one, you cannot draw directly from an arbitrary point in time. Requiring “the frame is a pure function of time and exposes a seek function” enforces no cross-frame state.
The second is non-reproducible randomness. Only a pseudo-random sequence with a fixed seed guarantees that two renders are identical.
The third is a loop that does not close. Setting the period of every periodic term to a divisor of the total duration makes the last frame match the first, so looped playback has no jump.
// Pure function of time + fixed seed + period divides total durationconst DURATION = 30; // total duration (seconds)const PERIOD = DURATION / 6; // 5-second loop, divides total durationfunction draw(ctx, t) {const phase = (t % PERIOD) / PERIOD; // normalized phaseconst sway = Math.sin(phase * Math.PI * 2);// all random values derive from a fixed seed, independent of the previous framerenderAurora(ctx, sway, seededRandom(20260101));}function seek(t) { clear(); draw(ctx, t); } // jump directly to any moment
On the engineering side, add the render and encoding path: capture frame by frame with an automated browser, then encode into a video file with a fixed resolution and frame rate using a command-line video encoding tool. The tool names do not need to be fixed; just state the split of responsibilities between “frame capture” and “video encoding.”
5. Two Ready-to-Use Templates
Template 1: looping night animation. An aurora fjord on a 30-minute cycle semantics: deep night, silhouettes of snow-covered mountains on both banks, calm water fully reflecting the sky; the aurora rises from the horizon as vertical light bands with internal vertical fibers, swaying slowly; fixed star points; a warm yellow glow in the window of a lakeside cabin as the only warm color. Reuse the technical and delivery sections from the four-part structure.
Template 2: static indoor light beam. An afternoon interior with a white wall, wooden floor, and a paned glass door; a beam slants into the room, forming grid-shaped light patches on the floor and wall with penumbra transitions at the edges; fine dust is visible in the air but must not be exaggerated into smoke. The technical section emphasizes “a single draw produces the complete frame, all textures generated procedurally”; the delivery section requires a low-resolution preview to confirm composition first, then the full-resolution image.
6. Delivery and Acceptance
Acceptance checks only three things: whether the frame can be drawn directly from any point in time, whether two renders are completely identical, and whether there is no jump at the loop point. Put these three items in the delivery section of the prompt and require a one-page note distinguishing “simulated effects” from “unimplemented items,” and an uncontrollable one-shot generation becomes an iterable, maintainable code asset. If rendering is heavy, container platforms and object storage can handle batch task distribution and artifact archiving, while logging and monitoring alerts track failed frames—general engineering practice, independent of any specific vendor.
