I have fabricjs canvas, which I need to zoom in and out, and also change the image / object several times.
To do this, I set the canvas for the first time the page loads as follows:
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);
Then, when I need to change the image / object in the canvas or when the page reloads, I try to reset the canvas as follows:
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);
Not sure, it matters, but the way to change the image is to change the source in "my_image" and resell the canvas using the above method.
This works well until I use canvas.zoomToPoint , according to this thread, after that the image / object starts to change, when I reset the scale or click on the canvas with the mouse while it is enlarged, it seems that it jumps with every change in the top left corner eventually disappears from view.
Reset Scale:
canvas.setZoom(1); resetCanvas();
How to restore the position of the image / object?
I tried to do the initial setup instead of reset and take a photo to work visually, but actually added a new layer of the top canvas with each new setup, so this is not good.
Is there a way to reset the canvas to its original state without causing this behavior and still be able to scale / delete correctly?