- Write your sketch, export to window scope
- Build with
canvas-sketch sketch.js --build --dir=dist
- Use the
.js
as a vendor script in your preferred HTML/JS framework.
Created
January 31, 2023 10:00
-
-
Save mattdesl/8cc7ecc4f35f42101cac8a542f78bb5d to your computer and use it in GitHub Desktop.
using canvas-sketch with your own web framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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