-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
462 lines (380 loc) · 11.3 KB
/
main.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
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
/**
* @author Hagar Shilo <[email protected]>
*/
"use strict";
// DO EVERYTHING
$(function(){
/*
var mobile_flag = true;
if (!(/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()))) {
mobile_flag = false; // TODO Change back to false when done testing
}
*/
var canvas, ctx, flag = false,
prevCoords = [0,0],
currCoords = [0,0],
dot_flag = false,
w,
h,
canvasHistory = [],
historyIndex = 0;
// localStorage settings
function settingsVariable(name, defaultValue) {
if (!localStorage.getItem(name)) {
localStorage.setItem(name, defaultValue);
}
return {
get: function() {
return localStorage.getItem(name);
},
set: function(value) {
localStorage.setItem(name, value);
}
};
}
var settings = {
currentColor: settingsVariable('currentColor', '#449afc'),
lineWidth: settingsVariable('lineWidth', 2),
rotationsNum: settingsVariable('rotationsNum', 5),
doReflect: settingsVariable('doReflect', true)
};
$(".do-reflect").change(function() {
if(this.checked) {
settings.doReflect.set(true);
}
else {
// This is a hack, meant to fix a bug quickly. I pass an empty string
// instead of the boolean value false, because localStorage converts
// everything into string, which means it reads 'false' as a non-empty
// string, which absurdly makes its boolean value TRUE (badness ensues).
settings.doReflect.set('');
}
});
// Pre-paint the canvas white - should be called on clear(); too
function paintWhite(){
ctx.beginPath();
ctx.rect(0, 0, w, h);
ctx.fillStyle = "white";
ctx.fill();
canvasHistory = [canvas.toDataURL()]; // clear undo/redo history
historyIndex = 0;
}
// Draw background grid
// function drawBoard(){
// ctx.moveTo(w/2,0);
// ctx.lineTo(w/2,h);
// ctx.moveTo(0,h/2);
// ctx.lineTo(w,h/2);
// ctx.lineWidth = 1; // So line doesn't change to user settings
// ctx.strokeStyle = "#f5f5f5";
// ctx.stroke();
// }
function init() {
window.onbeforeunload = warnBeforeLeave;
// Create and display canvas for either desktop or mobile device
function setCanvasSize(){
if (isMobile()){
canvas = document.getElementById('mobile-canvas');
$('#mobile').show();
if (window.innerWidth < window.innerHeight) {
canvas.width = canvas.height = window.innerWidth - 30;
}
else {
canvas.height = window.innerHeight - $('#menu').height();
canvas.width = window.innerHeight - $('#menu').height();
}
}
else {
canvas = document.getElementById('desktop-canvas');
$('#desktop').show();
canvas.height = window.innerHeight-35;
canvas.width = window.innerHeight-35;
}
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
}
setCanvasSize();
// Pre-paint canvas so it has white bg on save
paintWhite();
// Drow bg grid
// drawBoard();
// Handle mouse/touch events
$('canvas').on('mousemove', function (e) {
handleMouseMove(e.clientX, e.clientY);
});
$('canvas').on('touchmove', function (e) {
e.preventDefault();
handleMouseMove(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
});
$('canvas').on('mousedown', function (e) {
handleMouseDown(e.clientX, e.clientY);
});
$('canvas').on('touchstart', function (e) {
e.preventDefault();
handleMouseDown(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
});
$('canvas').on('mouseup mouseout', function (e) {
stopDrawing();
});
$('canvas').on('touchend touchcancel', function (e) {
e.preventDefault();
stopDrawing();
});
// Color picker selection palette
$(".selectionPalette").spectrum({
showPalette: true,
maxSelectionSize: 100,
togglePaletteOnly: true,
showInitial: true,
color: settings.currentColor.get(),
chooseText: "Save color",
palette: [ ],
showSelectionPalette: true, // true by default
hideAfterPaletteSelect:true,
selectionPalette: [ ],
change: function(color){
settings.currentColor.set(color.toHexString());
},
move: function(color){
settings.currentColor.set(color.toHexString());
}
});
// Hide color picker when mouse leaves the selection palette
$(".sp-container").mouseleave(function () {
$(".selectionPalette").spectrum("hide");
});
// Handle download of an image file of the canvas
// No support for some iOS devices at this point
// Some iPhone users may need jpg format
$('.btn-download').click(function () {
if (isMobile()) {
document.getElementById("mobile-canvas").toBlob(function(blob) {
saveAs(blob, 'Mandala.jpg');
});
}
else {
document.getElementById("desktop-canvas").toBlob(function(blob) {
saveAs(blob, 'Mandala.jpg');
});
}
});
/*
//TODO try this for creating a URL
$('.btn-url').click(function () {
var dataURL = canvas.toDataURL();
alert(dataURL);
});
*/
// Clear the canvas
$('.btn-clear').click(clear);
// read lineWidth from localStorage
$('.line-width').val(settings.lineWidth.get());
// Read rotations-num from localStorage
$('.rotations-num').val(settings.rotationsNum.get());
// Read do-reflect from localStorage
$('.do-reflect').attr(settings.doReflect.get());
}
init();
// Let user set brush size
$(".line-width").bind('keyup mouseup', function () {
settings.lineWidth.set($(this).val());
});
//Allow user to change the number of rotations
$(".rotations-num").bind('keyup mouseup', function () {
settings.rotationsNum.set($(this).val());
});
// Flip the coordinates
function flip(x,y) {
var y = h-y;
var coordinateArray = [x,y];
return coordinateArray;
}
// Draw a dot in response to a single mouse click
function drawDot() {
ctx.fillStyle = settings.currentColor.get();
// Array of coordinate pairs
var origPointAndItsRotations = [
currCoords // These are initialized at the top of the big inclusive function
];
// Store rotation coordinates in an array
while (origPointAndItsRotations.length<settings.rotationsNum.get()) {
var x_,y_;
[x_,y_] = origPointAndItsRotations[origPointAndItsRotations.length-1];
origPointAndItsRotations.push(rotate(x_,y_,settings.rotationsNum.get()));
}
// Draw the rotation coordinates kept in the array
for (var i=0; i<settings.rotationsNum.get(); i++) {
ctx.beginPath();
ctx.arc(
origPointAndItsRotations[i][0],
origPointAndItsRotations[i][1],
settings.lineWidth.get() / 2,
0,
2 * Math.PI
);
ctx.fill();
}
if (settings.doReflect.get()) {
var flippedCoordinates = []; // Array of arrays
/**
* Reflects the rotated coordinates
*/
for (var i=0; i<settings.rotationsNum.get(); i++) {
// Get flipped coordinates and store in vars a,b
var a = origPointAndItsRotations[i][0];
var b = origPointAndItsRotations[i][1];
// Flip coordinates
var flipResult = flip(a,b);
// Add flipped coordinates to array
flippedCoordinates.push(flipResult);
}
// Draw/display the flipped coordinates kept in the array
for (var i=0; i<settings.rotationsNum.get(); i++) {
ctx.beginPath();
ctx.arc(
flippedCoordinates[i][0],
flippedCoordinates[i][1],
settings.lineWidth.get() / 2,
0,
2 * Math.PI
);
ctx.fill();
}
}
}
// Calculate rotations and store rotated coordinates in array
function rotate(x,y,numOfRotations){
var c = Math.cos(2*Math.PI/numOfRotations);
var s = Math.sin(2*Math.PI/numOfRotations);
var x2 = c*(x-w/2)+s*(h/2-y)+w/2;
var y2 = c*(y-h/2)+s*(x-w/2)+h/2;
var coordinateArray = [x2,y2];
return coordinateArray;
}
// Draw/display lines where the user drags the mouse
function drawLine() {
var x, y, a;
ctx.beginPath();
var lineStartPoints = [
prevCoords
];
var lineEndPoints = [
currCoords
];
// Rotate line start point coordinates and store the rotation coordinates in an array
while (lineStartPoints.length<settings.rotationsNum.get()) {
a = lineStartPoints[lineStartPoints.length-1];
x = a[0];
y = a[1];
lineStartPoints.push(rotate(x,y,settings.rotationsNum.get()));
}
// Rotate line end point coordinates and store the rotation coordinates in an array
while (lineEndPoints.length<settings.rotationsNum.get()) {
a = lineEndPoints[lineEndPoints.length-1];
x = a[0];
y = a[1];
lineEndPoints.push(rotate(x,y,settings.rotationsNum.get()));
}
for (var i=0; i<settings.rotationsNum.get(); i++) {
ctx.moveTo(lineStartPoints[i][0],lineStartPoints[i][1]);
ctx.lineTo(lineEndPoints[i][0],lineEndPoints[i][1]);
}
/**
* Reflects the rotated coordinates
*/
if (settings.doReflect.get()) {
var flippedLineStartPoints = [];
for (var i=0; i<settings.rotationsNum.get(); i++) {
flippedLineStartPoints.push(flip(lineStartPoints[i][0],lineStartPoints[i][1]));
}
var flippedLineEndPoints = [];
for (var i=0; i<settings.rotationsNum.get(); i++) {
flippedLineEndPoints.push(flip(lineEndPoints[i][0],lineEndPoints[i][1]));
}
for (var i=0; i<settings.rotationsNum.get(); i++) {
ctx.moveTo(flippedLineStartPoints[i][0],flippedLineStartPoints[i][1]);
ctx.lineTo(flippedLineEndPoints[i][0],flippedLineEndPoints[i][1]);
}
}
// Brush settings
ctx.strokeStyle = settings.currentColor.get();
ctx.lineWidth = settings.lineWidth.get();
ctx.lineCap = 'round';
// Display the linez
ctx.stroke();
ctx.closePath();
}
// Confirm before clearing the canvas
function clear() {
var m = confirm("Clear everything?");
if (m) {
// Removing paintWhite below will make the clear steps undone-able
// (once undo function is written).
ctx.clearRect(0, 0, w, h);
paintWhite();
// drawBoard();
}
}
function eventToCanvasCoords(x, y) {
var rect = canvas.getBoundingClientRect();
return [x - rect.left, y - rect.top];
}
function handleMouseDown(x, y) {
currCoords = eventToCanvasCoords(x, y);
flag = true;
dot_flag = true;
if (dot_flag) {
drawDot();
dot_flag = false;
}
}
function stopDrawing() {
if (flag) {
// Update canvas undo/redo history
canvasHistory = canvasHistory.slice(0, historyIndex+1);
canvasHistory.push(canvas.toDataURL());
historyIndex++;
}
flag = false;
}
function handleMouseMove(x, y) {
if (flag) {
prevCoords = currCoords;
currCoords = eventToCanvasCoords(x, y);
drawLine();
}
}
/* Undo / Redo */
function undo() {
if (historyIndex > 0) {
historyIndex--;
updateDisplay();
}
}
function redo() {
if(historyIndex < canvasHistory.length-1) {
historyIndex++;
updateDisplay();
}
}
function updateDisplay() {
var img = new window.Image();
img.onload = function(){
ctx.drawImage(img ,0 ,0);
};
img.src = canvasHistory[historyIndex];
}
$('.btn-undo').click(undo);
$(document).on('keypress', function(e){
var zKey = 26;
if(e.ctrlKey && e.which === zKey){
undo()
}});
$('.btn-redo').click(redo);
$(document).on('keypress', function(e){
var yKey = 25;
if(e.ctrlKey && e.which === yKey){
redo();
}});
});