I need a simple help, i have a svg
<svg viewBox="-8 -8 136 136">
<path stroke="#000000" stroke-width="8" d="m0 51.82677l0 0c0 -28.623135 23.203636 -51.82677 51.82677 -51.82677l0 0c13.745312 0 26.927654 5.4603047 36.64706 15.17971c9.719406 9.719404 15.17971 22.901749 15.17971 36.64706l0 0c0 28.623135 -23.203636 51.82677 -51.82677 51.82677l0 0c-28.623135 0 -51.82677 -23.203636 -51.82677 -51.82677zm25.913385 0l0 0c0 14.311565 11.60182 25.913387 25.913385 25.913387c14.311565 0 25.913387 -11.601822 25.913387 -25.913387c0 -14.311565 -11.601822 -25.913385 -25.913387 -25.913385l0 0c-14.311565 0 -25.913385 11.60182 -25.913385 25.913385z" fill="none"></path>
</svg>
I want to add this to the fabric canvas when I click a button can anybody say how to do it?
CodePudding user response:
fabric.js offers a couple of helper methods to deal with SVG content. If - as in your case - the SVGs content is represented by a string, the .loadSVGFromString()
function comes to the rescue.
Here's an example:
let svg = `<svg viewBox="-8 -8 136 136">
<path stroke="#000000" stroke-width="8" d="m0 51.82677l0 0c0 -28.623135 23.203636 -51.82677 51.82677 -51.82677l0 0c13.745312 0 26.927654 5.4603047 36.64706 15.17971c9.719406 9.719404 15.17971 22.901749 15.17971 36.64706l0 0c0 28.623135 -23.203636 51.82677 -51.82677 51.82677l0 0c-28.623135 0 -51.82677 -23.203636 -51.82677 -51.82677zm25.913385 0l0 0c0 14.311565 11.60182 25.913387 25.913385 25.913387c14.311565 0 25.913387 -11.601822 25.913387 -25.913387c0 -14.311565 -11.601822 -25.913385 -25.913387 -25.913385l0 0c-14.311565 0 -25.913385 11.60182 -25.913385 25.913385z" fill="none"></path>
</svg>`;
let canvas = new fabric.Canvas("canvas");
let path = fabric.loadSVGFromString(svg, function(objects, options) {
let obj = fabric.util.groupSVGElements(objects, options);
obj.set({
left: canvas.width / 2 - obj.width / 2,
top: canvas.height / 2 - obj.height / 2
});
canvas.add(obj).renderAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js" crossorigin="anonymous"></script>
<canvas id="canvas" width="400px" height="300px"></canvas>