Pixel_Plante/script2.js

118 lines
3.2 KiB
JavaScript

//Importer canva
const canvas = document.getElementById("canva");
const ctx = canvas.getContext("2d");
// Redimensionner le canvas à la taille de l'écran
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
// 1. Définir la liste des images
const allImages = [
"./img/001.JPG",
"./img/JV01.jpg",
"./img/real01.jpg",
"./img/rdrd2.jpg",
"./img/real02.JPG",
"./img/Cyberpunk_01.png",
"./img/rdrd3.jpg",
"./img/Fleur_02.JPG",
"./img/Fleur_08.JPG",
"./img/rdrd4.jpg",
"./img/Forêt_2.JPG"
];
// 2. Pré-charger toutes les images
const loadedImages = [];
let imagesLoaded = 0;
allImages.forEach(src => {
const img = new Image();
img.src = src;
img.onload = () => {
loadedImages.push(img);
imagesLoaded++;
if (imagesLoaded === allImages.length) {
startAnimation();
}
};
});
let currentImageIndex = 0; // image de base (fond)
let tps = 0;
let lastTime = 0;
function startAnimation() {
requestAnimationFrame(update);
}
function update(currentTime) {
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
tps += (-0.00 + Math.random() * 0.01) * deltaTime;
tps = Math.max(0, Math.min(100, tps));
draw(tps);
// Quand tps atteint 100, passer à l'image suivante
if (tps >= 100 && currentImageIndex < allImages.length - 1) {
currentImageIndex++;
tps = 0;
// Boucle infinie : si on est à la dernière image, revenir à la première
if (currentImageIndex >= allImages.length - 1) {
currentImageIndex = 0;
}
}
requestAnimationFrame(update);
}
function draw(tps) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 1. Dessiner le FOND (image actuelle : allImages[currentImageIndex])
const backgroundImg = loadedImages[currentImageIndex];
ctx.drawImage(backgroundImg, 0, 0, canvas.width, canvas.height);
// 2. Dessiner les carrés avec l'image SUIVANTE (allImages[currentImageIndex + 1])
const nextImageIndex = currentImageIndex + 1;
if (nextImageIndex < loadedImages.length) {
const nextImg = loadedImages[nextImageIndex];
const cols = 100;
const rows = 100;
const cellWidth = canvas.width / cols;
const cellHeight = canvas.height / rows;
const fillCount = Math.floor((tps / 100) * cols * rows);
const positions = [];
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
positions.push({ x, y });
}
}
// Mélanger
for (let i = positions.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[positions[i], positions[j]] = [positions[j], positions[i]];
}
// Dessiner les carrés avec l'image suivante
for (let i = 0; i < fillCount; i++) {
const { x, y } = positions[i];
const posX = x * cellWidth;
const posY = y * cellHeight;
ctx.drawImage(
nextImg,
posX, posY, cellWidth, cellHeight,
posX, posY, cellWidth, cellHeight
);
}
}
}