Usage
What you need for most integrations. The API reference covers every class, option and type.
Install
three.js is a peer dependency. V2 is published under the beta tag.
npm install minerender@beta three
# or
yarn add minerender@beta three
Without a build step, load the bundle. It includes three.js and exposes everything as window.MineRender.
<script src="https://unpkg.com/minerender@beta/dist/bundle.js"></script>
<script>
const renderer = new MineRender.Renderer({ controls: { enabled: true } });
renderer.appendTo(document.getElementById("render"));
renderer.start();
</script>
Your first render
Create a renderer, attach it to an element that has a size, start the loop, then add content to its scene. Every add method is asynchronous because assets load on demand.
import { AssetKey, BlockStates, Renderer } from "minerender";
const renderer = new Renderer({
camera: { position: [40, 30, 50], lookingAt: [0, 0, 0] },
controls: { enabled: true } // built-in orbit controls
});
renderer.appendTo(document.getElementById("render")!);
renderer.start();
// A player skin
await renderer.scene.addSkin("https://example.com/skin.png");
// A block, from its blockstate
const state = await BlockStates.get(AssetKey.parse("blockstates", "grass_block"));
const block = await renderer.scene.addBlock(state!);
block.setPosition(block.getPosition().set(32, 0, 0)); // 1 block = 16 units
// When the view goes away
renderer.dispose();
Renderer options
All options are optional and deep-merged over these defaults.
| Option | Default | Description |
camera.type | "perspective" | Or "orthographic". |
camera.position | [50, 50, 50] | Initial camera position as a Vector3 or [x, y, z]. |
camera.lookingAt | [0, 0, 0] | Camera target, and the orbit centre when controls are enabled. |
camera.near, camera.far | 1, 5000 | Clipping planes in scene units. |
camera.perspective.fov | 50 | Field of view in degrees. |
render.fpsLimit | 60 | Maximum frames per second. Zero or negative removes the cap. |
render.antialias | true | WebGL antialiasing. |
render.pixelRatio | 1 | Drawing-buffer pixels per CSS pixel. Also scales toImage() output. |
render.shade | true | Minecraft-style per-face shading on models. |
render.autoResize | true | Resize the canvas when the window resizes. |
render.renderAlways | false | Render every frame instead of only when the scene is dirty. |
render.stats | false | Show a stats.js overlay. |
composer.enabled | true | Route output through a post-processing composer. Disable for the fastest path. |
controls.enabled | false | Create renderer-owned controls, available as renderer.controls. |
controls.mode | "orbit" | Use "fly" for creative-style flight. Switch at runtime with renderer.setControlsMode(). |
debug.grid, debug.axes | false | Add grid and axes helpers. |
Scene and objects
renderer.scene is a three.js Scene with asset-aware add methods.
scene.addSkin(textureUrl?, options?) // SkinObject
scene.addBlock(blockState, options?) // BlockObject
scene.addModel(model, options?) // ModelObject | InstanceReference
scene.addEntity(entityModel, options?) // EntityObject | InstanceReference
scene.addGui(layers, options?) // GuiObject
scene.stats // object and instance counts
Scene objects extend Object3D. Beyond the usual three.js properties they offer setPosition, setRotation, setScale, getGroupByName, getMeshByName, toggleGroupVisibility, removeFromScene and dispose. Skins add setSkinTexture, setSlim and setCapeTexture; blocks add setState; entities add getLayerGroup.
Every add method accepts the same base options, plus type-specific ones.
{
mergeMeshes: true, // one geometry per model
instanceMeshes: true, // share an InstancedMesh per model
maxInstanceCount: 50, // slots per instanced model
wireframe: false, // debug outlines
// models and blocks
displayPosition: DisplayPosition.GUI, // apply a display transform
tints: { 0: 0x79c05a }, // sRGB color per tint index
// skins
slim: undefined, // true, false, or undefined to detect
legacy: undefined, // 64×32 layout; undefined to detect
// entities
tints: { wool_color: 0xf9801d }, // colors for the dataset's tint labels
flip: undefined // true forces vanilla's plain flip, false keeps raw model space
}
With instanceMeshes on, repeated models return an InstanceReference that only carries transforms. Its dispose() frees the slot for reuse. Pass instanceMeshes: false for a standalone object.
Blocks whose model has no geometry in the game (chests, beds, skulls, signs, banners, shulker boxes) are drawn through the entity models the dataset maps them to, rotated by their blockstate properties. block.blockEntities holds those objects.
Entity models draw main plus the passes the dataset lists for them. Passes with a condition are enabled through when; tint labels take colors through tints. An explicit layers list draws exactly those geometry layers instead.
const key = new BasicAssetKey("minecraft", "sheep");
await Entities.getPassList(key); // [{ layer: "wool", when: "not_sheared", tint: "wool_color" }, ...]
const model = await Entities.getEntity(key, undefined, { when: ["not_sheared"] });
const sheep = await scene.addEntity(model!, { tints: { wool_color: 0xf9801d } });
sheep.getLayerGroup("wool")!.visible = false; // every layer is a group
Item definitions take the game's item state. Pass data components, item-model properties, a stack count and item references to Models.getMerged; GUI item layers accept the same context. Dyed armor, banner patterns, shields, shulker boxes, bundles and tridents resolve from it. Stack size, durability and glint use the vanilla defaults for the selected version unless you pass the component. Supply any other components a selector reads.
const shield = await Models.getMerged(new AssetKey("minecraft", "shield", "models", "item"), {
components: {
"minecraft:base_color": "blue",
"minecraft:banner_patterns": [{ pattern: "minecraft:stripe_center", color: "white" }]
}
});
await scene.addModel(shield!, { displayPosition: DisplayPosition.GUI });
await Models.getMerged(bundle, {
properties: { "minecraft:bundle/has_selected_item": true },
itemReferences: { "minecraft:bundle/selected_item": apple } // AssetKey of the item drawn inside
});
Mobs with keyframe animations (warden, frog, camel, breeze, armadillo, sniffer, bat and others) expose them through Entities.getAnimations. The entity owns no clock, so advance it from a frame callback. playAnimations plays several clips on one clock and adds their weighted offsets.
const animations = await Entities.getAnimations(key); // undefined without any
warden.playAnimation(animations!.roar, { loop: true, speed: 1 });
const stop = renderer.onFrame(({ delta }) => warden.advanceAnimation(delta));
warden.setAnimationTime(1.5); // or pose at an explicit time
warden.stopAnimation(); // restores the default pose
warden.playAnimations([animations!.roar, animations!.sniff], { weights: [1, 0.5] });
warden.setAnimationWeights([1, 0.25]); // without restarting playback
GUIs take ordered texture, item and text layers in GUI pixels, with y growing down. Item layers draw stack counts and durability bars from their context; set decorations: false to hide both. gui.bounds reports the drawn area for fitting an orthographic camera, GuiHelper.inventorySlot turns a slot index into a position, and GuiHelper.recipe lays out a crafting recipe, including the result count. Text layers draw the resource pack's bitmap and Unihex fonts, and GuiHelper.container, bossBar, book and tooltip return ready layer lists.
const gui = await scene.addGui([
{ texture: "minecraft:gui/container/generic_54", crop: [0, 0, 176, 222] },
{ item: "minecraft:item/apple", position: GuiHelper.inventorySlot(0, [8, 18]), context: { count: 16 } },
{ item: "minecraft:item/diamond_pickaxe", position: GuiHelper.inventorySlot(1, [8, 18]), context: { components: { damage: 400 } } }
]);
const table = await scene.addGui(GuiHelper.recipe(recipeJson, {
resolveIngredient: () => "minecraft:diamond" // concrete item for tags and alternatives
}));
const hud = await scene.addGui([
...await GuiHelper.bossBar({ color: "purple", progress: 0.65 }),
...await GuiHelper.tooltip([[{ text: "Diamond Pickaxe", color: 0x55ffff }], "Efficiency IV"], { position: [12, 24] }),
{ text: "Score: 42", position: [0, 80], shadow: true }
]);
Redraws and animation
Frames are drawn only when something changed. The built-in controls and the scene's add methods mark the scene dirty. Set renderer.dirty after other changes.
skin.getGroupByName("head")!.rotation.y = 0.5;
renderer.dirty = true;
// Other event sources can request redraws too
renderer.registerEventDispatcher(myControls, "change");
For continuous motion, subscribe to frames. Callbacks run before each draw while the loop is started, respect fpsLimit, pause with stop() and keep the scene drawing without dirty flags. Both values are seconds.
const head = skin.getGroupByName("head")!;
const unsubscribe = renderer.onFrame(({ time, delta }) => {
head.rotation.y = Math.sin(time) * 0.5;
});
unsubscribe(); // when done; dispose() clears all callbacks
Assets and versions
Assets are addressed by AssetKey and loaded through an ordered list of sources. The default source is a CDN with vanilla assets for the version in AssetLoader.ROOT.
import { AssetKey, AssetLoader, Caching, HostedAssetSource, Models } from "minerender";
// Keys
AssetKey.parse("blockstates", "minecraft:oak_log");
new AssetKey("minecraft", "diamond_sword", "models", "item", "assets");
// Another game version for everything that follows
AssetLoader.setVersion("1.20.4");
// Sources added later are searched first
AssetLoader.addSource("pack", new HostedAssetSource("https://cdn.example/pack"));
// In-memory caches
Caching.clear();
await Models.clearCache();
Resource-pack ZIPs work in the browser through BrowserArchiveProxy and ArchiveAssetSource; see the example. Persistent caches (IndexedDB in browsers, a directory in Node) are keyed by asset root and source set, so versions and resource packs never collide.
Registry data such as item defaults and potion colors is published per release. If the selected version has none, the nearest earlier release's data is used; models and textures keep the requested version. MineRenderData.resolve() reports which one was picked.
Worlds and files
MineRenderWorld stores blocks in 16³ chunks with signed coordinates. Faces against opaque neighbors are not drawn, nor are faces between touching glass, ice or connected panes, as in vanilla. With sectionMeshing, block models of any shape, animated textures, and fluid surfaces are merged into solid, translucent, and fluid meshes per section; block entities stay individual objects.
import { AnvilParser, AnvilWorldSource, MineRenderWorld, NBTHelper, SchematicParser, StructureParser, WorldStreamer } from "minerender";
const world = new MineRenderWorld(renderer.scene, { sectionMeshing: true });
// Blocks from code
await world.setBlockAt(0, 0, 0, { type: "minecraft:stone" });
await world.setBlockAt(0, 1, 0, { type: "minecraft:oak_fence", properties: { north: "true" } });
// Vanilla structure files and legacy schematics
const nbt = await NBTHelper.fromBuffer(bytes);
await world.placeMultiBlock(await StructureParser.parse(nbt));
await world.placeMultiBlock(await SchematicParser.parse(nbt));
// Java region files: list the stored chunks, then place one at its world position
const chunks = AnvilParser.getChunkList(regionBytes);
const chunk = await AnvilParser.parseChunk(regionBytes, chunks[0].x, chunks[0].z);
await world.placeChunk(chunk!);
await world.clear();
// Or stream a Java world around the view: the source reads r.<x>.<z>.mca on demand
const source = new AnvilWorldSource(async (x, z, signal) => {
const response = await fetch(`/world/region/r.${x}.${z}.mca`, { signal });
return response.ok ? response.arrayBuffer() : undefined;
});
const streamer = new WorldStreamer(world, source, { loadRadius: 2, unloadRadius: 3 });
await streamer.updatePosition(renderer.orbitControls!.target); // call again whenever the view moves
await streamer.dispose(); // unloads its columns
The library also loads Sponge .schem files through SpongeSchematicParser and Litematica .litematic files through LitematicaParser. Anvil loading reads numeric and paletted chunks with gzip, zlib or LZ4 compression; the optional readExternalChunk and readEntityRegion callbacks add external .mcc payloads and the separate entity region files.
Bulk placement resolves each block state once and yields to the page every few milliseconds, and section meshes are built in a worker when your bundle keeps the package's section.worker file next to the module. Saved biomes supply grass, foliage and water colors.
With section meshing, a world can also shade terrain from the light saved in Anvil chunks, darken corners with ambient occlusion and blend biome colors across borders. renderEntities draws supported saved mobs, and raycasts return the block or mob under the pointer. Light propagation and level of detail are not supported.
import { Raycaster } from "three";
const world = new MineRenderWorld(renderer.scene, {
sectionMeshing: true,
savedLighting: true, // sky and block light from the save
ambientOcclusion: true, // corner shading next to opaque blocks
biomeBlendRadius: 3, // average biome colors over 3 blocks
renderEntities: true // supported mobs at their saved positions
});
const raycaster = new Raycaster();
raycaster.setFromCamera(pointer, renderer.camera); // pointer in normalized device coordinates
const block = world.raycast(raycaster); // { position, block, point, normal, distance }
const mob = world.raycastEntities(raycaster); // { type, position, object, ... }
Exporting
toImage renders a fresh frame and returns a data URL, toVideo records the running scene, and SceneExporter writes the visible meshes with their instance placements.
import { SceneExporter } from "minerender";
const png = renderer.toImage(); // full canvas
const jpeg = renderer.toImage(true, "image/jpeg", 0.9); // trimmed to the drawn pixels
const glb = await SceneExporter.toGLTF(renderer.scene, { binary: true }); // textures and tints kept
const obj = SceneExporter.toObj(renderer.scene); // geometry only
const ply = SceneExporter.toPLY(skin); // any Object3D as the root
const video = await renderer.toVideo({ duration: 4, fps: 30 }); // real-time WebM or MP4 Blob; check video.type
glTF export needs a browser. Custom shading is not baked into the exported materials. Video recording runs in real time through MediaRecorder, keeps the canvas size at the start, fills transparent pixels with black and can be cancelled with an AbortSignal.
Embeds
To show a render on another page without bundling the library, use the embed page in an iframe. It takes one source: skin, block, item, entity, model, a scene link from the editor's Copy embed button, or an HTTPS src pointing to a scene document.
<iframe
src="https://beta.minerender.org/embed/?item=minecraft:diamond_sword"
title="Diamond sword"
width="320" height="320" loading="lazy"
style="border:0"></iframe>
The embed fits the scene to the iframe when no camera is given, and releases its WebGL context while scrolled out of view. The embed reference lists every URL parameter.
Lifecycle
stop() pauses the loop and start() resumes it. dispose() is final: it releases the WebGL context, the controls and owned helpers. Shared assets stay cached.
renderer.stop();
renderer.start();
renderer.dispose();
// In Node, or before unloading a page: end caches, queues and timers
import { shutdown } from "minerender";
shutdown();
Logging
The library prints only warnings and errors. Raise the level for one component while investigating a problem:
import { Logging } from "minerender";
Logging.configure({ level: "warn", namespaces: { HostedAssetSource: "debug" } });
On a deployed page, set localStorage["minerender:log"] = "debug" and reload; in Node, set MINERENDER_LOG=debug. See logging for handlers and the setting format.
Node
NodeRenderer.create() opens a native WebGL 2 context without a browser DOM. renderToBuffer() draws a fresh frame and returns PNG bytes. Use Node.js 22.12 or later with working native canvas and gl dependencies; headless Linux also needs Mesa and an X server such as Xvfb. See the platform setup guide.
Save this as render.mjs beside a Minecraft skin.png, then run node render.mjs.
import { readFile, writeFile } from "node:fs/promises";
import { NodeRenderer, shutdown } from "minerender/node";
const renderer = await NodeRenderer.create({
width: 256,
height: 256,
camera: { position: [40, 30, 60], lookingAt: [0, 16, 0] }
});
try {
const skin = await readFile("skin.png");
await renderer.scene.addSkin(`data:image/png;base64,${skin.toString("base64")}`);
await writeFile("render.png", await renderer.renderToBuffer({ trim: true }));
} finally {
renderer.dispose();
shutdown();
}
Native rendering disables antialiasing; render.pixelRatio increases output resolution. start() and toImage() are not available in Node.
To render over HTTP, run the repository's rendering API. Submit a scene document to POST /v1/renders, then use the returned PNG URL while the image remains cached.
Performance
- One renderer per visible area. Browsers limit WebGL contexts. This page keeps at most two alive and swaps the rest for snapshots.
- Dispose what scrolls away and recreate it on demand. Assets stay cached, so the second load is quick.
- Leave instancing on for repeated models, and set
maxInstanceCount above the number of copies you expect.
- Turn on
sectionMeshing for worlds and large structures. Each section becomes a few meshes instead of thousands of instances, built in a worker when the bundle ships section.worker.
- Disable the composer when you do not need post-processing, and keep
pixelRatio at 1 unless you need sharper output.
- Lower
fpsLimit on busy pages. The dirty flag already skips idle frames.