关注我 么么哒

【函数封装】

  • 作者:smile
  • 学无止境
  • 时间:Fri Jul 10 2020 20:30:57 GMT+0800 (China Standard Time)
  • 81人已阅读
简介 canvas绘制箭头

实线箭头

drawArrow (Object)

参数说明

  • ctx: context对象
  • fromX: 开始点x坐标
  • fromY: 开始点y坐标
  • toX: 目标点x坐标
  • toY: 目标点y坐标
  • controlX: 控制点X坐标
  • controlY: 控制点Y坐标
  • theta 分叉角度
  • headlen 箭头大小
  • width 线条宽度(默认1px)
  • color 线条颜色(默认黑色)
  • type 线条类型(默认折线)
drawArrow (arrow) {
      var ctx = typeof (arrow.ctx) !== 'undefined' ? arrow.ctx : this.context
      var fromX = arrow.fromX
      var fromY = arrow.fromY
      var toX = arrow.toX
      var toY = arrow.toY
      var controlX = typeof (arrow.controlX) !== 'undefined' ? arrow.controlX : arrow.fromX
      var controlY = typeof (arrow.controlY) !== 'undefined' ? arrow.controlY : arrow.fromY
      var theta = typeof (arrow.theta) !== 'undefined' ? arrow.theta : 30
      var headlen = typeof (arrow.headlen) !== 'undefined' ? arrow.headlen : 10
      var width = typeof (arrow.width) !== 'undefined' ? arrow.width : 1
      var color = typeof (arrow.color) !== 'undefined' ? arrow.color : '#000'
      var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI
      var type = typeof (arrow.type) !== 'undefined' ? arrow.type : 'line'
      if (type === 'curve') {
        angle = Math.atan2(controlY - toY, controlX - toX) * 180 / Math.PI
      } else if (type === 'broken') {
        angle = Math.atan2(toY - toY, fromX - toX) * 180 / Math.PI
      }
      var angle1 = (angle + theta) * Math.PI / 180
      var angle2 = (angle - theta) * Math.PI / 180
      var topX = headlen * Math.cos(angle1)
      var topY = headlen * Math.sin(angle1)
      var botX = headlen * Math.cos(angle2)
      var botY = headlen * Math.sin(angle2)
      ctx.save()
      ctx.beginPath()
      var arrowX = fromX - topX
      var arrowY = fromY - topY
      if (type === 'line') {
        ctx.moveTo(arrowX, arrowY)
        ctx.moveTo(fromX, fromY)
        ctx.lineTo(toX, toY)
      } else if (type === 'broken') {
        ctx.moveTo(fromX, fromY)
        ctx.lineTo(fromX, toY)
        ctx.lineTo(toX, toY)
      } else if (type === 'curve') {
        ctx.moveTo(fromX, fromY)
        ctx.quadraticCurveTo(controlX, controlY, toX, toY)
      }
      arrowX = toX + topX
      arrowY = toY + topY
      ctx.moveTo(arrowX, arrowY)
      ctx.lineTo(toX, toY)
      arrowX = toX + botX
      arrowY = toY + botY
      ctx.lineTo(arrowX, arrowY)
      ctx.strokeStyle = color
      ctx.lineWidth = width
      ctx.stroke()
      ctx.restore()
    }

说明:当分叉角度与箭头大小均为0时可画直线

 

文章评论