A
A
Andrey Ilinskiy2017-01-15 21:04:41
JavaScript
Andrey Ilinskiy, 2017-01-15 21:04:41

What is the easiest way to change the attributes of an SVG element through JS?

Hello everybody! I want to change the x2, y2 coordinates of the line element to the values ​​of some function from the mouse coordinates and the coordinates of other SVG elements. I am writing a JS script. I work through getAttribute, setAttribute like this:

<svg width="100" height="100">
  <line id="line1" x1="10" y1="10" x2="50" y2="50" stroke="red"/>
  <line id="line2" x1="10" y1="10" x2="50" y2="50" stroke="red"/>
<svg>

<script>
  var line1=document.getElementById("line1");
  var line2=document.getElementById("line2");
  
  var x1=line1.getAttribute("x2")
  
  line2.setAttribute("x2", функция(координаты мышки, x1, другие переменные));
</script>

Maybe something easier? At least through object.property=...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter, 2017-01-15
@petermzg

_elm: function(sel){
     return this._cldElm(this.svg, sel);
},
_cldElm: function(elm, sel){
    return elm.querySelector(sel);
},
setAttr: function(el, ns, nm, vl){
     el.setAttributeNS(ns, nm, vl);
},
setAttrs: function(el, attrs){
     for (var a in attrs)
         this.setAttr(el, null, a, attrs[a]);
},
// и пример использования
var ln = this._elm('.svg-line');
this.setAttrs(ln, { x1: x - 50, y1: (rowId * 80) + 40, x2: x - 10, y2: y + 35 });

L
lega, 2017-01-16
@lega

https://jsfiddle.net/lega911/2u9ucevz/

D
ddd329, 2017-01-17
@ddd329

ractivejs
e75e4b64da304558b3a1be4486dcad75.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question