Generative Design
JS & CSS
2024 - 2025
JS 101
Concepts basiques
Créer un élément HTML
Générer un nombre aléatoire
// Retourne un nombre décimal entre 0 et 0.99999…
let randomNumber1 = Math.random();
// Retourne un nombre décimal entre 0 et 9.99999…
let randomNumber2 = Math.random() * 10;
Arrondir un nombre
Avoir un nombre décimal nous permet entre autre d'être précis. Dans certains cas il sera nécessaire d'avoir des nombres entiers.
Ex: accéder aux éléments d'un tableau, éviter les demi-pixels, améliorer les performances, etc.Math.floor( 10.50 ); // 10
Math.floor( -3.65 ); // -4
Math.ceil( 10.50 ); // 11
Math.ceil( -3.65 ); // -3
Math.round( 10.50 ); // 11
Math.round( -3.50 ); // -3
Math.round( -3.65 ); // -4
Position aléatoire
Les template literals permettent d'insérer du code dans une chaîne de caractèresTaille aléatoire
Boucle simple
for( let i = 0; i < 3; i++ ) {
console.log( i );
// 0 pour la première itération
// 1 pour la seconde
// 2 pour la dernière
}
Plus de particules
Récupérer un élément aléatoire dans un tableau
const getRandomElement = ( array ) => {
const randomIndex = Math.floor( Math.random() * array.length );
return array[ randomIndex ];
}
Plus de couleurs
CSS keyframes
From & to
@keyframes toRight {
from {
transform: translate( 0%, 0% );
}
to {
transform: translate( 0, 100% );
}
}
.myElement{
animation: toRight .32s ease;
}
Les pourcentages
@keyframes opacityBounce {
0% {
opacity: 0;
}
50%{
opacity: 1;
}
100% {
opacity: 0;
}
}
.myElement{
animation: opacityBounce .32s ease;
}
Animer les particules
Delais aléatoire
CSS Custom Properties
Syntaxe
:root{
--background: red;
}
.myElement{
background: var(--background);
}
En pratique
Récupérer & modifier en JS
Pointer custom
Normaliser un nombre
Cela permet de retranscrire un nombre entre 0 et 1, basé sur une valeur maximale. L'avantage est de pouvoir travailler avec n'importe quelle unité par la suite, que ce soit en pixel, en pourcentage, etc.
const mouseX = 643,
windowWidth = 1440;
const normalizedMouseX = mouseX / windowWidth;
// Retourne 0.446527777777778