tldraw/utils/svg.ts

64 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-05-09 13:04:42 +00:00
// Some helpers for drawing SVGs.
2021-05-31 19:13:43 +00:00
import * as vec from './vec'
import { getSweep } from 'utils/utils'
2021-05-09 13:04:42 +00:00
// General
export function ellipse(A: number[], r: number) {
return `M ${A[0] - r},${A[1]}
a ${r},${r} 0 1,0 ${r * 2},0
a ${r},${r} 0 1,0 -${r * 2},0 `
}
export function moveTo(v: number[]) {
return `M ${v[0]},${v[1]} `
}
export function lineTo(v: number[]) {
return `L ${v[0]},${v[1]} `
}
export function line(a: number[], ...pts: number[][]) {
return moveTo(a) + pts.map((p) => lineTo(p)).join()
}
export function hLineTo(v: number[]) {
return `H ${v[0]},${v[1]} `
}
export function vLineTo(v: number[]) {
return `V ${v[0]},${v[1]} `
}
export function bezierTo(A: number[], B: number[], C: number[]) {
return `C ${A[0]},${A[1]} ${B[0]},${B[1]} ${C[0]},${C[1]} `
}
export function arcTo(C: number[], r: number, A: number[], B: number[]) {
return [
2021-05-31 19:13:43 +00:00
moveTo(A),
'A',
2021-05-09 13:04:42 +00:00
r,
r,
0,
2021-05-31 19:13:43 +00:00
getSweep(C, A, B) > 0 ? '1' : '0',
2021-05-09 13:04:42 +00:00
0,
B[0],
B[1],
2021-05-31 19:13:43 +00:00
].join(' ')
2021-05-09 13:04:42 +00:00
}
export function closePath() {
2021-05-31 19:13:43 +00:00
return 'Z'
2021-05-09 13:04:42 +00:00
}
export function rectTo(A: number[]) {
2021-05-31 19:13:43 +00:00
return ['R', A[0], A[1]].join(' ')
2021-05-09 13:04:42 +00:00
}
export function getPointAtLength(path: SVGPathElement, length: number) {
const point = path.getPointAtLength(length)
return [point.x, point.y]
}