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</title>
- <style>
- canvas {
- border: 1px solid black;
- image-rendering: pixelated;
- }
- </style>
- </head>
- <body>
- <canvas width="580" height="580" id="canvas"></canvas>
- <script>
- const canvas = document.getElementById("canvas");
- const ctx = canvas.getContext("2d");
- const pixelSize = 5; // size of each pixel
- const numPixels = canvas.width / pixelSize; // number of pixels in each row/column
- // create a 2D array to hold the pixel colors
- const pixels = new Array(numPixels);
- for (let i = 0; i < numPixels; i++) {
- pixels[i] = new Array(numPixels);
- }
- // initialize the pixel colors with random values
- for (let i = 0; i < numPixels; i++) {
- for (let j = 0; j < numPixels; j++) {
- pixels[i][j] = getRandomColor();
- }
- }
- // draw the pixels on the canvas
- 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);
- }
- }
- // a helper function to get a random color
- function getRandomColor() {
- const red = Math.floor(Math.random() * 256);
- const green = Math.floor(Math.random() * 256);
- const blue = Math.floor(Math.random() * 256);
- return `rgb(${red},${green},${blue})`;
- }
- // 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
- let sumR = 0;
- let sumG = 0;
- let sumB = 0;
- for (const neighborColor of neighborColors) {
- const rgba = neighborColor.replace(/[^\d,]/g, "").split(",");
- sumR += parseInt(rgba[0]);
- sumG += parseInt(rgba[1]);
- sumB += parseInt(rgba[2]);
- }
- const avgR = Math.round(sumR / neighborColors.length);
- const avgG = Math.round(sumG / neighborColors.length);
- const avgB = Math.round(sumB / neighborColors.length);
- return `rgb(${avgR},${avgG},${avgB})`;
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement