Download SVG in KineticJS

I am trying to load an SVG file and want to display it on the canvas using KineticJS (KJS), so you need to know if it is possible to show any SVG file with random shapes and paths in it, in the canvas using KJS?

Now SVGs exported through other software are also very different, say, for example, SVG exported via Adobe Illustrator has a fill, stroke, stroke width, etc. As attributes for their respective tags, while SVG exported via Inkscape, all of these are Fill, Stroke, Stroke Width, etc. As the string value of the "style" attribute, their respective tags correspond.

So, I am on the verge of my own SVG parser specific to the SVG format exported by AI, and then use it to redraw the SVG on the canvas via KJS. But before doing this, I just wanted to check:

  • Is there any tool available there that can convert all primitive (straight, straight, round, etc.) tags as a path tag? That is, instead of the rect tag and the ellipse, they are converted to equivalent path tags.
  • Is there an alternative way to load SVG onto a canvas other than KJS?
+4
source share
2 answers

Unfortunately, you cannot drawImage SVG in Canvas ( test ).

But you can use canvg to draw an SVG in a custom KineticJS form ( test ):

 var drawSvg = new Kinetic.Shape ({ x: 10, y: 10, drawFunc: function (canvas) { canvas.getContext().drawSvg (svgSource, 0, 0, 25, 25) } }); layer.add (drawSvg) 
+5
source

Actually, you can make drawImage () SVG in Canvas (the code from ArtemGr works in FF and Chrome for me).

But in Chrome, you encountered an Origin Policy error (there is an error that is reported in https://bugs.webkit.org/show_bug.cgi?id=17352 ).

I tried to use canvg with kinetics, but I found 2 problems:

  • It's slow when kinetic listening is enabled;
  • Rendering quality is very poor if you need to scale the image;

The solution I found was to use fabric rendering svg rendering, which turned out to be very excellent. The code is as follows:

 var fabricSvg; // uses the fabric SVG engine fabric.loadSVGFromUrl(svgSource, function(objects, opts) { if (objects.length > 1) fabricSvg = new fabric.PathGroup(objects, opts); else fabricSvg = objects; fabricSvg.originX = 'left'; fabricSvg.originY = 'top'; var drawSvg = new Kinetic.Shape({ x: 10, y: 10, drawFunc: function(canvas) { // use fabric SVG engine with Kinetic canvas context fabricSvg.render(canvas.getContext()); } }); layer.add(drawSvg); }); 

Thus, we can use the kinetic animation engine, which has better performance than the fabric, and the SVG Fabric rendering module.

+3
source

Source: https://habr.com/ru/post/1448065/


All Articles