mattdesl / canvas-sketch

[beta] A framework for making generative artwork in JavaScript and the browser.
MIT License
5.05k stars 394 forks source link

Is it possible to use my own container to render three js scene via canvas-sketch and handle it with canvas-sketch-cli? #75

Open vadym1930 opened 5 years ago

vadym1930 commented 5 years ago

So I need to explain it a bit. I created three js scene using amazing canvas-sketch and canvas-sketch-cli. Now I would like to implement this kind of 3d animation into the site.

So could I setup cli somehow to get a js bundle which should work with my own container for the canvas on whatever site it would be connected with?

And do we actually have some ready to use three js template canvas-sketch settings for rendering scene in a particular container?

It seems to be like more stack overflow question, but my point is maybe with the issue the part of documentation about cli or some different use cases could be described in docs and help someone and me of course to use canvas-sketch and canvas-sketch-cli.

Regards

mattdesl commented 5 years ago

For a ThreeJS template, you can do this:

canvas-sketch sketch.js --new --template=three

It will scaffold a basic 3D cube scene.

By default, all the templates/examples run the sketch immediately, but instead of calling canvasSketch(sketch, settings) you will want to wrap it in a function like so:

function create3DAnimation (opt = {}) {
  return canvasSketch(sketch, Object.assign(
    settings,
    opt
  ));
};

Now you can call that function with settings like create3DAnimation({ canvas: myCanvasElement }) to have it load into an existing canvas tag.

In terms of building to a site, you have two options basically:

1. If you are already using Webpack/Parcel/CRA/etc in your site, you can just place all of your sketch code in a new file and require it like any other module.

2. If you are not using a bundler, you can build the sketch to a JS+HTML file. Within this approach there are different ways of doing it.

2A You can use an iframe to embed the HTML+JS

2B Or, you could 'expose' that function above to your larger framework/website by assigning it to global scope:

window.create3DAnimation = create3DAnimation;

I don't have a full example of this but it would be nice to add.

vadym1930 commented 5 years ago

That's a great answer. Thank you so much. I switched to a "custom" three js + React template. But I'm going to go back to canvas-sketch armed with the information provided above