forked from milaflops/dithering
-
Notifications
You must be signed in to change notification settings - Fork 0
/
drawings.js
421 lines (391 loc) · 14.1 KB
/
drawings.js
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
// for drawing grids on canvases and stuff!
// I made this to generate some dithered patterns for crochet
//
// mikayla 2021
// random number cache & regenerator
// this prevents static when changing parameters
// and prevents this static from obfuscating how the sliders change the image
const {makeRandomizer, reRandomize} = (() => {
const lookupSize = 12329; // just an arbitrary prime number
let lookupTable = [];
// run once to populate lookup table, and expose to world for regeneration
const populateLookupTable = () => {
lookupTable = [];
for(let i = 0; i < lookupSize; i++) {
lookupTable.push(Math.random())
}
}
// takes "seed" (rough starting position) from 0-1 & returns a function
// which gives you the next number (looping)
const makeRandomizer = seed => {
let index = Math.round(seed * lookupSize);
return () => {
index = (index + 1) % lookupSize;
return lookupTable[index];
}
}
populateLookupTable();
return {
makeRandomizer,
reRandomize: populateLookupTable
}
})();
// make the base image (noise, gradient, etc.)
const makeBaseImage = ({base, image}) => {
// set comparator for shading the gradient
let comparator = (base.width - 1) + (base.height - 1);
let grid = [];
let rand = makeRandomizer(0.25);
for (let i=0; i<base.height; i++) {
let row = [];
for (let j=0; j<base.width; j++) {
// weight each contribution according to params
row.push((
rand() * image.noise
) + (
((i + j) / comparator) * image.gradient
) + (
0 * image.solidBlack
) + (
1 * image.solidWhite
));
}
grid.push(row);
}
return grid;
}
const duplicateGrid = grid =>
grid.map(row => (
row.map(cell => cell)
))
// diffuse the error in the bulldozer fashion
const floydSteinberg = grid => {
grid = duplicateGrid(grid)
// sloppy input check
const outOfBounds = (row_idx,col_idx) => {
if (row_idx < 0)
return true
else if (row_idx > grid.length - 1)
return true
else if (col_idx < 0)
return true
else if (col_idx > grid[0].length - 1)
return true
}
const getGrid = (row_idx,col_idx) => {
if (outOfBounds(row_idx,col_idx))
return 0
return grid[row_idx][col_idx]
}
const updateGrid = (row_idx,col_idx,newvalue) => {
if (!outOfBounds(row_idx,col_idx))
grid[row_idx][col_idx] = newvalue
}
for(let row_idx = 0; row_idx < grid.length; row_idx++) {
for(let col_idx = 0; col_idx < grid[row_idx].length; col_idx++) {
let oldpixel = grid[row_idx][col_idx]
let newpixel = Math.round(oldpixel)
grid[row_idx][col_idx] = newpixel
let error = oldpixel - newpixel
// x+1, y
updateGrid(row_idx,col_idx+1,getGrid(row_idx,col_idx+1) + (error * (7/16)))
// x - 1, y + 1
updateGrid(row_idx+1,col_idx-1,getGrid(row_idx+1,col_idx-1) + (error * (3/16)))
// x, y+1
updateGrid(row_idx+1,col_idx,getGrid(row_idx+1,col_idx) + (error * (5/16)))
// x + 1, y + 1
updateGrid(row_idx+1,col_idx+1,getGrid(row_idx+1,col_idx+1) + (error * (1/16)))
}
}
return grid;
}
// modify base image
const ditherPrePass = (grid,{dither}) => {
let rand = makeRandomizer(0.75);
let fs_dithered = floydSteinberg(grid)
return grid.map((row,row_idx) => (
row.map((element,col_idx) => (
(
dither.image *
element
) + (
dither.noise *
rand()
) + (
dither.maze * (
(row_idx % 2 == 0 ? 0 : 0.5) +
(col_idx % 2 == 0 ? 0 : 0.5)
)
) + (
dither.checkerboard * (
( row_idx + col_idx ) % 2 == 0 ? 0.25 : 0.75
)
) + (
dither.floydSteinberg *
fs_dithered[row_idx][col_idx]
)
))
))
}
// experimenting with a new blending mode (not super great yet)
const newDitherPrePass = (grid,{dither}) => {
let rand = makeRandomizer(0.75);
return grid.map((row,row_idx) => (
row.map((element,col_idx) => {
let ditherFilter = (
dither.image *
element
) + (
dither.noise *
rand()
) + (
dither.maze * (
(row_idx % 2 == 0 ? 0 : 0.5) +
(col_idx % 2 == 0 ? 0 : 0.5)
)
) + (
dither.checkerboard * (
( row_idx + col_idx ) % 2 == 0 ? 0 : 0.75
)
)
// weight is how close base image is to middle grey
// weight == 0 when image == 0
// weight == 1 when image == 0.5
// weight == 0 when image == 1
let weight = 1 - (Math.abs(element - 0.5) * 2)
return (
(ditherFilter * weight) + (element * (1 - weight))
)
})
))
}
// round up or down to 1 or 0
const posturize = (grid,{base}) => {
return grid.map(row => (
row.map(element => (
(base.posturize ? (element > 0.5 ? 1 : 0) : element)
))
))
}
// compose base image, dither prepass, and posturization
const fullGenerate = params =>
posturize(ditherPrePass(makeBaseImage(params),params),params)
// plant the rectangles onto the grid based on input grid and params
const drawScaledImage = (canvas,grid,params) => {
const ctx = canvas.getContext("2d");
const {contrast, borderWidth} = params.display;
// TODO: come up with a better way to fit the grid into the canvas
// (maybe support margins for stitch number markings, or something?)
// it's just a square now, so I'm leaving it as-is
const scalar = Math.min(canvas.height, canvas.width) / Math.max(grid.length, grid[0].length)
grid.forEach((row,row_idx) => {
row.forEach((cell,col_idx) => {
// contrast only affects final display shade
let shade = 255 * (
(0.5 * (1 - contrast)) +
(cell * contrast)
);
ctx.fillStyle = `rgb(${shade},${shade},${shade})`
ctx.fillRect(
(col_idx * scalar) + borderWidth,
(row_idx * scalar) + borderWidth,
scalar-borderWidth,
scalar-borderWidth
)
})
})
}
const clearCanvas = (canvas) => {
const ctx = canvas.getContext("2d");
ctx.clearRect(0,0,canvas.width,canvas.height)
}
// normalize all "image" params so they total to 1
// and all "dither" params so they total to 1
const normalizeParams = ({base, display, image, dither}) => {
let imageGenTotal = image.noise + image.gradient + image.solidWhite + image.solidBlack;
let ditherTotal = dither.image + dither.noise + dither.maze + dither.floydSteinberg + dither.checkerboard;
// prevent zero division
if (imageGenTotal == 0) {
imageGenTotal = 0.01
}
if (ditherTotal == 0) {
ditherTotal = 0.01
}
return {
base,
display,
image: {
noise: image.noise / imageGenTotal,
gradient: image.gradient / imageGenTotal,
solidWhite: image.solidWhite / imageGenTotal,
solidBlack: image.solidBlack / imageGenTotal
},
dither: {
image: dither.image / ditherTotal,
noise: dither.noise / ditherTotal,
maze: dither.maze / ditherTotal,
floydSteinberg: dither.floydSteinberg / ditherTotal,
checkerboard: dither.checkerboard / ditherTotal
}
}
}
// always good to have throttling on canvas stuff, taken from internet
function throttle(func, wait) {
var context, args, result;
var timeout = null;
var previous = 0;
var later = function() {
previous = Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = Date.now();
if (!previous) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// wait for elements to be on page before rendering
document.addEventListener("DOMContentLoaded", () => {
const canvas = document.getElementById("graphdisplayer");
const parameters = {
base: {
width: 25,
height: 25,
levels: 2,
posturize: true
},
display: {
contrast: 0.75,
borderWidth: 0.5
},
image: {
noise: 0.25,
gradient: 0.75,
solidWhite: 0,
solidBlack: 0
},
dither: {
image: 1,
noise: 0.25,
maze: 0.5,
floydSteinberg: 0,
checkerboard: 0
}
}
// attach to settings sliders
document.getElementById("baseResolution").addEventListener("input", event => {
parameters.base.height = event.target.value;
parameters.base.width = event.target.value;
document.getElementById("baseResolutionDisp").innerHTML = (parameters.base.width + " x " + parameters.base.height);
limitedRedraw()
})
// updates slider text spans with normalized values
// hopefully this helps the user understand how things are being blended
const sliderDisplays = {
image: {
noise: document.getElementById("imageNoiseDisp"),
gradient: document.getElementById("imageGradientDisp"),
solidWhite: document.getElementById("imageSolidWhiteDisp"),
solidBlack: document.getElementById("imageSolidBlackDisp"),
},
dither: {
image: document.getElementById("ditherImageDisp"),
noise: document.getElementById("ditherNoiseDisp"),
maze: document.getElementById("ditherMazeDisp"),
floydSteinberg: document.getElementById("ditherFloydSteinbergDisp"),
checkerboard: document.getElementById("ditherCheckerboardDisp"),
}
}
const percentString = float => Math.round(float * 100) + "%"
const updateSliderDisplays = () => {
params = normalizeParams(parameters);
sliderDisplays.image.noise.innerHTML = percentString(params.image.noise);
sliderDisplays.image.gradient.innerHTML = percentString(params.image.gradient);
sliderDisplays.image.solidWhite.innerHTML = percentString(params.image.solidWhite);
sliderDisplays.image.solidBlack.innerHTML = percentString(params.image.solidBlack);
sliderDisplays.dither.image.innerHTML = percentString(params.dither.image);
sliderDisplays.dither.noise.innerHTML = percentString(params.dither.noise);
sliderDisplays.dither.maze.innerHTML = percentString(params.dither.maze);
sliderDisplays.dither.floydSteinberg.innerHTML = percentString(params.dither.floydSteinberg);
sliderDisplays.dither.checkerboard.innerHTML = percentString(params.dither.checkerboard);
}
// attach listeners to image generation sliders
document.getElementById("imageNoise").addEventListener("input", event => {
parameters.image.noise = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("imageGradient").addEventListener("input", event => {
parameters.image.gradient = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("imageSolidWhite").addEventListener("input", event => {
parameters.image.solidWhite = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("imageSolidBlack").addEventListener("input", event => {
parameters.image.solidBlack = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
// attach listeners to dithering sliders
document.getElementById("ditherImage").addEventListener("input", event => {
parameters.dither.image = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("ditherNoise").addEventListener("input", event => {
parameters.dither.noise = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("ditherMaze").addEventListener("input", event => {
parameters.dither.maze = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("ditherFloydSteinberg").addEventListener("input", event => {
parameters.dither.floydSteinberg = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
document.getElementById("ditherCheckerboard").addEventListener("input", event => {
parameters.dither.checkerboard = event.target.value / 100
updateSliderDisplays()
limitedRedraw()
})
// rerandomize upon button click
document.getElementById("reRandomize").addEventListener("click", event => {
reRandomize()
limitedRedraw()
})
// clear canvas, generate a new grid, and draw onto canvas
const redraw = () => {
clearCanvas(canvas)
let params = normalizeParams(parameters);
let grid = fullGenerate(params);
drawScaledImage(canvas, grid, params)
}
// limit redraws to 15 frames per second
const limitedRedraw = throttle(redraw, 1000 / 15)
redraw()
updateSliderDisplays()
})