Using predefined SVG file for creating a custom Jo

2019-02-28 05:06发布

问题:

I have a series of pre-created SVG symbols I want to use in JointJS. I've searched about using precreated SVGs and I found to be possible to create a complete custom elements using SVG by putting the SVG in the 'markup' property - (https://groups.google.com/forum/#!topic/jointjs/pQvN_0lXPVk).

Below is the example of an SVG. Your help about how can I embed this definition in the markup property and add ports to it will be highly appreciated.

Thanks

<?xml version="1.0" standalone="no"?>
<svg viewBox="0 0 1024 768" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" stroke-linecap="round" stroke-linejoin="round" fill-rule="evenodd" xml:space="preserve" >
<defs >
<clipPath id="clipId0" >
<path d="M0,768 1024,768 1024,0 0,0 z" />
</clipPath>
</defs>
<g stroke-width="0.1" clip-path="url(#clipId0)" fill="none" stroke="rgb(0,0,0)" />
<g stroke-width="0.25" clip-path="url(#clipId0)" fill="rgb(0,0,0)" stroke="none" >
<path d="M1013.96,634.98 10.0392,634.98 1013.96,133.02 z" />
</g>
<g stroke-width="0.25" clip-path="url(#clipId0)" fill="none" stroke="rgb(0,0,0)" >
<polyline points="10.0392,133.02 1013.96,133.02 1013.96,634.98 10.0392,634.98 10.0392,133.02 " />
<polyline points="10.0392,634.98 1013.96,133.02 " />
</g>
</svg>

回答1:

You can add the SVGImageElement to your markup to display arbitrary SVG in your shapes. Just convert the SVG file content to dataURL and set the xlink:href attribute.

var shape = new joint.shapes.basic.Image({
  // markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',      
  attrs: {
    image: {
      'xlink:href': 'data:image/svg+xml;utf8,' + encodeURLComponent(svgFileContent)
    } 
  }
});

http://jsfiddle.net/kumilingus/eqen3pdf/

In order to create a shape showing an SVG image and yet having ports you can e.g. use devs.Model shape and replace the only SVGRectElement in its markup with an SVGImageElement.

new joint.shapes.devs.Model({
  markup: '<g class="rotatable"><g class="scalable"><image class="body"/></g><text class="label"/><g class="inPorts"/><g class="outPorts"/></g>',
  attrs: {
  '.body': {
    'xlink:href': 'data:image/svg+xml;utf8,' + encodeURLComponent(svgFileContent)
  },
  inPorts: ['in'],
  outPorts: ['out']
});

http://jsfiddle.net/kumilingus/tm2ctvxq/

Note, that it's possible to insert the SVG file content directly into your markup (without <?xml version="1.0" standalone="no"?>). I would not recommended it for more complex SVG though.

For instance when SVG contains an SVGClipPathElement with an id. Creating 2 instances of your shape breaks condition that all the IDs in the SVG must be unique.