Pierre Olivier Tran
Pierre Olivier Tran

Reputation: 1875

fabricJS - get object classes

I'm importing a simple SVG, including two paths. Both of them have CSS classes.

Once loaded in my canvas, I'd like to access these classes. Is it possible ?

I tried using myPath.class, returned undefined, and inspecting my object itself doesn't show anything that looks like my classes.

Upvotes: 0

Views: 1161

Answers (1)

Marius Turcu
Marius Turcu

Reputation: 1511

You need to add the class attribute to fabric.SHARED_ATTRIBUTES array. Here is an example for rectangle.

fabric.Rect.ATTRIBUTE_NAMES.push('class');
canvas = new fabric.Canvas('editorCanvas', {
  backgroundColor: 'white',
  selectionLineWidth: 2,
  width: $("#canvasContainer").width(),
  height: $("#canvasContainer").height()
});


fabric.loadSVGFromString($('#textareaId').val(), function(objects, options) {

  var obj = fabric.util.groupSVGElements(objects, options);
  canvas.add(obj).renderAll();
  alert(canvas.getObjects()[0].class);
});
#canvasContainer {
  width: 100%;
  height: 100vh;
  background-color: gray;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script>

<div id="canvasContainer">
  <canvas id="editorCanvas"></canvas>
</div>
<textarea rows="4" cols="50" id="textareaId">
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 width="100px" height="200px" viewBox="0 0 100 200" style="enable-background:new 0 0 100 200;" xml:space="preserve">
<style type="text/css">
	.st0{fill:#8DC63F;}
	
</style>
<rect x="3.2" y="8.8" class="st0" width="92.6" height="72.4"/>

</svg>

</textarea>

Upvotes: 1

Related Questions