响应式CHART svg

时间:2015-10-15 21:48:14

标签: javascript jquery d3.js svg rickshaw

我正在尝试做响应式图表...我使用了这个,但它没有响应,只是当我刷新页面缩放到正确的宽度...然后我有任何其他的想法?

我尝试使用divviewBox设置preserveAspectRatio ..但结果相同..

var graph = new Rickshaw.Graph( {
    element: document.querySelector("#chart"),
    height: 100,  
    series: [{
        color: '#1abc9c',
        data: [ 
            { x: 0, y: 50 }, 
            { x: 1, y: 50 }, 
            { x: 2, y: 40 }, 
            { x: 3, y: 40 }, 
            { x: 4, y: 30 },
            { x: 5, y: 20 },
            { x: 6, y: 0 },
            { x: 7, y: 0 } ]
    }]
});
 
graph.render();

var svg = d3.select('.chart-container').append("svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 '+Math.min(width,height)+' '+Math.min(width,height))
    .attr('preserveAspectRatio','xMinYMin')
    .append("g")
    .attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");
<div class="chart-container" id="chart"></div>

1 个答案:

答案 0 :(得分:0)

好的,谢谢 Mark Sizer ..解决方案就在这里:

var seriesData = [ [
            { x: 0, y: 50 }, 
            { x: 1, y: 50 }, 
            { x: 2, y: 50 }, 
            { x: 3, y: 40 }, 
            { x: 4, y: 40 },
            { x: 5, y: 20 },
            { x: 6, y: 0 },
            { x: 7, y: 0 } ] ];
var graph = new Rickshaw.Graph( {
	element: document.getElementById("chart"),
	renderer: 'area',
	series: [
		{
			data: seriesData[0],
			color: '#1abc9c'
		}
	]
} );
var resize = function() {
	graph.configure({
		width: window.innerWidth * 0,
		height: window.innerHeight * 0.20
	});
	graph.render();
}
window.addEventListener('resize', resize); 
resize();
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rickshaw/1.5.1/rickshaw.js"></script>


<div id="chart"></div>