放大和缩小图像不能正常工作

时间:2018-03-25 16:18:08

标签: javascript

我有一张地图图片,我想用滚轮放大和缩小。 这只在放大或缩小时完美地工作,但是当我改变方向时(从放大到缩小),狗屎开始。

如果我滚动3次放大然后改变方向缩小它会在开始缩小之前需要尽可能多的滚动-1同时它会继续放大使ctx.scale变为香蕉。

感谢您的回复< 3

    var scaleY = 1;
    var scaleX = 1;

    //function to draw the map
     function loader(){

    //load background
     var canvas = document.getElementById("mycanvas");
     var ctx = canvas.getContext("2d");

     var background = new Image();
     background.src = "map2.png";
     background.onload = function(){
     ctx.clearRect(0,0,1375,850);
     ctx.scale(scaleY,scaleX);
     ctx.drawImage(background,0,0);
     ctx.font = "15px arial";
     ctx.fillText(scaleY,25,pos); 
     }
     }
    function userActions(){
    var canvas = document.getElementById("mycanvas");

    //detect scroll activity
    canvas.addEventListener("wheel", zoom);

     //function to decide if the scroll si up or down
      function zoom(e){
      if (e.deltaY < 0){
      //change the scale 
      scaleY = Math.round((scaleY + 0.1) * 10) / 10;
      scaleX = Math.round((scaleX + 0.1) * 10) / 10; 
      loader(scaleY, scaleX);
      } 
      if(e.deltaY > 0){
      //change the scale
      scaleY = Math.round((scaleY - 0.1) * 10) / 10;
      scaleX = Math.round((scaleX - 0.1) * 10) / 10;   
      loader(scaleY, scaleX);
      }

      }

      }

1 个答案:

答案 0 :(得分:0)

scale is not absolute, but multiplies the scale factors onto the current transformation matrix. You should reset it after every draw call. This can be done via:

ctx.setTransform(1, 0, 0, 1, 0, 0);

var scaleY = 1;
var scaleX = 1;

var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

var background = new Image();
background.src = "https://www.gravatar.com/avatar/c35af79e54306caedad37141f13de30c?s=128&d=identicon&r=PG";
background.onload = draw;

//function to draw the map
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.scale(scaleY, scaleX);
  ctx.drawImage(background, 0, 0);

  // reset current transformation matrix to the identity matrix
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

//function to decide if the scroll si up or down
function zoom(e) {
  if (e.deltaY < 0) {
    //change the scale 
    scaleY = Math.round((scaleY + 0.1) * 10) / 10;
    scaleX = Math.round((scaleX + 0.1) * 10) / 10;
    draw();
  }
  if (e.deltaY > 0) {
    //change the scale
    scaleY = Math.round((scaleY - 0.1) * 10) / 10;
    scaleX = Math.round((scaleX - 0.1) * 10) / 10;
    draw();
  }
  e.preventDefault();
}
canvas.addEventListener("wheel", zoom);
<canvas id="mycanvas" height="200" width="200"/>