ng2-canvas-whiteboard icon indicating copy to clipboard operation
ng2-canvas-whiteboard copied to clipboard

(FIX FOR ERROR TypeError: this.x.toFixed) Saving and Reloading without edit Doubles the length of the updates array

Open Solvengo opened this issue 4 years ago • 1 comments

A problem occurs when the drawing gets saved to Sessionstorage, or in our case to a string variable. After an initial save, when the drawing is loaded it can't be saved again. update.stringify() throws an TypeError "this.x.toFixed()". I noticed that the length of the updates arrays doubles. What causes this? Did you forget to reset the array after an initial update.stringify()? Or does this.canvasWhiteboardService.drawCanvas(updates) add the drawing twice which causes problems?

savetoDB() {
    const updates: Array<CanvasWhiteboardUpdate> = this.canvasWhiteboardComponent.getDrawingHistory();
    console.log(updates.length); // 415 first time, 830 second time without editing

    const stringifiedUpdatesArray: Array<string> = updates.map((update) =>
      update.stringify()
    );
    console.log(stringifiedUpdatesArray.length);
    const stringifiedStorageUpdates: string = JSON.stringify(
      stringifiedUpdatesArray
    );
    // Save the item in storage of choice
    this.formService.currentProject.drawingBase64 = stringifiedStorageUpdates;
  }

  loadFromDB() {
    console.log(this.formService.currentProject.drawingBase64);
    const canvasDrawingsJson: string = this.formService.currentProject
      .drawingBase64;

    if (canvasDrawingsJson != null && canvasDrawingsJson !== '') {
      console.log('null');
      const parsedStorageUpdates: Array<string> = JSON.parse(
        canvasDrawingsJson
      );

      const updates: Array<CanvasWhiteboardUpdate> = parsedStorageUpdates.map(
        (updateJSON) => CanvasWhiteboardUpdate.deserializeJson(updateJSON)
      );

      this.canvasWhiteboardService.drawCanvas(updates);
    }
  }

Solvengo avatar Feb 26 '21 14:02 Solvengo

I fixed it by adding this to the loadFromStorage() method. This prevents the code from pushing the saved array to the original array twice.

      if (
        this.canvasWhiteboardComponent.getDrawingHistory().length !=
        updates.length
      ) {
        this.canvasWhiteboardService.drawCanvas(updates);
      }

I also added this to the savetoStorage() method.

    const updates: Array<CanvasWhiteboardUpdate> = this.canvasWhiteboardComponent.getDrawingHistory();

    for (const u of updates) {
      u.x = Number(u.x);
      u.y = Number(u.y);
    }

I'll do a pull request later this day.

fatihbabacan92 avatar Feb 26 '21 14:02 fatihbabacan92