svg中画三次贝塞尔曲线

传入点数组,点对象有x,y属性

op为坐标轴原点,也可用做曲线起点

xLen为x轴长度,yLen为y轴长度,即曲线横纵跨度

smooth调节平滑程度

const line = (pointA, pointB) => {
  const lengthX = pointB.x - pointA.x
  const lengthY = pointB.y - pointA.y
  return {
    length: Math.sqrt(lengthX * lengthX + lengthY * lengthY),
    angle: Math.atan2(lengthY, lengthX)
  }
}
const svgPath = (points, command) => points.reduce((acc, point, i, a) => i === 0 ? `M ${point.x},${point.y}` : `${acc} ${command(point, i, a)}`, '')
const controlPoint = (current, previous, next, reverse, smooth) => {
  const p = previous || current
  const n = next || current
  const o = line(p, n)
  const angle = o.angle + (reverse ? Math.PI : 0)
  const length = o.length * smooth
  const x = current.x + Math.cos(angle) * length
  const y = current.y + Math.sin(angle) * length
  return [x, y]
}
const bezierCommand = (point, i, a) => {
  if (i > 0) {
    const isPartOfStraightLine = (index) => {
      if (index < 1 || index >= a.length - 1)
        return false
      return Math.abs(a[index].y - a[index - 1].y) < 0.001 && 
             Math.abs(a[index].y - a[index + 1].y) < 0.001
    }
    if (isPartOfStraightLine(i) || isPartOfStraightLine(i - 1))
      return `L ${point.x},${point.y}`
    const [cpsX, cpsY] = controlPoint(a[i - 1], a[i - 2], point, false, smooth.value)
    const [cpeX, cpeY] = controlPoint(point, a[i - 1], a[i + 1], true, smooth.value)
    const maxDistance = line(a[i - 1], point).length * 0.3
    const clampControlPoint = (x, y, anchorX, anchorY) => {
      const dist = Math.sqrt((x - anchorX) ** 2 + (y - anchorY) ** 2)
      if (dist > maxDistance) {
        const ratio = maxDistance / dist
        return [anchorX + (x - anchorX) * ratio, anchorY + (y - anchorY) * ratio]
      }
      return [x, y]
    }
    const [clampedCpsX, clampedCpsY] = clampControlPoint(cpsX, cpsY, a[i - 1].x, a[i - 1].y)
    const [clampedCpeX, clampedCpeY] = clampControlPoint(cpeX, cpeY, point.x, point.y)
    return `C ${clampedCpsX},${clampedCpsY} ${clampedCpeX},${clampedCpeY} ${point.x},${point.y}`
  }
  return ''
}
const dotString = computed(() => {
  return svgPath(dotList.value, bezierCommand)
})
const fillString = computed(() => {
  if (!dotList.value || dotList.value.length === 0) return ''
  const pathData = svgPath(dotList.value, bezierCommand)
  return `M ${op.x},${op.y} L` + pathData.substr(1) + `L ${op.x + xLen},${op.y}`
})

 仅个人记录,方便下次使用

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Newlz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值