-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1763 lines (1499 loc) · 51.8 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
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const EditorVersion = "0.6.0";
//
// Setup
//
// start the program when the window has loaded
window.addEventListener("load", setup, false);
function setup() {
// elements
// canvases
Els.editor = document.querySelector("#editor"); // main image canvas (this is exported at the end)
Els.transparency = document.querySelector("#transparency"); // transparency canvas
Els.overlay = document.querySelector("#overlay"); // overlay canvas (where save selection darkening is drawn)
Els.saveCanvas = document.querySelector("#saveCanvas"); // image save canvas (always hidden)
Els.template = document.querySelector("#template"); // template canvas
// hidden elements (shown when a certain menu is opened)
Els.savedImageWrapper = document.querySelector("#savedImageWrapper"); // save art wrapper (hidden unless saved art is shown)
Els.loadArtLocalWrapper = document.querySelector("#loadArtLocalWrapper"); // load art wrapper (hidden until load art to local storage)
Els.metadataWrapper = document.querySelector("#metadataWrapper"); // metadata wrapper (hidden until art metadata is changed)
Els.loadArtJSONWrapper = document.querySelector("#loadArtJSONWrapper"); // file upload screen
Els.updateWrapper = document.querySelector("#updateWrapper"); // load art wrapper (hidden until load art to local storage)
Els.uploadTemplateWrapper = document.querySelector("#uploadTemplateWrapper"); // file upload screen
// settings
Els.toolButtons = document.getElementsByName("tool"); // tool setting radio buttons
Els.colorWell = document.querySelector("#colorWell"); // color well
Els.colorHexInput = document.querySelector("#colorHexInput"); // hexadecimal input of color
Els.brushSizeSelect = document.querySelector("#brushSizeSelect"); // brush size
Els.localStoreEnabled = document.querySelector("#localStoreEnabled"); // local storage on setting
// texturer
Els.texturerCheckbox = document.querySelector("#texturerCheckbox"); // on or off
Els.texturerDepth = document.querySelector("#texturerDepth"); // number input - amount to texture by
// symmetry
Els.verticalSymCheckbox = document.querySelector("#verticalSymCheckbox"); // on or off
Els.horizontalSymCheckbox = document.querySelector("#horizontalSymCheckbox"); // on or off
// template
Els.templateInput = document.querySelector("#templateInput");
Els.templateInput.addEventListener('change', uploadTemplate, false);
Els.templateTransparency = document.querySelector("#templateTransparency");
// metadata inputs
Els.artNameInput = document.querySelector("#artNameInput"); // art name
Els.authorInput = document.querySelector("#authorInput"); // author name
// load from local storage output
Els.savedArtList = document.querySelector("#savedArtList"); // list of saved art
// upload JSON file input
Els.artInput = document.querySelector("#artInput");
// tool radio button elements
Els.toolBrush = document.querySelector("#toolBrush");
Els.toolFill = document.querySelector("#toolFill");
Els.toolEraser = document.querySelector("#toolEraser");
Els.toolEraserFill = document.querySelector("#toolEraserFill");
Els.toolColorPicker = document.querySelector("#toolColorPicker");
// canvas context
Ctx.editor = Els.editor.getContext('2d');
Ctx.transparency = Els.transparency.getContext('2d');
Ctx.overlay = Els.overlay.getContext('2d');
Ctx.template = Els.template.getContext('2d');
// brush
Tool = "brush";
Brush.color = Els.colorWell.value; // default color
Els.brushSizeSelect.addEventListener("change", updateBrushSize, false);
init();
// update the brush color upon color change
Els.colorWell.addEventListener("change", updateColor, false);
Els.colorWell.select();
Els.colorHexInput.addEventListener("change", updateColor, false);
// local storage
setLocaStorageSetting(); // radio button
loadCurrentArt(); // load art if setting is on
// canvas event listeners (for painting)
// added to overlay because it is on top
Els.overlay.addEventListener("mousemove", paint); // paint tile if mouse is moved (checks if mouse is down)
Els.overlay.addEventListener("mousedown", mouseDown); // mouse set to down
Els.overlay.addEventListener("mouseup", mouseUp); // mouse set to up
Els.overlay.addEventListener("mouseout", mouseUp); // also set mouse to up when user leaves the canvas with mouse
// hotkeys
document.addEventListener("keydown", function (event) {
switch (event.key) {
case "z":
// undo
if (event.ctrlKey) {
undo();
}
break;
case "y":
// redo
if (event.ctrlKey) {
redo();
}
break;
case "s":
// save
if (event.ctrlKey) {
if (event.altKey) {
// selection
saveArtSelection();
}
else {
// whole thing
saveArt(Els.editor);
}
// avoid it being
event.preventDefault();
}
break;
// tools
case "1":
// brush
Els.toolBrush.checked = true;
break;
case "2":
// fill
Els.toolFill.checked = true;
break;
case "3":
// eraser
Els.toolEraser.checked = true;
break;
case "4":
// eraser fill
Els.toolEraserFill.checked = true;
break;
case "5":
// color picker
Els.toolColorPicker.checked = true;
break;
case "6":
// texturer
Els.texturerCheckbox.checked = !Els.texturerCheckbox.checked;
break;
}
});
}
//
// Init new canvas (called every time a new canvas is created, e.g. canvas resized)
//
function init() {
updateBrushSize(); // set canvas size variables, set brush.size value, and draw transparency grid
initImageData();
// reset undo and redo
undoArray = [];
redoArray = [];
// reset metadata
Els.artNameInput.value = "";
Els.authorInput.value = "";
// add deep copied version of empty image data to undoArray
undoArray.push(deepCopyImageData(ImageData));
}
// fill transparency grid background (grey and white)
// called on init and whenever brush size changes
function drawTransparency() {
// clear canvas
Ctx.transparency.clearRect(0, 0, Els.transparency.width, Els.transparency.height);
// set color for drawing
Ctx.transparency.fillStyle = "#eeeeee"; // tbd more specific color?
let cols = Els.editor.width / Brush.size;
let rows = Els.editor.height / Brush.size;
// for loops to draw squares in checkerboard pattern
for (let col = 0; col < cols; col++) {
for (let row = col % 2; row < rows; row += 2) {
// +=2 to make every other square grey
// starting position alternates between 0 and 1
Ctx.transparency.fillRect(col * Brush.size, row * Brush.size, Brush.size, Brush.size);
// +1 so border is not drawn on
}
}
}
// initialise art variable as a transparent canvas
// imageData[x][y] gets the (x,y) coord in imageData
function initImageData() {
ImageResolution = 16;
// reset imageData
ImageData = [];
let cols = Els.editor.width / 16;
let rows = Els.editor.height / 16;
for (let col = 0; col < cols; col++) {
let foo = [];
for (let row = 0; row < rows; row++) {
foo[row] = undefined; // undefined = transparent
}
ImageData[col] = foo;
}
}
//
// Global variable definition
//
var ImageData = [];
var ImageResolution = 16; // resolution of image data (brush size for each element)
var Brush = {};
var Tool = "";
var Els = {}; // elements
var Ctx = {}; // canvas contexts
var mouseIsDown = false; // set to false when mouse is up (on editor canvas) and true when it is down
var saving = false; // set to the save dimensions when the image is in the process of being saved
var undoArray = []; // array of previous canvas state ImageDatas (saved on mouse up)
var redoArray = []; // array of future canvas state ImageDatas (added to by undo function and wiped on mouse down)
// the empty image data is added to undoArray by the init function
var afterMetadataClose; // set to a function that should be called after metadata is closed
var previousPaintedTile = {}; // set to the tile that was last painted (row and col)
var previousPaintedColor = undefined; // set to the Color of the tile that was last painted
var texturedTiles = []; // records textured tiles and their colors at the start of each fill, to make sure texturing size is even across fill
//
// Event listener functions
//
// called on mouse down
function mouseDown(event) {
mouseIsDown = true; // set to down
if (saving !== false) {
// saving selection
if (saving.startPos === undefined) {
let position = findTileAtMouse(event, Brush.size);
// saving start position has not been saved yet
saving.startPos = position;
}
}
else {
// not saving
// remove any redos from the player now they are drawing
redoArray = [];
// update selected tool (since it can only be changed before mouseDown is called - not whilst mouse is down)
Tool = getSelectedTool();
// paint should not be called if the action does not occur on mouse dragging
if (Tool === "colorPicker") {
// set color to picked color
// 4 is used as the brush size so that resolution doesn't matter
setColor(getTileAtMouse(event));
}
else if (Tool === "fill" || Tool === "eraserFill") {
// 4 is used as the brush size so that resolution doesn't matter
fillStart(findTileAtMouse(event, 4));
}
else {
paint(event); // initial paint tile (for click)
// note paint is also called on mouse drag, and subsequently calls either setTile or eraseTile
}
}
}
// called on mouse up or leave
function mouseUp(event) {
mouseIsDown = false; // set to up
if (saving !== false && saving.startPos !== undefined) {
// saving selection
// save finish position for saving
let position = findTileAtMouse(event, Brush.size);
saving.finishPos = position;
// image save popup
// the image is copied to another canvas that is set to the desired size - the image on this other cangvas is hence saved
// thanks to https://stackoverflow.com/a/16974203/9713957
// set starting variable values (because user would not have always started at top left)
let startPos = {
col: Math.min(saving.startPos.col, saving.finishPos.col),
row: Math.min(saving.startPos.row, saving.finishPos.row),
};
let finishPos = {
col: Math.max(saving.startPos.col, saving.finishPos.col),
row: Math.max(saving.startPos.row, saving.finishPos.row),
};
// set image properties from saving variables
let clippingX = startPos.col * Brush.size;
let clippingY = startPos.row * Brush.size;
let imageWidth = finishPos.col * Brush.size - clippingX + Number(Brush.size);
let imageHeight = finishPos.row * Brush.size - clippingY + Number(Brush.size);
// set size of save canvas
Els.saveCanvas.width = imageWidth;
Els.saveCanvas.height = imageHeight;
// draw the image onto the save canvas
Els.saveCanvas.getContext('2d').drawImage(Els.editor, clippingX, clippingY, imageWidth, imageHeight, 0, 0, imageWidth, imageHeight);
saveArt(Els.saveCanvas);
}
else if (Tool !== "colorPicker") {
// not saving nor colorpicking hence art has been changed; save this version of the art to undoArray
// check the art has changed
if (JSON.stringify(undoArray[undoArray.length-1]) !== JSON.stringify(ImageData)) {
// deep copy image data array (so it does not change when in undoArray)
let currentImageData = deepCopyImageData(ImageData);
// add to undo history
undoArray.push(currentImageData);
// save to local storage if user has setting enabled (so they can refesh and it is still there)
saveCurrentArt();
}
}
}
//
// Setting functions
//
// returns the currently selected tool (called on mouseDown to set Tool)
function getSelectedTool() {
for (let i = 0; i < Els.toolButtons.length; i++) {
if (Els.toolButtons[i].checked) {
// selected tool found
return Els.toolButtons[i].value;
}
}
}
// set brush color (called from color picker element with event object)
function updateColor(event) {
setColor(event.target.value);
}
// set brush color
function setColor(color) {
// test color is a hexadecimal value
let regExp = new RegExp(/^#[0-9A-F]{6}$/i);
if (regExp.test(color)) {
// is a hex value
Brush.color = color;
Els.colorWell.value = color; // update value shown on color well
Els.colorHexInput.value = color; // update value in hexadecimal input
// canvas fill color is updated on every tile set (to allow for texturer to work if it is enabled)
}
}
// update brush size and transparency background
function updateBrushSize() {
Brush.size = Els.brushSizeSelect.options[Els.brushSizeSelect.selectedIndex].value; // brush size
drawTransparency(); // background
}
// init art selection save
function saveArtSelection() {
// check that nothing is being currently saved
if (saving === false) {
saving = {}; // ready for startPos and finishPos to be saved, in the format of an object with row and col parameters
// fill in overlay canvas
Ctx.overlay.globalAlpha = 0.3;
Ctx.overlay.fillRect(0, 0, Els.overlay.width, Els.overlay.height);
}
}
// save art based on a canvas
// parameter is canvas element which should be saved (this might be the saveCanvas if only a subsection of the data is being saved)
function saveArt(canvas) {
// create image element
let img = canvas.toDataURL("image/png");
let imgEl = document.createElement("img");
imgEl.src = img;
imgEl.id = "savedImage"; // for styling (positioned in centre)
// append it to saved image wrapper
Els.savedImageWrapper.appendChild(imgEl);
// set saving variable so the editor is aware that an image is showing
// this is set back to closed once the image is dismissed, in order to stop two images being shown at once
saving = "saved";
// show the whole wrapper (image and close button)
Els.savedImageWrapper.hidden = false;
}
// close the saved art being shown, hence allowing the user to draw / save again
function closeSavedArt() {
let element = document.getElementById("savedImage"); // get the image
if (element !== null) {
// there is a saved image showing
element.parentNode.removeChild(element); // remove it
// reset saving variable so user can draw again
saving = false;
// hide the whole wrapper (image and close button)
Els.savedImageWrapper.hidden = true;
// clear overlay canavs
Ctx.overlay.clearRect(0, 0, Els.overlay.width, Els.overlay.height);
}
}
// user setting to clear the editor canvas
function clearAll() {
if (confirm("Are you sure you want to clear the canvas? The previous states will still be accessible in the undo history.")) {
clearCanvas(true);
}
}
// set the dimensions of the canvases
// this clears any existing drawing on it
function setDimensions() {
// check they are happy for their art to be cleared
if (confirm("Are you sure you want to resize the canvas? This will clear any existing art on it and remove the undo history.")) {
// take inputs
let width = parseInt(prompt("Please enter pixel width value for canvas (leave blank to remain the same)"));
let height = parseInt(prompt("Please enter height width value for canvas (leave blank to remain the same)"));
resizeCanvas(width, height);
}
}
// user setting to reset (re-init) the editor canvas
function resetCanvas() {
if (confirm("Are you sure you want to reset the canvas? This will also reset the canvas dimensions and delete the undo history.")) {
// reset height and width to their default values
// also re-inits canvas
resizeCanvas(512, 512);
}
}
// open and init local storage import menu
function loadArtLocalMenu(canvas) {
if (confirmLocalStorage()) {
// local storage enabled
// parse the array of saved art so .metadata and .imageData can be accessed for each element
let savedArtArray = parseArtArray(localStorage.getItem("savedArt"));
if (savedArtArray !== null) {
// art has been saved before
// init the menu
loadArtLocalMenuUpdate(savedArtArray);
// show the whole wrapper
Els.loadArtLocalWrapper.hidden = false;
}
else {
// no need to open menu since nothing has been saved
alert("You have no local saved art to load!");
}
}
}
// re-init the display of the load art local menu
function loadArtLocalMenuUpdate(savedArtArray) {
// wipe the previously generated saved art list
Els.savedArtList.innerHTML = "";
if (savedArtArray == null || savedArtArray.length === 0) {
// parameter is undefined, null, or empty (double equals are intentional to catch undefined)
// no art to display; display a nice message instead
Els.savedArtList.innerHTML += "No local saved art to be shown."
}
else {
// now add art to the saved art list from the saved art array
for (let i = 0; i < savedArtArray.length; i++) {
// delete art from local storage element
let deleteArtElement = document.createElement('span');
// styling
deleteArtElement.classList.add("artDeleteButton");
deleteArtElement.innerText = "delete";
// onclick to delete the art (done via closure)
deleteArtElement.onclick = createArtDeleteOnclick(savedArtArray[i].metadata.name);
// add the element!
Els.savedArtList.appendChild(deleteArtElement);
// list element the art is contained in
let listElement = document.createElement('li');
// add onclick to load the art
listElement.onclick = createArtLoadOnclick(savedArtArray[i].imageData, savedArtArray[i].metadata);
// displayed text for the art
// name
listElement.innerHTML += "<strong>" + savedArtArray[i].metadata.name + "</strong>";
// last edited
listElement.innerHTML += " <i>(last edited: " + savedArtArray[i].metadata.date + ")</i>";
// add the element!
Els.savedArtList.appendChild(listElement);
}
}
}
// save art as JSON file
function saveArtJSON() {
if (confirmMetadata(saveArtJSON)) {
// metadata is fine
// get the art's JSON
let artJSON = getArtJSON();
// create the file
let filename = Els.artNameInput.value + ".json";
let blob = new Blob([artJSON], {type: "text/plain"});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
}
else {
let e = document.createEvent("MouseEvents");
let a = document.createElement("a");
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ["text/plain", a.download, a.href].join(":");
e.initEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
}
}
// called once an uploaded file has been confirmed
function readUploadedFile() {
const file = Els.artInput.files[0];
if (file !== undefined) {
// set up new file reader
let reader = new FileReader();
let fileContents;
// called by readAsText
reader.onload = (function(e) {
contents = e.target.result;
// now use these contents
loadArtJSON(contents);
// close the menu and reset the file input
Els.loadArtJSONWrapper.hidden = true;
Els.artInput.value = null;
});
// read as text
reader.readAsText(file);
}
else {
alert("No file selected!");
}
}
//
// Tile finding functions
//
// take into account scrolled viewport and moved canvas
function getMouseCoords(event) {
let rect = Els.editor.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
return {x: x, y: y};
}
// find tile to draw, based on mouse position
// returns object with properties col (column) and row
// based on brush size (returns col and row in the transparency grid)
// resolution = brush size (detail to look at the canvas)
function findTileAtMouse(event, resolution) {
let mouseCoords = getMouseCoords(event);
return findTileAtCoords(mouseCoords.x, mouseCoords.y, resolution);
}
// find tile at coordinates
// returns object with properties col (column) and row
// based on brush size (returns col and row in the transparency grid)
// resolution = brush size (detail to look at the canvas)
function findTileAtCoords(x, y, resolution) {
let col = Math.floor(x / resolution);
let row = Math.floor(y / resolution);
return {col: col, row: row};
}
// get the contents of the tile at the mouse's position
// resolution used is the smallest possible (4)
function getTileAtMouse(event) {
return getTile(findTileAtMouse(event, 4), 4);
}
// get the contents of the tile at a specific position (row col object from findTile)
// note that this could return an object if the brush's size is larger than the resolution of the tile
// resolution = resolution used to generate tile
function getTile(position, resolution) {
let sizeFactor = resolution/ImageResolution; // used to find x and y in imageData
let imageDataX = position.col * sizeFactor;
let imageDataY = position.row * sizeFactor;
// indices in imageData that the pixel can be found within
let indexX = Math.floor(imageDataX);
let indexY = Math.floor(imageDataY);
let imageDataMultiplier = 1; // used to calculate which array to index into, incrememented by factors of 2 in while loop
let pixel = ImageData[indexX][indexY];
// repeat until resolution of returned tile is equal to resolution (for smaller brush sizes within a pixel)
for (let size = 16; size > resolution; size /= 2) {
if (Array.isArray(pixel)) {
// still more that can be indexed into
// find whether selected pixel is in top/bottom left/right of "pixel" variable
let pixelLocation;
if (imageDataY % (1/imageDataMultiplier) < 0.5 / imageDataMultiplier) {
// top
pixelLocation = 0;
}
else {
// bottom
pixelLocation = 2;
}
if (imageDataX % (1/imageDataMultiplier) < 0.5 / imageDataMultiplier) {
// left
}
else {
// right
pixelLocation++;
}
pixel = pixel[pixelLocation];
imageDataMultiplier *= 2;
}
else {
break;
}
}
return pixel;
}
// returns true or false depending on if the tile is on the canvas
// position is an object in the same format as the one returned by findTile functions (varies based on brush size)
// resolution = resolution used to generate position (in findTile)
function tileIsOnCanvas(position, resolution) {
let sizeFactor = resolution / ImageResolution;
// indices in image data it can be found in
let imageDataX = Math.floor(position.col * sizeFactor);
let imageDataY = Math.floor(position.row * sizeFactor);
if (ImageData.hasOwnProperty(imageDataX) && ImageData[imageDataX].hasOwnProperty(imageDataY)) {
return true;
}
return false;
}
//
// Canvas functions (tools)
//
// paint a tile
// this function is called on mouse move, hence it needs to check if the mouse is up or down first
// TBD - possibly inefficient that this is called so often?
function paint(event) {
// check if the mouse is down
if (mouseIsDown) {
// find cursor row and column
let position = findTileAtMouse(event, Brush.size);
// make sure that last tile painted is not the current tile, and that tile is on canvas
if ((position.col !== previousPaintedTile.col || position.row !== previousPaintedTile.row || (Tool === "eraser" && previousPaintedColor !== "eraser") || (Tool !== "eraser" && previousPaintedColor !== Brush.color)) && tileIsOnCanvas(position, Brush.size)) {
// only paint when the image is not being saved and a saved image is not shown
if (saving === false) {
if (Tool === "brush") {
// set the tile's color
setTile(position, Brush.size);
}
else if (Tool === "eraser") {
// erase the tile
eraseTile(position, Brush.size);
}
// if there is reflection, rerun setTile
let rect = Els.editor.getBoundingClientRect();
if (Els.horizontalSymCheckbox.checked) {
let newEvent = {};
newEvent.clientX = event.x;
newEvent.clientY = Els.editor.height - event.y + 2*rect.top;
let newPosition = findTileAtMouse(newEvent, Brush.size);
if (Tool === "brush") {
setTile(newPosition, Brush.size);
}
else if (Tool === "eraser") {
eraseTile(newPosition, Brush.size);
}
}
if (Els.verticalSymCheckbox.checked) {
let newEvent = {};
newEvent.clientX = Els.editor.width - event.x + 2*rect.left;
newEvent.clientY = event.y;
let newPosition = findTileAtMouse(newEvent, Brush.size);
if (Tool === "brush") {
setTile(newPosition, Brush.size);
}
else if (Tool === "eraser") {
eraseTile(newPosition, Brush.size);
}
}
if (Els.verticalSymCheckbox.checked && Els.horizontalSymCheckbox.checked) { // 4-way symmetry
let newEvent = {};
newEvent.clientX = Els.editor.width - event.x + 2*rect.left;
newEvent.clientY = Els.editor.height - event.y + 2*rect.top;
let newPosition = findTileAtMouse(newEvent, Brush.size);
if (Tool === "brush") {
setTile(newPosition, Brush.size);
}
else if (Tool === "eraser") {
eraseTile(newPosition, Brush.size);
}
}
}
else {
// change display on overlay canvas to show currently saved area
Ctx.overlay.clearRect(0, 0, Els.overlay.width, Els.overlay.height);
Ctx.overlay.fillRect(0, 0, Els.overlay.width, Els.overlay.height);
// code used to find position and width is same as the code in mouseUp
let startPos = {
col: Math.min(saving.startPos.col, position.col),
row: Math.min(saving.startPos.row, position.row),
};
let finishPos = {
col: Math.max(saving.startPos.col, position.col),
row: Math.max(saving.startPos.row, position.row),
};
let startX = startPos.col * Brush.size;
let startY = startPos.row * Brush.size;
let finishX = finishPos.col * Brush.size;
let finishY = finishPos.row * Brush.size;
let width = finishX - startX + Number(Brush.size);
let height = finishY - startY + Number(Brush.size);
Ctx.overlay.clearRect(startX, startY, width, height);
}
previousPaintedTile = position;
if (Tool === "eraser") {
previousPaintedColor = "eraser";
}
else {
previousPaintedColor = Brush.color;
}
}
}
}
// sets a tile and renders this change onto the editor canvas
// position is from findTile functions
function setTile(position, size) {
// set color
if (Els.texturerCheckbox.checked) {
// texturer
if (Tool !== "fill" || size >= 16) {
Ctx.editor.fillStyle = textureColor(Brush.color, Els.texturerDepth.value);
}
else {
// fill tool with size < 16
// texturing size should be even throughout no matter what brush size is
// convert position from small brush size to normal
let sizeFactor = size/ImageResolution;
let indexX = Math.floor(position.col * sizeFactor);
let indexY = Math.floor(position.row * sizeFactor);
// check if last textured tile has been textured before this fill
let foundTile = texturedTiles.find(tile => tile.position.x === indexX && tile.position.y === indexY);
if (foundTile !== undefined) {
// has been textured before, thus do same color
Ctx.editor.fillStyle = foundTile.color;
}
else {
// different one, pick a new texture color
Ctx.editor.fillStyle = textureColor(Brush.color, Els.texturerDepth.value);
// record color for future tiles filled by this fill
texturedTiles.push({
position: {
x: indexX,
y: indexY
},
color: Ctx.editor.fillStyle
});
}
}
}
else {
// no texturer
Ctx.editor.fillStyle = Brush.color;
}
// update imagedata
setImageData(position, Ctx.editor.fillStyle, size);
// draw change onto editor canvas
Ctx.editor.fillRect(position.col * size, position.row * size, size, size);
}
// position should contian the col and row of the fill location (from findTileAtMouse())
// position passed ni is with resolution 4
function fillStart(position) {
let colorBeingFilled = getTile(position, 4); // all tiles of this color within a boundary will be filled
if ((colorBeingFilled !== Brush.color && Tool === "fill") || Els.texturerCheckbox.checked || (colorBeingFilled !== undefined && Tool === "eraserFill")) {
// not trying to fill color that is already there
// calculate less accurate fill position (since filling happens with size 16)
let fillPosition = {
col: Math.floor(position.col/4),
row: Math.floor(position.row/4)
};
if (Els.texturerCheckbox.checked) {
// texturing will occur in fill
// to ensure size of texturing remains constant, textured tiles of size 16 are saved
texturedTiles = [];
}
fill(fillPosition, undefined, colorBeingFilled, 16);
}
}
// recursion function for fillStart (should only be called by fillStart)
// direction is the direction that the fill came from, so it knows not to start a new fill in the opposite direction (i.e. where it came from)
// direction 1 = right, 4 = up, moving clockwise...
// color is the colors that should be replaced by this fill
// size is the size of the fill (this is decremented by a factor of 2 when an array of smaller colors is reached)
function fill(position, direction, color, size) {
// check tile is on the canvas
if (tileIsOnCanvas(position, size)) {
let tile = getTile(position, size);
if (tile === color) {
// tile is of correct color to be filled
// set the tile to the brush color
if (Tool === "fill") {
// fill color
setTile(position, size);
}
else if (Tool === "eraserFill") {
// erase
eraseTile(position, size);
}
// commence fill in other directions
if (direction !== 1) {
// fill left
fill({
col: position.col-1,
row: position.row,
}, 3, color, size);
}
if (direction !== 4) {
// fill down
fill({
col: position.col,
row: position.row+1,
}, 2, color, size);
}
if (direction !== 3) {
// fill right
fill({
col: position.col+1,
row: position.row,
}, 1, color, size);
}
if (direction !== 2) {
// fill up
fill({
col: position.col,
row: position.row-1,
}, 4, color, size);
}
}
// check for array of colors
else if (Array.isArray(tile) && size > 4) {
// resolution is higher than fill paint size
// decrement size and try again in same location
size /= 2;
// update position
position.row *= 2;
position.col *= 2;
// position is now top left
// decide location in smaller tile based on direction it came from
if (direction === 1) {
// came from left
fill({
col: position.col,
row: position.row,
}, 3, color, size);
fill({
col: position.col,
row: position.row+1,
}, 3, color, size);
}
else if (direction === 4) {
// came from down
fill({
col: position.col,
row: position.row+1,
}, 2, color, size);
fill({
col: position.col+1,
row: position.row+1,
}, 2, color, size);
}
else if (direction === 3) {
// came from right
fill({
col: position.col+1,
row: position.row,
}, 3, color, size);
fill({
col: position.col+1,
row: position.row+1,
}, 3, color, size);
}
else if (direction === 2) {
// came from up
fill({
col: position.col,
row: position.row,
}, 2, color, size);
fill({
col: position.col+1,
row: position.row,
}, 2, color, size);
}
else if (direction === undefined) {
// fill initialised
fill({
col: position.col,
row: position.row,
}, 2, color, size);
fill({
col: position.col+1,
row: position.row,
}, 2, color, size);
fill({
col: position.col,
row: position.row+1,
}, 3, color, size);
fill({
col: position.col+1,
row: position.row+1,
}, 3, color, size);
}
}
// if color was not the color to be replaced, this direction of the fill fizzles
}
}
// sets a tile and renders this change onto the editor canvas
function eraseTile(position, size) {
// update imagedata
setImageData(position, undefined, size); // undefined = transparent
// draw change onto editor canvas
Ctx.editor.clearRect(position.col * size, position.row * size, size, size);
}
// clears the editor canvas
// addToUndo is a boolean of whether the cleared canvas should be saved to undo