Ashish
Ashish

Reputation: 498

Fabricjs: Update SVG on the canvas

I am using fabricjs 1.6.4 and I want to update the existing svg with the new one. I am using this code to add the new SVG:

fabric.loadSVGFromURL(url, function (objects, options) {
          var image = fabric.util.groupSVGElements(objects, options);
          image.name = 'sticker';
          canvas.add(image);
          image.scaleToHeight(100);
          image.center();
          image['selectable'] = false;
          image['evented'] = false;
          image.setCoords();
          canvas.renderAll();
        });
      }

How can I replace the existing SVG with the new one. I have done something related to this in the image but I can not replicate in SVG. Here is the code for image:

$scope.fillImage = function(src) {
    fabric.Image.fromURL(src, function(img) {
        var object = canvas.getActiveObject();
        object._element.src = src;
        canvas.renderAll();
    });
}

I need something like this. Please help.

Upvotes: 2

Views: 1901

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17594

You already have the variable image just make it global an you can remove before you add...
here is an example:

var image;
var canvas = new fabric.Canvas('canvas');
var url = "http://swagger-net-test.azurewebsites.net/api/SvgImage?"

function callback(objects, options) {
  if (image) canvas.remove(image);
  image = fabric.util.groupSVGElements(objects, options);
  image.name = 'sticker';
  canvas.add(image);
  image.scaleToHeight(60);
  image.center();
  image.setCoords();
  canvas.renderAll();
}

fabric.loadSVGFromURL(url + "color=red", callback)
setTimeout(
  function() {
    fabric.loadSVGFromURL(url + "color=blue", callback)
  },
  3000
);
<canvas id="canvas" width="180" height="180"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.3.4/fabric.min.js"></script>

Upvotes: 1

Related Questions