|
| 1 | +const now = performance.now(); |
| 2 | + |
| 3 | +const noiseCanvas = document.createElement("canvas"); |
| 4 | +const noiseCtx = noiseCanvas.getContext("2d"); |
| 5 | +const noiseSize = 100; |
| 6 | +const noiseRectSize = Math.ceil(Math.sqrt(Math.pow(noiseSize, 2) * 2)); |
| 7 | +const noiseOffset = (noiseRectSize - noiseSize) / 2; |
| 8 | +noiseCanvas.width = noiseRectSize; |
| 9 | +noiseCanvas.height = noiseRectSize; |
| 10 | + |
| 11 | +const cacheCanvas = document.createElement("canvas"); |
| 12 | +const cacheCtx = cacheCanvas.getContext("2d"); |
| 13 | +cacheCanvas.width = noiseSize; |
| 14 | +cacheCanvas.height = noiseSize; |
| 15 | +const cacheCenter = noiseSize / 2; |
| 16 | + |
| 17 | +const drawCanvas = document.createElement("canvas"); |
| 18 | +const drawCtx = drawCanvas.getContext("2d"); |
| 19 | +const drawSize = 1000; |
| 20 | +drawCanvas.width = drawSize; |
| 21 | +drawCanvas.height = drawSize; |
| 22 | + |
| 23 | +document.body.appendChild(noiseCanvas); |
| 24 | +document.body.appendChild(cacheCanvas); |
| 25 | +document.body.appendChild(drawCanvas); |
| 26 | + |
| 27 | +const noiseImageData = noiseCtx.createImageData(noiseRectSize, noiseRectSize); |
| 28 | +const pixels = noiseImageData.data; |
| 29 | +const baseLight = .7; |
| 30 | +const maxLight = 1; |
| 31 | + |
| 32 | +const pixelSize = pixels.length; |
| 33 | +for (let i = 0; i < pixelSize; i += 4) { |
| 34 | + pixels[i] = pixels[i + 1] = pixels[i + 2] = (baseLight + Math.random() * (maxLight - baseLight)) * 255; // Set a random gray |
| 35 | + pixels[i + 3] = 255; // 100% opaque |
| 36 | +} |
| 37 | +noiseCtx.putImageData(noiseImageData, 0, 0); |
| 38 | + |
| 39 | +cacheCtx.save(); |
| 40 | +function setCacheNoise() { |
| 41 | + cacheCtx.restore(); |
| 42 | + |
| 43 | + const randomNumb = Math.random(); |
| 44 | + if (1) { |
| 45 | + const offset = Math.floor(randomNumb * noiseOffset); |
| 46 | + cacheCtx.translate(-offset, -offset); |
| 47 | + cacheCtx.drawImage(noiseCanvas, 0, 0); |
| 48 | + cacheCtx.translate(offset, offset); |
| 49 | + } else { |
| 50 | + const degrees = Math.PI / 180 * randomNumb * 360; |
| 51 | + cacheCtx.translate(cacheCenter, cacheCenter); |
| 52 | + cacheCtx.rotate(degrees); |
| 53 | + cacheCtx.drawImage(noiseCanvas, -cacheCenter, -cacheCenter); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +function drawPattern(x, y) { |
| 58 | + setCacheNoise(); |
| 59 | + drawCtx.drawImage(cacheCanvas, x, y); |
| 60 | +} |
| 61 | + |
| 62 | +const lineX = Math.ceil(drawCanvas.width / noiseSize); |
| 63 | +const lineY = Math.ceil(drawCanvas.height / noiseSize); |
| 64 | + |
| 65 | + |
| 66 | +for (let x = 0; x < lineX; x++) { |
| 67 | + for (let y = 0; y < lineY; y++) { |
| 68 | + drawPattern(x * noiseSize, y * noiseSize); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +console.log(`run time by: ${performance.now() - now}ms`); |
0 commit comments