Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw curved lines with css or canvas

I need to draw dynamic curved lines to show flight durations.

Any idea how I can do it?

I was try with clean css but have some rendering problems, I think only method is to use canvas.

enter image description here

like image 710
vrabota Avatar asked Jan 15 '16 10:01

vrabota


People also ask

How do I draw a curved line in canvas?

Curved lines are drawn on the canvas with the quadraticCurveTo() method or the bezierCurveTo() method. The difference between the two methods is that the former allows you to specify one curve, while the latter will enable you to specify two. The curves are made by adding a control point.

Which tool do you use to draw curved lines?

Use the Pen tool. Optionally, use the Line tool to draw a straight line. Then use the Selection tool to make the line curve. To draw curves freehand, use the Pencil tool with smoothing.

How do you draw a curved line in HTML?

The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve. A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve.


1 Answers

You could use SVG it's a bit more browser agnostic I suppose.

SVG Browser Support

Canvas Browser Support

Something like this in your 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>

Of course this could be generated via Javascript and then rendered. JSFiddle

SVG Tutorial

A Brief intro into the dynamic JS generation would be something along these lines. :

Create your dom element :

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

Now we add some JS attributes that you will generated based on variables in flight info:

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);

Add some CSS Animation to make it a little prettier and you end up with the following example :

JSFiddle Dynamic

like image 175
Pogrindis Avatar answered Oct 19 '22 18:10

Pogrindis