|
| 1 | +const patternCanvas = document.createElement("canvas"); |
| 2 | +const patternCtx = patternCanvas.getContext("2d"); |
| 3 | +const patternSize = 40; |
| 4 | +const patternRectSize = patternSize * 4; |
| 5 | +patternCanvas.width = patternRectSize; |
| 6 | +patternCanvas.height = patternRectSize; |
| 7 | + |
| 8 | +const drawCanvas = document.createElement("canvas"); |
| 9 | +const drawCtx = drawCanvas.getContext("2d"); |
| 10 | +const drawSize = 1000; |
| 11 | +drawCanvas.width = drawSize; |
| 12 | +drawCanvas.height = drawSize; |
| 13 | + |
| 14 | +document.body.appendChild(patternCanvas); |
| 15 | +document.body.appendChild(drawCanvas); |
| 16 | + |
| 17 | +const noiseImageData = patternCtx.createImageData(patternRectSize, patternRectSize); |
| 18 | +const pixels = noiseImageData.data; |
| 19 | +const baseLight = .7; |
| 20 | +const maxLight = 1; |
| 21 | + |
| 22 | +const pixelSize = pixels.length; |
| 23 | +for (let i = 0; i < pixelSize; i += 4) { |
| 24 | + pixels[i] = pixels[i + 1] = pixels[i + 2] = (baseLight + Math.random() * (maxLight - baseLight)) * 255; // Set a random gray |
| 25 | + pixels[i + 3] = 255; // 100% opaque |
| 26 | +} |
| 27 | +patternCtx.putImageData(noiseImageData, 0, 0); |
| 28 | + |
| 29 | + |
| 30 | +function getNoiseOffset() { |
| 31 | + return Math.floor(Math.random() * (patternRectSize - patternSize * 2)); |
| 32 | +} |
| 33 | + |
| 34 | +function drawPattern(x, y) { |
| 35 | + const imageData = patternCtx.getImageData(getNoiseOffset(), getNoiseOffset(), patternSize, patternSize); |
| 36 | + drawCtx.putImageData(imageData, x, y); |
| 37 | +} |
| 38 | + |
| 39 | +const lineX = Math.ceil(drawCanvas.width / patternSize); |
| 40 | +const lineY = Math.ceil(drawCanvas.height / patternSize); |
| 41 | + |
| 42 | +for (let x = 0; x < lineX; x++) { |
| 43 | + for (let y = 0; y < lineY; y++) { |
| 44 | + drawPattern(x * patternSize, y * patternSize); |
| 45 | + } |
| 46 | +} |
0 commit comments