Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>TwoToneContours</title>
- <style>
- canvas {
- border: 1px solid black;
- }
- </style>
- </head>
- <body>
- <canvas id="patternCanvas" width="640" height="640"></canvas>
- <button onclick="createPattern()">REGENERATE</button>
- <script>
- const canvas = document.getElementById('patternCanvas');
- const ctx = canvas.getContext('2d');
- const ww = canvas.width;
- const hh = canvas.height;
- const p = 64;
- const n = 50;
- function createGrid() {
- const grid = new Array(hh + p).fill(null).map(() => new Array(ww + p).fill(255));
- for (let y = 0; y < hh + p; y += 32) {
- for (let x = 0; x < ww + p; x += 32) {
- const color = Math.random() > 0.5 ? 0 : 255;
- for (let i = 0; i < 32; i++) {
- for (let j = 0; j < 32; j++) {
- grid[y + i][x + j] = color;
- }
- }
- }
- }
- return grid;
- }
- function displayPattern(grid) {
- ctx.clearRect(0, 0, ww, hh);
- for (let y = 0; y < hh + p; y++) {
- for (let x = 0; x < ww + p; x++) {
- ctx.fillStyle = `rgb(${grid[y][x]}, ${grid[y][x]}, ${grid[y][x]})`;
- ctx.fillRect(x, y, 1, 1);
- }
- }
- }
- function applyBlur() {
- ctx.filter = 'blur(20px)';
- ctx.drawImage(canvas, 0, 0);
- ctx.filter = 'none';
- }
- function twoTone() {
- const imageData = ctx.getImageData(0, 0, ww, hh);
- const data = imageData.data;
- for (let i = 0; i < data.length; i += 4) {
- const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
- const newColor = avg > 128 ? 255 : 0;
- data[i] = newColor;
- data[i + 1] = newColor;
- data[i + 2] = newColor;
- }
- ctx.putImageData(imageData, 0, 0);
- }
- function cropAndResize() {
- const croppedCanvas = document.createElement('canvas');
- const croppedCtx = croppedCanvas.getContext('2d');
- croppedCanvas.width = ww - 2 * n;
- croppedCanvas.height = hh - 2 * n;
- croppedCtx.drawImage(canvas, n, n, ww - 2 * n, hh - 2 * n, 0, 0, ww - 2 * n, hh - 2 * n);
- ctx.clearRect(0, 0, ww, hh);
- ctx.drawImage(croppedCanvas, 0, 0, ww - 2 * n, hh - 2 * n, 0, 0, ww, hh);
- }
- function createPattern() {
- const grid = createGrid();
- displayPattern(grid);
- applyBlur();
- twoTone();
- cropAndResize();
- }
- createPattern();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement