【问题标题】:Draw curved lines with css or canvas用css或canvas画曲线
【发布时间】:2016-04-20 22:13:04
【问题描述】:

我需要绘制动态曲线来显示飞行时长。

知道我该怎么做吗?

我尝试使用干净的 css,但有一些渲染问题,我认为唯一的方法是使用画布。

【问题讨论】:

    标签: javascript html css canvas


    【解决方案1】:

    您可以使用SVG,我想它与浏览器无关。

    SVG Browser Support

    Canvas Browser Support

    在你的 HTML 中有这样的东西:

    <?xml version="1.0" standalone="no"?>
    <svg width="190px" height="160px" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <path d="M10 80 Q 95 10 180 80" stroke="black" fill="transparent"/>
    </svg>
    

    当然这可以通过Javascript 生成然后渲染。 JSFiddle

    SVG Tutorial

    对动态 JS 生成的简要介绍将是这样的。 :

    创建你的 dom 元素:

    <svg id="flight" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    </svg>
    

    现在我们添加一些您将根据航班信息中的变量生成的 JS 属性:

    var svgNS = "http://www.w3.org/2000/svg";
    var flightPath = document.createElementNS(svgNS,"path");
    
    flightPath.setAttributeNS(null,"id","path_1");
    //This is what you need to generate based on your variables
    flightPath.setAttributeNS(null,"d","M10 80 Q 95 10 180 80");
    //Now we add our flight path to the view. 
    document.getElementById("flight").appendChild(flightPath);
    

    添加一些 CSS 动画让它更漂亮一点,你会得到以下示例:

    JSFiddle Dynamic

    【讨论】:

    • 这是一个很好的解决方案!您可以轻松地让 JS 根据 SVG 元素的宽度计算路径的弧度。比如:jsfiddle.net/t93tmh8m/2
    • @Moob 我们也可以为飞机从左到中设置动画吗?
    • @vrabota 我不明白为什么不这样做。这是an example of SVG motion along a path from the docs。我在this jsFiddle 中添加了一个简单的示例——只需稍加努力,animateMotion 元素的创建也可以使用 JS 本身来完成。附言您可能希望使用看起来像平面的多边形来代替圆;)
    猜你喜欢
    • 2014-01-15
    • 2013-01-07
    • 1970-01-01
    • 2016-01-22
    • 2014-12-16
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    相关资源
    最近更新 更多