I have a simple svg file containing 2 rectangles and a text :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg id="mySvg" onload="init()" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="100%" width="100%" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 1371.4286 773.5047">
<script xlink:href="snap.svg-min.js" type="text/ecmascript"/>
<rect id="blackRect" style="color-rendering:auto;color:#000000;isolation:auto;mix-blend-mode:normal;shape-rendering:auto;solid-color:#000000;image-rendering:auto" ry=".16344" height="773.5" width="1371.4" y="161.71" x="-371.43" fill="#ffb380"/>
<rect id="hoverTarget" style="color-rendering:auto;color:#000000;isolation:auto;mix-blend-mode:normal;shape-rendering:auto;solid-color:#000000;image-rendering:auto" ry=".098402" height="177.14" width="286.62" y="369.51" x="180" fill="#008080"/>
<text id="viewboxText" style="word-spacing:0px;letter-spacing:0px" font-weight="bold" xml:space="preserve" font-size="27.5px" line-height="125%" y="810.93359" x="-3.165039e-005" font-family="sans-serif" fill="#000000"><tspan id="tspan3348" x="-3.165039e-005" y="810.93359">Viewbox :</tspan></text>
</svg>
and before the closing </svg> tag i added this script:
<script><![CDATA[
var mySvg, hoverTarget, viewboxText;
function init(){
mySvg=Snap("#mySvg");
hoverTarget=mySvg.select("#hoverTarget");
viewboxText=mySvg.select("#viewboxText");
hoverTarget.mousemove(hoverCursor);
}
function hoverCursor(evt){
var cursorX, cursorY;
if(evt.type==="mousemove"){
cursorX=...;
/*this is my question : how to interrogate the evt object to get X position of the cursor
according to mySvg viewbox?*/
cursorY=...;
//and, of course, how to get Y position from the evt object..
//and after that, display it on the text...
viewboxText.attr({text : "X : " + cursorX + ", Y : " + cursorY});
}
}
]]></script>
My question is : is there any way to interrogate snap event object of the event handler function to obtain viewbox coordinate of the svg parent element?
If there is, what is the syntax?
This is what I think you may be after...
First we get the inverse matrix from the element to the screen
var m = Snap.matrix( evt.target.getScreenCTM().inverse() )
// you may want to use this instead, but should be same for this case
// var m = Snap.matrix( mySvg.node.getScreenCTM().inverse() )
var newX = m.x( cursorX, cursorY )
var newY = m.y( cursorX, cursorY )
m.x(), m.y() convert the x,y coordinates with the new matrix.
jsfiddle
Related
I have an HTML file that embeds two different SVG files, like so:
<html>
<body>
<object id="svg0" data="histograms.svg" type="image/svg+xml"></object>
<object id="svg1" data="test.svg" type="image/svg+xml"></object>
</body>
</html>
Both SVG files are interactive, by adding a javascript function that is triggered by onclick, like such:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:ns1="http://www.w3.org/1999/xlink" height="172pt" version="1.1" viewBox="0 0 1209 172" width="1209pt">
<script type="text/ecmascript">
function choose(obj) {
var values = [0.08,0.77];
var names = [ "hist_1", "hist_2", "hist_3", "hist_4", "hist_5", "hist_6", "hist_7", "hist_8", "hist_9", "hist_10", "hist_11" ];
for ( var i=0; i<names.length; i++) {
var o = document.getElementById( names[i] );
o.style['opacity'] = values[0];
}
obj.style['opacity'] = values[1];
}
</script>
...
<g id="figure_1">
<g id="patch_1">
<path d=" M0 172.8 L1209.6 172.8 L1209.6 0 L0 0 z " style="fill:#ffffff;" />
</g>
<g id="axes_1">
<g cursor="pointer" id="hist_1" onclick="choose(this)">
<path d=" M20.835 70.52 L189.696 70.52 L189.696 12.96 L20.835 12.96 z " style="fill:#ffe6cc;" />
</g>
...
How can I have a click in one SVG file trigger javascript in the other SVG file? (Possibly via top level .html file as intermediate, if necessary?)
If you're writing code in test.svg then top gets you the containiner, so
var svg0 = top.document.getElementById("svg0");
would get you the object element from the container document.
Then
obj0Document = svg0.contentDocument;
if (obj0Document && obj0Document.defaultView)
obj0Window = obj0Document.defaultView;
else if (svg0.window)
obj0Window = svg0.window;
gets you the content's document and window.
accessing the SVG document's "window" allows you to access variables and functions defined in scripts in the SVG document.
e.g. obj0Window.choose(something)
Everything must have the same domain for this to work.
I have a scatter plot with line created using D3.js (as shown in the image).
The initial value to the circle radius is set to 4 however, when mouseover or click event are fired on the circle it should become 6 (r=6).
Whereas I am able to achieve this in chrome as following:
document.getElementById('dotGain' + count).style.r = 6;
the same doesn't work in IE.
The HTML created as dom is:
<circle xmlns="http://www.w3.org/2000/svg" class="dotGain" id="dotGain51" style="cursor: pointer; fill: red;" cx="440.621" cy="3.78507" r="4" />
I need to modify the r="4" to "6" on click/mouseOver in IE.
Some added help:
I tried the following to achieve the required in IE, but in vain
document.getElementById('dotGain' + count).r.animVal.valueAsString = "6";
document.getElementById('dotGain' + count).r.animVal.value = 6;
You should be changing the r attribute, not the style; and this is wrong: document.getElementById('#MyCircle') because you have a hashtag in the id name.
See a working example here:
var c = document.getElementById('c');
c.addEventListener('click', function(){
c.setAttribute('r', 6);
})
Click the circle
<svg viewBox="0 0 120 120" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="4" id="c"/>
</svg>
r is a element attribute. To change it You can use jQuery
$(el).attr('r', 6)
or in vanilla js
el.setAttribute('r', 6);
I want to scale the element created by use by keeping the fixed position in svg.
I read this
but my element is created by use
so it shows
Simply I can remove the old one and create a new one ,but I feel this a bit trouble.
So I wonder whether it exists any convenient way?
function tableBindMouseClick(parametersObject)
{
var table = document.getElementById("PointsTable");
var length = $('#PointsTable tbody tr').length;//get table rows number
for(var i =0;i<length;i++)
{
var id = i;
$($('#PointsTable tbody tr')[i]).bind('click',
(function(id)
{
return function()
{
var p = parametersObject.pointArray[id];
var x = p[0] -5;//coordinate x
var y = p[1] -5;//coordinate y
var icon = document.getElementById("point"+id);
icon.setAttributeNS(null, "transform", "translate("+-x+"," + -y +") scale(3) translate("+x+","+y+")");
};
})(id));
}
I do not know whether it is enough.
I am still modifying it.It can run but its effect is still incorrect.
The result
I can not see the error...
PS:Unfortunately,I use the defs element instead of symbol element to create icon.I also want to know difference in them,including g element.
I complete it by this parameters:
icon.setAttributeNS(null, "transform", "translate("+-2*x+"," + -2*y +")" + " scale(3)" );
I think the post makes some mistakes...
This example may make sense.
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Scalable Vector Graphics (SVG) 1.1 (Second Edition)</title>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1" width="5000" height="5000" viewBox="0 0 5000 5000">
<rect x="100" y="100" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>
<rect x="100" y="100" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"
transform ="translate(-230,-230 ) scale(3)" />
</svg>
</body>
</html>
How do I create an SVG anchor through JavaScript? Please see relevant section and an example from spec. How do I convert this example to JavaScript (basically, how to dynamically generate the container element a so that when I click the ellipse, it navigates away.
<?xml version="1.0"?>
<svg width="5cm" height="3cm" viewBox="0 0 5 3" version="1.2" baseProfile="tiny"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Example 17_01</title>
<desc>A simple link on an ellipse.</desc>
<rect x=".01" y=".01" width="4.98" height="2.98"
fill="none" stroke="blue" stroke-width=".03"/>
<a xlink:href="http://www.w3.org/">
<ellipse cx="2.5" cy="1.5" rx="2" ry="1"
fill="red" />
</a>
</svg>
This is just basic DOM:
var xlinkNS="http://www.w3.org/1999/xlink", svgNS="http://www.w3.org/2000/svg";
var a = document.createElementNS(svgNS, "a");
a.setAttributeNS(xlinkNS,"href","http://www.w3.org/");
var ellipse = document.createElementNS(svgNS, "ellipse");
ellipse.setAttributeNS(null,"cx","2.5");
ellipse.setAttributeNS(null,"cy","1.5");
ellipse.setAttributeNS(null,"rx","2");
ellipse.setAttributeNS(null,"ry","1");
ellipse.setAttributeNS(null,"fill","red");
a.appendChild(ellipse);
document.documentElement.appendChild(a);
Using my function below, it's as easy as this:
// Find the first SVG element
var svg = document.getElementsByTagName('svg')[0];
var a = createOn(svg,'a',{'xlink:href':'http://www.w3.org/'});
createOn(a,'ellipse',{cx:2.5,cy:1.5,rx:1,ry:1,fill:'red'});
function createOn(root,name,attrs,text){
var doc = root.ownerDocument,
svg = root.ownerSVGElement || root; // In case the root _is_ the <svg>
var svgNS = svg.getAttribute('xmlns');
var el = doc.createElementNS(svgNS,name);
for (var attr in attrs){
if (!attrs.hasOwnProperty(attr)) continue;
var parts = attr.split(':');
if (parts[1]) el.setAttributeNS(
svg.getAttribute('xmlns:'+parts[0]),parts[1],attrs[attr]
);
else el.setAttributeNS(null,attr,attrs[attr]);
}
if (text) el.appendChild(document.createTextNode(text));
return root.appendChild(el);
}
If you already have the ellipse and want to wrap it, then create the 'a' element and:
// Get a reference to the ellipse however you like
var ellipse = document.getElementsByTagName('ellipse')[0];
// Put the anchor node immediately preceding the ellipse
ellipse.parentNode.insertBefore(a,ellipse);
// Move the ellipse to be a child of the anchor
a.appendChild(ellipse);
I am trying to create an interactive SVG code with JavaScript, by embedding the JavaScript in the SVG. I don't know if this is the right way to do this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg"
onkeypress="move()">
<script type="text/javascript">
<![CDATA[
var x;
var y;
function move()
{
x = new Number(svg.getElementsByTagName("circle")[0].getAttribute("cx"));
y = new Number (svg.getElementsByTagName("circle")[0].getAttribute("cy"));
switch (event.keyCode)
{
case 119:
y--;
y = y.toString();
svg.getElementsByTagName("circle").setAttribute("cy",y);
break;
case 115:
y++;
y = y.toString();
svg.getElementsByTagName("circle").setAttribute("cy",y);
break;
case 97:
x--;
x = x.toString();
svg.getElementsByTagName("circle").setAttribute("cx",x);
break;
case 100:
x++;
x = x.toString();
svg.getElementsByTagName("circle").setAttribute("cx",x);
break;
default:
}
}
]]>
</script>
<rect x="0" y="0" height="500" width="500" style="stroke-width:1; stroke:black; fill:white"></rect>
<circle cx="250" cy="250" r="50" stroke="red" stroke-width="1" fill="red"></circle>
</svg>
It is supposed to have a ball that moves with wasd, but the ball doesn't move. What am I doing wrong?
Here is a working version as I would write it:
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<circle cx="250" cy="250" r="50" fill="red" />
<script type="text/javascript"><![CDATA[
var KEY = { w:87, a:65, s:83, d:68 };
var moveSpeed = 5;
var circle = document.getElementsByTagName("circle")[0];
var x = circle.getAttribute('cx')*1,
y = circle.getAttribute('cy')*1;
document.documentElement.addEventListener('keydown',function(evt){
switch (evt.keyCode){
case KEY.w:
circle.setAttribute('cy',y-=moveSpeed);
// Alternatively:
// circle.cy.baseVal.value = (y-=moveSpeed);
break;
case KEY.s:
circle.setAttribute('cy',y+=moveSpeed);
break;
case KEY.a:
circle.setAttribute('cx',x-=moveSpeed);
break;
case KEY.d:
circle.setAttribute('cx',x+=moveSpeed);
break;
}
},false);
]]></script>
</svg>
Some notes:
Don't re-get the reference to the circle again and again. Making your code DRY makes it more robust, less typing, and (in this case) faster to execute.
Edit: If you cannot figure out how to do this given my code above, post any code that is not working for you.
Don't rely on a global event object; that's old IE nonsense. Use the event object passed to your event handler.
Edit: If you reference event in your code with no parameter or local variable by that name, you are assuming that there will be a global event object set. Instead, see the code I wrote for you, which shows that the event handler is passed an event object. By giving that a name, such as I gave it the name evt, you are receiving an event object specific to your event handler.
Since you are modifying the x and y variables, there's no need to re-get the cx and cy attributes each key press.
Edit: In your original code and the answer you accepted, you have declared var x outside your event handler, and you have x = ... at the start of your event handler, and then x++ in one of the event handlers. You can either re-get the current value of x each time (as you did) and then setAttribute(...,x+1), or (as I did) you can only fetch the value of the attribute once before the event handlers and then assume that this value is correct each time you handle the key event.
Don't put your JavaScript event handlers on your elements, attach them programmatically.
Edit: In your SVG markup you have: <svg ... onkeypress="move()">. Mixing your behavior with your markup is a really bad idea in HTML, and a bad idea in SVG. Instead of using onfoo="..." attributes to describe what should happen when an event occurs on an element, instead use addEventListner() to attach the event handlers via code, without editing your SVG markup.
There's no need to coerce the numbers to strings before setting them as attributes.
Use keydown and the ASCII event codes I supplied above instead of keypress and the odd numbers you were using if you want it to work in all browsers.
Edit: You complained in another post that you cannot do this because you want the event handler to be processed repeatedly as the key is held down. Note that your desired behavior is achieved with my sample code in Chrome, Safari, Firefox, and IE (I don't have Opera to test). In other words keydown works as you wanted, despite how you thought it should behave.
Edit 2: If you want to include a script block at the top of your document, before all elements have necessarily been created, you can do something like the following:
<svg ...>
<script type="text/javascript">
window.addEventListener('load',function(){
var circle = ...;
document.rootElement.addEventListener('keydown',function(evt){
...
},false);
},false);
</script>
...
</svg>
The outer function will only run once the page has loaded, so you can be sure that the elements exist to reference them.
you can add script js into svg code by declare script tag into svg tag:
<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="40px" height="40px" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">
...
<script type="text/javascript">
window.addEventListener('load',function(){
alert('Hi')
})
</script>
</svg>
This works in Chrome. You had a few errors, like indexing getElementsByTagName only sometimes. Plus the big problem was that the onkeypress attribute wasn't binding.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
<script type="text/javascript">
<![CDATA[
var x;
var y;
function move()
{
x = new Number(document.getElementsByTagName("circle")[0].getAttribute("cx"));
y = new Number (document.getElementsByTagName("circle")[0].getAttribute("cy"));
switch (event.keyCode)
{
case 119:
y--;
y = y.toString();
document.getElementsByTagName("circle")[0].setAttribute("cy",y);
break;
case 115:
y++;
y = y.toString();
document.getElementsByTagName("circle")[0].setAttribute("cy",y);
break;
case 97:
x--;
x = x.toString();
document.getElementsByTagName("circle")[0].setAttribute("cx",x);
break;
case 100:
x++;
x = x.toString();
document.getElementsByTagName("circle")[0].setAttribute("cx",x);
break;
default:
}
}
document.documentElement.addEventListener("keypress", move);
]]>
</script>
<rect x="0" y="0" height="500" width="500" style="stroke-width:1; stroke:black; fill:white"></rect>
<circle cx="250" cy="250" r="50" stroke="red" stroke-width="1" fill="red"></circle>
</svg>
Simple Example
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M90,18c-90-45-115,102,0,69v-21l4-3h-23l-8,4h16v19c-80,15-65-106,2-63l-4,5l4-1z" fill="#CCC" stroke="#DDD" stroke-width="2" stroke-linejoin="round"/>
<path d="M87,15c-90-45-115,102,0,69v-21l4-3h-23l-8,4h16v19c-80,15-65-106,2-63l-4,5l4-1z" fill="#00F"/>
<script>
alert("Hello world");
</script>
</svg>