欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何在Canvas中添加事件的方法示例

程序员文章站 2024-01-23 18:47:46
这篇文章主要介绍了如何在Canvas中添加事件的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 19-05-21...

作为一个前端,给元素添加事件是一件司空见惯的事情。可是在canvas中,其所画的任何东西都是无法获取的,更别说添加事件,那么我们对其就束手无策了吗?当然不是的!我们在平时项目中肯定都用过许多canvas的框架,我们发现事件在这些框架中已经使用的十分成熟了,而且并没有出现特别严重的问题。那么我们可以肯定的是,事件在canvas中并不是一个无法触及的事情。

一个傻瓜式的方式

我们都知道一个元素在触发一个事件时,其鼠标的位置基本处于该元素之上,那么我们就自然而然的想到通过当前鼠标的位置以及物体所占据的位置进行比对,从而我们就能得出该物体是否应触发事件。这种方式比较简单,我就不用代码演示了,不过既然我叫它傻瓜式的方式,很明显它不是一个有效的解决方式。因为物体所占据的位置并不一定是十分容易获取,如果是矩形、圆形等我们还能通过一些简单的公式获取其占据的位置,可是在复杂点的多边形,甚至是多边形的某些边是弧线的,显而易见,我们这时候再获取其所占据的位置时是一件极其复杂且难度极大的事情,所以这种方式只适合自己在做一些demo中使用,并不适用于大多数的情况。

一个较聪明的方式

既然上面这种方式碰壁了,那么我们只能另辟蹊径。在翻阅canvasapi的时候,找到了一个方法ispointinpath,貌似正是我们苦苦寻找的良药。

介绍ispointinpath

ispointinpath的作用:顾名思义,我们很直观的可以知道该方法用以判断点是否处于路径当中。

ispointinpath的入参出参:ctx.ispointinpath([path, ]x, y [, fillrule]),该方法的参数有4个,其中path和fillrule为选填,x和y为必填。我们依次介绍4个参数。

path:看到这个参数,我开始以为是beginpath或者closepath的返回值,很可惜的是这两个方法并没有返回值,在查阅了资料后,发现是path2d构造函数new的对象。path2d构造函数具体用法。不过可惜的是该方法可能由于兼容性的问题,目前看了一些开源框架都还未使用。

x,y:这两个参数很好理解,就是x轴和y轴的距离,需要注意的是,其相对位置是canvas的左上角。

fillrule:nonzero(默认),evenodd。非零环绕规则和奇偶规则是图形学中判断一个点是否处于多边形内的规则,其中非零环绕规则是canvas的默认规则。想具体了解这两种规则的,可以自己去查阅资料,这里就不增加篇幅介绍了。

上面介绍完了入参,那么ispointinpath方法的出参想必大家都可以猜到了,就是true和false。

使用ispointinpath

上一节介绍完ispointinpath方法后,我们现在就来使用它吧。

先来一个简单的demo:

  const canvas = document.getelementbyid('canvas')
  const ctx = canvas.getcontext('2d')

  ctx.beginpath()
  ctx.moveto(10, 10)
  ctx.lineto(10, 50)
  ctx.lineto(50, 50)
  ctx.lineto(50, 10)
  ctx.fillstyle= 'black'
  ctx.fill()
  ctx.closepath()

  canvas.addeventlistener('click', function (e) {
    const canvasinfo = canvas.getboundingclientrect()
    console.log(ctx.ispointinpath(e.clientx - canvasinfo.left, e.clienty - canvasinfo.top))
  })

如何在Canvas中添加事件的方法示例

