我渲染一个SVG线,每隔50ms就会添加一个新点。几秒钟后,该行不在页面上。如何让SVG保持视图中最新的部分,同时将旧部分移出视图
var $series = $('#series');
var data = [];
setInterval(function() {
// Add random data step
var newValue = Math.floor(Math.random() * 10) - 5;
data.push(newValue)
// Rerender line
var newPoints = 'M10 50 ';
data.forEach(function(y) {
console.log(y);
newPoints += "l 10 " + y + " ";
});
console.log(newPoints);
$('#series').attr('d', newPoints);
}, 50);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width="1000" height="500" version="1.1" xmlns="http://www.w3.org/2000/svg">
<path id="series" d="M10 250 l 10 10 l 10 20 l 10 50 l 10 -20" stroke="red" stroke-width="2" fill="none" />
</svg>
&#13;
答案 0 :(得分:1)
var $series = $('#series');
var chart = $('#chartdiv').find('svg')[0];
var data = [];
var xmin = 0;
setInterval(function() {
// Add random data step
xmin = xmin + 10;
var newValue = Math.floor(Math.random() * 10) - 5;
data.push(newValue)
// Rerender line
var newPoints = 'M10 50 ';
data.forEach(function(y) {
//console.log(y);
newPoints += "l 10 " + y + " ";
});
//console.log(newPoints);
$('#series').attr('d', newPoints);
if (xmin > 1000 )
{
var gmin = xmin - 1000;
chart.setAttribute('viewBox', gmin + " 0 1000 500");
}
}, 50);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='chartdiv'>
<svg viewBox="0 0 1000 500" width="1000" height="500" version="1.1" xmlns="http://www.w3.org/2000/svg">
<path id="series" d="M10 250 l 10 10 l 10 20 l 10 50 l 10 -20" stroke="red" stroke-width="2" fill="none" />
</svg>
</div>
&#13;
尝试上面的这个代码段。我添加了一个viewBox并增加了viewBox&#34; x&#34;每个循环中的值,以便在绘制时实时移动查看区域。