-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathsymmetry-sketcher.js
362 lines (296 loc) · 9.5 KB
/
symmetry-sketcher.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
/*
* Symmetry sketcher
*
* Copyright (c) 2022 Project Nayuki
* All rights reserved. Contact Nayuki for licensing.
* https://www.nayuki.io/page/symmetry-sketcher-javascript
*/
"use strict";
/*---- Global variables ----*/
// HTML elements
let canvasElem = element("canvas");
let undoButtonElem = element("undo-button");
let doneButtonElem = element("done-button");
// Graphics initialization
let width = null;
let height = null;
let baseCanvas = document.createElement("canvas"); // Off-screen
let guideCanvas = document.createElement("canvas"); // Off-screen
let baseGfx = baseCanvas .getContext("2d");
let guideGfx = guideCanvas.getContext("2d");
let screenGfx = canvasElem .getContext("2d");
initCanvasesSize();
// Cached values from form inputs
let strokeWidth = null; // Type number, positive
let paintColor = null; // Type string
let backgroundColor = null; // Type string
let rotationSymmetry = null; // Type integer, positive
let mirrorSymmetry = null; // Type boolean
let showGuidelines = null; // Type boolean
// State variables
let isDone = true;
let isMouseDown = false;
let lastCoord = null; // Is null iff isMouseDown is false
let undoImages = [];
undoButtonElem.disabled = undoImages.length == 0;
// Internal configuration
const MAX_UNDO_IMAGES = 5;
function initCanvasesSize() {
width = height = parseInt(document.getElementById("canvas-size").value, 10);
canvasElem.width = guideCanvas.width = baseCanvas.width = width;
canvasElem.height = guideCanvas.height = baseCanvas.height = height;
guideGfx.strokeStyle = "#C0C0FF";
}
/*---- Drawing functions ----*/
// Refreshes the on-screen canvas, and draws onto it a cursor centered at the given coordinates.
function drawHover(x, y) {
screenGfx.drawImage(guideCanvas, 0, 0);
screenGfx.fillStyle = backgroundColor;
const temp = strokeWidth;
strokeWidth *= 1.2;
drawPoint(screenGfx, x, y);
strokeWidth = temp;
screenGfx.fillStyle = paintColor;
drawPoint(screenGfx, x, y);
const crossSize = Math.max(strokeWidth * 2.5, 10);
screenGfx.lineWidth = Math.max(strokeWidth / 8, 1);
screenGfx.beginPath();
screenGfx.moveTo(x - crossSize / 2, y);
screenGfx.lineTo(x + crossSize / 2, y);
screenGfx.moveTo(x, y - crossSize / 2);
screenGfx.lineTo(x, y + crossSize / 2);
screenGfx.stroke();
}
// Symmetrizes the point at the given coordinates, and draws them on the given
// graphics context,using the global stroke width and the graphics context's stroke style.
function drawPoint(gfx, x, y) {
for (const [sx, sy] of getSymmetryPoints(x, y)) {
gfx.beginPath();
gfx.arc(sx, sy, strokeWidth / 2, 0, Math.PI * 2, false);
gfx.fill();
}
}
// Symmetrizes the line between the given coordinates, and draws them on the given
// graphics context, using the global stroke width and the graphics context's stroke style.
function drawLine(gfx, x0, y0, x1, y1) {
const starts = getSymmetryPoints(x0, y0);
const ends = getSymmetryPoints(x1, y1);
gfx.lineWidth = strokeWidth;
gfx.beginPath();
for (let i = 0; i < starts.length; i++) {
gfx.moveTo(starts[i][0], starts[i][1]);
gfx.lineTo(ends [i][0], ends [i][1]);
}
gfx.stroke();
}
// Returns an array of pairs representing the symmetries of the given point coordinates,
// based on the current global rotation symmetry and mirror settings.
function getSymmetryPoints(x, y) {
// The coordinate system has its origin at the center of the canvas,
// has up as 0 degrees, right as 90 deg, down as 180 deg, and left as 270 deg.
const ctrX = width / 2;
const ctrY = height / 2;
const relX = x - ctrX;
const relY = ctrY - y;
const dist = Math.hypot(relX, relY);
const angle = Math.atan2(relX, relY); // Radians
let result = [];
for (let i = 0; i < rotationSymmetry; i++) {
const theta = angle + Math.PI * 2 / rotationSymmetry * i; // Radians
x = ctrX + Math.sin(theta) * dist;
y = ctrY - Math.cos(theta) * dist;
result.push([x, y]);
if (mirrorSymmetry) {
x = ctrX - Math.sin(theta) * dist;
result.push([x, y]);
}
}
return result;
}
// Refreshes the guide canvas based on the base canvas, and draws guidelines if enabled.
function redrawGuideCanvas() {
guideGfx.drawImage(baseCanvas, 0, 0);
if (!showGuidelines)
return;
const halfwidth = width / 2;
const halfheight = height / 2;
guideGfx.lineWidth = 1;
guideGfx.beginPath();
const dist = Math.min(halfwidth, halfheight);
guideGfx.arc(halfwidth, halfwidth, dist, Math.PI * 2, false);
guideGfx.stroke();
guideGfx.beginPath();
guideGfx.moveTo(halfwidth, halfwidth);
let theta = mirrorSymmetry ? 0 : -Math.PI / rotationSymmetry; // Radians
let x = halfwidth + Math.sin(theta) * dist;
let y = halfheight - Math.cos(theta) * dist;
guideGfx.lineTo(x, y);
guideGfx.moveTo(halfwidth, halfwidth);
theta = Math.PI / rotationSymmetry; // Radians
x = halfwidth + Math.sin(theta) * dist;
y = halfheight - Math.cos(theta) * dist;
guideGfx.lineTo(x, y);
guideGfx.stroke();
}
function updatePaintColor() {
baseGfx.strokeStyle = paintColor;
baseGfx.fillStyle = paintColor;
screenGfx.strokeStyle = paintColor;
screenGfx.fillStyle = paintColor;
}
// Clears the base canvas, redraws the guide canvas, and redraws the on-screen canvas.
function clearBaseCanvas() {
baseGfx.fillStyle = backgroundColor;
baseGfx.fillRect(0, 0, width, height);
baseGfx.fillStyle = paintColor;
redrawGuideCanvas();
screenGfx.drawImage(guideCanvas, 0, 0);
}
function getLocalCoordinates(ev) {
return [ev.offsetX + 0.5, ev.offsetY + 0.5];
}
/*---- Event handlers ----*/
// Handlers for canvas element
canvasElem.onmouseover = ev => {
if (isDone)
return;
const coord = getLocalCoordinates(ev);
drawHover(coord[0], coord[1]);
};
canvasElem.onmousemove = ev => {
if (isDone)
return;
const coord = getLocalCoordinates(ev);
if (isMouseDown) {
drawPoint(baseGfx, coord[0], coord[1]);
if (lastCoord !== null)
drawLine(baseGfx, coord[0], coord[1], lastCoord[0], lastCoord[1]);
redrawGuideCanvas();
lastCoord = coord;
}
drawHover(coord[0], coord[1]);
};
canvasElem.onmouseout = () => {
if (isDone)
return;
screenGfx.drawImage(guideCanvas, 0, 0);
canvasElem.onmouseup();
};
canvasElem.onmousedown = ev => {
if (!isDone && !isMouseDown) {
undoImages.push(baseGfx.getImageData(0, 0, width, height));
if (undoImages.length > MAX_UNDO_IMAGES)
undoImages.splice(0, undoImages.length - MAX_UNDO_IMAGES);
undoButtonElem.disabled = undoImages.length == 0;
isMouseDown = true;
const coord = getLocalCoordinates(ev);
drawPoint(baseGfx, coord[0], coord[1]);
redrawGuideCanvas();
drawHover(coord[0], coord[1]);
lastCoord = coord;
}
};
canvasElem.onmouseup = () => {
isMouseDown = false;
lastCoord = null;
};
canvasElem.onwheel = ev => {
if (isDone)
return;
if (!isMouseDown && !isNaN(strokeWidth)) {
// Scroll up to increase stroke width, down to decrease
const step = -ev.deltaY / Math.abs(ev.deltaY); // Signum
strokeWidth *= Math.pow(10, step / 10);
strokeWidth = Math.max(strokeWidth, 0.1);
strokeWidth = Math.min(strokeWidth, 300);
element("stroke-width").value = strokeWidth.toFixed(2);
const coord = getLocalCoordinates(ev);
drawHover(coord[0], coord[1]);
}
return false;
};
canvasElem.oncontextmenu = () => {
if (!isDone)
return false;
};
// Handlers for form input elements
setAndCallHandler("stroke-width", "oninput", function() {
strokeWidth = parseFloat(this.value);
});
setAndCallHandler("paint-color", "oninput", function() {
paintColor = this.value;
updatePaintColor();
});
setAndCallHandler("background-color", "oninput", function() {
backgroundColor = this.value;
});
setAndCallHandler("rotation-symmetry", "oninput", function() {
rotationSymmetry = parseInt(this.value, 10);
redrawGuideCanvas();
screenGfx.drawImage(guideCanvas, 0, 0);
});
setAndCallHandler("mirror-symmetry", "onchange", function() {
mirrorSymmetry = this.checked;
redrawGuideCanvas();
screenGfx.drawImage(guideCanvas, 0, 0);
});
setAndCallHandler("show-guidelines", "onchange", function() {
showGuidelines = this.checked;
redrawGuideCanvas();
screenGfx.drawImage(guideCanvas, 0, 0);
});
// Handlers for button elements
element("clear-button").onclick = () => {
if (confirm("Clear the drawing?")) {
initCanvasesSize();
updatePaintColor();
clearBaseCanvas();
if (isDone)
doneButtonElem.onclick();
undoImages = [];
undoButtonElem.disabled = true;
}
};
undoButtonElem.onclick = () => {
baseGfx.putImageData(undoImages.pop(), 0, 0);
undoButtonElem.disabled = undoImages.length == 0;
redrawGuideCanvas();
screenGfx.drawImage(guideCanvas, 0, 0);
};
doneButtonElem.onclick = () => {
if (isDone) {
doneButtonElem.value = "Done";
isDone = false;
canvasElem.style.removeProperty("cursor");
} else {
doneButtonElem.value = "Resume";
isDone = true;
undoImages = [];
undoButtonElem.disabled = true;
screenGfx.drawImage(baseCanvas, 0, 0);
canvasElem.style.cursor = "unset";
}
};
document.onkeydown = ev => {
if (!isMouseDown && undoImages.length > 0 && ev.key == "z" && ev.ctrlKey) {
undoButtonElem.onclick();
return false;
}
};
// For the text boxes, confine keystrokes to the element itself and not propagate to the document root
for (let elem of document.getElementsByTagName("input"))
elem.onkeypress = ev => ev.stopPropagation();
/*---- Utilities and initialization ----*/
function setAndCallHandler(elemName, eventName, func) {
let elem = element(elemName);
elem[eventName] = func;
func.call(elem);
}
function element(name) {
let result = document.getElementById(name);
if (result === null)
throw new RangeError("Element ID not found: " + name);
return result;
}
clearBaseCanvas();
doneButtonElem.onclick();