Using SVG code saved within a variable as a texture

Hi. I just started playing with Babylon.js and I have created a bunch of ribbons mathematically. I have also created an SVG to use as a texture, as it uses the heights of the ribbons to colour different areas of the SVG depending on their heights. Now if I save the SVG code to a .svg file then this works great. But I would like the ribbons to be dynamic, so I want to use the SVG code inside a variable to apply my texture. So instead of:

myMaterial.diffuseTexture = new BABYLON.Texture(‘temporaryIsland1Texture.svg’, scene);
ribbon.material = myMaterial;

I want to use:

myMaterial.diffuseTexture = new BABYLON.Texture(variableContainingSVGCode, scene);
ribbon.material = myMaterial;

This doesn’t seem to work. Is there anyway I can trick babylon.js into treating my variable code like it is an SVG file? Ideally without any extra libraries if possible.

Hi @TameAim

I found this post that might help you: How to fill a texture with base64 data? - Questions & Answers - HTML5 Game Devs Forum

PG taken from the post: https://www.babylonjs-playground.com/#1RTIYC#0

2 Likes

Thanks @slin
I’ve learnt a bit about base64 now but I still can’t quite get this to work (although I’m not getting any errors in the console, but still no texture).

let ribbon = BABYLON.MeshBuilder.CreateRibbon(islandsObj.island1.name, { pathArray: pathArray, closeArray: false, closePath: false}, scene );
// THE FOLLOWING THROWS ERRORS
let serializer = new XMLSerializer().serializeToString(variableContainingSVGCode)
// BUT APPLYING THE SVG CODE TO A RANDOM DIV AND THEN RECALLING IT DID NOT THROW ERRORS
let serializer = new XMLSerializer().serializeToString(document.getElementById(“tempShowSVG”))

// I THEN USED THIS
let encodedData = window.btoa(serializer);

// I TRIED EACH OF THE FOLLOWING AFTER SERIALIZING
let texture = ‘data:image/jpg;base64,’ + encodedData
let texture = ‘data:image/png;base64,’ + encodedData
let texture = ‘data:image/svg+xml;base64,’ + encodedData

// I TRIED EACH OF THESE WITHOUT ENCODING TOO, BUT ALSO NO LUCK
let texture = ‘data:image/svg+xml;utf8,’ + variableContainingSVGCode
let texture = ‘data:image/jpg;base64,’ + variableContainingSVGCode

// SO THIS DOES NOTHING FOR ANY OF THE ABOVE EXAMPLES
let myMaterial = new BABYLON.StandardMaterial(“island1Texture”, scene);
myMaterial.diffuseTexture = new BABYLON.Texture(texture, scene);
ribbon.material = myMaterial;

Also the solution in this topic could help, it looks like they’re doing it more like you are with the XMLSerializer, but using Texture.LoadFromDataString instead of the Texture constructor. :slight_smile:

2 Likes

Hello just checking in, was your question answered? @TameAim

Hi @carolhmj,
Unfortunately I could not get this to work, so I moved onto using bitmaps instead. That’s not to say the techniques suggested wouldn’t work for someone who understands the procedure better.

1 Like