Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Nearest Pixels Animation</title>
- <style>
- canvas {
- border: 1px solid black;
- image-rendering: pixelated;
- }
- </style>
- </head>
- <body>
- <canvas width="540" height="540" id="canvas"></canvas>
- <script>
- const canvas = document.getElementById("canvas");
- const ctx = canvas.getContext("2d");
- const pixelSize = 3; // size of each pixel
- const numPixels = Math.floor(canvas.width / pixelSize); // number of pixels in each row/column
- // create a 2D array to hold the pixel colors
- const pixels = Array.from({length:numPixels}, _ => Array.from({length:numPixels}, _ => getRandomColor()));
- // draw the pixels on the canvas
- function drawPixels() {
- for (let i = 0; i < numPixels; i++) {
- for (let j = 0; j < numPixels; j++) {
- ctx.fillStyle = blendColors(i, j);
- ctx.fillRect(i * pixelSize, j * pixelSize, pixelSize, pixelSize);
- }
- }
- requestAnimationFrame(drawPixels);
- }
- requestAnimationFrame(drawPixels);
- // a helper function to get a random value between -1.0 and 1.0 for each component
- function getRandomColor() {
- return {
- r: Math.random() * 2 - 1,
- g: Math.random() * 2 - 1,
- b: Math.random() * 2 - 1
- };
- }
- // a function to blend the color of a pixel with its neighbors
- function blendColors(x, y) {
- const top = y <= 0 ? y + numPixels - 1 : y - 1;
- const left = x <= 0 ? x + numPixels - 1 : x - 1;
- const right = x >= numPixels - 1 ? x - numPixels + 1 : x + 1;
- const bottom = y >= numPixels - 1 ? y - numPixels + 1 : y + 1;
- const neighborColors = [
- pixels[left][top],
- pixels[x][top],
- pixels[right][top],
- pixels[left][y],
- pixels[right][y],
- pixels[left][bottom],
- pixels[x][bottom],
- pixels[right][bottom]
- ];
- // calculate the average color of the pixel and its neighbors for each component
- const [rAvg,gAvg,bAvg] = neighborColors.reduce((acc,nc) => [acc[0]+ nc.r, acc[1]+ nc.g, acc[2]+ nc.b], [0,0,0]).map(avg => avg / neighborColors.length);
- // update the color of the pixel with a random value between -0.1 and 0.1 for each component
- pixels[x][y] = {
- r: Math.min(1, Math.max(-1, rAvg + (Math.random() - 0.5) * 0.2)),
- g: Math.min(1, Math.max(-1, gAvg + (Math.random() - 0.5) * 0.2)),
- b: Math.min(1, Math.max(-1, bAvg + (Math.random() - 0.5) * 0.2))
- };
- // map the color values to RGB values between 0 and 255
- const r = Math.round((pixels[x][y].r + 1) * 127.5);
- const g = Math.round((pixels[x][y].g + 1) * 127.5);
- const b = Math.round((pixels[x][y].b + 1) * 127.5);
- return `rgb(${r},${g},${b})`;
- }
- </script>
- </body>
- </html>
Advertisement
Advertisement