Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabricjs canvas reset after zooming

I have a fabricjs canvas that I need to be able to zoom in and out and also change the image/object inside several times.

For this I setup the canvas in the first time the page loads like this:

fabric.Object.prototype.hasBorders = false;
fabric.Object.prototype.hasControls = false;

canvas = new fabric.Canvas('my_canvas', {renderOnAddRemove: false, stateful: false});

canvas.defaultCursor = "pointer";
canvas.backgroundImageStretch = false;
canvas.selection = false;
canvas.clear();

var image =  document.getElementById('my_image');
if (image != null) {
  imageSrc = image.src;
  if(imageSrc.length > 0){
    fabric.Image.fromURL(imageSrc, function(img) {
      img = scaleImage(canvas, img); //shrinks the image to fit the canvas
      img.selectable = false;
      canvas.centerObject(img);
      canvas.setActiveObject(img);
      canvas.add(img);
    });
  }
}
canvas.deactivateAll().renderAll();

Then when I need to change the image/object in the canvas or when the page reloads, I try to reset the canvas like this:

canvas.clear();
canvas.remove(canvas.getActiveObject());
var image =  document.getElementById('my_image');
if (image != null) {
  imageSrc = image.src;
  if(imageSrc.length > 0){
    fabric.Image.fromURL(imageSrc, function(img) {
      img = scaleImage(canvas, img); //shrinks the image to fit the canvas
      img.selectable = false;
      canvas.centerObject(img);
      canvas.setActiveObject(img);
      canvas.add(img);
    });
  }
}

Not sure if it matters but the way I change the image is by changing the source in 'my_image' and reseting the canvas with the above method.

This works well until I use canvas.zoomToPoint, as per this thread, after this, the image/object starts changing position when I reset the zoom or click the canvas with the mouse while it is zoomed, seeming to jump at each change in the top left corner direction, eventually disappearing from view.

Reset Zoom:

canvas.setZoom(1);
resetCanvas(); //(above method)

How can I restore the image/object position?

I tried doing the initial setup instead of the reset and seamed to work visually but was in fact adding a new layer of upper canvas at each new setup so it is no good.

Is there a way to reset the canvas to original state without causing this behavior and still be able to zoom in/out correctly?

like image 828
Mikel Avatar asked Mar 04 '15 19:03

Mikel


1 Answers

Although this question is very old, here is what I did using the current version of fabric.js 2.2.4:

canvas.setViewportTransform([1,0,0,1,0,0]); 

For your information: zooming to a point is a recalculation of the viewport transformation. The upper matrix is this is the initial viewport transform matrix.

like image 124
Tom-Steve Watzke Avatar answered Sep 28 '22 00:09

Tom-Steve Watzke