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
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 apiUrl: '/api/proxy',8 createAdapter: ctx => new Adapter(ctx),9 });1011 const design = core3d.createDesign();12 const model = await core3d.loadModel(Model.Tee);13 const cotton = await core3d.loadMaterial(Material.Cotton);1415 design.setModel(model);1617 for (const mesh of design.listMeshes()) {18 design.apply(cotton, mesh);19 }2021 await design.render();2223 const scene = await core3d.loadScene({24 layout: 'front',25 target: design,26 });2728 scene.fit();29 scene.start();3031 const colors = [32 'RebeccaPurple',33 '#CC5500',34 'rgb(100, 160, 140)',35 ];3637 async function loop(i = 0) {38 cotton.setColor(colors[i]);39 await cotton.render();40 setTimeout(() => loop(i === colors.length - 1 ? 0 : i + 1), 1000);41 };4243 loop();4445 return {46 scene,47 };48}4950export {51 main,52};
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 apiUrl: '/api/proxy',8 createAdapter: ctx => new Adapter(ctx),9 });
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
11 const design = core3d.createDesign();12 const model = await core3d.loadModel(Model.Tee);13 const cotton = await core3d.loadMaterial(Material.Cotton);1415 design.setModel(model);
We apply the cotton material to all meshes in the design, and trigger an initial render.
- example.ts
17 for (const mesh of design.listMeshes()) {18 design.apply(cotton, mesh);19 }2021 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
23 const scene = await core3d.loadScene({24 layout: 'front',25 target: design,26 });2728 scene.fit();29 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
31 const colors = [32 'RebeccaPurple',33 '#CC5500',34 'rgb(100, 160, 140)',35 ];3637 async function loop(i = 0) {38 cotton.setColor(colors[i]);39 await cotton.render();40 setTimeout(() => loop(i === colors.length - 1 ? 0 : i + 1), 1000);41 };4243 loop();