HTML5 canvas 实现图片的缩放与平移

定义所需要的变量

var canvas=document.getElementById("myCanvas");
var canvasDraw=canvas.getContext("2d");
var startPointX=0;//起始点 x
var startPointY=0;//起始点 y
var imgX=0;//设置img在的位置
var imgY=0;//
var imgX1=0;
var imgY1=0;//中间变量
var imgScale=1;
var imgScaleUp=1;

 

加载图片

var img=new Image()
img.src="img/map1.png"
img.onload = function(){
  canvasDraw.drawImage(img,imgX,imgY,img.width,img.height);
}

对canvas绑定滚轮事件,startPointX、startPointY为鼠标点击的位置,以(startPointX,startPointY)为中心点进行图片的缩放。设当前为图片没有缩放的状态、图片位置为(imgX,imgY),当进行缩放时,缩放值为imgScale,则(startPointX-imgX)*imgScale=(startPointX-imgX1)(imgX1为变化后的位置),得imgX1=(imgX-startPointX)*imgScale+startPointX;。当图片进行缩放时,获取点击位置到图片位置的距离,并将该距离恢复为没有缩放的状态,即imgX1=((imgX-startPointX)/imgScaleUp)*imgScale+startPointX;,imgScaleUp为缩放结束时的缩放值

function imgScaleWheel(){
  canvas.onmousewheel=canvas.onwheel=function(event){//chrome firefox浏览器兼容
   
    if(event.wheelDelta>0){
        imgScale+=0.1;
    }else{
        if(imgScale>0.2){
          imgScale-=0.1;
        }
    };
     //需要xy的中间变量
     imgX1=((imgX-startPointX)/imgScaleUp)*imgScale+startPointX;
     imgY1=((imgY-startPointY)/imgScaleUp)*imgScale+startPointY;
     canvasDraw.clearRect(0,0, canvas.width,canvas.height);//清除整个画布
     drawImg(img,imgX1,imgY1,imgScale);
     console.log("滚轮 imgX1",imgX1,"imgY1",imgY1)
  }
  
}

对canvas绑定鼠标事件,但鼠标点击时,imgScaleUp获取当前缩放值,imgX imgY获取当前图片的位置。endPointX1为在鼠标移动过程中的x坐标,将endPointX1-startPointX 即为图片x的偏移量

function movexy() {

  canvas.onmousedown = function (e) {
        startPointX=getScreen(e).x;
        startPointY=getScreen(e).y;
        var buttonType=e.button;
        //获取缩放后的最终
        imgX=imgX1;
        imgY=imgY1;
        imgScaleUp=imgScale;
        console.log("startPointX",startPointX,"startPointY",startPointY)
       canvas.onmousemove = function (evt) { //实时改变位置
          var e = event || window.event;
          var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
          var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
          var endPointX1 = e.pageX || e.clientX + scrollX;
          var endPointY1 = e.pageY || e.clientY + scrollY;
          endPointX1-=canvas.offsetLeft;
          endPointY1-=canvas.offsetTop;
          if(buttonType==1){//滚轮平移
             canvasDraw.clearRect(0,0, canvas.width,canvas.height);//清除整个画布
             translateX=endPointX1-startPointX;
             translateY=endPointY1-startPointY;
             imgX1=imgX+translateX;
             imgY1=imgY+translateY;
             drawImg(img,imgX1,imgY1,imgScale);

          }
         
          endPointX=endPointX1;
          endPointY=endPointY1;

        }
        //停止按下与拖动事件
        canvas.onmouseup = function () {
          canvas.onmousemove = null;
          canvas.onmouseup = null;
          
        }
    }
}

 

你可能感兴趣的:(JavaScript)