话不多说 直接贴代码


一、实现鼠标滚轮缩放画布

// 可以实现鼠标滚轮缩放 最小为原来的百分之一,最大为原来的20倍
    canvas.on('mouse:wheel', function (opt) {
      var delta = opt.e.deltaY
      var zoom = canvas.getZoom()
      zoom *= 0.999 ** delta
      if (zoom > 20) zoom = 20
      if (zoom < 0.01) zoom = 0.01
      this.setZoom(zoom)
      opt.e.preventDefault()
      opt.e.stopPropagation()
    })

使用说明,我的canvas画布定义为 canvas,替他均不用额外设置变量。canvas = new fabric.Canvas('editorCanvas', {...


二、实现鼠标按下变抓手,并可移动画布中内容

// 鼠标按下事件
    canvas.on('mouse:down', function (e) {
      this.panning = true
      canvas.selection = false
    })
    // 鼠标抬起事件
    canvas.on('mouse:up', function (e) {
      this.panning = false
      canvas.selection = true
    })
    // 移动画布事件
    canvas.on('mouse:move', function (e) {
      if (this.panning && e && e.e) {
        var delta = new fabric.Point(e.e.movementX, e.e.movementY)
        canvas.relativePan(delta)
      }
    })

使用说明:data中定义panning: false,用来标记鼠标按下状态(是否鼠标按下)。

原理,通过偏移量

添加 鼠标为缩放原点:
 

"mouse:wheel": (e) => {
            this.zoom = (event.deltaY > 0 ? -0.1 : 0.1) + canvas.getZoom();
            this.zoom = Math.max(0.1, this.zoom); //最小为原来的1/10
            this.zoom = Math.min(3, this.zoom); //最大是原来的3倍
            this.zoomPoint = new fabric.Point(e.pointer.x,e.pointer.y);
            canvas.zoomToPoint(this.zoomPoint, this.zoom);
            
            this.lastzoomPoint.x = this.lastzoomPoint.x + (this.zoomPoint.x - this.lastmousePoint.x - this.relativeMouseX) / this.lastzoom
            this.lastzoomPoint.y = this.lastzoomPoint.y + (this.zoomPoint.y - this.lastmousePoint.y - this.relativeMouseY) / this.lastzoom

            this.lastmousePoint.x = this.zoomPoint.x
            this.lastmousePoint.y = this.zoomPoint.y
            this.lastzoom = this.zoom
          
            this.tempmouseX = this.relativeMouseX
            this.tempmouseY = this.relativeMouseY
            this.relativeMouseX = 0
            this.relativeMouseY = 0
            
          },
————————————————
版权声明:本文为CSDN博主「qq_38860536」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38860536/article/details/104759042

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