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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,012评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,589评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,819评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,652评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,954评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,381评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,687评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,404评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,082评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,355评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,880评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,249评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,864评论 3 232
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,007评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,760评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,394评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,281评论 2 259