Skip to content

Instantly share code, notes, and snippets.

@peterszerzo
Created April 20, 2019 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterszerzo/ec406952f40c60f1db461b69daa989be to your computer and use it in GitHub Desktop.
Save peterszerzo/ec406952f40c60f1db461b69daa989be to your computer and use it in GitHub Desktop.
canvas-sketch hex animation
const canvasSketch = require("canvas-sketch");
const dim = 1000;
const range = n => [...Array(n).keys()];
const settings = {
dimensions: [dim, dim],
animate: true,
duration: 30,
fps: 30
};
const line = ({ x, y, rot, len }) => context => {
context.save();
context.translate(x, y);
context.rotate(rot);
context.beginPath();
context.moveTo(-len / 2, -len / 2);
context.lineTo(len / 2, len / 2);
context.stroke();
context.restore();
};
const hex = ({ x, y, r, rot }) => context => {
context.save();
context.translate(x, y);
context.rotate(rot);
context.beginPath();
context.moveTo(r, 0);
[0, 1, 2, 3, 4, 5, 6].forEach(index => {
context.lineTo(
r * Math.cos((index * Math.PI) / 3),
r * Math.sin((index * Math.PI) / 3)
);
});
context.stroke();
context.restore();
};
const hexagons = range(20).map(num => ({
index: num,
radius: 25 * (1 / Math.cos(Math.PI / 6)) ** num,
rotation: 0
}));
const sketch = () => ({ context, width, height, deltaTime }) => {
context.fillStyle = "rgb(255, 255, 255)";
context.fillRect(0, 0, width, height);
context.strokeStyle = "rgb(0, 0, 0)";
context.lineWidth = "3";
context.lineCap = "round";
hexagons.forEach(hexagon => {
hexagon.rotation += (deltaTime * 1.5 * (hexagon.index - 9.5)) / 9.5;
hex({ x: dim / 2, y: dim / 2, r: hexagon.radius, rot: hexagon.rotation })(
context
);
});
};
canvasSketch(sketch, settings);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment