<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Animation of color changing and moving cube</title>
<script src=
"https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js">
</script>
</head>
<body>
<h2 style="color: green;">
GeeksforGeeks
</h2>
<script>
let angle = 0;
let colorIndex = 0;
let targetColor;
let currentColor;
let cubeX = 0;
let cubeY = 0;
let cubeZ = 0;
let cubeSpeed = 0.05;
let colors = [[255, 0, 0],
[0, 255, 0],
[0, 0, 255],
[255, 255, 0],
[0, 255, 255],
[255, 0, 255],
[255, 255, 255],
];
function setup() {
createCanvas(300, 300, WEBGL);
targetColor = color(colors[colorIndex][0],
colors[colorIndex][1], colors[colorIndex][2]);
currentColor = targetColor;
}
function draw() {
background(0);
noStroke();
lights();
translate(cubeX, cubeY, cubeZ);
rotateX(angle);
rotateY(angle * 1.3);
rotateZ(angle * 0.7);
currentColor = lerpColor(currentColor, targetColor, 0.1);
fill(currentColor);
box(100);
angle += 0.03;
if (frameCount % 60 === 0) {
colorIndex = (colorIndex + 1) % colors.length;
targetColor = color(colors[colorIndex][0],
colors[colorIndex][1], colors[colorIndex][2]);
}
cubeX += cubeSpeed;
if (cubeX > width / 10 || cubeX < -width / 10) {
cubeSpeed = -cubeSpeed;
}
cubeY += cubeSpeed;
if (cubeY > height / 10 || cubeY < -height / 10) {
cubeSpeed = -cubeSpeed;
}
cubeZ += cubeSpeed;
if (cubeZ > width / 10 || cubeZ < -width / 10) {
cubeSpeed = -cubeSpeed;
}
}
</script>
</body>
</html>