Changing an SVG image with JS

I have an SVG image (thanks to @Archibald) which I need to change using JS. The replacement image is a data image.

<svg class="nboard" viewbox="0 0 268 143" xmlns="http://www.w3.org/2000/svg">
  <image class="nbimg" href="img/noticeboard.png" x="0" y="0" />
</svg>

I have two issues.

  1. The href attribute is supposed to be a URL, so is there some way to replace the image with a data image?
  2. How do I change the attributes? I tried s.SVGImageElement.x = "-43.28%";
    but I get an error: There was an error: TypeError: Cannot set properties of undefined (setting ‘x’)

So… how have you put this onto your page? Is the SVG on the page? or is this encoded into an img src?

The code I’ve posted is on the page and works.

Once the page loads an AJAX request fires and gets a screenshot of another page and returns the screenshot as a data image. That all works. What doesn’t work cos I’m not sure how to do it, is replacing the image that’s there with the returned data image.

is the “returned data image” in a data URI format already? (something like “data:image/png,base64,…”) or is it just a bunch of bytes or what?

Oh, two options. How to confuse a wizard! :biggrin: 'Tis already formatted.

If it’s already a properly formatted data uri, you should be able to just write it in as the HREF of the image tag.

Which leads us back to #2.
I assume ‘s’ in your opening post is a reference to the SVG element.

the image is a tag inside the tag. So you could s.getElementsByClassName or s.getElementsByClassName or s.children, reference the 0th element of the set, and then modify the x parameter in the following way:

s.children[0].x.baseVal.value

Alternatively (and the way that the CSS guys would prefer me to tell you), apply a transform:translate to the element.

s.children[0].style.transform = translateX(somenumberofpixels)

1 Like

Actually, it’s a reference to the image tag. Yeah, I know, crap naming!

I’ll play with your code a bit.

s[0].href = text; doesn’t seem to do it.

Well if s is pointing at the image tag, you’d just reference s? or is s pointing at the collection result?

Also, .href.baseVal (Because SVG has to be fancy and use objects.)

Theoretically you should run .decode, but…meh.

1 Like

s[0].href.baseVal - yeay!

Still working on positioning and sizing the wretched thing.

I have limited experience working with svgs, but console.dir is kind of useful here.

Putting a console.dir(s) into m_hutley’s codepen, gives a clearer picture (to me anyway :))

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.