Fabric.js+vue 实现鼠标滚轮缩放画布+移动画布

话不多说 直接贴代码


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

// 可以实现鼠标滚轮缩放 最小为原来的百分之一,最大为原来的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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值