Reputation: 59
I want to make an SVG element pan-able, it seems to be possible by only manipulating the first 2 values of the viewBox attribute. I cant figure out however if it's possible to use variables inside setAttribute.
Here is my js code so far:
function panSvg(event) {
var x = event.clientX - 498;
var y = event.clientY - 183;
//show coordinates in a <p> element
document.getElementById("opf").innerHTML = "X: " + x + " Y: " + y;
//make viewBox react to mouse movement
document.getElementById("svag").setAttribute("viewBox", y x 100 100);
}
the html:
<svg id="svag" onmousemove="panSvg(event)" width="600" height="600" viewBox="0 0 100 100">
I know or feel that x and y in the place of user defined left and right corner values (where there is originally 0 0 in the html) kinda hurts, but maybe I just need proper syntax? (For now I only want to see if it does something with the viewBox, I didn't figure out yet how to set x and y for proper panning). I saw way too complex solutions for zooming, which I achieved rather easily, I hope there is an elegant solution for this too.
Upvotes: 3
Views: 11789
Reputation: 7526
String concatination becomes easier with es6 template strings. You can use variables in strings like this:
document.getElementById("svag").setAttribute("viewBox",`${y} ${x} 100 100`);
Upvotes: 3
Reputation: 123985
If you already have a viewBox attribute you can use the DOM to manipulate it. No parsing or string concatenation required.
function panSvg(evt) {
var x = (evt.clientX - 50) / 2;
var y = (evt.clientY - 50) / 2;
//make viewBox react to mouse movemen;
root = document.getElementById("svag");
root.viewBox.baseVal.x = x;
root.viewBox.baseVal.y = y;
}
<svg id="svag" onmousemove="panSvg(evt)" width="600" height="600" viewBox="0 0 100 100">
<rect width="100" height="100" fill="blue"/>
</svg>
Upvotes: 4
Reputation: 17351
I don't believe you can use variables, but just make it into a string via concatenation and manipulate it so that the pattern of spaces mimics the desired output.
I.e., change this line:
document.getElementById("svag").setAttribute("viewBox", y x 100 100);
to this:
document.getElementById("svag").setAttribute("viewBox", y + " " + x + " 100 100");
Upvotes: 2
Reputation: 21565
You can simply use a string of concatenated variables:
document.getElementById("svag").setAttribute("viewBox", y + " " + x + " 100 100");
Upvotes: 3