htmlsvgx3dom

HTML - Include SVG image as MFString


Is there anyway, in one HTML file, can you include the SVG generated as an MFString?

My situation is as followed. Let's say there is a simple SVG draw like:

<svg id="wanna-be-background" width="400" height="110">
  <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)">
  Sorry, your browser does not support inline SVG.  
</svg>

And in X3DOM, the background field backURL take into argument as MFString, as described here:

<background backurl="<wanna-be-background>"></background>

Can you some how include the SVG generated from HTML to X3DOM, without the need of an external SVG image?


Solution

  • Apparently you can do it using a dataURI version of your svg markup.

    However, I experienced some bug at first while doing tests, so there may be some caveats...

    Here is an example code :

    // the svg to use
    var svgEl = document.getElementById('wanna-be-background');
    // serialize it to a string
    var svgStr = new XMLSerializer().serializeToString(svgEl);
    svgEl.parentNode.removeChild(svgEl)
    // convert this string to a dataURI one
    var dataURI = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgStr);
    
    //set your background's attributes
    bg.setAttribute('frontURL', dataURI);
    bg.setAttribute('backURL', dataURI);
    bg.setAttribute('topURL', dataURI);
    bg.setAttribute('bottomURL', dataURI);
    bg.setAttribute('leftURL', dataURI);
    bg.setAttribute('rightURL', dataURI);
    
    // works also for imageTexture's url
    iT.setAttribute('url', dataURI.replace('red', 'blue'))
    <script type='text/javascript' src='http://www.x3dom.org/download/x3dom.js'>
    </script>
    <link rel='stylesheet' type='text/css' href='http://www.x3dom.org/download/x3dom.css'></link>
    </head>
    
    <body>
    
      <x3d width='600px' height='400px'>
        <scene>
          <shape>
            <appearance>
    
              <ImageTexture id="iT" metadata='X3DMetadataObject'></ImageTexture>
            </appearance>
            <box></box>
          </shape>
          </transform>
          <background id="bg"></background>
        </scene>
      </x3d>
    
      <svg id="wanna-be-background" width="120" height="120" viewPort="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg">
    
        <polygon points="60,20 100,40 100,80 60,100 20,80 20,40" fill="red" />
    
      </svg>