canvas图形放大缩小鼠标拖拽

canvas图形放大缩小鼠标拖拽

在网上找的都是放大缩小,或者鼠标拖拽,没有两者都满足的
一开始我天真的以为两个合并就可以了,但其实当鼠标松开和点击的时候,坐标原点是会变的,就是每次拖拽都是清除之前,放大缩小也是,所以那个原点很不好确定,
主要思路就是保存之前的原点坐标

过程比较麻烦,意会一下就好了,直接上代码

var that = this;

      var canvas = document.getElementById('myDiv')
      var ctx = canvas.getContext('2d')
      let obj = {
          fontX: 0,
          fontY: 0,
          fontZoom: 1,
          curZoom: 1,
          translateX: 0,
          translateY: 0,
          z:1,
          movex:0,
          movey:0,
          x:0,
          y:0,
          zoom(offsetX, offsetY, z) {
              console.log('zoom')
              ctx.clearRect(0,0,1300,640)
              ctx.save()
              ctx.translate(obj.x, obj.y)
              ctx.save()
              this.curZoom = this.fontZoom + obj.z
              console.log(this.curZoom,'缩放比例')
              this.translateX = offsetX - (offsetX - this.translateX) * this.curZoom / this.fontZoom  
              this.translateY = offsetY - (offsetY - this.translateY) * this.curZoom / this.fontZoom 
              ctx.translate(this.translateX, this.translateY)
              ctx.scale(this.curZoom, this.curZoom);
              that.toDraw()
              ctx.restore()
              ctx.restore()
              this.fontY = offsetY
              this.fontX = offsetX
              this.fontZoom =this.fontZoom + obj.z
          },
          mou(offsetX, offsetY){
          //   console.log('mou')
            ctx.clearRect(0,0,1300,640)
            ctx.save()
            console.log(offsetX, offsetY,this.translateX,this.translateY)
            ctx.translate(offsetX+this.translateX, offsetY+this.translateY)
            ctx.scale(this.curZoom, this.curZoom);
            that.toDraw()
            // if(isDrop){
            ctx.restore()
            // }
          }
      }
      console.log(document.getElementById('myDiv'))
      document.getElementById('myDiv').addEventListener('mousewheel', (e) => {
          obj.z = e.deltaY > 0 ? -0.1 : 0.1
          obj.zoom(e.offsetX, e.offsetY, obj.z)
      })
      var isDrop = false;
      document.getElementById('myDiv').onmousedown = function(e){
        isDrop = true
        var clientX = e.clientX
        var clientY = e.clientY
        document.getElementById('myDiv').onmousemove=function(e){
          if(isDrop){
            obj.movex = e.clientX -clientX + obj.x
            obj.movey = e.clientY -clientY + obj.y
            // console.log(e.clientX -clientX,obj.x)
            obj.mou(obj.movex,obj.movey)
          }
         
          document.getElementById('myDiv').onmouseup = function(){
            isDrop = false; 
            obj.x = obj.movex
            obj.y = obj.movey
            console.log('停止了')

          }
        }
      }

toDraw的函数自己写一个随便画个圆圈啥的都行,看卡效果就好,上面就是关键代码

你可能感兴趣的:(js,canvas,javascript,前端,canvas)