Mergim Ujkani
Mergim Ujkani

Reputation: 329

Snap SVG change line x,y coordinates using JavaScript

I want to change the x and y coordinates of the svg line, but it keeps drawing multiple lines itself over and over again. Here is the result: http://prntscr.com/6tdexj

How do I draw only one line every 1 second ?

var paper = Snap('#one');

var timer = setInterval(function() {my_var()}, 1000);

function my_var() {
    x = Math.floor((Math.random() * 100) + 1);
    y = Math.floor((Math.random() * 100) + 1);

    console.log(x, y);

    // SVG LINE
    var line = paper.line(10, 10, x, y).attr({
        fill: 'f44',
        stroke: '#000'
    });
};

Upvotes: 0

Views: 2297

Answers (1)

joews
joews

Reputation: 30330

You're creating a new line in each interval. You should create a single line and change its properties instead:

var paper = Snap('#one');

var line = paper.line(10, 10, 10, 10)
  .attr({
  fill: 'f44',
  stroke: '#000'
})

setInterval(function() {
  var x = Math.floor((Math.random() * 100) + 1),
      y = Math.floor((Math.random() * 100) + 1);

  line.attr({ x2: x, y2: y })
}, 1000);

You could make the line transition smoothly by calling line.animate instead of line.attr:

line.animate({ x2: x, y2: y }, 500);

http://jsbin.com/josuyo/2/edit

Upvotes: 2

Related Questions