如图所示,灰色部分为canvas所占据的区域,黑色为我们实际添加事件的区域,在我们点击黑色区域后,实际也的确如我们所愿,打印出来的值为true。貌似canvas的事件监听就这么简单的解决了,不过事情真有这么简单吗。显然是不可能的!我们再来举个例子,这时候有两个区域,并且我们需要分别给其绑定不同的事件:

  const canvas = document.getelementbyid('canvas')
  const ctx = canvas.getcontext('2d')

  ctx.beginpath()
  ctx.moveto(10, 10)
  ctx.lineto(10, 50)
  ctx.lineto(50, 50)
  ctx.lineto(50, 10)
  ctx.fillstyle= 'black'
  ctx.fill()
  ctx.closepath()

  ctx.beginpath()
  ctx.moveto(100, 100)
  ctx.lineto(100, 150)
  ctx.lineto(150, 150)
  ctx.lineto(150, 100)
  ctx.fillstyle= 'red'
  ctx.fill()
  ctx.closepath()

  canvas.addeventlistener('click', function (e) {
    const canvasinfo = canvas.getboundingclientrect()
    console.log(ctx.ispointinpath(e.clientx - canvasinfo.left, e.clienty - canvasinfo.top))
  })

如何在Canvas中添加事件的方法示例

这个时候,结果就不再如同我们所预计的一样,当点击其中黑色区域时,打印的值为false,点击红色区域时,打印的值为true。

其实原因很简单,因为上述代码,我们实际创建了两个path,而ispointinpath方法实际只检测当前点是否处于最后一个path当中,而例子中红色区域为最后一个path,所以只有点击红色区域时,ispointinpath方法才能判断为true。现在我们改造一下代码:

  const canvas = document.getelementbyid('canvas')
  const ctx = canvas.getcontext('2d')
  let drawarray = []

  function draw1 () {
    ctx.beginpath()
    ctx.moveto(10, 10)
    ctx.lineto(10, 50)
    ctx.lineto(50, 50)
    ctx.lineto(50, 10)
    ctx.fillstyle= 'black'
    ctx.fill()
  }

  function draw2 () {
    ctx.beginpath()
    ctx.moveto(100, 100)
    ctx.lineto(100, 150)
    ctx.lineto(150, 150)
    ctx.lineto(150, 100)
    ctx.fillstyle= 'red'
    ctx.fill()
    ctx.closepath()
  }

  drawarray.push(draw1, draw2)  

  drawarray.foreach(it => {
    it()
  })

  canvas.addeventlistener('click', function (e) {
    ctx.clearrect(0, 0, 400, 750)
    const canvasinfo = canvas.getboundingclientrect()
    drawarray.foreach(it => {
      it()
      console.log(ctx.ispointinpath(e.clientx - canvasinfo.left, e.clienty - canvasinfo.top))
    })
  })

上面的代码我们进行了一个很大的改造,我们将每个path放入到一个单独的函数当中,并将它们push到一个数组当中。当触发点击事件时,我们清空canvas,并遍历数组重新绘制,每当绘制一个path进行一次判断,从而在调用ispointinpath方法时,我们能实时的获取当前的最后一个path,进而判断出当前点所处的path当中。

现在我们已经间接的实现了对每个path的单独事件监听,可是其实现的方式需要一次又一次的重绘,那么有办法不需要重绘就能监听事件吗?

首先我们需要知道一次又一次重绘的原因是因为ispointinpath方法是监听的最后一个path,不过我们在介绍这个方法的时候,说过其第一个参数是一个path对象,当我们传递了这个参数后,path就不再去取最后一个path而是使用我们传递进去的这个path,现在我们来个demo来验证其可行性:

  const canvas = document.getelementbyid('canvas')
  const ctx = canvas.getcontext('2d')

  const path1 = new path2d();
  path1.rect(10, 10, 100,100);
  ctx.fill(path1)
  const path2 = new path2d();
  path2.moveto(220, 60);
  path2.arc(170, 60, 50, 0, 2 * math.pi);
  ctx.stroke(path2)

  canvas.addeventlistener('click', function (e) {
    console.log(ctx.ispointinpath(path1, e.clientx, e.clienty))
    console.log(ctx.ispointinpath(path2, e.clientx, e.clienty))
  })

如何在Canvas中添加事件的方法示例

如上图所示,我们点击了左边图形,打印true,false;点击右边图形,打印false,true。打印的结果表明是没有问题的,不过由于其兼容性还有待加强,所以目前建议还是使用重绘方式来监听事件。

结语

