all repos — simplyrpg @ b7dad4e64551b9afaadd503db6389daa3362ccd3

Fork of https://github.com/harperd1/simplyRPG — multi-map VTT, token visibility, dark theme, stream HUD

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