Last active
April 20, 2022 03:25
-
-
Save jsbueno/ae0324efaed05b716c00c8c9714d68ba to your computer and use it in GitHub Desktop.
How to manipulate an SVG image in a document that is loaded in an <img > tag.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<img src="bla2.svg"> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//javascript typed at the console to recreate a new image from the image above, withg attributes changed | |
// ########### retrieve SVG contents as text: | |
aa = document.getElementsByTagName("img")[0]; | |
bb = await fetch(aa.src); | |
cc = await bb.arrayBuffer(); | |
dd = new TextDecoder("utf-8").decode(cc); | |
// yes - these four steps just to get the SVG source: it can't be retrieved from the | |
// DOM and have to be "re-downloaded" (at least the browser usually caches it in another layer) | |
// and then the surprise is that the "arraybuffer" thing is completly opaque. | |
// ######### convert the XML string into a live thing with a DOM | |
ee = (new DOMParser()).parseFromString(gg, "image/svg+xml"); | |
// ######### TheGoodPartsTM: manipulate SVG as DOM at will! | |
ee.children[0].children[0].style.fill="#08f"; | |
// ######### Render DOM object back to string | |
jj = new XMLSerializer().serializeToString(ii); | |
// ######### prepare string to be used as inline data for an IMG object | |
kk = encodeURI(jj); | |
// ########## Create a new image object on the document DOM | |
ll = document.createElement("img"); | |
// ########## Create image contents by pasting the encoded image data as the SRC attribute | |
// NB. : no matter what you do, your image is represented twice in memory: once | |
// as the serialized string in the src attribute, and once internal to the Image object, | |
// opaque to all javascript | |
ll.src = "data:image/svg+xml;charset=utf-8," + ll | |
// ######### Insert new image into document | |
document.body.append(ll); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment