响应式SVG图表的CSS解决方案(折线坐标) [英] css solution for responsive SVG chart (polyline coordinates)

查看:91
本文介绍了响应式SVG图表的CSS解决方案(折线坐标)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript生成折线图中 polyline 元素的点坐标.图表必须具有固定的高度( 210px )和响应宽度(始终为其父div的 100%).

I'm using javascript to generate the points coordinates of a polyline element inside a line chart. The chart must have a fixed height (210px) and a responsive width (always 100% of its parent div).

问题是调整窗口大小时多段线的点坐标不变.

Problem is the points coordinates of the polyline don't change when resizing the window.

有没有一种方法可以将 polyline 的坐标设置为其父级 div 的百分比,以便在调整窗口大小时改变水平坐标?

Is there a way to set the coordinates of the polyline as percentage of its parent div so that the horizontal coordinates change when resizing the window ?

我知道我可以使用javascript来监听窗口调整大小并重新计算折线的点坐标,但是似乎有些矫kill过正,所以我希望有一个更轻便的纯CSS解决方案.

I know I could use javascript to listen for window resize and recalculate the points coordinates of the polyline but it seems somewhat overkill so I was hoping there was a lighter, pure CSS solution.

小提琴: https://jsfiddle.net/Hal_9100/1cnq389g/

推荐答案

您需要将 viewBox 添加到SVG.如果您希望图形水平伸展以适合该框,则还需要添加一个合适的 preserveAspectRatio 值.

You need to add a viewBox to your SVG. If you want the graph to stretch horizontally, to fit the box, then you'll also want to add a suitable preserveAspectRatio value.

* {padding: 0; margin: 0;}

#container {
    width: 60%; height: 210px;
    background: #fff;
}
svg {
    width: 100%; height: 210px;
    position: relative;
    border: 2px solid black;
}

<div id="container">
    <svg viewBox="0 0 450 210" preserveAspectRatio="none">
        <polyline id="myLine" fill="none" stroke="#2681DC" stroke-width="2" points="0,210 50,67 100,174 150,198 200,202 250,190 300,205 350,207 400,198 450,19 "></polyline>
    </svg>
</div>

https://jsfiddle.net/1cnq389g/2/

这篇关于响应式SVG图表的CSS解决方案(折线坐标)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