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 demonstrates how you can achieve that.
Contents
Example
Code
- example.ts
- React Usage
- LiveExample.tsx
1import { Core3D, Material, Model } from '@core3d/sdk';2import { Adapter } from '@core3d/sdk-adapter-three';34async function main() {5 const core3d = new Core3D({6 apiKey: '<your core3d api token>',7 createAdapter: ctx => new Adapter(ctx),8 });910 const design = core3d.createDesign();11 const model = await core3d.loadModel(Model.Tee);12 const cotton = await core3d.loadMaterial(Material.Cotton);1314 design.setModel(model);1516 for (const mesh of design.listMeshes()) {17 design.apply(cotton, mesh);18 }1920 await design.render();2122 const scene = await core3d.loadScene({23 layout: 'front',24 target: design,25 });2627 scene.fit();28 scene.start();2930 const colors = [31 'RebeccaPurple',32 '#CC5500',33 'rgb(100, 160, 140)',34 ];3536 async function loop(i = 0) {37 cotton.setColor(colors[i]);38 await cotton.render();39 setTimeout(() => loop(i === colors.length - 1 ? 0 : i + 1), 1000);40 };4142 loop();4344 return {45 scene,46 };47}4849export {50 main,51};
Breaking It Down
First, we initialize the Core3D SDK. You'll need your own API token for this.
- example.ts
5 const core3d = new Core3D({6 apiKey: '<your core3d api token>',7 createAdapter: ctx => new Adapter(ctx),8 });
Then we create an empty design, and load the publicly available t-shirt model and cotton material, and set the model on the design.
- example.ts
10 const design = core3d.createDesign();11 const model = await core3d.loadModel(Model.Tee);12 const cotton = await core3d.loadMaterial(Material.Cotton);1314 design.setModel(model);
We apply the cotton material to all meshes in the design, and trigger an initial render.
- example.ts
16 for (const mesh of design.listMeshes()) {17 design.apply(cotton, mesh);18 }1920 await design.render();
Then boot up a scene with our design, fit() the viewport to the design, and start() the scene to enable controls and auto-updates.
- example.ts
22 const scene = await core3d.loadScene({23 layout: 'front',24 target: design,25 });2627 scene.fit();28 scene.start();
Finally, we define an array of CSS color values, then trigger a loop to update the color of the cotton material every second.
- example.ts
30 const colors = [31 'RebeccaPurple',32 '#CC5500',33 'rgb(100, 160, 140)',34 ];3536 async function loop(i = 0) {37 cotton.setColor(colors[i]);38 await cotton.render();39 setTimeout(() => loop(i === colors.length - 1 ? 0 : i + 1), 1000);40 };4142 loop();