Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created May 29, 2019 14:11
Show Gist options
  • Save mattdesl/1e9ab019534838e8c870ae06371be469 to your computer and use it in GitHub Desktop.
Save mattdesl/1e9ab019534838e8c870ae06371be469 to your computer and use it in GitHub Desktop.
canvas-sketch + typescript

canvas-sketch + TypeScript

After installing canvas-sketch globally, create a new folder to hold your sketch:

mkdir my-sketch
cd my-sketch

Now run the following to generate a new default .ts file, package.json, etc:

canvas-sketch sketch.ts --new

Once the server is running, kill it (Ctrl + C) and run the following to grab TypeScript, plugin and Node.js definitions:

npm install typescript tsify @types/node --save-dev

Now, overwrite the default file with the full sketch.ts code in this gist. If you copy the code to clipboard you can run the following:

pbpaste > sketch.ts

Now you can run canvas-sketch again, but make sure to specify the tsify plugin like so, after a 'full stop' flag (--) which will pass down any additional browserify transforms/plugins.

canvas-sketch sketch.ts --open -- -p [ tsify --noImplicitAny ]

Congrats! Now you are using TypeScript with canvas-sketch.

const canvasSketch = require('canvas-sketch');
const settings = {
duration: 5,
animate: true,
dimensions: [ 512, 512 ]
};
interface Props {
context: CanvasRenderingContext2D;
width: number;
height: number;
time: number;
playhead: number;
}
const sketch = () => {
return ({ context, width, height, playhead }: Props) => {
context.fillStyle = 'hsl(0, 0%, 95%)';
context.fillRect(0, 0, width, height);
const x: number = width / 2;
const y: number = height / 2;
const radius: number = width * 0.25;
const start: number = Math.sin(playhead * Math.PI * 2) * Math.PI;
const end: number = start + Math.PI / 2 + Math.sin(playhead * Math.PI * 2 + Math.PI / 2) * Math.PI * 0.4;
const thickness: number = width * 0.01 + (Math.sin(playhead * Math.PI * 2) * 0.5 + 0.5) * width * 0.05;
context.beginPath();
context.arc(x, y, radius, start, end, false);
context.lineWidth = thickness;
context.lineJoin = 'round';
context.lineCap = 'round';
context.strokeStyle = 'tomato';
context.stroke();
};
};
canvasSketch(sketch, settings);
@dmitru
Copy link

dmitru commented Jul 5, 2023

Just to check in that on July 5, 2023 this recipe still works.
Thanks for sharing this! 🙏

@josevitola
Copy link

Hi! I am experiencing the same error as @ELI7VH. Was anyone able to solve this problem for Windows?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment