Reputation: 598
I am just learning d3 and I want to know if its the right way to render svg line everysecond?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>d3 test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<script>
//Width and Height
var w = 500;
var h = 50;
//Create SVG Element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Global array
var linedata = [];
//random multiplier
var randNum = 50;
setInterval(function() {
var random = {
a: Math.floor(Math.random()*randNum),
};
linedata = [ "M 0 0 L 200 " + (100+random.a) ];
line = svg.selectAll("path")
.data(linedata)
.enter()
.append("path");
line.attr("d", function(d) {
return d;
})
.attr("stroke","orange")
.attr("stroke-width", 7)
.attr("fill","none");
}, 10);
setInterval(function() {
svg.selectAll("path")
.remove();
}, 10);
</script>
Problem My problem is that line keeps flickering even the time I set at setInterval is very fast.
what I want is the line wont flicker and renders smoothly every millisecond or not noticeable that it rerenders
what I want to achieve is similar to this one, but its in Javascript and Jquery not with d3 library
SVG animation with mousemove function inside setInterval function
Regards.
Upvotes: 0
Views: 706
Reputation: 124199
If you have one function adding something and the other removing it, it's going to flicker. Just move the existing line.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>d3 test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<script>
//Width and Height
var w = 500;
var h = 50;
//Create SVG Element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var line = svg.append("path")
.attr("stroke","orange")
.attr("stroke-width", 7)
.attr("fill","none");
//Global array
var linedata = [];
//random multiplier
var randNum = 50;
setInterval(function() {
var random = {
a: Math.floor(Math.random()*randNum),
};
linedata = [ "M 0 0 L 200 " + (100+random.a) ];
line.data(linedata);
line.attr("d", function(d) {
return d;
})
}, 10);
</script>
Upvotes: 1