Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created January 31, 2023 10:00
Show Gist options
  • Save mattdesl/8cc7ecc4f35f42101cac8a542f78bb5d to your computer and use it in GitHub Desktop.
Save mattdesl/8cc7ecc4f35f42101cac8a542f78bb5d to your computer and use it in GitHub Desktop.
using canvas-sketch with your own web framework
  1. Write your sketch, export to window scope
  2. Build with canvas-sketch sketch.js --build --dir=dist
  3. Use the .js as a vendor script in your preferred HTML/JS framework.
<body>
<div id="canvas-container">
<div>hello world</div>
<canvas id="main-canvas"></canvas>
</div>
<script src="./dist/sketch.js"></script>
<script>
// Retrieve your API from window scope
const KEY = Symbol.for("MyArtAPI");
const createArtwork = window[KEY];
(async () => {
// Load the sketch, wait for it to finish
const sketch = await createArtwork({
// If you don't specify a { canvas } attribute you should
// specify a parent container, otherwise it's added to <body>
// parent: document.querySelector('#canvas-container'),
canvas: document.querySelector("#main-canvas"),
});
// Now you have a SketchManager that you can pause/play/export/etc
console.log("SketchManager:", sketch);
})();
</script>
</body>
const canvasSketch = require("canvas-sketch");
const settings = {
dimensions: [2048, 2048],
};
const sketch = () => {
return ({ context, width, height }) => {
context.fillStyle = "red";
context.fillRect(0, 0, width, height);
context.fillStyle = "blue";
context.fillRect(0, 0, width / 2, height);
};
};
// Get a unique key for your art API
const KEY = Symbol.for("MyArtAPI");
// Assign to global scope
window[KEY] = function createArtwork(opts = {}) {
return canvasSketch(sketch, { ...settings, ...opts });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment