I'm encountering difficulties when attempting to import SVGs to the canvas and use setZoom() with FabricJS. I am currently working with version "2.0.0.rc4".
I have made attempts to import them using two different methods, each with its own set of challenges:
1- loadSVGFromURL
fabric.loadSVGFromURL(src, function(objects, options) {
let loadedObjects = new fabric.Group(group);
var obj = fabric.util.groupSVGElements(objects, options);
canvas.add(obj).renderAll();
});
While this method successfully loads some SVGs onto the canvas, there are instances where the SVGs are displayed incorrectly. However, the zoom function works flawlessly.
loadSVGFromURL loads the SVG incorrectly
2- new fabric.Image
const image = new Image();
image.crossOrigin = "Anonymous";
image.src = src;
let imageObject;
image.onload = () => {
imageObject = new fabric.Image(image, {
scaleY: 1,
scaleX: 1,
cropX: 0,
cropY: 0,
lockUniScaling: true,
crossOrigin: 'Anonymous'
});
}
Using this method, every SVG is imported correctly. However, when I attempt to zoom in my application, the shapes of the SVGs within the viewbox/container adjust their size independently, appearing cropped or clipped. This issue may be related to the preserveAspectRatio property, but I have been unable to resolve it.
The zoom function I am utilizing is as follows. While it works effectively for the canvas and other objects, it does not produce the desired outcome for the SVGs imported using the previous method.
setCanvasZoom(value) {
// value ranges from 10 to 500.
// the zoomFactor will range from 0.1 to 5
let zoomFactor = parseInt(value, 10) / 100;
this.canvas.setZoom(zoomFactor);
this.canvas.setWidth(this.templateDimensions.width * zoomFactor);
this.canvas.setHeight(this.templateDimensions.height * zoomFactor);
this.canvas.renderAll();
}
The shapes are adjusted independently to the container
Could there be a mistake in how I am using the first method to import SVGs? I have attempted optimizing the SVGs with svgo and editing them in Illustrator without success (the issue also persists in fabricjs/kitchensink).
Is there a way to confine the SVGs within the container using the second method? Should a different approach be taken with setting the zoom?
Any assistance with these challenges would be greatly appreciated.