B4J Tutorial [Web] Plug 'n Play external SVG loader

Hi Fam

As it is, I'm working on SithasoDaisy5, the next iteration of SithasoDaisy. I have been wondering if there was a way to load SVG files and then update their properties, like color, width and height as and when needed. I did not want to use the Font Awesome css files as they are including the fonts, so I have been trying to use the img tag. Thing is, with this approach you cant change anything about the SVG file easily.

Comes in the svg-loader.


And it's very simple as ABC. Let's check this code out..

SVG-Loader:
<!--
    Include this script anywhere in your code, preferably <HEAD> so
    icons can be fetched faster.
-->
<script type="text/javascript" src="svg-loader.min.js" async></script>

<!-- Use an external SVG -->
<svg
  data-src="https://unpkg.com/@mdi/svg@5.9.55/svg/star.svg"
  width="50"
  height="50"
  fill="red"></svg>
<svg
  data-src="https://unpkg.com/@mdi/svg@5.9.55/svg/heart.svg"
  width="50"
  height="50"
  fill="red"></svg>

<svg
  data-src="https://unpkg.com/@mdi/svg@5.9.55/svg/cog.svg"
  width="50"
  height="50"
  fill="currentColor"
  style="color: purple;"></svg>

For FontAwersome, if you want to host your SVG icons locally, when you have found your icon, you have to choose the SVG tab and then download your icon (top right). Then you will have to use it with the data-src.

1740929363032.png


With the tests so far, things are happening well..

1740930427314.png


To change the color of any SVG icon based on a file, you just update the style of the svg element as demonstrated below.

B4X:
<svg
  data-src="https://unpkg.com/@mdi/svg@5.9.55/svg/cog.svg"
  width="50"
  height="50"
  fill="currentColor"
  style="color: purple;"></svg>


Enjoy and have fun!
 

Mashiane

Expert
Licensed User
Longtime User
The above component monitors everything on your webapp page and refreshes everything. This was not ideal for my use case.

I have created a new component which suits my needs.

1745051978989.png


B4X:
' HERE STARTS YOUR APP
Sub BANano_Ready()
    ' get the body tag
    Private body As BANanoElement
    body.Initialize("#body")
    body.Append($"<svg-renderer id="otter" data-src="./assets/otter-solid.svg" data-js="enabled" style="margin:20px;color:red;width:64px;height:64px"></svg-renderer>"$)
    BANano.GetElement("#otter").On("click", Me, "otter_click")
End Sub

private Sub otter_click(e As BANanoEvent)
    BANano.Alert("Otter Click!")
End Sub
 

Attachments

  • SVGRender.zip
    5.5 KB · Views: 136
Last edited:
Top