-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpixel_pattern_blur_simulator.html
More file actions
500 lines (426 loc) · 16.2 KB
/
pixel_pattern_blur_simulator.html
File metadata and controls
500 lines (426 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Pixel Pattern Blur Simulator</title>
<style>
body {
font-family: sans-serif;
background: #111;
color: #eee;
margin: 0;
padding: 16px;
}
.controls {
display: grid;
grid-template-columns: repeat(1, 1fr);
gap: 12px;
margin-bottom: 12px;
}
label {
font-size: 14px;
}
canvas {
border: 1px solid #444;
image-rendering: pixelated;
}
select, input {
width: 256px;
}
select {
height: 40px;
}
</style>
</head>
<body>
<h2>Pixel Pattern Blur Simulator</h2>
<div class="controls">
<label>
Pattern </br>
<select id="pattern">
<option value="grid">Square Grid</option>
<option value="stagger">Row Stagger</option>
<option value="hexagonal">Hexagonal Grid</option>
<option value="sine">Sinusoidal</option>
<option value="blue">Blue Noise Voronoi</option>
<option value="hexagonalblue">Hexagonal + Temporarily White Noise Voronoi</option>
</select>
</label>
<label>
Pixel Pitch (px)</br>
<input type="range" id="pitch" min="6" max="40" value="12" oninput="this.nextElementSibling.value = this.value" />
<output>12</output>
</label>
<label>
Gap Width (px)</br>
<input type="range" id="gap" min="1" max="8" value="3" oninput="this.nextElementSibling.value = this.value" />
<output>3</output>
</label>
<p></p>
<label>
Sine Amplitude (px)</br>
<input type="range" id="amp" min="0" max="5" value="2" step="0.1"oninput="this.nextElementSibling.value = this.value" />
<output>2</output>
</label>
<label>
Sine Wavelength (px)</br>
<input type="range" id="wave" min="1" max="200" value="20" oninput="this.nextElementSibling.value = this.value" />
<output>20</output>
</label>
<label>
Sine Phase Offset (px)</br>
<input type="range" id="phase" min="0" max="10" value="4" step="0.1" oninput="this.nextElementSibling.value = this.value" />
<output>4</output>
</label>
<label>
Blue noise allowed diameter deviation (%)</br>
<input type="range" id="voronoiDeviation" min="0" max="100" value="5" step="5" oninput="this.nextElementSibling.value = this.value" />
<output>5</output>
</label>
<p></p>
<label style="font-weight: bold;">
Blur Radius (px)</br>
<input type="range" id="blur" min="0" max="40" value="25" step="1" oninput="this.nextElementSibling.value = this.value" />
<output>25</output>
</label>
</div>
<canvas id="src" width="256" height="256"></canvas>
<canvas id="dst" width="256" height="256"></canvas>
<script>
const src = document.getElementById('src');
const dst = document.getElementById('dst');
const sctx = src.getContext('2d');
const dctx = dst.getContext('2d');
const controls = document.querySelectorAll('input, select');
controls.forEach(c => c.addEventListener('input', (event) => {
//console.log(`Input changed: ${event.target.id}, New Value: ${event.target.value}`);
render(event.target.id);
}));
function drawSinusoid(startX, startY, length, amplitude, frequency, phaseOffset, strokeWidth, direction) {
sctx.lineWidth = strokeWidth;
sctx.beginPath();
if (direction === 'horizontal') {
for (let i = 0; i <= length; i += 0.5) {
const x = startX + i;
const y = startY + amplitude * Math.sin(frequency * i + phaseOffset);
if (i === 0) {
sctx.moveTo(x, y);
} else {
sctx.lineTo(x, y);
}
}
} else { // vertical
for (let i = 0; i <= length; i += 0.5) {
const x = startX + amplitude * Math.sin(frequency * i + phaseOffset);
const y = startY + i;
if (i === 0) {
sctx.moveTo(x, y);
} else {
sctx.lineTo(x, y);
}
}
}
sctx.stroke();
}
function thresholdImageData(sctx) { // Get the image data from the canvas
const imageData = sctx.getImageData(0, 0, src.width, src.height);
const data = imageData.data;
// Apply thresholding to make the sinusoid either black or white
for (let i = 0; i < data.length; i += 4) {
const brightness = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
const threshold = 128; // Adjust this value as needed
const value = brightness > threshold ? 255 : 0;
data[i] = value; // Red
data[i + 1] = value; // Green
data[i + 2] = value; // Blue
}
// Put the modified image data back onto the canvas
sctx.putImageData(imageData, 0, 0);
}
function applyBoxBlur(ctx, radius) {
if (radius <= 0) return;
// Get the image data
const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
const width = imageData.width;
const height = imageData.height;
const data = imageData.data;
// Create output buffer
const output = new Uint8ClampedArray(data.length);
const radiusCeil = Math.ceil(radius);
const radiusSquared = radius * radius;
// Single pass radial blur
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let r = 0, g = 0, b = 0, a = 0;
let count = 0;
// Sample pixels in a circular pattern
for (let ky = -radiusCeil; ky <= radiusCeil; ky++) {
for (let kx = -radiusCeil; kx <= radiusCeil; kx++) {
// Check if within circle
const distSquared = kx * kx + ky * ky;
if (distSquared <= radiusSquared) {
const sx = x + kx;
const sy = y + ky;
if (sx >= 0 && sx < width && sy >= 0 && sy < height) {
const idx = (sy * width + sx) * 4;
r += data[idx];
g += data[idx + 1];
b += data[idx + 2];
a += data[idx + 3];
count++;
}
}
}
}
const idx = (y * width + x) * 4;
output[idx] = r / count;
output[idx + 1] = g / count;
output[idx + 2] = b / count;
output[idx + 3] = a / count;
}
}
// Put the blurred data back
const outputImageData = new ImageData(output, width, height);
ctx.putImageData(outputImageData, 0, 0);
}
/**
* Draw a hexagon centered at (cx, cy) with a given radius
* @param {CanvasRenderingContext2D} ctx - The canvas context
* @param {number} cx - Center x coordinate
* @param {number} cy - Center y coordinate
* @param {number} radius - Radius from center to vertex
*/
function drawHexagon(ctx, cx, cy, radius) {
ctx.beginPath();
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 3) * i + Math.PI / 6;
const x = cx + radius * Math.cos(angle);
const y = cy + radius * Math.sin(angle);
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.closePath();
ctx.fill();
}
function generateHexagonCenters(pitch) {
let centers = [];
const rowHeight = pitch;
const colWidth = pitch * Math.sqrt(3) / 2;
for (let row = 0; row * rowHeight < src.height + pitch; row++) {
const y = row * rowHeight;
for (let col = 0; col * colWidth < src.width + pitch; col++) {
const yOffset = (col % 2) * (pitch / 2);
const x = col * colWidth;
centers.push({x: x, y: y + yOffset});
}
}
return centers;
}
/**
* Generate blue noise distributed points using Poisson disk sampling
* @param {number} width - Canvas width
* @param {number} height - Canvas height
* @param {number} pitch - Average spacing between points
* @param {number} deviationPercent - Percentage deviation allowed
* @returns {Array} Array of {x, y} points
*/
function generateBlueNoiseCenters(width, height, pitch, deviationPercent) {
const points = [];
const minDist = pitch * (1 - deviationPercent / 100);
const maxDist = pitch * (1 + deviationPercent / 100);
const cellSize = minDist / Math.sqrt(2);
const cols = Math.ceil(width / cellSize);
const rows = Math.ceil(height / cellSize);
const grid = new Array(cols * rows).fill(-1);
const active = [];
const k = 300; // Number of attempts before rejection
// Helper function to get grid index
function gridIndex(x, y) {
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
if (col < 0 || col >= cols || row < 0 || row >= rows) return -1;
return row * cols + col;
}
// Helper function to check if point is valid
function isValid(x, y) {
if (x < 0 || x >= width || y < 0 || y >= height) return false;
const gidx = gridIndex(x, y);
if (gidx === -1) return false;
// Check neighboring cells
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
for (let r = Math.max(0, row - 2); r <= Math.min(rows - 1, row + 2); r++) {
for (let c = Math.max(0, col - 2); c <= Math.min(cols - 1, col + 2); c++) {
const neighborIdx = r * cols + c;
const pointIdx = grid[neighborIdx];
if (pointIdx !== -1) {
const dx = x - points[pointIdx].x;
const dy = y - points[pointIdx].y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist) {
return false;
}
}
}
}
return true;
}
// Start with a random point
const startX = Math.random() * width;
const startY = Math.random() * height;
points.push({x: startX, y: startY});
active.push(0);
grid[gridIndex(startX, startY)] = 0;
// Process active list
while (active.length > 0) {
const randomIdx = Math.floor(Math.random() * active.length);
const pointIdx = active[randomIdx];
const point = points[pointIdx];
let found = false;
for (let i = 0; i < k; i++) {
// Generate random point around the current point
const angle = Math.random() * 2 * Math.PI;
const radius = minDist + Math.random() * (maxDist - minDist);
const newX = point.x + radius * Math.cos(angle);
const newY = point.y + radius * Math.sin(angle);
if (isValid(newX, newY)) {
const newIdx = points.length;
points.push({x: newX, y: newY});
active.push(newIdx);
grid[gridIndex(newX, newY)] = newIdx;
found = true;
break;
}
}
if (!found) {
active.splice(randomIdx, 1);
}
}
return points;
}
/**
* Draw pixels with blue noise centers and Voronoi edges
* @param {CanvasRenderingContext2D} ctx - The canvas context to draw on
* @param {number} gapWidth - Width of the gap between pixels (in pixels)
*/
function drawVoronoi(ctx, points, gapWidth) {
const width = ctx.canvas.width;
const height = ctx.canvas.height;
// Draw Voronoi cells for each pixel
const imageData = ctx.createImageData(width, height);
const data = imageData.data;
// For each pixel in the canvas, find the nearest point
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const idx = (y * width + x) * 4;
// Find nearest point
let minDist = Infinity;
let nearestIdx = -1;
for (let i = 0; i < points.length; i++) {
const dx = x - points[i].x;
const dy = y - points[i].y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist) {
minDist = dist;
nearestIdx = i;
}
}
// Check if we're near the edge of the Voronoi cell (gap)
let secondMinDist = Infinity;
for (let i = 0; i < points.length; i++) {
if (i === nearestIdx) continue;
const dx = x - points[i].x;
const dy = y - points[i].y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < secondMinDist) {
secondMinDist = dist;
}
}
// If the difference between nearest and second-nearest is small, we're at an edge
const edgeThreshold = gapWidth / 2;
const isEdge = (secondMinDist - minDist) < edgeThreshold;
// Set pixel color (white for cell, black for edge/gap)
const value = isEdge ? 255 : 0;
data[idx] = value; // R
data[idx + 1] = value; // G
data[idx + 2] = value; // B
data[idx + 3] = 255; // A
}
}
// Draw the blue noise center points
points.forEach(point => {
const x = Math.round(point.x);
const y = Math.round(point.y);
const idx = (y * width + x) * 4;
data[idx] = 255; // R
data[idx + 1] = 255; // G
data[idx + 2] = 255; // B
data[idx + 3] = 255; // A
});
ctx.putImageData(imageData, 0, 0);
}
function render(updatedId) {
const pitch = +document.getElementById('pitch').value;
const gap = +document.getElementById('gap').value;
const blur = +document.getElementById('blur').value;
const amp = +document.getElementById('amp').value;
const wave = +document.getElementById('wave').value;
const phase = +document.getElementById('phase').value;
const voronoiDeviation = +document.getElementById('voronoiDeviation').value;
const pat = document.getElementById('pattern').value;
if (updatedId !== 'blur') {
if (pat === 'sine') {
sctx.fillStyle = '#000';
sctx.fillRect(0, 0, src.width, src.height);
sctx.strokeStyle = '#fff';
for (let x = 0; x <= src.width; x += pitch) {
drawSinusoid(x, 0, 256, amp, (2 * Math.PI) / wave, (x/pitch) * phase, gap, 'vertical');
}
for (let y = 0; y <= src.height; y += pitch) {
drawSinusoid(0, y, 256, amp, (2 * Math.PI) / wave, (y/pitch) * phase, gap, 'horizontal');
}
} else if (pat === 'hexagonal') {
const centers = generateHexagonCenters(pitch);
drawVoronoi(sctx, centers, gap);
} else if (pat === 'blue') {
let centers = generateBlueNoiseCenters(src.width, src.height, pitch, voronoiDeviation);
drawVoronoi(sctx, centers, gap);
} else if (pat === 'hexagonalblue') {
let centers = generateHexagonCenters(pitch);
// Introduce some noise to hex centers
centers = centers.map(c => {
const angle = Math.random() * 2 * Math.PI;
const radius = (Math.random() - 0.5) * (pitch * voronoiDeviation / 100);
return {
x: c.x + radius * Math.cos(angle),
y: c.y + radius * Math.sin(angle)
};
});
drawVoronoi(sctx, centers, gap);
} else {
sctx.fillStyle = '#fff';
sctx.fillRect(0, 0, src.width, src.height);
sctx.fillStyle = '#000';
for (let y = 1; y < src.height; y += pitch) {
let xoff = 1;
if (pat === 'stagger' && ((y-1) / pitch) % 2) xoff = pitch / 2;
for (let x = -pitch; x < src.width + pitch; x += pitch) {
let gx = x + xoff;
let gy = y;
sctx.fillRect(gx, gy, pitch - gap, pitch - gap);
}
}
}
thresholdImageData(sctx);
}
dctx.clearRect(0, 0, dst.width, dst.height);
dctx.drawImage(src, 0, 0);
applyBoxBlur(dctx, blur);
}
render();
</script>
</body>
</html>