My objective is to change the viewBox attribute in an SVG file retrieved from an API server through a websocket by scrolling the mouse wheel. Here's how I accomplish this:
Create
<object id={"std-chart"} class="mouse-wheel-pannable" type="image/svg+xml" />
Receive data
svgStr
from the websocket, then dynamically insert it into the<object>
element.let obj = document.getElementById('std-chart'); var objUrl = 'data:image/svg+xml;utf8,'+ svgStr; obj.setAttributeNS(null,'data',objUrl);
where svgStr
looks something like this:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1081" height="184" viewBox="0 0 1081 184" >
<path d="M 0.0 98.7 L 0.3 98.7 .../>
</svg>
Q1. Why do I have to append data:image/svg+xml;utf8,
before the svgStr
? Without it, the image doesn't display correctly.
In my mouseWheelScroll() function, I attempt to locate the svg element and update its viewBox. However, I encounter the issue that
contentDocument
returns null.var svgObjs = document.getElementsByClassName("mouse-wheel-pannable"); var svgObj = svgObjs[0].contentDocument; //svgObj returns null var svg = svgObj.getElementsByTagName('svg')[0]; //error here svg.setAttributeNS(null, 'viewBox', someNewViewBox);
How can I obtain a valid contentDocument i.e.
<svg>
element to modify the viewBox?
Thank you.
I experimented using <embed>
instead of <object>
, saw the embed item in the Chrome console, yet I still struggle with accessing the underlying <svg>
. Is the <svg>
shown in the image below still relevant?
Please click here to view the chrome console screenshot.
Thank you.
Further testing revealed that setting <object data=xxxxxx.svg/>
initially, i.e., storing the svg content in a file and loading it when initializing <object>
, works perfectly. The question arises of how to dynamically "reload" the svg content for the <object>
.
Thank you.