Canvas事件绑定

 

canvas事件绑定

众所周知canvas是位图,在位图里我们可以在里面画各种东西,可以是图片,可以是线条等等。那我们想给canvas里的某一张图片添加一个点击事件该怎么做到。而js只能监听到canvas的事件,很明显这个图片是不存在与dom里面的图片只是画在了canvas里而已。下面我就来简单的实现一个canvas内部各个图片的事件绑定。

  • 我先来讲下实现原理:其实就是canvas绑定相关事件,在通过记录图片所在canvas的坐标,判断事件作用于哪个图片中。这样讲是不是感觉跟事件代理有点相似咧。不过实现起来还是有稍许复杂的。

  • ps:下面的代码我是用ts写的,大家当es6看就好了,稍有不同的可以查看
    typescript的文档(typescript真的很好用,建议大家多多了解)。

1、建立图片和canvas之间的联系(这里我用色块来代替图片)

这里要色块和canvas建立一定的联系,而不是单纯的渲染。还要记录色块所在坐标、宽高。我们先一步一步来实现
首先写基本的html页面创建一个canvas:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>canvas事件</title>
  8. <style>
  9. html, body {
  10. height: 100%;
  11. background: #eee;
  12. }
  13. canvas {
  14. background: #fff;
  15. display: block;
  16. margin: 0 auto;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas width="500" height="500" id="canvas"></canvas>
  22. </body>
  • 下一步,我们要定一个Canvas的类,这个类应该要有些什么功能呢?
  1. 要有对应的canvas。
  2. 装色块数据的容器。
  3. 有添加色块的方法。
  4. 渲染色块的方法。
  5. 渲染所有色块的方法。
  • 因为色块也有自己的一些参数,为了方便拓展,我们也为色块定一个类,这类需要的功能有:

    宽、高、颜色、坐标(x,y),还有Canvas实例;初步就定这几个吧

ok开始写

  1. // Canvas类
  2. class Canvas {
  3. blockList: Block[]
  4. ctx: any
  5. canvas: any
  6. createBlock (option) {
  7. option.Canvas = this
  8. this.blockList.push(new Block(option))
  9. this.painting()
  10. }
  11. rendering (block) { // 渲染色块函数
  12. this.ctx.fillStyle = block.color
  13. this.ctx.fillRect(block.x, block.y, block.w, block.h)
  14. }
  15. painting () { // 将容器里的色块全部渲染到canvas
  16. // 清空画布(渲染之前应该将老的清空)
  17. this.ctx.fillStyle = '#fff'
  18. this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
  19. this.blockList.forEach(ele => {
  20. this.rendering(ele)
  21. })
  22. }
  23. constructor (ele) { // 初始化函数(输入的是canvas)
  24. // 设置canvas
  25. this.canvas = ele
  26. this.ctx = this.canvas.getContext('2d')
  27. // 色块容器
  28. this.blockList = []
  29. }
  30. }
  31. class Block {
  32. w: number
  33. h: number
  34. x: number
  35. y: number
  36. color: string
  37. Canvas: Canvas
  38. hierarchy: number
  39. constructor ({ w, h, x, y, color, Canvas }) { // 初始化设置色块相关属性
  40. this.w = w
  41. this.h = h
  42. this.x = x
  43. this.y = y
  44. this.color = color
  45. this.Canvas = Canvas
  46. }
  47. }

下面运行一波试试

  1. // 创建Canvas实例,并添加蓝色个宽高100px,位置(100,100)、(300,100)红色和蓝色的色块
  2. var canvas = new Canvas(document.getElementById('canvas'))
  3. canvas.createBlock({ // 红色
  4. x: 100,
  5. y: 100,
  6. w: 100,
  7. h: 100,
  8. color: '#f00'
  9. })
  10. canvas.createBlock({ // 蓝色
  11. x: 100,
  12. y: 100,
  13. w: 300,
  14. h: 100,
  15. color: '#00f'
  16. })

运行结果如下:

2、给色块添加点击事件

这里并不能直接给色块添加点击事件的,所以要通过坐标的方式判断目前点击的是哪个色块。

  1. 先给canvas添加点击事件。
  2. 判断色块区域。
  3. 执行相应事件。
  1. class Block {
  2. // ...省略部分代码
  3. checkBoundary (x, y) { // 判断边界方法
  4. return x > this.x && x < (this.x + this.w) && y > this.y && y < (this.y + this.h)
  5. }
  6. mousedownEvent () { // 点击事件
  7. console.log(`点击了颜色为${this.color}的色块`)
  8. }
  9. }
  10. class Canvas {
  11. // ...省略部分代码
  12. constructor (ele) {
  13. this.canvas = ele
  14. this.ctx = this.canvas.getContext('2d')
  15. this.blockList = []
  16. // 事件绑定(这里有一个要注意的,我这里用了bind方法,是为了将“mousedownEvent”方法内的this指向切换到Canvas)
  17. this.canvas.addEventListener('click', this.mousedownEvent.bind(this)) // 点击事件
  18. }
  19. mousedownEvent () { // 点击事件
  20. const x = e.offsetX
  21. const y = e.offsetY
  22. // 这里将点击的坐标传给所有色块,根据边界判断方法判断是否在点击在内部。是的话执行色块的事件方法。
  23. this.blockList.forEach(ele => {
  24. if (ele.checkBoundary(x, y)) ele.mousedownEvent(e)
  25. })
  26. }
  27. }

到这里为止已经实现了对不同canvas内不同色块绑定对应的点击事件。不过这个点击事件是不完美的,因为目前为止我们还没有引入层级的概念,就是说两个色块重叠部分点击的话,全部都会触发。所以我们还要给色块加入层级的属性。实现一个点击某一个色块改色块的层级就会提升到最高。

  1. class Block {
  2. // ...省略部分代码
  3. constructor ({ w, h, x, y, color, Canvas, hierarchy }) { // 初始化设置色块相关属性
  4. this.w = w
  5. this.h = h
  6. this.x = x
  7. this.y = y
  8. this.color = color
  9. this.Canvas = Canvas
  10. this.hierarchy = 0
  11. }
  12. }
  13. class Canvas {
  14. // ...省略部分代码
  15. constructor (ele) {
  16. this.canvas = ele
  17. this.ctx = this.canvas.getContext('2d')
  18. this.blockList = []
  19. // 事件绑定(这里有一个要注意的,我这里用了bind方法,是为了将“mousedownEvent”方法内的this指向切换到Canvas)
  20. this.canvas.addEventListener('click', this.mousedownEvent.bind(this)) // 点击事件
  21. this.nowBlock = null // 当前选中的色块
  22. }
  23. createBlock (option) { // 创建色块函数(这里的Block是色块的类)
  24. option.Canvas = this
  25. // 创建最新的色块的层级应该是最高的
  26. option.hierarchy = this.blockList.length
  27. this.blockList.push(new Block(option))
  28. this.rendering()
  29. }
  30. mousedownEvent (e) { // 点击事件
  31. const x = e.offsetX
  32. const y = e.offsetY
  33. // 获取点中里层级最高的色块
  34. this.nowBlock = (this.blockList.filter(ele => ele.checkBoundary(x, y))).pop()
  35. // 如果没有捕获的色块直接退出
  36. if (!this.nowBlock) return
  37. // 将点击到的色块层级提高到最高
  38. this.nowBlock.hierarchy = this.blockList.length
  39. // 重新排序(从小到大)
  40. this.blockList.sort((a, b) => a.hierarchy - b.hierarchy)
  41. // 在重新从0开始分配层级
  42. this.blockList.forEach((ele, idx) => ele.hierarchy = idx)
  43. // 重新倒序排序后再重新渲染。
  44. this.painting()
  45. this.nowBlock.mousedownEvent(e) // 只触发选中的色块的事件
  46. }
  47. }
  48. // 这里我们还得加入第三块色块与红色色块重叠的色块
  49. canvas.createBlock({
  50. x: 150,
  51. y: 150,
  52. w: 100,
  53. h: 100,
  54. color: '#0f0'
  55. })

Canvas中“mousedownEvent”方法内的代码是有点复杂的,主要是有点绕。

  1. 首先是this.nowBlock = (this.blockList.filter(ele => ele.checkBoundary(x, y))).pop()这段代码是怎么获取到点击到的色块中层级最高的色块。这里因为我们每次添加色块都是设置了最高层级的,所以“blockList”内的色块都是按层级从小到大排序的。所以我们取最后一个就可以了。
  2. 第二步就是将拿到的色块的层级提升到最高。
  3. 第三步就是从小到大重新排列色块。
  4. 因为第二步的时候我们修改了选中色块的层级,导致所有色块的层级不是连续的,为了避免层级不可控,我们还得重新定义层级。
  5. 重新渲染色块到canvas中,因为“blockList”内的色块是排好序的,所以按顺序渲染即可。

运行后的效果就是下面这样了:

3、实现对不同色块进行拖拽

在上面我们已经实现了获取不同的色块,并修改它的层级。下面我们要实现色块的拖拽,主要就是获取鼠标移动过程中和一开始点击下去时位置坐标的变化。这个原理和普通的dom拖拽实现原理一样。

  1. 获取点击色块的点,距离色块左边和上边的距离(disX, disY)。
  2. 鼠标移动时,用鼠标当前距离canvas左边和上边的距离减去(disX, disY)这里就是色块的x,y坐标了。
  1. class Block {
  2. // ...省略部分代码
  3. mousedownEvent (e: MouseEvent) {
  4. /* 这里 disX和disY的计算方式: e.offsetX获取到的是鼠标点击距离canvas左边的距离,this.x是色块距离canvas左边的距离。e.offsetX-this.x就是色块左边的距离。这应该很好理解了 */
  5. const disX = e.offsetX - this.x // 点击时距离色块左边的距离
  6. const disY = e.offsetY - this.y // 点击时距离色块上边的距离
  7. // 绑定鼠标滑动事件;这里mouseEvent.offsetX同样是鼠标距离canvas左侧的距离,mouseEvent.offsetX - disX就是色块的x坐标了。同理y也是这样算的。最后在重新渲染就好了。
  8. document.onmousemove = (mouseEvent) => {
  9. this.x = mouseEvent.offsetX - disX
  10. this.y = mouseEvent.offsetY - disY
  11. this.Canvas.painting()
  12. }
  13. // 鼠标松开则清空所有事件
  14. document.onmouseup = () => {
  15. document.onmousemove = document.onmousedown = null
  16. }
  17. // console.log(`点击了颜色为${this.color}的色块22`)
  18. }
  19. }

效果如下:

下面贴上完整的代码(html和调用的方法就不放了)这个例子只是简单实现给canvas内的内容绑定事件,大家可以实现复杂一点的,例如把色块换成图片,除了拖拽还以给图片缩放,旋转,删除等等。

  1. class Canvas {
  2. blockList: Block[]
  3. ctx: any
  4. canvas: any
  5. nowBlock: Block
  6. createBlock (option) {
  7. option.hierarchy = this.blockList.length
  8. option.Canvas = this
  9. this.blockList.push(new Block(option))
  10. this.painting()
  11. }
  12. rendering (block) {
  13. this.ctx.fillStyle = block.color
  14. this.ctx.fillRect(block.x, block.y, block.w, block.h)
  15. }
  16. painting () {
  17. // 清空画布
  18. this.ctx.fillStyle = '#fff'
  19. this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
  20. this.blockList.forEach(ele => {
  21. this.rendering(ele)
  22. })
  23. }
  24. mousedownEvent (e: MouseEvent) { // 点击事件
  25. const x = e.offsetX
  26. const y = e.offsetY
  27. // 获取点中里层级最高的色块
  28. this.nowBlock = (this.blockList.filter(ele => ele.checkBoundary(x, y))).pop()
  29. // 如果没有捕获的色块直接退出
  30. if (!this.nowBlock) return
  31. // 将点击到的色块层级提高到最高
  32. this.nowBlock.hierarchy = this.blockList.length
  33. // 重新排序(从小到大)
  34. this.blockList.sort((a, b) => a.hierarchy - b.hierarchy)
  35. // 在重新从0开始分配层级
  36. this.blockList.forEach((ele, idx) => ele.hierarchy = idx)
  37. // 重新倒序排序后再重新渲染。
  38. this.painting()
  39. this.nowBlock.mousedownEvent(e)
  40. // this.blockList.forEach(ele => {
  41. // if (ele.checkBoundary(x, y)) ele.clickEvent(e)
  42. // })
  43. }
  44. constructor (ele) {
  45. this.canvas = ele
  46. this.ctx = this.canvas.getContext('2d')
  47. this.blockList = []
  48. // 事件绑定
  49. this.canvas.addEventListener('mousedown', this.mousedownEvent.bind(this))
  50. }
  51. }
  52. class Block {
  53. w: number
  54. h: number
  55. x: number
  56. y: number
  57. color: string
  58. Canvas: Canvas
  59. hierarchy: number
  60. constructor ({ w, h, x, y, color, Canvas, hierarchy }) {
  61. this.w = w
  62. this.h = h
  63. this.x = x
  64. this.y = y
  65. this.color = color
  66. this.Canvas = Canvas
  67. this.hierarchy = hierarchy
  68. }
  69. checkBoundary (x, y) {
  70. return x > this.x && x < (this.x + this.w) && y > this.y && y < (this.y + this.h)
  71. }
  72. mousedownEvent (e: MouseEvent) {
  73. const disX = e.offsetX - this.x
  74. const disY = e.offsetY - this.y
  75. document.onmousemove = (mouseEvent) => {
  76. this.x = mouseEvent.offsetX - disX
  77. this.y = mouseEvent.offsetY - disY
  78. this.Canvas.painting()
  79. }
  80. document.onmouseup = () => {
  81. document.onmousemove = document.onmousedown = null
  82. }
  83. // console.log(`点击了颜色为${this.color}的色块22`)
  84. }
  85. }

canvas 事件绑定的更多相关文章

  1. Canvas事件绑定

    canvas事件绑定 众所周知canvas是位图,在位图里我们可以在里面画各种东西,可以是图片,可以是线条等等.那我们想给canvas里的某一张图片添加一个点击事件该怎么做到.而js只能监听到canv ...

  2. Vue之变量、数据绑定、事件绑定使用举例

    vue1.html <!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/19 ...

  3. javascript 的事件绑定和取消事件

    研究fabricjs中发现,它提供canvas.on('mousemove', hh) 来绑定事件, 提供 canvas.off()来取消绑定事件这样的接口,很是方便, 那我们就不妨探究一下内在的实现 ...

  4. 微信小程序~事件绑定和冒泡

    [1]事件绑定和冒泡 事件绑定的写法同组件的属性,以 key.value 的形式. key 以bind或catch开头,然后跟上事件的类型,如bindtap.catchtouchstart.自基础库版 ...

  5. MVVM设计模式和WPF中的实现(四)事件绑定

    MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...

  6. 7 HTML&JS等前端知识系列之jquery的事件绑定

    preface 我们知道,每一个a,input等等标签都可以为其绑定一个事件,onclick也好,focus 也罢,都可以绑定的.但是众神key想过这个问题没有,倘若这里有1000个input标签需要 ...

  7. 兼容8事件绑定与解绑addEventListener、removeEventListener和ie的attachEvent、detachEvent

    兼容8事件绑定与解绑addEventListener.removeEventListener和ie的attachEvent.detachEvent   ;(function(){ // 事件绑定 bi ...

  8. jQuery中事件绑定到bind、live、delegate、on方法的探究

    1. 给页面上的某个元素绑定事件,最初采用下面的方式实现: $(‘selector’).click(function(){ //code }); 缺点: 不能同时绑定多个事件,不能绑定动态的元素. 后 ...

  9. jQuery中的事件绑定方法

    在jQuery中,事件绑定方法大致有四种:bind(),live(), delegate(),和on(). 那么在工作中应该如何选择呢?首先要了解四种方法的区别和各自的特点. 在了解这些之前,首先要知 ...

随机推荐

  1. Ubuntu上安装与配置JDK1.8

    Ubuntu上安装与配置JDK1.8 一.下载 下载JDK,由于是Ubuntu. 所以去官网下载tar.gz格式的就可以(ubuntu使用浏览器下载网速比較慢,所以推荐到window上下载好). ht ...

  2. 我的第一个reactnative

    由于在做极光推送,前端使用的框架是reactnative,后台写好后为了测试一下,所以按照react官方的教程搭了遍react. 开发环境: 1.windows 7(建议各位如果开发react的最好还 ...

  3. 在ChemDraw中输入千分号的方法

    很多的用户都会使用ChemDraw化学绘图工具来绘制一些化学反应的过程,但是一些化合物中有些元素所占的比例是非常小的,这个时候往往就需要千分号来显示比例.但是在ChemDraw的工具栏上只有百分号没有 ...

  4. (转)QT中QWidget、QDialog及QMainWindow的区别

    QWidget类是所有用户界面对象的基类. 窗口部件是用户界面的一个基本单元:它从窗口系统接收鼠标.键盘和其它事件,并且在屏幕上绘制自己.每一个窗口部件都是矩形的,并且它们按Z轴顺序排列.一个窗口部件 ...

  5. double类型转化成string

    public static void main(String[] args) { double priceWithFreight = 1200.5698d; System.out.println(pr ...

  6. Android 扁平化button

    View 创建 colors.xml 文件定义两个颜色 1. <resources> 2.     <color name="blue_pressed">@ ...

  7. wireshark抓取OpenFlow数据包

    在写SDN控制器应用或者改写控制器源码的时候,经常需要抓包,验证网络功能,以及流表的执行结果等等,wireshark是个很好的抓包分析包的网络工具,下面简介如何用wireshark软件抓取OpenFl ...

  8. 选项卡jQuery(ele).each()

    $("li").each(index){    $(this).mouseover(fucntion(){           $("div.contentin" ...

  9. Go语言性能优化

    原文:http://bravenewgeek.com/so-you-wanna-go-fast/ 我曾经和很多聪明的人一起工作.我们很多人都对性能问题很痴迷,我们之前所做的是尝试逼近能够预期的(性能) ...

  10. 命名空间 <iostream>和<iostream.h> 由程序设计者命名的内存区域

    namespace_百度百科 https://baike.baidu.com/item/namespace/1700121?fromtitle=命名空间 namespace即“命名空间”,也称“名称空 ...