mattdesl / canvas-sketch

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

Method for saving canvas #190

Closed max-kibosh closed 1 year ago

max-kibosh commented 1 year ago

I want to export the canvas (usually done with ctrl + s) through code. I'm using Tweakpane and would like to export upon a button being pressed but I can't find a relevant method in the docs.

Would appreciate any guidance :)

const createPane = () => {
    const pane = new Tweakpane.Pane({
        title: 'Einstellungen'
    });

    const exportButton = pane.addButton({
        title: "Export"
    })

    exportButton.on("click", () => {
        // ?
    })
}
mattdesl commented 1 year ago

You can call props.exportFrame() where props is the main parameter to your sketch.

max-kibosh commented 1 year ago

Thanks! In regards to the props, I'm using the standard way described in the docs:

const sketch = () => {
    return ({ context, width, height, frame }) => {
       // ...   
    }
};

and calling Tweakpane and canvasSketch at the end:

createPane();
canvasSketch(sketch, settings);

exportFrame() would be a function of what here? Sorry for the inconvenience.

max-kibosh commented 1 year ago

Figured it out, I was a bit confused but figured out the context. Thanks for the help!

mattdesl commented 1 year ago

For future reference for anybody stumbling upon this issue, it looks like this:

const sketch = (props) => {
  myButton.onclick = () => props.exportFrame();

  return () => { /* render fn */ };
}

Cheers :smile: