canvas 画线与四边形框

不规则四边形.png

线段.png

代码

// 获取到myCanvas 元素
const myCanvas = document.getElementById("myCanvas");
const ctx = myCanvas.getContext("2d");

// 新建一个空数组 存line
let graphs = []
const updateAnimations = () => {
  ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
  graphs.map((graph) => {
    graph.animations.map((animation) => {
      animation()
    })
  })
}



class Graph {
  constructor(ctx, updateAnimations) {
    this.ctx = ctx
    this.lines = [];
    this.points = [];
    this.animations = [];
    this.animations.push(() => { this.draw_line() })
    this.animations.push(() => { this.draw_point() })

    this.update = updateAnimations
    this.index = 0
  }

  // 画线
  draw_line() {
    if (this.lines.length <= 1) return
    this.ctx.beginPath();
    this.ctx.lineCap = "round";
    this.ctx.moveTo(...this.lines[0]);
    this.lines.map((point, index) => {
      this.ctx.lineTo(...point);

      if (index >= 3) {
        this.ctx.closePath();
      }
    })
    this.ctx.stroke();
  }

  // 画点
  draw_point () {
    this.points.map((point) => {
      this.ctx.beginPath();
      //创建渐变对象
      const radialGrad  = this.ctx.createRadialGradient( ...point, 0, ...point, 10 );
      //颜色断点
      radialGrad.addColorStop(0, 'rgba(224, 87, 79, 1)');
      radialGrad.addColorStop(1, 'rgba(224, 87, 79, 1)');
      this.ctx.fillStyle = radialGrad;
      this.ctx.arc(...point, 10, 0, 2 * Math.PI, true);
      this.ctx.closePath();
      this.ctx.fill();
    })
  }

  // 按住点 移动
  move_point (index, point) {
    let lines = [...this.lines]
    lines[index] = point
    if (
      this.checkCross(lines[0], lines[1], lines[2], lines[3])
      ||
      this.checkCross(lines[0], lines[3], lines[2], lines[1])
    ) {
      return
    }

    this.lines[index] = point
    this.points[index] = point
    this.update && this.update()
  }

  // 点击时候, 新增一个点
  set_point (point) {
    if (this.index >= 3) {
      if (
        this.checkCross(this.lines[0], this.lines[1], this.lines[2], point)
        ||
        this.checkCross(this.lines[0], point, this.lines[2], this.lines[1])
      ) {
        return
      }
    }

    this.lines[this.index] = point
    this.points[this.index] = point

    this.index = this.index + 1
  }

  // 单独的线段, 会跟着鼠标移动
  set_line (point) {
    if (this.index >= 3) {
      if (
        this.checkCross(this.lines[0], this.lines[1], this.lines[2], point)
        ||
        this.checkCross(this.lines[0], point, this.lines[2], this.lines[1])
      ) {
        return
      }
    }

    this.lines[this.index] = point
  }

  // 移动线条
  onmousemove (e) {
    
    this.set_line([e.offsetX, e.offsetY])
    this.update && this.update()
  }

  // 点击确认一个点
  onmousedown (e) {
    this.set_point([e.offsetX, e.offsetY])
    this.update && this.update()
  }

  //计算向量叉乘
  crossMul (v1, v2) {
    return v1.x * v2.y - v1.y * v2.x;
  }  
  // 判断两条线段是否相交
  checkCross (p1, p2, p3, p4) {
    let v1 = {x: p1[0] - p3[0], y: p1[1] - p3[1]},
    v2 = {x: p2[0] - p3[0], y: p2[1] - p3[1]},
    v3 = {x: p4[0] - p3[0], y: p4[1] - p3[1]},
    v = this.crossMul(v1, v3) * this.crossMul(v2, v3)
    v1 = {x: p3[0] - p1[0], y: p3[1] - p1[1]}
    v2 = {x: p4[0] - p1[0], y: p4[1] - p1[1]}
    v3 = {x: p2[0] - p1[0], y: p2[1] - p1[1]}
    return (v <= 0 && this.crossMul(v1, v3) * this.crossMul(v2, v3) <= 0) ? true : false
  }
}


// 新建图形
const newly_build = (e) => {
  // quantity 是点的数量 , 从零开始数, 1 是两个点(一条线)  3是四个点(四边形)
  const quantity = Math.random() > 0.4 ?  1 : 3

  // 新建图形实例, 并存在动画更新数组中, (如果要在一个画面建多个, 可以graphs[index], 把每次index递增)
  const line = new Graph(ctx, updateAnimations);
  graphs[0] = line;
  line.onmousedown(e)

  myCanvas.onmousemove = (e) => {
    e.preventDefault()
    line.onmousemove(e)
  }

  let index = 0;

  setTimeout(() => {
    myCanvas.onmousedown = (e) => {
      e.preventDefault()
      line.onmousedown(e)
      index ++
      if (index >= quantity) {
        myCanvas.onmousemove = {}
        myCanvas.onmousedown = onmousedown
      }
    }
  }, 10);
}

// 编辑点的位置
const onmousedown_point = (e) => {
  let line = null
  let index = null

  // 判断有没有按住点, 并且拿到点的位置
  graphs.map((graph) => {
    graph.points.map((point, point_index) => {
      if ( 
        (
          e.offsetX > (point[0] - 15)
          && e.offsetX < (point[0] + 15)
        )
        &&
        (
          e.offsetY > (point[1] - 15)
          && e.offsetY < (point[1] + 15)
        )
      ) {
        graph.move_point(point_index, [e.offsetX, e.offsetY])
        line = graph,
        index = point_index
      }
    })
  })

  // 判断是否点击在 点上
  if (line) {
    // 编辑点的位置
    myCanvas.onmousemove = (e) => {
      e.preventDefault()
      line.move_point(index, [e.offsetX, e.offsetY])
    }

    myCanvas.onmouseup = (e) => {
      e.preventDefault()
      line.move_point(index, [e.offsetX, e.offsetY])
      myCanvas.onmousemove = {}
      myCanvas.onmouseup = {}
      myCanvas.onmousedown = onmousedown
    }
  
    return true
  } 


  return false
}


// '鼠标点击: ', e.offsetX, e.offsetY
const onmousedown = (e) => {
  e.preventDefault()
  myCanvas.onmousedown = {}

  // 判断用户点击是编辑点, 还是新建图形
  const is_edit = onmousedown_point(e);

  !is_edit && newly_build(e)

}


// 准备好了
const initMyCanvas = () => {
  // 定好 canvas 宽高
  myCanvas.height = 500
  myCanvas.width = 500

  // 定好线条颜色宽度
  ctx.lineWidth = 6;
  ctx.strokeStyle = "#f7d9cf";
  
  // 绑定 鼠标点击 or 离开 事件
  myCanvas.onmousedown = onmousedown
}

  initMyCanvas()

你可能感兴趣的:(canvas 画线与四边形框)