libraries/canvasModule.js (view raw)
1const globs = {
2 windowLocation: null,
3 canvasMode:'circleMoving',
4 canvasX:null,
5 canvasY:null,
6 newCanvasWidth:null,
7 newCanvasHeight:null,
8 newCircleX: null,
9 newCircleY: null,
10 gridDrawn: false,
11 gridWidth: 1.25,
12 circleHandles: [],
13 imageSrc: null,
14 backgroundBitmap: null,
15 canvasResizeFactor: 1,
16 pxPerFoot: 5,
17 imageCompression: true,
18 canvasNeedsUpdate: false,
19 lastResizeCanvasWidth: null,
20 grid: {
21 gridlines: [],
22
23 drawGrid: function(pxPerFoot) {
24 let centerX = globs.canvasX/2;
25 let centerY = globs.canvasY/2;
26 let gridSpacing = 5*pxPerFoot; //in pixels
27 let numLinesX = (globs.canvasX - globs.canvasX%gridSpacing)/gridSpacing;
28 let numLinesY = (globs.canvasY - globs.canvasY%gridSpacing)/gridSpacing;
29
30 for (let xCoord = centerX - (gridSpacing*numLinesX)/2;
31 xCoord < globs.canvasX; xCoord += gridSpacing) {
32 const line = new createjs.Shape();
33 //Specify top right corner with x,y,width,height
34 line.graphics.beginFill("rgba(180,180,180,0.45)").drawRect(xCoord,0,globs.gridWidth,globs.canvasY);
35 stage.addChildAt(line, globs.backgroundBitmap ? 1 : 0);
36 this.gridlines.push(line);
37 }
38
39 for (let yCoord = centerY - (gridSpacing*numLinesY)/2;
40 yCoord < globs.canvasY; yCoord += gridSpacing) {
41 const line = new createjs.Shape();
42 //Specify top right corner with x,y,width,height
43 line.graphics.beginFill("rgba(180,180,180,0.45)").drawRect(0,yCoord,globs.canvasX,globs.gridWidth);
44 stage.addChildAt(line, globs.backgroundBitmap ? 1 : 0);
45 this.gridlines.push(line);
46 }
47 stage.update()
48 },
49
50 removeGrid: function() {
51 for (let counter = 0; counter < this.gridlines.length; counter += 1) {
52 line = this.gridlines[counter];
53 stage.removeChild(line);
54 }
55 this.gridlines = [];
56 stage.update();
57 },
58
59 redrawGrid: function() {
60 this.removeGrid();
61 this.drawGrid();
62 }
63 }
64}
65
66//Define a broadcast channel class that automatically packages the canvas size and window location with the message
67const broadcastChannel = {
68 bc: new BroadcastChannel('primaryChannel'),
69
70 postMessage: function (message) {
71 this.bc.postMessage([[globs.canvasX,globs.canvasY,globs.windowLocation],message])
72 }
73}
74
75function applyBroadcast(broadcastData,otherX,otherY) {
76 // let broadcastRescaleX = globs.canvasX/otherX;
77 // let broadcastRescaleY = /globs.canvasY/otherY;
78 // same for both
79 let broadcastRescale = globs.canvasY/otherY;
80
81
82 if (broadcastData[0] === "loadMap") {
83 loadMapImage(broadcastData[1]);
84 } else if (broadcastData[0] === "toggleGrid") {
85 globs.pxPerFoot = broadcastData[2]*broadcastRescale;
86 updateGrid(broadcastData[1],globs.pxPerFoot);
87 } else if (broadcastData[0] === "updateScale") {
88 updateCanvasScale(broadcastData[1]*broadcastRescale);
89 } else if (broadcastData[0] === "newCircle") {
90 drawNewCircle(broadcastData[1],broadcastData[2],broadcastData[3],'encounterMap',broadcastData[4]);
91 } else if (broadcastData[0] === "labelUpdate") {
92 let labels = broadcastData[1];
93 for (let i=0;i<labels.length;i+=1) {
94 let circleHandle = globs.circleHandles[i];
95 let label = labels[i];
96 if (label) {
97 circleHandle.namedSubElements.labelbox.value = label;
98 }
99 }
100 updateCanvas();
101 } else if (broadcastData[0] === 'removeCircle') {
102 let circleID = broadcastData[1];
103 let circleHandle = globs.circleHandles[circleID];
104 if (circleHandle) {
105 circleHandle.removeCircle();
106 circleHandle.removeHandle();
107 circleHandle.removeFromMasterList();
108 }
109 } else if (broadcastData[0] === "moveCircle") {
110 let circleID = broadcastData[1];
111 let circleHandle = globs.circleHandles[circleID];
112 if (circleHandle) {
113 circleHandle.updateLocation(broadcastData[2]*broadcastRescale,broadcastData[3]*broadcastRescale)
114 }
115 } else if (broadcastData[0] === "appendNullToken") {
116 globs.circleHandles.push(null);
117 } else if (broadcastData[0] === "drawLine") {
118 drawSingleLine(broadcastData[1]*broadcastRescale,broadcastData[2]*broadcastRescale,
119 broadcastData[3]*broadcastRescale,broadcastData[4]*broadcastRescale,
120 broadcastData[5],broadcastData[6]);
121 } else if (broadcastData[0] === 'eraseAllLines') {
122 eraseAllLines();
123 } else if (broadcastData[0] === "drawMeasurer") {
124 drawSingleMeasurer(broadcastData[1]*broadcastRescale,broadcastData[2]*broadcastRescale,
125 broadcastData[3]*broadcastRescale,broadcastData[4]*broadcastRescale);
126 } else if (broadcastData[0] === "eraseMeasurer") {
127 eraseMeasurer();
128 } else if (broadcastData[0] === "updateCanvas") {
129 updateCanvas();
130 } else if (broadcastData[0] === "newRotation") {
131 let circleHandle = globs.circleHandles[broadcastData[1]];
132 if (circleHandle) {
133 circleHandle.updateRotation(broadcastData[2]);
134 }
135 } else if (broadcastData[0] === "setCircleVisibility") {
136 let circleHandle = globs.circleHandles[broadcastData[1]];
137 if (circleHandle) {
138 circleHandle.setVisibility(broadcastData[2], false);
139 }
140 } else if (broadcastData[0] === "manuallyAppendImage") {
141 globs.circleHandles[broadcastData[1]].manuallyAppendImageFile(broadcastData[2]);
142 } else if (broadcastData[0] === "requestOppositePageElements") {
143 broadcastPageElements();
144 } else if (broadcastData[0] === "toggleImageCompression") {
145 if (globs.imageCompression) {
146 globs.imageCompression = false;
147 } else {
148 globs.imageCompression = true;
149 }
150 } else if (broadcastData[0] === "removeLineSegment") {
151 let lineSegment = drawer.lineSegments[broadcastData[1]];
152 lineSegment.remove();
153 } else if (broadcastData[0] === "cleanUpNullLines") {
154 cleanUpNullLines();
155 } else if (broadcastData[0] === "clearCanvas") {
156 _clearCanvas();
157 } else if (broadcastData[0] === "setGMNotes") {
158 if (typeof applyGMNotes === 'function') {
159 applyGMNotes(broadcastData[1]);
160 }
161 } else if (broadcastData[0] === "setHume") {
162 if (typeof applyHumeValue === 'function') {
163 applyHumeValue(broadcastData[1]);
164 }
165 } else {
166 console.log("Broadcast message not understood! "+broadcastData[0]+' '+broadcastData[1]);
167 }
168}
169
170function broadcastPageElements () {
171 //broadcasts everything on the current page to the new page
172
173 //All the images should have been compressed on the first go-round, so no need to do so again
174 broadcastChannel.postMessage(["toggleImageCompression"]) //turn image compression off
175
176 if (globs.imageSrc) {
177 broadcastChannel.postMessage(['loadMap',globs.imageSrc]);
178 }
179
180 //Draw the grid on the new window if it's already on the current window
181 if (globs.gridDrawn) {
182 let gridChecked = true;
183 if (document.getElementById('includeGrid')) {
184 gridChecked = document.getElementById('includeGrid').checked;
185 }
186 broadcastChannel.postMessage(['toggleGrid',gridChecked,globs.pxPerFoot]);
187 }
188
189 //Update the map scale of the new window to match that of the current window
190 broadcastChannel.postMessage(['updateScale',globs.pxPerFoot]);
191
192 //Draw the currently existing circle on the new page
193 for (let i=0;i<globs.circleHandles.length;i+=1) {
194 let circleHandle = globs.circleHandles[i];
195 if (circleHandle) {
196 let circle = circleHandle.namedSubElements.circle;
197 broadcastChannel.postMessage(['newCircle',circle.circleRadius*2,circle.circleColor,circle.circleText,circle.circleType]);
198 let x = circle.dragObject.x;
199 let y = circle.dragObject.y;
200 broadcastChannel.postMessage(['moveCircle',i,x,y]);
201 let rot = circle.dragObject.rotation;
202 broadcastChannel.postMessage(['newRotation',i,rot]);
203 broadcastChannel.postMessage(['setCircleVisibility',i,circle.visible]);
204
205 if (circle.imageFile) {
206 broadcastChannel.postMessage(["manuallyAppendImage",circle.id,circle.imageFile]);
207 }
208 } else {
209 broadcastChannel.postMessage(["appendNullToken"]);
210 }
211 }
212
213 //Draw the currently existing lines on the new page
214 for (let i = 0; i < drawer.lineSegments.length; i += 1) {
215 line = drawer.lineSegments[i]
216 if (line) {
217 broadcastChannel.postMessage(['drawLine',line.startX,line.endX,line.startY,line.endY,line.width,line.color])
218 }
219 }
220
221 //Draw the currently existing measurer, if applicable
222 if (measurer.currentLine) {
223 broadcastChannel.postMessage(['drawMeasurer',measurer.currentLine.startX,measurer.currentLine.endX,
224 measurer.currentLine.startY,measurer.currentLine.endY])
225 }
226
227 broadcastChannel.postMessage(['updateCanvas']);
228 broadcastChannel.postMessage(["toggleImageCompression"]) //turn image compression back on
229 if (typeof broadcastHUDState === 'function') {
230 broadcastHUDState();
231 }
232}
233
234 class DraggableCircle {
235 constructor(circleRadius,circleColor,circleText,windowLocation,id,circleType,askUserForFile=true,visible=true) {
236 this.circleRadius = circleRadius;
237 this.circleColor = circleColor;
238 this.circleText = circleText;
239 this.windowLocation = windowLocation;
240 this.id = id;
241 this.circleType = circleType;
242 this.visible = visible;
243
244 this.moveable = null;
245 this.moveEvent = null;
246
247 this.imageFile = null; //The File object for the image
248 this.image = null; //The Image object for the image
249 this.conversionMatrix = null; //Matrix for converting the original image to the new one
250 this.needsRedraw = false; //if the image isn't available at the first draw, draw again
251 if ((circleType === "custom" || circleType === "customCircle") && windowLocation === "main") {
252 if (askUserForFile) {
253 this.upload();
254 }
255 }
256
257 //The drag object is used for removing the circle from the canvas
258 //It also contains the circle's current position with .x and .y properties
259 this.dragObject = this.drawNew();
260 if (globs.canvasMode === "circleMoving") {
261 this.makeMoveable();
262 }
263
264 //Variables used in event detection
265 this.tmpFunction = null;
266 this.oldRotationX = null;
267 this.oldRotationY = null;
268 }
269
270 drawNew(x=globs.newCircleX,y=globs.newCircleY,rotation=0) {
271 let circle = new createjs.Shape();
272 let circleRadiusInPx = this.circleRadius*globs.pxPerFoot;
273
274 // Circle with x coord, y coord, and radius
275 // The acutal location of the circle will be set using the draggable container, so x and y should be 0
276 let circleGraphic = circle.graphics.beginFill(this.circleColor)
277 if (this.circleType === 'circle') {
278 circle.graphics.beginFill(this.circleColor).drawCircle(0, 0, circleRadiusInPx);
279 } else if (this.circleType === 'square') {
280 circle.graphics.beginFill(this.circleColor).drawRect(-1*circleRadiusInPx, -1*circleRadiusInPx, circleRadiusInPx*2, circleRadiusInPx*2);
281 } else if (this.circleType === 'cone') {
282 //3 sides with 0 point radius and 60 degree angles makes a cone
283 //the 1.3094 is a conversion unique to the equilateral triangle that lets us use axis length instead of side length
284 circle.graphics.beginFill(this.circleColor).drawPolyStar(0, 0, circleRadiusInPx*1.3094, 3, 0, 60);
285 } else if (this.circleType === 'customCircle') {
286 if (this.image) {
287 this.findTransformationMatrix(false);
288 circle.graphics.beginBitmapFill(this.image,"no-repeat",this.transformationMatrix).drawCircle(0, 0, circleRadiusInPx);
289 this.needsRedraw = false;
290 } else {
291 this.needsRedraw = true;
292 }
293 } else if (this.circleType === 'custom') {
294 if (this.image) {
295 let rescalers = this.findTransformationMatrix(true);
296 circle = new createjs.Bitmap(this.image);
297 circle.x = -1*circleRadiusInPx;
298 circle.y = -1*circleRadiusInPx;
299 circle.scaleX = rescalers[0];
300 circle.scaleY = rescalers[1];
301 this.needsRedraw = false;
302 } else {
303 this.needsRedraw = true;
304 }
305 } else {
306 console.log('symbol type not recognized: '+this.circleType)
307 }
308 // Add text to the circle
309 let fontsize = circleRadiusInPx;
310 let label = new createjs.Text(this.circleText, `bold ${fontsize}px Arial`, "#FFFFFF");
311 label.textAlign = "center";
312 label.x = 0;
313 label.y = 0 - fontsize*7/16;
314
315 const dragger = new createjs.Container();
316 dragger.windowLocation = this.windowLocation;
317 dragger.id = this.id;
318 dragger.x = x;
319 dragger.y = y;
320 dragger.rotation = rotation;
321 dragger.addChild(circle,label);
322 stage.addChild(dragger);
323 this.applyVisibilityToContainer(dragger);
324
325 stage.update();
326 return dragger;
327 }
328
329 applyVisibilityToContainer(container) {
330 if (!container) return;
331 if (this.windowLocation === 'main') {
332 container.visible = true;
333 container.alpha = this.visible ? 1 : 0.35;
334 } else {
335 container.visible = Boolean(this.visible);
336 container.alpha = 1;
337 }
338 }
339
340 setVisibility(isVisible) {
341 this.visible = Boolean(isVisible);
342 this.applyVisibilityToContainer(this.dragObject);
343 stage.update();
344 }
345
346 mousedown(evt) {
347 function pressmove(evt) {
348 // Calculate the new X and Y based on the mouse new position plus the offset.
349 evt.currentTarget.x = evt.stageX + evt.currentTarget.offset.x;
350 evt.currentTarget.y = evt.stageY + evt.currentTarget.offset.y;
351 broadcastChannel.postMessage(['moveCircle',evt.currentTarget.id,
352 evt.currentTarget.x,evt.currentTarget.y]);
353 // make sure to redraw the stage to show the change:
354 stage.update();
355 }
356
357 function pressrotate(evt) {
358 if (evt.currentTarget.oldRotationX && evt.currentTarget.oldRotationY) {
359 //Do the math to find the angle of the movement relative to the original shape
360 let delta = [evt.stageX - evt.currentTarget.oldRotationX,evt.stageY - evt.currentTarget.oldRotationY];
361 let deltaLength = Math.pow(Math.pow(delta[0],2)+Math.pow(delta[1],2),.5);
362 let referenceVector = [evt.currentTarget.oldRotationX - evt.currentTarget.x, evt.currentTarget.oldRotationY - evt.currentTarget.y];
363 let referenceVectorLength = Math.pow(Math.pow(referenceVector[0],2)+Math.pow(referenceVector[1],2),.5);
364 let differenceVector = [referenceVector[0]-delta[0],referenceVector[1]-delta[1]];
365 let differenceVectorLength = Math.pow(Math.pow(differenceVector[0],2)+Math.pow(differenceVector[1],2),.5);
366 let angleBetween = Math.acos((Math.pow(referenceVectorLength,2)+Math.pow(deltaLength,2)-Math.pow(differenceVectorLength,2))/(2*deltaLength*referenceVectorLength));
367 let pi = 3.14159265;
368 // ArcCOS returns NAN when the angle is 90 degrees
369 if (!angleBetween) {
370 angleBetween = pi/2;
371 }
372 let projectedVectorLength = Math.cos((pi/2)-angleBetween)*deltaLength;
373 let deltaRotationAngle = Math.atan(projectedVectorLength/referenceVectorLength)*(360/(2*pi));
374
375 // calculate just the z component of the cross project between the delta and reference vectors
376 // This tells us if we should rotate the shape clockwise or counterclockwise
377 let crossZ = delta[0]*referenceVector[1] - delta[1]*referenceVector[0];
378 if (crossZ > 0) {
379 deltaRotationAngle = deltaRotationAngle*-1
380 }
381 evt.currentTarget.rotation = evt.currentTarget.rotation + deltaRotationAngle;
382 broadcastChannel.postMessage(['newRotation',evt.currentTarget.id,evt.currentTarget.rotation])
383 }
384 evt.currentTarget.oldRotationX = evt.stageX;
385 evt.currentTarget.oldRotationY = evt.stageY;
386 // make sure to redraw the stage to show the change:
387 stage.update();
388 }
389 // keep a record on the offset between the mouse position and the container
390 // position. currentTarget will be the container that the event listener was added to:
391 evt.currentTarget.offset = {x: this.x - evt.stageX, y: this.y - evt.stageY};
392 if (!evt.nativeEvent.altKey) {
393 evt.currentTarget.tmpFunction = evt.currentTarget.on("pressmove",pressmove)
394 } else {
395 evt.currentTarget.tmpFunction = evt.currentTarget.on("pressmove",pressrotate)
396 }
397 }
398
399 pressup(evt) {
400 evt.currentTarget.off("pressmove",evt.currentTarget.tmpFunction)
401 // console.log(evt.currentTarget._listeners);
402 }
403
404 makeMoveable () {
405 this.moveable = true;
406 this.dragObject.on("mousedown", this.mousedown);
407 this.dragObject.on("pressup",this.pressup)
408 }
409
410 makeUnmoveable () {
411 this.moveable = false;
412 this.dragObject.removeAllEventListeners();
413 }
414
415 redraw() {
416 stage.removeChild(this.dragObject);
417 this.dragObject = this.drawNew(this.dragObject.x,this.dragObject.y,this.dragObject.rotation);
418 if (this.moveable) {
419 this.makeMoveable();
420 };
421 }
422
423 remove() {
424 stage.removeChild(this.dragObject);
425 stage.update()
426 }
427
428 updateLocation(x,y) {
429 this.dragObject.x = x;
430 this.dragObject.y = y;
431 stage.update()
432 }
433
434 updateRotation(rot) {
435 this.dragObject.rotation = rot;
436 stage.update();
437 }
438
439 findTransformationMatrix(keepOrignalProportions=true) {
440 //Transformation matrix applied when the image is converted to a dragable token
441 //We want this to reduce the image's size and appropriate amount
442 // new createjs.Matrix2D(a,b,c,d,tx,ty)
443 // a: less than one shrinks y axes, more than 1 streches it
444 // b: unknown. leave at default of 0
445 // c: unknown. leave at default of 0
446 // d: less than one shrinks x axes, more than 1 streches it
447 // tx: horizontally shift
448 // ty: vertically shift
449
450 let circleRadiusInPx = this.circleRadius*globs.pxPerFoot;
451 let xRescaler = 1/(this.image.width/(circleRadiusInPx*2));
452 let yRescaler = 1/(this.image.height/(circleRadiusInPx*2));
453
454 if (keepOrignalProportions) {
455 if (xRescaler > yRescaler) {
456 xRescaler = yRescaler;
457 } else if (yRescaler > xRescaler) {
458 yRescaler = xRescaler;
459 }
460 }
461 this.transformationMatrix = new createjs.Matrix2D(xRescaler,0,0,yRescaler,-1*circleRadiusInPx,-1*circleRadiusInPx);
462 return [xRescaler,yRescaler]
463 }
464 preprocessImage (file) {
465 function handleImageCompression (result,passThroughVariable) {
466 function handlePreprocess () {
467 let circleHandle = globs.circleHandles[this.id];
468 circleHandle.processCustomImageLoad(); //Now that the image is ready, make sure that it's loaded ev÷erywhere
469 }
470 let circle = globs.circleHandles[passThroughVariable].namedSubElements.circle;
471 circle.compressedImage = result;
472
473 circle.image = new Image();
474 circle.image.id = passThroughVariable;
475 circle.image.src = URL.createObjectURL(result);
476 circle.image.onload = handlePreprocess;
477 circle.imageFile = result;
478 }
479 compressImageFile(file,this.circleRadius*2,handleImageCompression,this.id);
480 }
481
482 upload () {
483 function handleUpload (event) {
484 let circle = globs.circleHandles[this.id].namedSubElements.circle;
485 let uploadedFile = event.target.files[0];
486 if (circle.windowLocation === 'main') {
487 broadcastChannel.postMessage(["manuallyAppendImage",circle.id,uploadedFile]);
488 circle.preprocessImage(uploadedFile);
489 }
490 }
491 let element = document.createElement('input');
492 element.setAttribute('type', 'file');
493 element.style.display = 'none';
494 element.id = this.id;
495 element.onchange = handleUpload;
496 document.body.appendChild(element);
497 element.click();
498 document.body.removeChild(element);
499 }
500
501 manuallyAppendImageFile (file) {
502 //For use with the player view window
503 this.preprocessImage(file);
504 }
505}
506
507function formatHumeMeta(val) {
508 const clamped = Math.max(0.5, Math.min(5.0, Number(val) || 1.0));
509 const pct = ((clamped - 0.5) / 4.5) * 100;
510 let label = "Норма";
511 let color = "#34d399";
512 let bg = "rgba(16, 185, 129, 0.16)";
513 if (clamped < 0.8) {
514 label = "Сильное истончение";
515 color = "#f87171";
516 bg = "rgba(239, 68, 68, 0.18)";
517 } else if (clamped < 0.95) {
518 label = "Истончение";
519 color = "#e879f9";
520 bg = "rgba(217, 70, 239, 0.16)";
521 } else if (clamped <= 1.25) {
522 label = "Норма";
523 color = "#34d399";
524 bg = "rgba(16, 185, 129, 0.16)";
525 } else if (clamped <= 2.5) {
526 label = "Уплотнение";
527 color = "#38bdf8";
528 bg = "rgba(56, 189, 248, 0.16)";
529 } else {
530 label = "Высокая плотность";
531 color = "#fbbf24";
532 bg = "rgba(245, 158, 11, 0.18)";
533 }
534 return { clamped, pct, label, color, bg };
535}
536
537function setupCanvas () {
538 let widthAndHeight = findCanvasScale();
539 globs.canvasX = widthAndHeight[0];
540 globs.canvasY = widthAndHeight[1];
541
542 let canvas = document.getElementById('canvas');
543 canvas.width = globs.canvasX;
544 canvas.height = globs.canvasY;
545
546 globs.newCircleX = canvas.width/2;
547 globs.newCircleY = canvas.height/2;
548
549 let ticker = createjs.Ticker.addEventListener("tick", handleTick);
550 createjs.Ticker.framerate = 10; //set the framerate in frames per second
551 function handleTick(event) {
552 // Actions carried out each tick (aka frame)
553 if (!event.paused) {
554 // Actions carried out when the Ticker is not paused.
555 if (globs.canvasNeedsUpdate) {
556 _updateCanvas();
557 }
558 }
559 }
560}
561
562function findCanvasScale () {
563 let availW = window.innerWidth;
564 let availH = window.innerHeight;
565 if (globs.windowLocation === 'encounterMap') {
566 const holder = document.getElementById('mirroredEncounterMap');
567 const header = document.getElementById('playerTopBar');
568 const sideW = holder && holder.clientWidth > 100 ? holder.clientWidth : (availW >= 992 ? availW - 360 : availW - 32);
569 const topH = header ? header.offsetHeight + 24 : 72;
570 availW = Math.max(320, sideW - 16);
571 availH = Math.max(200, window.innerHeight - topH);
572 }
573
574 let height; let width;
575 if (availW > availH * (16 / 9)) {
576 height = availH;
577 width = availH * (16 / 9);
578 } else {
579 height = availW * (9 / 16);
580 width = availW;
581 }
582 if (globs.windowLocation === 'main') {
583 if (width > 576) {
584 //Styling for desktops
585 width = width*.52;
586 height = height*.52;
587 } else {
588 //Styling for phones
589 width = width*.92;
590 height = height*.92;
591 }
592 return [width,height];
593 } else if (globs.windowLocation === 'encounterMap') {
594 return [Math.floor(width), Math.floor(height)];
595 } else {
596 console.log(globs.windowLocation+'not recognized');
597 }
598}
599
600function resizeCanvas () {
601 let widthAndHeight = findCanvasScale();
602 let width = widthAndHeight[0];
603 let height = widthAndHeight[1];
604
605 globs.newCircleX = width/2;
606 globs.newCircleY = height/2;
607
608 if (!globs.lastResizeCanvasWidth) {
609 globs.lastResizeCanvasWidth = globs.canvasX; //when the page loads, these two are equal
610 }
611 globs.canvasResizeFactor = globs.canvasResizeFactor*(width/globs.lastResizeCanvasWidth);
612
613 globs.lastResizeCanvasWidth = width;
614 _updateCanvas();
615}
616
617function loadMapImage(mapImage) {
618 globs._mapLoadSeq = (globs._mapLoadSeq || 0) + 1;
619 const seq = globs._mapLoadSeq;
620 globs.imageSrc = mapImage;
621
622 function handleImageCompression (result) {
623 if (seq !== globs._mapLoadSeq) {
624 return;
625 }
626 var image = new Image();
627 image.src = URL.createObjectURL(result);
628 image.onload = function(event) {
629 if (seq !== globs._mapLoadSeq) {
630 return;
631 }
632 handleImageLoad(event);
633 };
634
635 globs.imageSrc = result;
636 }
637 if (globs.backgroundBitmap) {
638 stage.removeChild(globs.backgroundBitmap);
639 globs.backgroundBitmap = null;
640 }
641
642 compressImageFile(mapImage,100,handleImageCompression);
643}
644
645function handleImageLoad(event) {
646 var image = event.target;
647 var bitmap = new createjs.Bitmap(image);
648 stage.addChildAt(bitmap, 0);
649 globs.backgroundBitmap = bitmap;
650 updateCanvas();
651}
652
653function updateGrid(gridDrawn,pxPerFoot) {
654 _updateGrid(gridDrawn,pxPerFoot);
655 updateCanvas()
656}
657
658function _updateGrid(gridDrawn,pxPerFoot) {
659 if (gridDrawn) {
660 globs.grid.removeGrid(); //remove grid if it exists
661 globs.grid.drawGrid(pxPerFoot);
662 globs.gridDrawn = true;
663 } else {
664 globs.grid.removeGrid();
665 globs.gridDrawn = false;
666 }
667}
668
669function updateCanvasScale (pxPerFoot) {
670 globs.pxPerFoot = pxPerFoot;
671 updateCanvas()
672}
673
674function redrawCircles() {
675 for (let i = 0; i < globs.circleHandles.length; i += 1) {
676 circleHandle = globs.circleHandles[i]
677 if (circleHandle) {
678 if (!circleHandle.namedSubElements.circle.needsRedraw) {
679 // If the redraw flag is set, this circle is waiting for an image to uploaded. It shouldn't be redrawn by an update
680 let circle = circleHandle.namedSubElements.circle;
681 let oldX = circle.dragObject.x; let oldY = circle.dragObject.y;
682 circle.updateLocation(oldX*globs.canvasResizeFactor,oldY*globs.canvasResizeFactor);
683 circleHandle.redraw()
684 }
685 }
686 }
687}
688
689function redrawLines() {
690 for (let i = 0; i < drawer.lineSegments.length; i += 1) {
691 line = drawer.lineSegments[i]
692 if (line) {
693 let g = globs.canvasResizeFactor;
694 line.updateLocation(line.startX*g,line.endX*g,line.startY*g,line.endY*g);
695 line.redraw()
696 }
697 }
698}
699
700function redrawMeasurer () {
701 if (measurer.currentLine) {
702 let g = globs.canvasResizeFactor;
703 measurer.redrawMeasurer(measurer.currentLine.startX*g,measurer.currentLine.endX*g,
704 measurer.currentLine.startY*g,measurer.currentLine.endY*g,);
705 }
706}
707
708function resizeBackgroundImage () {
709 if (globs.backgroundBitmap) {
710 let width = globs.backgroundBitmap.getBounds().width;
711 let height = globs.backgroundBitmap.getBounds().height;
712
713 let rescaleFactor;
714 let xRescaleFactor = globs.canvasX/width;
715 let yRescaleFactor = globs.canvasY/height;
716
717 if (xRescaleFactor < yRescaleFactor) {
718 rescaleFactor = xRescaleFactor;
719 } else {
720 rescaleFactor = yRescaleFactor;
721 }
722
723 globs.backgroundBitmap.scaleX = rescaleFactor;
724 globs.backgroundBitmap.scaleY = rescaleFactor;
725
726 globs.backgroundBitmap.x = (globs.canvasX - width*rescaleFactor)/2;
727 globs.backgroundBitmap.y = (globs.canvasY - height*rescaleFactor)/2;
728
729 stage.update();
730 }
731}
732
733function drawNewCircle(circleDiameter,circleColor,circleText,windowLocation,circleType,notes="",circleImage=null,visible=true) {
734 _drawNewCircle(circleDiameter,circleColor,circleText,windowLocation,circleType,notes,circleImage,visible);
735 updateCanvas();
736}
737
738function _drawNewCircle(circleDiameter,circleColor,circleText,windowLocation,circleType,notes,circleImage,visible=true) {
739 if (circleImage) {
740 askUserForFile = false;
741 } else {
742 askUserForFile = true;
743 }
744
745 // Divide my 2 to account for the conversion from diameter to radius
746 circle = new DraggableCircle(circleDiameter * 1/2,circleColor,circleText,windowLocation,globs.circleHandles.length,circleType,askUserForFile,visible);
747 let circleHandle = new SymbolHandle(circle,globs.circleHandles.length,notes);
748 globs.circleHandles.push(circleHandle);
749 if (circleImage) {
750 circleHandle.manuallyAppendImageFile(circleImage);
751 }
752}
753
754function updateCanvas() {
755 //Sets the canvas to be updated the next time the ticker comes around
756 globs.canvasNeedsUpdate = true;
757}
758
759function _updateCanvas() {
760 //If the window size has changed, update the canvas scale to match
761 globs.pxPerFoot = globs.pxPerFoot*globs.canvasResizeFactor;
762 if (globs.windowLocation === 'main') {
763 //janky call to functions defined in index.html
764 document.getElementById("canvasScale").value = globs.pxPerFoot;
765 updateCanvasScaleLabel();
766 }
767
768 //Call to make sure that everything in the canvas is setup correctly and drawn in the right order
769 setupCanvas();
770 resizeBackgroundImage();
771 _updateGrid(globs.gridDrawn,globs.pxPerFoot);
772 redrawLines();
773 redrawCircles();
774 redrawMeasurer();
775 stage.update()
776 globs.canvasResizeFactor = 1;
777 globs.canvasNeedsUpdate = false;
778}
779
780function clearCanvas() {
781 _clearCanvas();
782 broadcastChannel.postMessage(['clearCanvas']);
783}
784
785function _clearCanvas() {
786 for (let i=0; i < globs.circleHandles.length; i+=1) {
787 let circleHandle = globs.circleHandles[i];
788 if (circleHandle) {
789 circleHandle.removeFromButton();
790 }
791 }
792
793 globs.grid.gridlines = [];
794 globs.gridDrawn = false;
795 stage.removeAllChildren();
796 drawer.lineSegments = [];
797 measurer.currentLine = null;
798 globs.circleHandles = [];
799 globs.imageSrc = null;
800 globs.backgroundBitmap = null;
801
802 updateCanvas();
803}
804
805function compressImageFile(file,sizeInFeet,successFunction,passThroughVariable=null) {
806 if (globs.imageCompression) {
807 let width = sizeInFeet*60 //Set each foot on the map to be represented by 15 pixels. This may need tweaking
808 let compressionSettings = {quality: 0.7,
809 maxHeight: 2000,
810 maxWidth: 2000,
811 width:width,
812 success(result) {
813 successFunction(result,passThroughVariable);
814 },
815 error(err) {
816 console.log(err.message);
817 }};
818
819 new Compressor(file, compressionSettings);
820 } else {
821 successFunction(file,passThroughVariable);
822 }
823}
824
825//Begin code for switching between the canvas' various modes
826function disableCurrentMode() {
827 if (globs.canvasMode === 'circleMoving') {
828 circleMover.disableMoving();
829 globs.canvasMode = null;
830 } else if (globs.canvasMode === 'lineDrawing') {
831 drawer.disableDrawing();
832 globs.canvasMode = null;
833 } else if (globs.canvasMode === "measuring") {
834 measurer.disableMeasuring();
835 globs.canvasMode = null;
836 } else if (globs.canvasMode === "lineErasing") {
837 eraser.disableErasing();
838 globs.canvasMode = null;
839 } else {
840 console.log('Cannot dissable canvas mode '+globs.canvasMode);
841 foo
842 }
843}
844
845//Code for enabling/disabling circle moving on the canvas
846circleMover = {
847 enableMoving: function () {
848 if (globs.canvasMode) {
849 console.log('Cant start moving mode while another mode is active!');
850 foo
851 }
852 for (let i=0;i<globs.circleHandles.length;i+=1) {
853 if (globs.circleHandles[i]) {
854 let circle = globs.circleHandles[i].namedSubElements.circle;
855 circle.makeMoveable();
856 }
857 }
858 globs.canvasMode = 'circleMoving';
859 },
860
861 disableMoving: function () {
862 for (let i=0;i<globs.circleHandles.length;i+=1) {
863 if (globs.circleHandles[i]) {
864 let circle = globs.circleHandles[i].namedSubElements.circle;
865 circle.makeUnmoveable();
866 }
867 }
868 }
869}
870
871function circleMoving () {
872 disableCurrentMode();
873 circleMover.enableMoving();
874}
875
876//Code for enabling/disabling drawing on the canvas
877class LineSegment {
878 constructor(startX,endX,startY,endY,width,color,dashed=false) {
879 this.startX = startX;
880 this.endX = endX;
881 this.startY = startY;
882 this.endY = endY;
883 this.width = width;
884 this.color = color;
885 this.dashed = dashed;
886
887 this.removed = false;
888
889 this.drawNew();
890 }
891
892 drawNew () {
893 let line = new createjs.Shape();
894 line.graphics.setStrokeStyle(this.width, 'round', 'round');
895 if (this.dashed) {
896 line.graphics.setStrokeDash([5, 5], 0);
897 }
898 line.graphics.beginStroke(this.color);
899 line.graphics.moveTo(this.startX,this.startY);
900 line.graphics.lineTo(this.endX,this.endY);
901 stage.addChild(line);
902 stage.setChildIndex(line,1000);
903 stage.update();
904
905 this.lineSegment = line;
906 }
907
908 redraw () {
909 let a = stage.removeChild(this.lineSegment);
910 this.drawNew();
911 }
912
913 remove() {
914 stage.removeChild(this.lineSegment);
915 this.removed = true;
916 }
917
918 updateLocation (startX,endX,startY,endY) {
919 this.startX = startX;
920 this.endX = endX;
921 this.startY = startY;
922 this.endY = endY;
923 }
924}
925
926drawer = {
927 lineSegments:[],
928 oldPt:null,
929 newPt:null,
930
931 handleDrawMouseDown: function (event) {
932 drawer.oldPt = [stage.mouseX,stage.mouseY];
933 stage.addEventListener("stagemousemove", drawer.handleDrawMouseMove);;
934 },
935
936 handleDrawMouseMove: function (event) {
937 width = document.getElementById("drawSize").value;
938 color = document.getElementById("drawColor").value;
939 drawer.newPt = [stage.mouseX,stage.mouseY];
940 drawer.drawLine(drawer.oldPt[0],drawer.newPt[0],drawer.oldPt[1],drawer.newPt[1],width,color);
941 drawer.oldPt = drawer.newPt;
942 },
943
944 handleDrawMouseUp: function (event) {
945 stage.removeEventListener("stagemousemove", drawer.handleDrawMouseMove);
946 },
947
948 drawLine: function (startX,endX,startY,endY,width,color) {
949 let line = new LineSegment(startX,endX,startY,endY,width,color);
950 broadcastChannel.postMessage(['drawLine',drawer.oldPt[0],drawer.newPt[0],drawer.oldPt[1],
951 drawer.newPt[1],width,color]);
952 drawer.lineSegments.push(line);
953 },
954
955 enableDrawing: function () {
956 if (globs.canvasMode) {
957 console.log('Cant start drawing mode while another mode is active!');
958 foo
959 }
960 globs.canvasMode = 'lineDrawing';
961 stage.addEventListener("stagemousedown", this.handleDrawMouseDown);
962 stage.addEventListener("stagemouseup", this.handleDrawMouseUp);
963 },
964
965 disableDrawing: function () {
966 stage.removeEventListener("stagemousedown", this.handleDrawMouseDown);
967 stage.removeEventListener("stagemouseup", this.handleDrawMouseUp);
968 },
969
970 eraseAllLines: function () {
971 for (let i=0; i<drawer.lineSegments.length; i+=1) {
972 stage.removeChild(drawer.lineSegments[i].lineSegment);
973 }
974 stage.update()
975 drawer.lineSegments = [];
976 }
977}
978
979function lineDrawing () {
980 disableCurrentMode();
981 drawer.enableDrawing();
982}
983
984function eraseAllLines () {
985 if (drawer.lineSegments.length > 0) {
986 drawer.eraseAllLines();
987 broadcastChannel.postMessage(['eraseAllLines'])
988 }
989}
990
991function drawSingleLine (startX,endX,startY,endY,width,color) {
992 let line = new LineSegment(startX,endX,startY,endY,width,color);
993 drawer.lineSegments.push(line);
994}
995
996//Code for enabling/disabling erasing on the canvas
997class LocalEraser {
998 constructor(x,y,radius) {
999 //x and y positions in px
1000 //radius in px
1001 this.x = x;
1002 this.y = y;
1003 this.radius = radius;
1004
1005 this.createNew();
1006 }
1007
1008 createNew() {
1009 let circle = new createjs.Shape();
1010 let circleRadiusInPx = this.circleRadius*globs.pxPerFoot;
1011
1012 // Circle with x coord, y coord, and radius
1013 circle.graphics.beginFill('rgba(155,155,155,.5)').drawCircle(this.x, this.y, this.radius);
1014 stage.addChild(circle);
1015
1016 this.eraser = circle;
1017 }
1018
1019 remove() {
1020 stage.removeChild(this.eraser);
1021 }
1022
1023}
1024
1025eraser = {
1026 currentEraser: null,
1027
1028 handleDrawMouseDown: function (event) {
1029 let width = document.getElementById("drawSize").value*5;
1030 eraser.createEraser(stage.mouseX,stage.mouseY,width);
1031 stage.addEventListener("stagemousemove", eraser.handleDrawMouseMove);
1032 },
1033
1034 handleDrawMouseMove: function (event) {
1035 let width = document.getElementById("drawSize").value*5;
1036 eraser.createEraser(stage.mouseX,stage.mouseY,width);
1037 },
1038
1039 handleDrawMouseUp: function (event) {
1040 stage.removeEventListener("stagemousemove", eraser.handleDrawMouseMove);
1041 },
1042
1043 createEraser: function (x,y,radius) {
1044 if (eraser.currentEraser) {
1045 eraser.currentEraser.remove();
1046 }
1047 eraser.currentEraser = new LocalEraser(x,y,radius);
1048 eraser.eraseLines();
1049 stage.update();
1050 },
1051
1052 eraseLines: function () {
1053 function distance(point1,point2) {
1054 return Math.sqrt(Math.pow(point1[0]-point2[0],2)+Math.pow(point1[1]-point2[1],2))
1055 };
1056
1057 //Pre-filter the lines in the hopes of speeding this up
1058 let trimmedLineSegments = [];
1059 let originalLineIndexes = [];
1060 let lowerX = eraser.currentEraser.x - eraser.currentEraser.radius;
1061 let upperX = eraser.currentEraser.x + eraser.currentEraser.radius;
1062 let lowerY = eraser.currentEraser.y - eraser.currentEraser.radius;
1063 let upperY = eraser.currentEraser.y + eraser.currentEraser.radius;
1064 for (let i=0; i<drawer.lineSegments.length; i+=1) {
1065 let lineSegment = drawer.lineSegments[i];
1066 if (lineSegment.startX > lowerX && lineSegment.startX < upperX && lineSegment.startY > lowerY && lineSegment.startY < upperY) {
1067 trimmedLineSegments.push(lineSegment);
1068 originalLineIndexes.push(i);
1069 } else if (lineSegment.endX > lowerX && lineSegment.endX < upperX && lineSegment.endY > lowerY && lineSegment.endY < upperY) {
1070 trimmedLineSegments.push(lineSegment);
1071 originalLineIndexes.push(i);
1072 }
1073 }
1074
1075 for (let i=0; i<trimmedLineSegments.length; i+=1) {
1076 let lineSegment = trimmedLineSegments[i];
1077 let originalIndex = originalLineIndexes[i];
1078 let lineStart = [lineSegment.startX,lineSegment.startY];
1079 let lineEnd = [lineSegment.endX,lineSegment.endY];
1080 let eraserLocation = [eraser.currentEraser.x,eraser.currentEraser.y];
1081
1082 let shortestDistance = Math.min(distance(lineStart,eraserLocation),distance(lineEnd,eraserLocation));
1083 if (shortestDistance < eraser.currentEraser.radius) {
1084 lineSegment.remove();
1085 broadcastChannel.postMessage(['removeLineSegment',originalIndex])
1086 stage.update();
1087 }
1088 }
1089
1090 cleanUpNullLines();
1091 broadcastChannel.postMessage(['cleanUpNullLines']);
1092
1093 },
1094
1095 enableErasing: function () {
1096 if (globs.canvasMode) {
1097 console.log('Cant start drawing mode while another mode is active!');
1098 foo
1099 }
1100 globs.canvasMode = 'lineErasing';
1101 stage.addEventListener("stagemousedown", this.handleDrawMouseDown);
1102 stage.addEventListener("stagemouseup", this.handleDrawMouseUp);
1103 },
1104
1105 disableErasing: function () {
1106 if (eraser.currentEraser) {
1107 eraser.currentEraser.remove();
1108 }
1109 stage.update();
1110 stage.removeEventListener("stagemousedown", this.handleDrawMouseDown);
1111 stage.removeEventListener("stagemouseup", this.handleDrawMouseUp);
1112 }
1113}
1114
1115function lineErasing() {
1116 disableCurrentMode();
1117 eraser.enableErasing();
1118}
1119
1120function cleanUpNullLines() {
1121 let indexesToRemove = [];
1122 for (let i=0; i<drawer.lineSegments.length; i+=1) {
1123 if (drawer.lineSegments[i].removed) {
1124 indexesToRemove.push(i);
1125 }
1126 }
1127 for (let i=indexesToRemove.length-1; i>=0; i-=1) {
1128 indexToRemove = indexesToRemove[i];
1129 drawer.lineSegments.splice(indexToRemove,1);
1130 stage.update();
1131 }
1132}
1133
1134//Code for enabling/disabling measuring on the canvas
1135class MeasureLine extends LineSegment {
1136 constructor (startX,endX,startY,endY,offsetLength=15) {
1137 //offset is the distance between the line and the text, in px
1138 super(startX,endX,startY,endY,2,"gray",true)
1139 this.startX = startX;
1140 this.endX = endX;
1141 this.startY = startY;
1142 this.endY = endY;
1143 this.offsetLength = offsetLength;
1144
1145 this.calculateLength();
1146 this.drawText();
1147
1148 let dragger = new createjs.Container();
1149 dragger.addChild(this.rectangle);
1150 dragger.addChild(this.text);
1151
1152 this.visibleText = dragger;
1153 stage.addChild(dragger);
1154 stage.update();
1155 }
1156
1157 drawText () {
1158 let textX = (this.startX+this.endX)/2.;
1159 let textY = (this.startY+this.endY)/2.;
1160
1161 let rise = (this.endY-this.startY);
1162 let run = (this.endX-this.startX);
1163 let offsetSlope = -1*(run/rise);
1164 let offsetX = 1; let offsetY = offsetSlope;
1165 let offsetNorm = Math.pow((Math.pow(offsetX,2)+Math.pow(offsetY,2)),.5)
1166 offsetX = offsetX/offsetNorm; offsetY = offsetY/offsetNorm;
1167 offsetX = offsetX*this.offsetLength; offsetY = offsetY*this.offsetLength;
1168
1169 //Handle cases where the offset is nan
1170 if ((!offsetX && !offsetY) && run > 0) {
1171 offsetX = 0; offsetY = -1*this.offsetLength;
1172 } else if ((!offsetX && !offsetY) && run < 0) {
1173 offsetX = 0; offsetY = this.offsetLength;
1174 }
1175
1176 //Set so the number is always clockwise relative to the line
1177 if (rise < 0) {
1178 offsetX = -1*offsetX; offsetY = -1*offsetY;
1179 }
1180
1181 textX = textX + offsetX; textY = textY +offsetY;
1182
1183 let text = new createjs.Text(this.length+'ft', "bold 14px Iosevka, monospace", "#eeeeee");
1184 text.x = textX;
1185 text.y = textY;
1186 text.textAlign = 'center';
1187 text.textBaseline = 'middle';
1188 this.text = text;
1189
1190 let rectangleBounds = text.getBounds();
1191 let rectangle = new createjs.Shape()
1192 rectangle.graphics.beginFill("#1c1c1c").drawRect(rectangleBounds.x+text.x-2,rectangleBounds.y+text.y-2,
1193 rectangleBounds.width+4,rectangleBounds.height);
1194 this.rectangle = rectangle;
1195 stage.addChild(rectangle);
1196 return text;
1197 }
1198
1199 calculateLength () {
1200 let rise = (this.endY-this.startY);
1201 let run = (this.endX-this.startX);
1202
1203 length = Math.pow((Math.pow(rise,2)+Math.pow(run,2)),.5);
1204 this.length = Math.round(length/globs.pxPerFoot);
1205 }
1206}
1207
1208measurer = {
1209 currentLine: null,
1210 oldPt:null,
1211 newPt:null,
1212
1213 handleDrawMouseDown: function (event) {
1214 measurer.oldPt = [stage.mouseX,stage.mouseY];
1215 stage.addEventListener("stagemousemove", measurer.handleDrawMouseMove);
1216 },
1217
1218 handleDrawMouseMove: function (event) {
1219 measurer.newPt = [stage.mouseX,stage.mouseY];
1220 eraseMeasurer();
1221 measurer.drawLine(measurer.oldPt[0],measurer.newPt[0],measurer.oldPt[1],measurer.newPt[1]);
1222 },
1223
1224 handleDrawMouseUp: function (event) {
1225 stage.removeEventListener("stagemousemove", measurer.handleDrawMouseMove);
1226 },
1227
1228 drawLine: function (startX,endX,startY,endY) {
1229 let line = new MeasureLine(startX,endX,startY,endY);
1230 broadcastChannel.postMessage(['drawMeasurer',startX,endX,startY,endY]);
1231 measurer.currentLine = line;
1232 },
1233
1234 enableMeasuring: function () {
1235 if (globs.canvasMode) {
1236 console.log('Cant start drawing mode while another mode is active!');
1237 foo
1238 }
1239 globs.canvasMode = 'measuring';
1240 stage.addEventListener("stagemousedown", this.handleDrawMouseDown);
1241 stage.addEventListener("stagemouseup", this.handleDrawMouseUp);
1242 },
1243
1244 disableMeasuring: function () {
1245 stage.removeEventListener("stagemousedown", this.handleDrawMouseDown);
1246 stage.removeEventListener("stagemouseup", this.handleDrawMouseUp);
1247 eraseMeasurer();
1248 broadcastChannel.postMessage(['eraseMeasurer'])
1249 },
1250
1251 redrawMeasurer (startX=this.currentLine.startX,endX=this.currentLine.startY,startY=this.currentLine.endX,endY=this.currentLine.endY) {
1252 eraseMeasurer();
1253 this.drawLine(startX,endX,startY,endY);
1254 }
1255}
1256
1257function measureMode () {
1258 disableCurrentMode();
1259 measurer.enableMeasuring();
1260}
1261
1262function drawSingleMeasurer (startX,endX,startY,endY) {
1263 eraseMeasurer();
1264 let line = new MeasureLine(startX,endX,startY,endY);
1265 measurer.currentLine = line;
1266 stage.update();
1267}
1268
1269function eraseMeasurer () {
1270 if (measurer.currentLine) {
1271 stage.removeChild(measurer.currentLine.lineSegment);
1272 stage.removeChild(measurer.currentLine.visibleText);
1273 stage.update();
1274 measurer.currentLine = null;
1275 }
1276}