### Run TanStack Start Development Server
Source: https://github.com/kane50613/takumi/blob/master/example/tanstack-start/README.md
Navigate to the example directory and start the development server for the TanStack Start application. Visit http://localhost:3000/ to view the running example.
```bash
cd example/tanstack-start
bun dev
```
--------------------------------
### Run development server
Source: https://github.com/kane50613/takumi/blob/master/example/svelte/README.md
Navigates to the Svelte example directory and starts the development server.
```bash
cd example/svelte
bun dev
```
--------------------------------
### Install and Run FFmpeg H.265 Example
Source: https://github.com/kane50613/takumi/blob/master/example/ffmpeg-keyframe-animation/README.md
Installs project dependencies using Bun and executes the main script to render animations and encode them into an H.265 MP4 video. This is the primary command for running the example.
```bash
bun install
bun src/index.ts
```
--------------------------------
### Run Next.js Development Server
Source: https://github.com/kane50613/takumi/blob/master/example/nextjs/README.md
Navigate to the Next.js example directory and start the development server. Visit http://localhost:3000/hello?name=Kane to view the application.
```bash
cd example/nextjs
bun dev
```
--------------------------------
### Install Takumi JS
Source: https://github.com/kane50613/takumi/blob/master/README.md
Install the Takumi JS library using Bun.
```bash
bun i takumi-js
```
--------------------------------
### Install @takumi-rs/helpers
Source: https://github.com/kane50613/takumi/blob/master/takumi-helpers/README.md
Install the @takumi-rs/helpers package using npm.
```bash
npm install @takumi-rs/helpers
```
--------------------------------
### Install Dependencies with Bun
Source: https://github.com/kane50613/takumi/blob/master/CONTRIBUTING.md
Installs all workspace dependencies and sets up lefthook. Run this after cloning the repository.
```bash
bun install
```
--------------------------------
### Install takumi-js
Source: https://github.com/kane50613/takumi/blob/master/takumi-image-response/README.md
Install the takumi-js package using npm.
```bash
npm install takumi-js
```
--------------------------------
### Install Takumi JS
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/sveltekit.mdx
Install the Takumi JS package using npm. This command installs the release candidate version.
```bash
npm i takumi-js@rc
```
--------------------------------
### Render CSS integration example
Source: https://github.com/kane50613/takumi/blob/master/example/css-library-integration/README.md
Executes the rendering process for the CSS library integration example.
```bash
cd example/css-library-integration
bun render
```
--------------------------------
### Run Satori HTML Example
Source: https://github.com/kane50613/takumi/blob/master/example/satori-html/README.md
Execute the Satori HTML example using Node.js. Note that Bun may fail due to an issue mentioned in the GitHub link.
```bash
cd example/satori-html
node index.ts # Bun fails https://github.com/natemoo-re/ultrahtml/issues/66
```
--------------------------------
### Install @takumi-rs/core
Source: https://github.com/kane50613/takumi/blob/master/takumi-napi/README.md
Install the core package using npm. This command adds the native Node.js bindings for Takumi to your project.
```bash
npm install @takumi-rs/core
```
--------------------------------
### Install takumi-js with Bun or npm
Source: https://github.com/kane50613/takumi/blob/master/takumi-js/README.md
Install the takumi-js package using either Bun or npm package managers.
```bash
bun add takumi-js
# or
npm install takumi-js
```
--------------------------------
### Install takumi-js v1
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v1.mdx
Use npm to install the latest v1 version of the takumi-js package.
```bash
npm i takumi-js@1
```
--------------------------------
### Quick Start: Render an Image with takumi-js
Source: https://github.com/kane50613/takumi/blob/master/takumi-js/README.md
Generate a PNG image with custom text and styling using the render function. This example demonstrates basic JSX usage and file writing in Node.js.
```tsx
import { render } from "takumi-js";
import { writeFile } from "node:fs/promises";
const image = await render(
Hello from Takumi
,
{ width: 1200, height: 630 },
);
await writeFile("./output.png", image);
```
--------------------------------
### Install Takumi Runtime Package
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/nuxt.mdx
Install the appropriate Takumi package based on your Nuxt runtime environment (Node or Edge).
```bash
npm install @takumi-rs/core@beta
```
--------------------------------
### Build Takumi Native Binary
Source: https://github.com/kane50613/takumi/blob/master/example/satori-html/README.md
Build the native binary for Takumi. Ensure Rust is installed before running this command.
```bash
cd takumi-napi
bun run build
```
--------------------------------
### Install v2 Packages
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
Use npm to install the beta versions of Takumi v2 packages. This command updates takumi-js, @takumi-rs/core, and @takumi-rs/wasm.
```bash
npm install takumi-js@rc @takumi-rs/core@beta @takumi-rs/wasm@beta
```
--------------------------------
### Add Blog Post Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the blog post template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/blog-post-template.json
```
--------------------------------
### Add astro-takumi Integration
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/astro.mdx
Install the astro-takumi integration and its peer dependencies, React and a font library.
```bash
npx astro add astro-takumi
```
```bash
npm i -D react @fontsource/roboto
```
--------------------------------
### Add Docs Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the documentation template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/docs-template.json
```
--------------------------------
### Add Repository Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the repository template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/repository-template.json
```
--------------------------------
### Install Takumi Rust Crate
Source: https://github.com/kane50613/takumi/blob/master/README.md
Add the Takumi crate to your Rust project using Cargo.
```bash
cargo add takumi
```
--------------------------------
### Add Product Card Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the product card template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/product-card-template.json
```
--------------------------------
### Install Nuxt OG Image Module
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/nuxt.mdx
Add the Nuxt OG Image module to your project using npx.
```bash
npx nuxt module add og-image
```
--------------------------------
### Add Changelog Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the changelog template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/changelog-template.json
```
--------------------------------
### Add Event Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the event template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/event-template.json
```
--------------------------------
### Generate Animated WebP with takumi-js
Source: https://github.com/kane50613/takumi/blob/master/takumi-js/README.md
Create an animated WebP image using the Renderer and fromJsx helpers. This example shows how to define scenes, durations, and render animations.
```tsx
import { Renderer } from "takumi-js/node";
import { fromJsx } from "takumi-js/helpers/jsx";
import { writeFile } from "node:fs/promises";
const renderer = new Renderer();
const { node, stylesheets } = await fromJsx(
,
);
const animation = await renderer.renderAnimation({
width: 400,
height: 400,
fps: 30,
format: "webp",
stylesheets,
scenes: [{ durationMs: 1000, node }],
});
await writeFile("./output.webp", animation);
```
--------------------------------
### Render Animation Frames for ffmpeg
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/keyframe-animation.mdx
This example demonstrates rendering individual frames using `render()` at specific times and piping them to ffmpeg for video output. It requires setting up ffmpeg as a child process and writing raw RGBA frame data to its stdin.
```tsx
import { render } from "takumi-js";
import { spawn } from "bun";
import { Scene, keyframes } from "./scene";
const fps = 30;
const durationSeconds = 4;
const width = 1200;
const height = 630;
const totalFrames = fps * durationSeconds;
const ffmpeg = spawn(
[
"ffmpeg",
"-y",
"-f",
"rawvideo",
"-pixel_format",
"rgba",
"-video_size",
`${width}x${height}`,
"-framerate",
`${fps}`,
"-i",
"pipe:0",
"output.mp4",
],
{ stdin: "pipe", stdout: "ignore", stderr: "ignore" },
);
const scene = ;
for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
const timeMs = (frameIndex / fps) * 1000;
const frame = await render(scene, {
width,
height,
format: "raw",
keyframes,
timeMs,
});
ffmpeg.stdin.write(frame);
}
ffmpeg.stdin.end();
await ffmpeg.exited;
```
--------------------------------
### Add Quote Template with shadcn CLI
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/templates.mdx
Use this command to add the quote template to your project. Ensure you have the shadcn CLI installed.
```bash
npx shadcn@latest add https://takumi.kane.tw/templates/registry/quote-template.json
```
--------------------------------
### OG Image Route Handler
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/tanstack-start.mdx
This example demonstrates how to create a file route with a server handler using `server.handlers` to generate an OG image. The handler extracts `title` and `description` from query parameters and uses `ImageResponse` from `takumi-js/response` to render the image.
```APIDOC
## GET /og-image
### Description
Handles GET requests to generate an Open Graph image. It extracts `title` and `description` from query parameters to customize the image content.
### Method
GET
### Endpoint
/og-image
### Query Parameters
- **title** (string) - Optional - The title to display on the OG image.
- **description** (string) - Optional - The description to display on the OG image.
### Request Example
GET /og-image?title=Hello&description=From%20TanStack%20Start
### Response
#### Success Response (200)
- **ImageResponse** - A dynamically generated image based on the provided title and description.
#### Response Example
(Image response, not representable as JSON)
```
--------------------------------
### Regenerate README for Rust Crate
Source: https://github.com/kane50613/takumi/blob/master/CONTRIBUTING.md
Regenerates the README.md file for the Rust crate. Run this command if Rust doc comments or crate-facing examples have changed.
```bash
cd takumi
```
```bash
cargo rdme
```
--------------------------------
### AI Upgrade Prompt for Takumi v2 (Rust)
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
This prompt guides an AI agent to upgrade Rust projects from Takumi v1 to v2. It details changes in imports, context handling, feature flags, output formats, and API adjustments for core enums and CSS properties.
```text
Rust (takumi crate):
- use takumi::prelude::*; use takumi::render; (internals now behind the `unstable` feature)
- GlobalContext -> Fonts, passed via RenderOptions::builder().fonts(&fonts)
- Cargo feature "raster" -> "raster-backend" (+ rayon); enable "svg-backend" for render_svg
- OutputFormat::Jpeg/WebP carry Quality; lossless -> WebPLossless; write_image(img, &mut out, fmt)
- measure_layout -> measure, render_sequence_animation -> render_animation; render -> Bitmap
- render_for_layout drops the current_color argument
- style value types (unstable): LengthDefaultsToZero -> Length, ColorDefaultsToTransparent -> ColorInput
- BackgroundPosition -> PositionValue, BackgroundPositions -> PositionValues; ObjectPosition/TransformOrigin removed -> PositionValue (PositionValue::center() for the 50% 50% default)
- core enums (NodeKind, ImageSource, ImageSourceInput, ImageCacheMode, Length, ColorInput) and css PropertyId/StyleDeclaration are now #[non_exhaustive]: add a wildcard match arm; build via constructors, not struct literals
```
--------------------------------
### Create Server File Route for OG Image
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/tanstack-start.mdx
Define an HTTP GET handler for an OG image route using `server.handlers`. This handler generates an image response based on query parameters for title and description.
```tsx
import { createFileRoute } from "@tanstack/react-router";
import ImageResponse from "takumi-js/response";
export const Route = createFileRoute("/og-image")({
server: {
handlers: {
GET({ request }) {
const url = new URL(request.url);
const title = url.searchParams.get("title") ?? "Takumi + TanStack Start";
const description =
url.searchParams.get("description") ?? "Render OG images from a route handler.";
return new ImageResponse(
,
{
width: 1200,
height: 630,
},
);
},
},
},
});
```
--------------------------------
### AI Upgrade Prompt for Takumi v2 (JS)
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
This prompt guides an AI agent to upgrade JavaScript projects from Takumi v1 to v2. It outlines specific API changes for takumi-js and @takumi-rs/* packages, including awaiting render functions, handling fonts and images, and using helper functions.
```text
Upgrade this project from Takumi v1 to v2. Apply `old -> new` for the packages it imports.
JS (takumi-js, @takumi-rs/*):
- await the top-level render/renderAnimation/renderSvg and the napi Renderer methods (they await resource loading)
- new Renderer({fonts}) -> new Renderer(); pass fonts per call: render(node, {fonts:[inter]})
- loadFont/loadFonts/loadFontSync -> registerFont (only to reuse a font across renders)
- render option fetchedResources -> images (keyed by src; no global image store)
- render option resourcesOptions -> images.fetch/images.timeout; combine pre-fetched entries and a shared byte cache with the group form images: { sources: [...], fetch: myFetch, fetchCache: myMap }
- extractResourceUrls + fetchResources helpers -> prepareImages({ node, fetchCache? }) from "takumi-js/helpers"
- format is a string ("png"|"jpeg"|"webp"|...) with optional quality (jpeg/lossy webp) and lossless (webp)
- createImageResponse(opts)(jsx) -> new ImageResponse(jsx, opts)
```
--------------------------------
### Measure Node (WASM Renderer)
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/measure-api.mdx
Example of using the `measure` function with the WASM renderer to get the dimensions of a text node.
```APIDOC
## measure(node, options)
### Description
Measures the laid-out size of a node without rendering it.
### Method
`renderer.measure(node, { stylesheets })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **node** (Node) - Required - The node to measure.
- **options** (object) - Required - An object containing options.
- **stylesheets** (Stylesheet[]) - Required - An array of stylesheets to apply during measurement.
### Request Example
```tsx
import { Renderer } from "takumi-js/wasm";
import { fromJsx } from "takumi-js/helpers/jsx";
const renderer = new Renderer();
const { node, stylesheets } = await fromJsx(I'm a text node);
const { width, height } = await renderer.measure(node, { stylesheets });
```
### Response
#### Success Response (200)
- **width** (number) - Laid-out width of the node.
- **height** (number) - Laid-out height of the node.
- **transform** ([number, number, number, number, number, number]) - Transformation matrix.
- **children** (MeasuredNode[]) - Measured child nodes.
- **runs** (MeasuredTextRun[]) - Text runs in the node, each with `x`, `y`, `width`, `height`.
#### Response Example
```json
{
"width": 100,
"height": 20,
"transform": [1, 0, 0, 1, 0, 0],
"children": [],
"runs": [
{
"x": 0,
"y": 0,
"width": 100,
"height": 20
}
]
}
```
```
--------------------------------
### Measure Node (Node Renderer)
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/measure-api.mdx
Example of using the `measure` function with the Node renderer to get the dimensions of a text node.
```APIDOC
## measure(node, options)
### Description
Measures the laid-out size of a node without rendering it.
### Method
`renderer.measure(node, { stylesheets })`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **node** (Node) - Required - The node to measure.
- **options** (object) - Required - An object containing options.
- **stylesheets** (Stylesheet[]) - Required - An array of stylesheets to apply during measurement.
### Request Example
```tsx
import { Renderer } from "takumi-js/node";
import { fromJsx } from "takumi-js/helpers/jsx";
const renderer = new Renderer();
const { node, stylesheets } = await fromJsx(I'm a text node);
const { width, height } = await renderer.measure(node, { stylesheets });
```
### Response
#### Success Response (200)
- **width** (number) - Laid-out width of the node.
- **height** (number) - Laid-out height of the node.
- **transform** ([number, number, number, number, number, number]) - Transformation matrix.
- **children** (MeasuredNode[]) - Measured child nodes.
- **runs** (MeasuredTextRun[]) - Text runs in the node, each with `x`, `y`, `width`, `height`.
#### Response Example
```json
{
"width": 100,
"height": 20,
"transform": [1, 0, 0, 1, 0, 0],
"children": [],
"runs": [
{
"x": 0,
"y": 0,
"width": 100,
"height": 20
}
]
}
```
```
--------------------------------
### Build native binary
Source: https://github.com/kane50613/takumi/blob/master/example/svelte/README.md
Compiles the native binary required for the project using bun.
```bash
bun --filter '*' run build
```
--------------------------------
### Bun Server with takumi-js Image Response
Source: https://github.com/kane50613/takumi/blob/master/takumi-js/README.md
Set up a simple Bun server that serves an image generated by takumi-js. This demonstrates integrating ImageResponse into a Bun fetch handler.
```tsx
import { ImageResponse } from "takumi-js/response";
import { serve } from "bun";
serve({
fetch() {
return new ImageResponse(
Hello from Takumi 👋
,
{ width: 1200, height: 630 },
);
},
port: 3000,
});
```
--------------------------------
### ImageResponse Error Handling with `ready` Promise
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/image-response.mdx
Illustrates how to handle potential errors during image rendering by awaiting the `ready` promise of the ImageResponse.
```APIDOC
## ImageResponse Error Handling
### Description
Handles potential rendering failures by awaiting the `ready` promise of `ImageResponse` and providing a fallback response.
### Method
N/A (Constructor and promise usage)
### Endpoint
N/A (Constructor and promise usage)
### Parameters
#### Request Body
- **JSX Element** (ReactNode) - The content to render as an image.
### Request Example
```tsx
const response = new ImageResponse();
try {
await response.ready;
return response;
} catch {
return new Response("Failed to generate image", { status: 500 });
}
```
### Response
#### Success Response (200)
- **Image** (Image) - The successfully rendered image.
#### Error Response (500)
- **Text** (string) - Fallback message indicating image generation failure.
```
--------------------------------
### Integrate Tailwind CSS with Vite
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/styling.mdx
Compile Tailwind CSS with Vite and import it for use in Takumi renders. Ensure Tailwind CSS is installed and configured in your Vite project.
```tsx
import { ImageResponse } from "takumi-js/response";
import stylesheet from "~/styles/global.css?inline";
export function GET() {
return new ImageResponse(
Hello Tailwind!
,
{
width: 1200,
height: 630,
stylesheets: [stylesheet],
},
);
}
```
```typescript
import { defineConfig } from "vite";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [tailwindcss()],
});
```
--------------------------------
### Apply 3px border with CSS
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
In v2, an omitted width in 'border' or 'outline' resolves to 'medium' (3px) instead of '0'. This example shows a 3px red border.
```html
3px border in v2, invisible in v1
```
--------------------------------
### Quality Gates for Rust Changes
Source: https://github.com/kane50613/takumi/blob/master/CONTRIBUTING.md
Runs clippy for code analysis and machete for dependency checks to match CI quality gates.
```bash
cargo clippy --all-targets --all-features -- -D warnings
```
```bash
cargo machete
```
--------------------------------
### Define Keyframes and Scene Component
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/keyframe-animation.mdx
Defines the keyframes for an animation and a React component that uses these keyframes with an inline style for CSS animations. This setup is used by both `render()` and `renderAnimation()`.
```tsx
import type { Keyframes } from "takumi-js";
export const keyframes: Keyframes = {
move: {
from: {
transform: "translateX(0)",
},
to: {
transform: "translateX(60px)",
},
},
};
// `keyframes` feeds render(); the inline
);
}
```
--------------------------------
### Configure astro-takumi Integration
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/astro.mdx
Configure the integration in astro.config.mjs, providing fonts and a render function. Set the site URL for absolute image paths. Note that astro-takumi only processes statically rendered pages.
```javascript
import { defineConfig } from "astro/config";
import * as fs from "node:fs";
import { fileURLToPath } from "node:url";
import astroTakumi, { presets } from "astro-takumi";
export default defineConfig({
site: "https://example.com",
integrations: [
astroTakumi({
options: {
fonts: [fs.readFileSync(fileURLToPath(import.meta.resolve("@fontsource/roboto/files/roboto-latin-400-normal.woff")))],
},
render: presets.blackAndWhite,
}),
],
});
```
--------------------------------
### Render UI Component Tree to Image
Source: https://github.com/kane50613/takumi/blob/master/takumi/README.md
Renders a UI component tree to an image. Requires setting up nodes, fonts, and viewport options. Reuse the Fonts context for performance.
```rust
use takumi::prelude::*;
use takumi::render;
let node = Node::container([Node::text("Hello, world!").with_style(
Style::default().with(StyleDeclaration::font_size(Length::Px(32.0).into()))
)]);
// Create a font context. Reuse it across renders to share the decode cache.
let mut fonts = Fonts::default();
// Load fonts
fonts
.register(FontResource::new(include_bytes!(
"../../assets/fonts/geist/Geist[wght].woff2"
)))
.unwrap();
let viewport = Viewport::new((1200, 630));
let options = RenderOptions::builder()
.viewport(viewport)
.node(node)
.fonts(&fonts)
.build();
let image = render(options).unwrap();
```
--------------------------------
### Tint SVG currentColor in TypeScript
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
If you relied on the old behavior to tint an icon, set the color in the SVG markup before passing it in. This example replaces 'currentColor' with a specific hex color.
```typescript
const tinted = icon.replace(/currentColor/g, "#3b82f6"); // [!code ++]
```
--------------------------------
### Render Image with @takumi-rs/core
Source: https://github.com/kane50613/takumi/blob/master/takumi-napi/README.md
Instantiate the Renderer and use it to render an image from a given element structure and dimensions. Ensure the Renderer is imported from the core package.
```typescript
import { Renderer } from "@takumi-rs/core";
const renderer = new Renderer();
const png = await renderer.render(
{
type: "Element",
tag: "div",
children: [{ type: "Text", value: "Hello from Takumi" }],
},
{
width: 1200,
height: 630,
},
);
```
--------------------------------
### Create a Svelte Component for SSR
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/sveltekit.mdx
Define a Svelte component with `css="injected"` to ensure styles are inlined in the SSR HTML. This example demonstrates a welcome message component.
```svelte
Welcome {name} to
Svelte world
```
--------------------------------
### Create ImageResponse Directly in v2
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
The `createImageResponse` helper is removed. Construct `ImageResponse` directly and pass options inline. For shared defaults, create your own helper function.
```tsx
const ogImage = createImageResponse({ fonts: [inter] }); // [!code --]
export function GET() {
return ogImage(); // [!code --]
return new ImageResponse(, { fonts: [inter] }); // [!code ++]
}
```
--------------------------------
### Render Single Frame with render()
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/keyframe-animation.mdx
Use `render()` to get a single frame of an animation at a specific point in time. This function requires the scene node, rendering options, and the keyframes definition.
```tsx
import { render } from "takumi-js";
import { Scene, keyframes } from "./scene";
const output = await render(, {
width: 100,
height: 100,
format: "png",
keyframes,
timeMs: 500,
});
```
--------------------------------
### Update Image Output Quality Configuration
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
Image output quality is now modeled per format. `OutputFormat::WebP` carries a `Quality` struct, and lossless WebP is handled by `OutputFormat::WebPLossless`. The `write_image` function no longer takes a separate quality argument.
```rust
write_image(&image, &mut output, OutputFormat::WebP { quality: Quality::new(80) })?;
```
--------------------------------
### Render with AbortSignal
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/output-formats.mdx
Incorporate an `AbortSignal` to allow for cancellation of rendering tasks, particularly useful for long-running operations like fetching fonts or images. An already aborted signal will prevent the render from starting.
```tsx
await render(, { width: 1200, height: 630, signal: request.signal });
```
--------------------------------
### Configure Next.js Server Externals
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/nextjs.mdx
Add `@takumi-rs/core` to `serverExternalPackages` in your Next.js configuration file to ensure it's bundled correctly.
```typescript
import type { NextConfig } from "next";
const config: NextConfig = {
serverExternalPackages: ["@takumi-rs/core"], // [!code ++]
};
export default config;
```
--------------------------------
### Configure npmrc for Native Binding Hoisting
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/troubleshooting.mdx
When using package managers like `pnpm` or `yarn` with a virtual store, add `public-hoist-pattern[]=@takumi-rs/core-*` to your `.npmrc` file. Re-run `pnpm i` to allow hoisting of the native binary and resolve 'Cannot find native binding' errors.
```text
public-hoist-pattern[]=@takumi-rs/core-*
```
--------------------------------
### Measure Node Layout with takumi-js/wasm
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/measure-api.mdx
This snippet demonstrates measuring a node's layout using the WebAssembly version of the takumi-js renderer. It requires importing the Renderer from takumi-js/wasm and the fromJsx helper.
```tsx
import { Renderer } from "takumi-js/wasm";
import { fromJsx } from "takumi-js/helpers/jsx";
const renderer = new Renderer();
const { node, stylesheets } = await fromJsx(I'm a text node);
// [!code ++]
const { width, height } = await renderer.measure(node, { stylesheets });
```
--------------------------------
### Render Svelte Component in SvelteKit Server Route
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/integration/sveltekit.mdx
This server route imports a Svelte component and renders it to HTML using `svelte/server.render`. It then returns an `ImageResponse` with the rendered component, styles, and fonts.
```typescript
import { render } from "svelte/server";
import style from "../app.css?inline";
import ImageResponse from "takumi-js/response";
import OgImage from "$lib/components/OgImage.svelte";
import type { RequestEvent } from "./$types";
export async function GET({ url }: RequestEvent) {
const { body, head } = await render(OgImage, {
props: {
name: url.searchParams.get("name") ?? "Goo goo gaga",
},
});
return new ImageResponse(`${head}${body}`, {
width: 1200,
height: 630,
stylesheets: [style],
fonts: ["https://takumi.kane.tw/fonts/Geist.woff2"],
});
}
```
--------------------------------
### Render Animated WebP with Takumi JS
Source: https://github.com/kane50613/takumi/blob/master/README.md
Generate an animated WebP image from a sequence of React components using `renderAnimation`. Each scene can have a specified duration. Requires `node:fs/promises` for file writing.
```tsx
import { renderAnimation } from "takumi-js";
import { writeFile } from "node:fs/promises";
const animation = await renderAnimation({
width: 400,
height: 400,
fps: 30,
format: "webp",
scenes: [
{
durationMs: 1000,
node: (
),
},
],
});
await writeFile("./output.webp", animation);
```
--------------------------------
### Using a Custom Renderer with ImageResponse
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/image-response.mdx
Pass a pre-configured Renderer instance to ImageResponse to reuse decoding caches for fonts and images, improving performance. Import Renderer from '@takumi-rs/core'.
```tsx
import { Renderer } from "@takumi-rs/core";
const renderer = new Renderer();
new ImageResponse(, { renderer });
```
--------------------------------
### Initialize Renderer Without Arguments in v2
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
The `Renderer` constructor in v2 takes no arguments. Fonts and other context should be passed to the render methods instead.
```typescript
const renderer = new Renderer({ fonts: [archivo] }); // [!code --]
const renderer = new Renderer(); // [!code ++]
const image = await renderer.render(node, { fonts: [archivo] }); // [!code ++]
```
--------------------------------
### Render with Different Raster Formats
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/output-formats.mdx
Use the `format` option to specify the desired output format. Quality and lossless settings are format-specific. PNG is lossless by default, JPEG is lossy, and WebP supports both lossy and lossless modes.
```tsx
import { render } from "takumi-js";
await render(, { width: 1200, height: 630, format: "png" });
await render(, { width: 1200, height: 630, format: "jpeg", quality: 80 });
await render(, { width: 1200, height: 630, format: "webp", lossless: true });
```
--------------------------------
### Use Viewport::new() constructor
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v1.mdx
Viewport no longer implements From<(u32, u32)>. Use the explicit Viewport::new() constructor with a tuple for dimensions.
```rust
let viewport = (800_u32, 600_u32).into(); // [!code --]
let viewport = Viewport::new((800, 600)); // [!code ++]
```
--------------------------------
### Update Renamed Entry Points: measure_layout
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
The `measure_layout` function has been renamed to `measure` and now returns a `MeasuredNode`.
```rust
let measured = measure(options)?;
```
--------------------------------
### Convert HTML to Takumi Node Tree
Source: https://github.com/kane50613/takumi/blob/master/takumi-helpers/README.md
Use the fromHtml helper to parse HTML strings into Takumi nodes. Requires an async context.
```ts
import { fromHtml } from "@takumi-rs/helpers/html";
const { node, stylesheets } = await fromHtml("Hello
");
```
--------------------------------
### Provide Pre-fetched Images
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/load-images.mdx
Supply images by key to avoid fetching them during rendering. These keys can be used in `src` attributes or CSS `background-image`/`mask-image` properties. The `data` function should return a `Promise`.
```tsx
import { ImageResponse } from "takumi-js/response";
export function GET() {
return new ImageResponse(, {
// [!code ++]
images: [
{
src: "my-logo",
data: () => fetch("/logo.png").then((res) => res.arrayBuffer()),
},
{
src: "background",
data: () => fetch("/background.png").then((res) => res.arrayBuffer()),
},
],
});
}
function OgImage() {
return (
);
}
```
--------------------------------
### Update Takumi Imports
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/upgrade/v2.mdx
Import necessary data structures from `takumi::prelude` and entry-point functions from the crate root. Backend internals are no longer re-exported directly.
```rust
use takumi::prelude::*;
use takumi::render;
```
--------------------------------
### Node Building Helpers
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/helpers.mdx
Functions for creating different types of nodes for the Takumi tree.
```APIDOC
## container(props)
### Description
Creates a container node.
### Returns
A container node.
## text(text, style?) / text(props)
### Description
Creates a text node.
### Parameters
- **text** (string) - The text content.
- **style** (object, optional) - The style object for the text.
### Parameters (props overload)
- **props** (object) - Properties for the text node, including `text` and `style`.
### Returns
A text node.
## image(props)
### Description
Creates an image node.
### Parameters
- **props** (object) - Properties for the image node, including `src` and `alt`.
### Returns
An image node.
## style(css)
### Description
Applies a style object, ensuring it is correctly typed.
### Parameters
- **css** (object) - The CSS style object.
### Returns
The same style object, typed.
```
--------------------------------
### Basic ImageResponse Usage
Source: https://github.com/kane50613/takumi/blob/master/docs/content/docs/image-response.mdx
Demonstrates the basic usage of ImageResponse within a route handler. It takes a JSX element and an options object for width and height.
```APIDOC
## GET /
### Description
Serves a rendered image using ImageResponse.
### Method
GET
### Endpoint
/
### Parameters
#### Request Body
This endpoint does not explicitly define a request body, but the `ImageResponse` constructor takes JSX and options.
### Request Example
```tsx
import { ImageResponse } from "takumi-js/response";
export function GET() {
return new ImageResponse(, { width: 1200, height: 630 });
}
```
### Response
#### Success Response (200)
- **Image** (Image) - The rendered image.
#### Response Example
(Image data)
```