(click anywhere to close)

# [Canvas] Lines & Curves

category: Website | course: Canvas | difficulty:

Let’s start with the most basic path elements of them all: straight and curved lines.

## Straight Lines

A straight line needs two things: a starting point, and subsequent points of the line.

Use `moveTo(x, y)` to set the starting point to (x,y).

Use `lineTo(x, y)` to create a line from the previous point to (x,y). You can put as many of these methods as you want after each other, but the order in which you supply them matters a lot; the line it creates uses the last coordinates as starting point.

```ctx.beginPath();
ctx.moveTo(10,10)
ctx.lineTo(20,50);
ctx.lineTo(50,20);
ctx.stroke();
```

A quadratic curve is a curved line between two points, which needs one extra control point to determine how exactly it is curved. The only difference from straight lines, therefore, is that instead of `lineTo()`, it uses:

`quadraticCurveTo(controlX, controlY, x, y) `

```ctx.beginPath();
ctx.moveTo(10,10)
ctx.stroke();
```

## Bezier Curve

The Bezier curve goes one step further, and needs two control points. This way, you make more complicated curves, going in two different directions between two points. Instead of `lineTo()`, it uses:

`bezierCurveTo(controlX1, controlY1, controlX2, controlY2, x, y)`

```ctx.beginPath();
ctx.moveTo(10,10)
ctx.bezierCurveTo(30,10,60,30,80,10);
ctx.stroke();
```

## Arc

An arc is a (part of a) circle. It allows you to create perfectly round paths from one point to another, without doing difficult things with control points. The syntax is:

`arc(x, y, r, startAngle, endAngle, direction)`

Basically, the arc draws a circle with centre point (x,y) and radius r, but then only takes the part between startAngle and endAngle.

The last parameter, direction, can be either `true` or `false`. In the first case, the arc is drawn clockwise. In the second case, counterclockwise.

```ctx.beginPath();
ctx.arc(30,30,20,0,Math.PI);
ctx.stroke();
```

## Arc Lines

Now you might be wondering: wouldn’t it be great if we could not only use arcs as standalone paths, but also as part of a path? Well you’re in luck, because instead of `lineTo()`, you can use

`arcTo(x1, y1, x2, y2, r)`

Instead of using angles, it uses two points to set the size and direction of the arc.

```ctx.beginPath();
ctx.moveTo(20,20);
ctx.arcTo(60,30,60,60,20);
ctx.stroke();
```

Such arcs are commonly used to create round corners for shapes.

CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)