• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    详解如何在Canvas中添加事件的方法

    发布者: Error | 发布时间: 2025-6-16 12:24| 查看数: 116| 评论数: 0|帖子模式

    作为一个前端,给元素添加事件是一件司空见惯的事情。可是在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:
    1.   const canvas = document.getElementById('canvas')
    2.   const ctx = canvas.getContext('2d')

    3.   ctx.beginPath()
    4.   ctx.moveTo(10, 10)
    5.   ctx.lineTo(10, 50)
    6.   ctx.lineTo(50, 50)
    7.   ctx.lineTo(50, 10)
    8.   ctx.fillStyle= 'black'
    9.   ctx.fill()
    10.   ctx.closePath()

    11.   canvas.addEventListener('click', function (e) {
    12.     const canvasInfo = canvas.getBoundingClientRect()
    13.     console.log(ctx.isPointInPath(e.clientX - canvasInfo.left, e.clientY - canvasInfo.top))
    14.   })
    复制代码

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

    3.   ctx.beginPath()
    4.   ctx.moveTo(10, 10)
    5.   ctx.lineTo(10, 50)
    6.   ctx.lineTo(50, 50)
    7.   ctx.lineTo(50, 10)
    8.   ctx.fillStyle= 'black'
    9.   ctx.fill()
    10.   ctx.closePath()

    11.   ctx.beginPath()
    12.   ctx.moveTo(100, 100)
    13.   ctx.lineTo(100, 150)
    14.   ctx.lineTo(150, 150)
    15.   ctx.lineTo(150, 100)
    16.   ctx.fillStyle= 'red'
    17.   ctx.fill()
    18.   ctx.closePath()

    19.   canvas.addEventListener('click', function (e) {
    20.     const canvasInfo = canvas.getBoundingClientRect()
    21.     console.log(ctx.isPointInPath(e.clientX - canvasInfo.left, e.clientY - canvasInfo.top))
    22.   })
    复制代码

    这个时候,结果就不再如同我们所预计的一样,当点击其中黑色区域时,打印的值为false,点击红色区域时,打印的值为true。
    其实原因很简单,因为上述代码,我们实际创建了两个Path,而isPointInPath方法实际只检测当前点是否处于最后一个Path当中,而例子中红色区域为最后一个Path,所以只有点击红色区域时,isPointInPath方法才能判断为true。现在我们改造一下代码:
    1.   const canvas = document.getElementById('canvas')
    2.   const ctx = canvas.getContext('2d')
    3.   let drawArray = []

    4.   function draw1 () {
    5.     ctx.beginPath()
    6.     ctx.moveTo(10, 10)
    7.     ctx.lineTo(10, 50)
    8.     ctx.lineTo(50, 50)
    9.     ctx.lineTo(50, 10)
    10.     ctx.fillStyle= 'black'
    11.     ctx.fill()
    12.   }

    13.   function draw2 () {
    14.     ctx.beginPath()
    15.     ctx.moveTo(100, 100)
    16.     ctx.lineTo(100, 150)
    17.     ctx.lineTo(150, 150)
    18.     ctx.lineTo(150, 100)
    19.     ctx.fillStyle= 'red'
    20.     ctx.fill()
    21.     ctx.closePath()
    22.   }

    23.   drawArray.push(draw1, draw2)  

    24.   drawArray.forEach(it => {
    25.     it()
    26.   })

    27.   canvas.addEventListener('click', function (e) {
    28.     ctx.clearRect(0, 0, 400, 750)
    29.     const canvasInfo = canvas.getBoundingClientRect()
    30.     drawArray.forEach(it => {
    31.       it()
    32.       console.log(ctx.isPointInPath(e.clientX - canvasInfo.left, e.clientY - canvasInfo.top))
    33.     })
    34.   })
    复制代码
    上面的代码我们进行了一个很大的改造,我们将每个Path放入到一个单独的函数当中,并将它们push到一个数组当中。当触发点击事件时,我们清空Canvas,并遍历数组重新绘制,每当绘制一个Path进行一次判断,从而在调用isPointInPath方法时,我们能实时的获取当前的最后一个Path,进而判断出当前点所处的Path当中。
    现在我们已经间接的实现了对每个Path的单独事件监听,可是其实现的方式需要一次又一次的重绘,那么有办法不需要重绘就能监听事件吗?
    首先我们需要知道一次又一次重绘的原因是因为isPointInPath方法是监听的最后一个Path,不过我们在介绍这个方法的时候,说过其第一个参数是一个Path对象,当我们传递了这个参数后,Path就不再去取最后一个Path而是使用我们传递进去的这个Path,现在我们来个demo来验证其可行性:
    1.   const canvas = document.getElementById('canvas')
    2.   const ctx = canvas.getContext('2d')

    3.   const path1 = new Path2D();
    4.   path1.rect(10, 10, 100,100);
    5.   ctx.fill(path1)
    6.   const path2 = new Path2D();
    7.   path2.moveTo(220, 60);
    8.   path2.arc(170, 60, 50, 0, 2 * Math.PI);
    9.   ctx.stroke(path2)

    10.   canvas.addEventListener('click', function (e) {
    11.     console.log(ctx.isPointInPath(path1, e.clientX, e.clientY))
    12.     console.log(ctx.isPointInPath(path2, e.clientX, e.clientY))
    13.   })
    复制代码

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

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

    自己写的一个demo
    1.   const canvas = document.getElementById('canvas')

    2.   class rectangular {
    3.     constructor (
    4.       ctx,
    5.       {
    6.         top = 0,
    7.         left = 0,
    8.         width = 30,
    9.         height = 50,
    10.         background = 'red'
    11.       }
    12.     ) {
    13.       this.ctx = ctx
    14.       this.top = top
    15.       this.left = left
    16.       this.width = width
    17.       this.height = height
    18.       this.background = background
    19.     }

    20.     painting () {
    21.       this.ctx.beginPath()
    22.       this.ctx.moveTo(this.left, this.top)
    23.       this.ctx.lineTo(this.left + this.width, this.top)
    24.       this.ctx.lineTo(this.left + this.width, this.top + this.height)
    25.       this.ctx.lineTo(this.left, this.top + this.height)
    26.       this.ctx.fillStyle = this.background
    27.       this.ctx.fill()
    28.       this.ctx.closePath()
    29.     }

    30.     adjust (left, top) {
    31.       this.left += left
    32.       this.top += top
    33.     }
    34.   }

    35.   class circle {
    36.     constructor (
    37.       ctx,
    38.       {
    39.         center = [],
    40.         radius = 10,
    41.         background = 'blue'
    42.       }
    43.     ) {
    44.       this.ctx = ctx
    45.       this.center = [center[0] === undefined ? radius : center[0], center[1] === undefined ? radius : center[1]]
    46.       this.radius = radius
    47.       this.background = background
    48.     }

    49.     painting () {

    50.       this.ctx.beginPath()
    51.       this.ctx.arc(this.center[0], this.center[1], this.radius, 0, Math.PI * 2, false)
    52.       this.ctx.fillStyle = this.background
    53.       this.ctx.fill()
    54.       this.ctx.closePath()
    55.     }

    56.     adjust (left, top) {
    57.       this.center[0] += left
    58.       this.center[1] += top
    59.     }
    60.   }

    61.   class demo {
    62.     constructor (canvas) {
    63.       this.canvasInfo = canvas.getBoundingClientRect()
    64.       this.renderList = []
    65.       this.ctx = canvas.getContext('2d')
    66.       this.canvas = canvas
    67.       this.rectangular = (config) => {
    68.         let target = new rectangular(this.ctx, {...config})
    69.         this.addRenderList(target)
    70.         return this
    71.       }

    72.       this.circle = (config) => {
    73.         let target = new circle(this.ctx, {...config})
    74.         this.addRenderList(target)
    75.         return this
    76.       }
    77.       this.addEvent()
    78.     }

    79.     addRenderList (target) {
    80.       this.renderList.push(target)
    81.     }

    82.     itemToLast (index) {
    83.       const lastItem = this.renderList.splice(index, 1)[0]

    84.       this.renderList.push(lastItem)
    85.     }

    86.     painting () {
    87.       this.ctx.clearRect(0, 0, this.canvasInfo.width, this.canvasInfo.height)
    88.       this.renderList.forEach(it => it.painting())
    89.     }

    90.     addEvent () {
    91.       const that = this
    92.       let startX, startY

    93.       canvas.addEventListener('mousedown', e => {
    94.         startX = e.clientX
    95.         startY = e.clientY
    96.         let choosedIndex = null
    97.         this.renderList.forEach((it, index) => {
    98.           it.painting()
    99.           if (this.ctx.isPointInPath(startX, startY)) {
    100.             choosedIndex = index
    101.           }
    102.         })
    103.         
    104.         if (choosedIndex !== null) {
    105.           this.itemToLast(choosedIndex)
    106.         }

    107.         document.addEventListener('mousemove', mousemoveEvent)
    108.         document.addEventListener('mouseup', mouseupEvent)
    109.         this.painting()
    110.       })

    111.       function mousemoveEvent (e) {
    112.         const target = that.renderList[that.renderList.length - 1]
    113.         const currentX = e.clientX
    114.         const currentY = e.clientY
    115.         target.adjust(currentX - startX, currentY - startY)
    116.         startX = currentX
    117.         startY = currentY
    118.         that.painting()
    119.       }

    120.       function mouseupEvent (e) {
    121.         const target = that.renderList[that.renderList.length - 1]
    122.         const currentX = e.clientX
    123.         const currentY = e.clientY

    124.         target.adjust(currentX - startX, currentY - startY)
    125.         startX = currentX
    126.         startY = currentY
    127.         that.painting()
    128.         document.removeEventListener('mousemove', mousemoveEvent)
    129.         document.removeEventListener('mouseup', mouseupEvent)
    130.       }
    131.     }
    132.   }

    133.   const yes = new demo(canvas)
    134.     .rectangular({})
    135.     .rectangular({top: 60, left: 60, background: 'blue'})
    136.     .rectangular({top: 30, left: 20, background: 'green'})
    137.     .circle()
    138.     .circle({center: [100, 30], background: 'red', radius: 5})
    139.     .painting()
    复制代码

    到此这篇关于详解如何在Canvas中添加事件的方法的文章就介绍到这了,更多相关Canvas添加事件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!


    来源:https://www.jb51.net/html5/771876.html
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表