Reputation: 783
Fabric docs suggest it might be possible to create an image from an SVG element using fabric.Image.fromElement(element, optionsopt, callback) → {fabric.Image}
I seem to be running into TypeError: t.getAttribute is not a function
when trying to test it out.
Any idea what I might be doing wrong? Does this method possibly not do what I think it does?
Code sample:
fetch('https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/tiger.svg')
.then((response) => response.text())
.then((svg) => {
fabric.Image.fromElement(svg, (image) => {
console.log('image: ', image);
});
})
.catch(function(error) {
console.log(error);
});
In a pen: https://codepen.io/sheepgobeep/pen/GwNOeE
Upvotes: 0
Views: 2707
Reputation: 14731
FromElement is not a public method. That is not clear and i'll fix the docs.
FromElement gets called from the svg parser, but you can use it just on the whole SVG, and you can then discard what you do not need.
In the case of the tiger.svg you get a bunch of shapes and lines that do not make sense if not handled in a group.
You can use
fabric.loadSVGFromString: function(string, callback, reviver, options)
and inside the callback:
callback(objects, options) {
var group = fabric.groupSVGElements(objects, options);
}
Or you can you the fromImage like suggested in the other answer. The difference is that the Image is like a jpeg that can scale better when zoomed, while the group is slower to render but gives you access to each pieces of the SVG ( that can be useless if you do not need to change anything )
Upvotes: 3
Reputation: 4988
While this is not obvious from fabric.js docs, if you want to create an image from an SVG URL, you should actually use fabric.Image.fromURL()
. Try this:
const canvas = new fabric.Canvas("c")
const callback = (image) => {
canvas.add(image).renderAll()
}
fabric.Image.fromURL('https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/tiger.svg', callback, {
width: 900,
height: 900,
scaleX: 0.2,
scaleY: 0.2
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<canvas id='c' width="500" height="400"></canvas>
Also, note that you're using an old version of the library (1.7.22) while you're looking at the updated version of docs (v2+)
Upvotes: 1