How can I render SVG dynamically?

I want to create a small SVG at the start of a level, and render it to a sprite. The content of the SVG depends on game conditions, so I can’t load it from a file. I tried calling scene.load.svg with a data: URL but got “Local data URIs are not supported”. Are there plans to change this? Is there another way to do it?

1 Like

I loaded an SVG the normal way, followed Phaser’s execution path in a debugger, and cribbed some of the code into a scene method that works for me in Chrome and Android Webview.

  svg2texture (key, svg_text) {
    return new Promise(function(resolve, reject) {
      const svg_image = new Image()
      svg_image.onload = () => {
        this.textures.addImage(key, svg_image)
        resolve()
      }
      svg_image.onerror = (error) => {
        reject(error)
      }
      svg_image.src = 'data:image/svg+xml,' + encodeURIComponent(svg_text)
    }.bind(this))
  }

It would be nice to have something like this built in.

My use case is re-using the same SVG with different fill and stroke colours for the various paths, but because I cannot alter the SVG once it is loaded by Phaser, the server ends up having to generate a new SVG file when a new colour combination is encountered.

It’s less than ideal because possible combinations across various files can potentially yield file counts of exceeding a million.

1 Like