Programmatic Variants
Creating design variants programmatically is a straightforward process. Platforms often want to show the same design / graphic placement / etc. in multiple colorways -- this technique is a great way to achieve that.
INFO
Check out the Create a Design guide before this one, it has info on setting up your development environment and most of the code below, which we'll skip here.
Contents
Step 1 — Color Iteration
We want to demonstrate a t-shirt in multiple colorways. Here we'll iterate over a list of colors and render them onto a single design in a loop within a running scene.
- index.ts
1import { Core3D, Material, Model } from '@core3d/sdk';2import { Adapter } from '@core3d/sdk-adapter-three';34const core3d = new Core3D({5 apiKey: '...', // your Core3D API token6 createAdapter: ctx => new Adapter(ctx),7});89const design = core3d.createDesign();10const model = await core3d.loadModel(Model.Tee);11const cotton = await core3d.loadMaterial(Material.Cotton);1213design.setModel(model);1415for (const mesh of design.listMeshes()) {16 design.apply(cotton, mesh);17}1819await design.render();2021const scene = await core3d.loadScene({22 layout: 'front',23 size: [512, 512],24 target: design,25});2627scene.fit();28scene.start();2930document.body.append(scene.element);31+32const colors = [+33 'purple',+34 'orange',+35 'rgb(100, 160, 140)',+36];+37+38async function loop(i = 0) {+39 cotton.setColor(colors[i]);+40 await cotton.render();+41 setTimeout(() => loop(i === colors.length - 1 ? 0 : i + 1));+42};+43+44loop();
Step 2 — View the Result
And the result is...
Step 3 — Going Further
The example above uses a single MaterialResource
(cotton
) and changes the color. Sometimes it's preferrable to pre-render a bunch of materials, for that use case you might create multiple material resources and swap them around as needed.
- index.ts
let selectedColor = 'blue';const [blueCotton,redCotton,] = await Promise.all([core3d.loadMaterial(Material.Cotton),core3d.loadMaterial(Material.Cotton),]);redCotton.setColor('red');blueCotton.setColor('blue');if (selectedColor === 'blue') {design.remove(redCotton);for (const mesh of design.listMeshes()) {design.apply(blueCotton, mesh);}} else {design.remove(blueCotton);for (const mesh of design.listMeshes()) {design.apply(redCotton, mesh);}}design.render();