How LLMs Generate Animations Through Code: A Technical Breakdown

    This article explains how large language models generate visual content such as slides, 2D animations, and 3D scenes by writing code that is rendered by a browser or runtime, rather than by generating pixels directly. It covers the four-layer pipeline from tokens to visuals, prompt and constraint design, sandboxed execution with error feedback loops, common failure modes and debugging strategies, a cloud architecture for production deployment, and an engineering checklist for building reproducible and scalable systems.

    1. Why Code-Generated Visuals Are Drawing Attention

    A wave of unusual AI-generated content has recently been making the rounds in overseas AI communities: a browser-based slide deck that has racked up more than seven million views and nearly thirty thousand likes on social platforms, a roughly 65-second hand-drawn style animation, and a detailed 3D mini-game. What sparked discussion was not the visual quality itself, but how the content was produced. None of it came directly from a dedicated video generation model. Instead, a large language model wrote code, and a browser or runtime rendered the result.

    There is an easily overlooked technical premise here: the native output of a large language model is text — more precisely, a sequence of tokens. It cannot directly synthesize video frames or audio waveforms. Most mainstream video generation approaches rely on diffusion models or spatiotemporal consistency modeling and output pixel sequences directly. The path discussed in this article is entirely different. It can be summarized as: the model writes code, the code produces the visuals, and the runtime delivers the result.

    Meanwhile, some tech media have reported that a leading model vendor appears to be running a staged rollout of a new model. Some users have noticed a clear shift in the visual aesthetics of outputs from the same entry point, and the community has taken to referring to this version by an incrementing version number. This article does not discuss any specific vendor or version. It focuses only on the general technical capability behind it: what happens to code-driven visual generation when a model’s spatial layout ability, aesthetic preferences, and code correctness all improve.

    2. How It Works: A Four-Layer Pipeline from Tokens to Visuals

    2.1 The Representation Layer: Why Code Instead of Pixels

    Making a model output pixels directly requires an extra decoder and enormous compute overhead, and the result is hard to edit. Having the model output code turns the “visual” into a structured artifact that is readable, modifiable, and version-controllable. Common carriers include HTML and CSS for slides, SVG for vector animation, the Canvas API for 2D drawing, WebGL wrapper libraries for 3D rendering, and general-purpose plotting libraries for charts and geometry.

    Another advantage of a code-based representation is composability. A slide deck can be split into four orthogonal dimensions — layout, color scheme, typography, and motion — each controlled by a separate prompt fragment. This makes it easy to regenerate one part without redoing the whole thing.

    A schematic structure looks like this:

    1. <!-- Skeleton of a single slide: layout separated from content -->
    2. <section class="slide">
    3. <h1 class="title">Title</h1>
    4. <ul class="points">
    5. <li>Point one</li>
    6. <li>Point two</li>
    7. </ul>
    8. <div class="chart" data-values="12,35,58"></div>
    9. </section>

    2.2 The Generation Layer: Prompt and Constraint Design

    The quality of code-generated visuals depends about eighty percent on how clearly the constraints are written. A reusable constraint checklist includes:

    • Runtime environment: specify whether it is a browser, a Node runtime, or a notebook environment, to avoid calling APIs that do not exist;
    • Canvas and coordinate system: width, height, units, and origin position, to prevent elements from going out of bounds;
    • Timeline: total duration, frame rate, and keyframe pacing — mandatory for animation tasks;
    • Asset policy: no external remote assets; all graphics drawn in code or embedded as inline data;
    • Fallback plan: degrade to pseudo-3D projection when 3D capability is unavailable.

    A practical prompt skeleton example:

    1. Role: Senior front-end engineer
    2. Task: Generate a single-file HTML implementing a 60-second hand-drawn style animation
    3. Constraints:
    4. 1. Use only the native Canvas 2D API; do not reference any external resources
    5. 2. Canvas 1280x720, 60fps, driven by requestAnimationFrame
    6. 3. Line jitter amplitude <= 1.5px to simulate hand-drawing; palette limited to 4 colors
    7. 4. Provide a window.__seek(t) function to support jumping by time for easier debugging
    8. Output: code only, no explanation

    The “provide a function to jump by time” requirement is a critical engineering technique. It turns an animation that cannot be debugged into a program that is reproducible and can be inspected frame by frame.

    2.3 The Execution Layer: Sandbox and Runtime

    Code generated by a model is untrusted and must be executed in isolation. In engineering practice, this typically means using a headless browser or a dedicated container to host rendering, combined with the following measures:

    • Network isolation: block outbound requests to prevent data leakage and asset hotlinking;
    • Resource limits: cap CPU time, memory, and rendered frames to avoid a dead loop taking down the service;
    • Timeout circuit breaker: terminate a single render once it exceeds a threshold and return an error summary to the model for a retry;
    • Error feedback: feed console errors and stack traces back in as new prompt input, forming an automatic repair loop.

    The loop in pseudocode:

    1. for attempt in range(3):
    2. code = model.generate(prompt + error_context)
    3. result = sandbox.run(code, timeout=30)
    4. if result.ok:
    5. return result.artifact
    6. error_context = result.stderr[-2000:]

    2.4 The Presentation Layer: Output Forms and Distribution

    The final artifact can be an interactive web page, an exported frame sequence, a video file captured via screen recording, or a converted presentation format. If audio is needed, it is usually synthesized as simple sound effects in code, or aligned to a licensed audio track along the timeline. The model does not “compose” music itself; what it outputs is a sequence of notes or synthesizer parameters.

    3. Why Visual Aesthetics Have Become the New Dividing Line

    Getting the code to run is only a passing grade. What truly impresses people is aesthetics. In code generation scenarios, aesthetic capability can be broken down into four optimizable items:

    1. Layout and whitespace: grid alignment, visual hierarchy, and control of information density per page;
    2. Color and contrast: no more than three primary colors, ensuring text-to-background contrast meets readability requirements;
    3. Motion pacing: choice of easing functions, entrance order, and total duration control, avoiding the mechanical feel of linear motion;
    4. Detail consistency: line width, corner radius, shadows, and font weights forming a coherent system, without mixing styles.

    All of these dimensions can be written as explicit constraints. Stability can also be improved with a two-stage prompt that produces the plan before the code: the first stage has the model give a textual plan for color scheme and layout, and the second stage generates code based on it.

    4. Common Failure Modes and Debugging Strategies

    • Elements out of bounds or overlapping: fix the canvas size in the prompt and require all coordinates to be normalized;
    • Animation stutter: reduce the redraw area per frame and avoid creating large numbers of temporary objects inside loops;
    • Clipping in 3D scenes: limit the camera range and compose simple geometric primitives rather than complex meshes;
    • Vague error messages: require the model to output observable self-check functions that print key state at runtime;
    • Style drift: pin style keywords and the color table in the system prompt, and do not rewrite them repeatedly across multiple turns.

    For debugging, it is recommended to build a “minimal reproducible snippet,” compressing the failing scenario down to a few dozen lines of code and then letting the model iterate. This saves far more time and compute than regenerating the whole thing.

    To productize this capability, you can adopt the following general architecture, described entirely in industry-standard product categories:

    • Access layer: a unified gateway handling authentication, rate limiting, and quota management;
    • Inference layer: a container platform hosting model services and a headless rendering cluster, scaling elastically by queue;
    • Storage layer: object storage for code artifacts, frame sequences, and screen recordings, paired with a content delivery network to accelerate distribution;
    • Async layer: a message queue decoupling the three stages of generation, rendering, and transcoding, smoothing out peaks and troughs;
    • Observability layer: a logging service collecting rendering errors, with monitoring and alerting tracking failure and timeout rates;
    • Security layer: a key management service holding credentials, with a unified sandbox egress enforcing a network allowlist.

    On Baidu AI Cloud, these capabilities can map respectively to container services, object storage, message services, and logging and monitoring products, deployed through unified resource orchestration to avoid the operational burden of building and maintaining your own rendering cluster.

    6. Engineering Practice Checklist

    1. Build a constraint template library first, fixing reusable fragments for canvas, duration, color scheme, and the ban on external links;
    2. Establish an automatic repair loop that feeds runtime errors back in a structured form;
    3. Decouple rendering from generation: generation only produces code, and rendering is handled by a separate cluster;
    4. Cache across the entire pipeline, reusing artifacts by prompt hash to significantly cut costs;
    5. Build an aesthetic evaluation set, assessed on two tracks — human scoring and automated metrics such as contrast, out-of-bounds rate, and frame rate stability;
    6. Keep all artifacts editable: output source code rather than only the finished product, making secondary creation easy.

    7. Conclusion

    The real lesson from these viral works is not that some model “can draw,” but that code is becoming the universal intermediate representation for visual content generation. As a model’s spatial understanding, code correctness, and aesthetic constraint capability improve in tandem, slides, 2D animations, and 3D scenes can all be unified into the same text-to-code-to-render pipeline. For developers, what is worth investing in is not chasing a version number, but making constraint design, sandboxed execution, error feedback, and observability solid — that is where reproducible, scalable, and deliverable competitiveness lies.