webfactorymk / ng2-canvas-whiteboard

Canvas whiteboard
MIT License
99 stars 50 forks source link

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

Open Solvengo opened 3 years ago

Solvengo commented 3 years ago

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);
    }
  }
fatihbabacan92 commented 3 years ago

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.