canvas的事件监听讲到这里基本就差不多了,原理很简单,大家应该都能掌握。
,欢迎start

附录

自己写的一个demo

  const canvas = document.getelementbyid('canvas')

  class rectangular {
    constructor (
      ctx, 
      {
        top = 0,
        left = 0,
        width = 30,
        height = 50,
        background = 'red'
      }
    ) {
      this.ctx = ctx
      this.top = top
      this.left = left
      this.width = width
      this.height = height
      this.background = background
    }

    painting () {
      this.ctx.beginpath()
      this.ctx.moveto(this.left, this.top)
      this.ctx.lineto(this.left + this.width, this.top)
      this.ctx.lineto(this.left + this.width, this.top + this.height)
      this.ctx.lineto(this.left, this.top + this.height)
      this.ctx.fillstyle = this.background
      this.ctx.fill()
      this.ctx.closepath()
    }

    adjust (left, top) {
      this.left += left
      this.top += top
    }
  }

  class circle {
    constructor (
      ctx, 
      {
        center = [],
        radius = 10,
        background = 'blue'
      }
    ) {
      this.ctx = ctx
      this.center = [center[0] === undefined ? radius : center[0], center[1] === undefined ? radius : center[1]]
      this.radius = radius
      this.background = background
    }

    painting () {

      this.ctx.beginpath()
      this.ctx.arc(this.center[0], this.center[1], this.radius, 0, math.pi * 2, false)
      this.ctx.fillstyle = this.background
      this.ctx.fill()
      this.ctx.closepath()
    }

    adjust (left, top) {
      this.center[0] += left
      this.center[1] += top
    }
  }

  class demo {
    constructor (canvas) {
      this.canvasinfo = canvas.getboundingclientrect()
      this.renderlist = []
      this.ctx = canvas.getcontext('2d')
      this.canvas = canvas
      this.rectangular = (config) => {
        let target = new rectangular(this.ctx, {...config})
        this.addrenderlist(target)
        return this
      }

      this.circle = (config) => {
        let target = new circle(this.ctx, {...config})
        this.addrenderlist(target)
        return this
      }
      this.addevent()
    }

    addrenderlist (target) {
      this.renderlist.push(target)
    }

    itemtolast (index) {
      const lastitem = this.renderlist.splice(index, 1)[0]

      this.renderlist.push(lastitem)
    }

    painting () {
      this.ctx.clearrect(0, 0, this.canvasinfo.width, this.canvasinfo.height)
      this.renderlist.foreach(it => it.painting())
    }

    addevent () {
      const that = this
      let startx, starty

      canvas.addeventlistener('mousedown', e => {
        startx = e.clientx
        starty = e.clienty
        let choosedindex = null
        this.renderlist.foreach((it, index) => {
          it.painting()
          if (this.ctx.ispointinpath(startx, starty)) {
            choosedindex = index
          }
        })
        
        if (choosedindex !== null) {
          this.itemtolast(choosedindex)
        }

        document.addeventlistener('mousemove', mousemoveevent)
        document.addeventlistener('mouseup', mouseupevent)
        this.painting()
      })

      function mousemoveevent (e) {
        const target = that.renderlist[that.renderlist.length - 1]
        const currentx = e.clientx
        const currenty = e.clienty
        target.adjust(currentx - startx, currenty - starty)
        startx = currentx
        starty = currenty
        that.painting()
      }

      function mouseupevent (e) {
        const target = that.renderlist[that.renderlist.length - 1]
        const currentx = e.clientx
        const currenty = e.clienty

        target.adjust(currentx - startx, currenty - starty)
        startx = currentx
        starty = currenty
        that.painting()
        document.removeeventlistener('mousemove', mousemoveevent)
        document.removeeventlistener('mouseup', mouseupevent)
      }
    }
  }

  const yes = new demo(canvas)
    .rectangular({})
    .rectangular({top: 60, left: 60, background: 'blue'})
    .rectangular({top: 30, left: 20, background: 'green'})
    .circle()
    .circle({center: [100, 30], background: 'red', radius: 5})
    .painting()

如何在Canvas中添加事件的方法示例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。