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


    话不多说 直接贴代码


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

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

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


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

    1. // 鼠标按下事件
    2. canvas.on('mouse:down', function (e) {
    3. this.panning = true
    4. canvas.selection = false
    5. })
    6. // 鼠标抬起事件
    7. canvas.on('mouse:up', function (e) {
    8. this.panning = false
    9. canvas.selection = true
    10. })
    11. // 移动画布事件
    12. canvas.on('mouse:move', function (e) {
    13. if (this.panning && e && e.e) {
    14. var delta = new fabric.Point(e.e.movementX, e.e.movementY)
    15. canvas.relativePan(delta)
    16. }
    17. })

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

    原理,通过偏移量

    添加 鼠标为缩放原点:
     

    1. "mouse:wheel": (e) => {
    2. this.zoom = (event.deltaY > 0 ? -0.1 : 0.1) + canvas.getZoom();
    3. this.zoom = Math.max(0.1, this.zoom); //最小为原来的1/10
    4. this.zoom = Math.min(3, this.zoom); //最大是原来的3倍
    5. this.zoomPoint = new fabric.Point(e.pointer.x,e.pointer.y);
    6. canvas.zoomToPoint(this.zoomPoint, this.zoom);
    7. this.lastzoomPoint.x = this.lastzoomPoint.x + (this.zoomPoint.x - this.lastmousePoint.x - this.relativeMouseX) / this.lastzoom
    8. this.lastzoomPoint.y = this.lastzoomPoint.y + (this.zoomPoint.y - this.lastmousePoint.y - this.relativeMouseY) / this.lastzoom
    9. this.lastmousePoint.x = this.zoomPoint.x
    10. this.lastmousePoint.y = this.zoomPoint.y
    11. this.lastzoom = this.zoom
    12. this.tempmouseX = this.relativeMouseX
    13. this.tempmouseY = this.relativeMouseY
    14. this.relativeMouseX = 0
    15. this.relativeMouseY = 0
    16. },
    17. ————————————————
    18. 版权声明:本文为CSDN博主「qq_38860536」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    19. 原文链接:https://blog.csdn.net/qq_38860536/article/details/104759042

  • 相关阅读:
    geoserver面的填充样式错误记录
    MongoDB从入门到实战之MongoDB工作常用操作命令
    【刷题】二叉树遍历思路解析
    csv文件导入mysql指定表中
    vue设置cookie和路由守卫
    第十二天Tensorflow基础和简单的线性回归实现
    docker安装
    Linux64Bit下安装MySQL5.6-不能修改root密码
    如何正确维护实验室超声波清洗器?
    Spring+SpringBoot+SpringCloud 全攻略
  • 原文地址:https://blog.csdn.net/Thea12138/article/details/132716209