Arpad Bajzath
Arpad Bajzath

Reputation: 896

How to fit SVG into parent object in Fabric.js

How do i set the SVG size in the Fabric.js loadSVGFromString method? I've could not find any solution to fit into a parent object (groupSVGElements). Also checked the docs, but everywhere i just saw they use always that canvas size which size has the SVG.

Example: http://codepen.io/bajzarpa/pen/wJOOdB?editors=1010

Upvotes: 0

Views: 1650

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

Since, your current SVG Element does not contain any width and height property, you'll need to use viewBox.baseVal.width and viewBox.baseVal.height to get it's width and height respectively and set it accordingly to fit into a parent object.

// get the svg's width and height
let svg = document.querySelector('#testvg');
let svgWidth = svg.viewBox.baseVal.width;
let svgHeight = svg.viewBox.baseVal.height;

// set to fit into a parent object (canvas)
graphic.set({
    top: 5,
    left: 5,
    width: svgWidth,
    height: svgHeight,
    scaleX: (canvas.width - 10) / svgWidth,
    scaleY: (canvas.height - 10) / svgHeight
 });

WORKING DEMO on CodePen

Upvotes: 1

Related Questions