Skip to content

Instantly share code, notes, and snippets.

@danbst
Created Nov 5, 2020
Embed
What would you like to do?
draw swap/rotation animation using p5.js
var figures = [];
var size = 50;
var margin = 1.5;
var postprocessed = false;
var centerX = 0;
let names = ["a", "b", "c", "d", "e", "f"];
function addFigure(col) {
figures.push([figures.length * size * margin, 0, col]);
}
function setup() {
createCanvas(400, 400);
noStroke();
fill(255);
rectMode(CENTER);
textAlign(CENTER, CENTER);
addFigure("red");
addFigure("grey");
addFigure("grey");
addFigure("grey");
addFigure("green");
centerX = (figures[figures.length - 1][0] - figures[0][0]) / 2;
}
function drawFigures(figures) {
for (var i = 0; i < figures.length; i++) {
let fig = figures[i];
resetMatrix();
translate(width / 2, height / 2);
fill(fig[2]);
textSize(32);
text(names[i], i * margin * size - centerX, size * margin);
rotate(fig[1]);
rect(fig[0] - centerX, 0, size, size);
}
}
function draw() {
background(245);
let animduration = 500;
let animcycle = 1000;
let currentState = millis() % animcycle;
if (currentState <= animduration) {
figures[0][1] = 3.141592 - 3.141592 * currentState / animduration;
for (let i = 1; i < figures.length; i++) {
let fig = figures[i];
fig[0] = i * size * margin + size * margin * currentState / animduration;
}
postprocessed = false;
} else if (!postprocessed) {
figures[0][0] = (figures.length - 1) * size * margin;
var temp;
for (let i = figures.length-1; i > 0; i--) {
temp = figures[i-1];
figures[i-1] = figures[i];
figures[i] = temp;
figures[i][1] = 0;
}
postprocessed = true;
}
drawFigures(figures);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment