基于canvas使用贝塞尔曲线平滑拟合折线段的方法

基于canvas使用贝塞尔曲线平滑拟合折线段的方法个别代码可能不理解,请回复我
参考文章

	let series = [
        { x: 1, y: 0 },
        { x: 2, y: 0 },
        { x: 3, y: 1 },
        { x: 4, y: 1.3 },
        { x: 5, y: 1 },
        { x: 6, y: 0 },
        { x: 7, y: 0 },
        { x: 8, y: 0 },
        { x: 9, y: 0 },
        { x: 10, y: 0 },
        { x: 11, y: 1 },
        { x: 12, y: 1.3 },
        { x: 13, y: 0 },
        { x: 14, y: 0 },
        { x: 15, y: -1 },
        { x: 16, y: -1.3 },
        { x: 17, y: -1 },
        { x: 18, y: -4 },
        { x: 19, y: 1 },
        { x: 20, y: 1.2 },
        { x: 21, y: 1.5 }
      ]
      const ratio = 0.1 //分别对于ab控制点的一个正数,可以分别自行调整
      this.ctxg.lineWidth = 2
      this.ctxg.lineDashOffset = 100
      // this.ctxg.moveTo(this.originX, this.originY)
      //找到前一个点到下一个点中间的控制点
      this.isLine = true
      series.forEach((item, index) => {
        //当期点坐标
        let nowX = this.rightX(series[index].x),
          nowY = this.rightY(series[index].y),
          //前一个点坐标
          last1X = this.rightX(series[index == 0 ? 0 : index - 1].x),
          last1Y = this.rightY(series[index == 0 ? 0 : index - 1].y),
          //前两个点坐标
          last2X = this.rightX(series[index <= 1 ? 0 : index - 2].x),
          last2Y = this.rightY(series[index <= 1 ? 0 : index - 2].y),
          //下一个点坐标
          nextX = this.rightX(series[index == series.length - 1 ? index : index + 1].x),
          nextY = this.rightY(series[index == series.length - 1 ? index : index + 1].y),
          cAx = Math.floor(last1X + (nowX - last2X) * ratio),
          cAy = Math.floor(last1Y + (nowY - last2Y) * ratio),
          cBx = Math.floor(nowX - (nextX - last1X) * ratio),
          cBy = Math.floor(nowY - (nextY - last1Y) * ratio)
        if (index === 0) {
          this.ctxg.save()
          this.ctxg.beginPath()
          this.ctxg.strokeStyle = StepOneLineColor
          this.ctxg.lineTo(nowX, nowY)
          return
        } else if (index === 1) {
          cAx = Math.floor(last1X + (nowX - 0) * ratio)
          cAy = Math.floor(last1Y + (nowY - this.originY) * ratio)
        } else if (index === series.length - 1) {
          cBx = Math.floor(nowX - (nowX - last1X) * ratio)
          cBy = Math.floor(nowY - (nowY - last1Y) * ratio)
        }
        console.log(cAx, cAy, cBx, cBy, nowX, nowY)
        //绘制出上一个点到当前点的贝塞尔曲线
        this.ctxg.bezierCurveTo(cAx, cAy, cBx, cBy, nowX, nowY)
        })
上一篇:数据结构--排序之冒泡排序


下一篇:数组