2017-08-05 138 views
0

Codepen:https://codepen.io/anon/pen/EvNqyYHTML畫布平移通過鼠標

使用Canvas,我在畫布上創造成千上萬圈和畫布充滿整個視口。我已經添加了一些平移功能,但在鼠標釋放後重新繪製問題。

基本上,用戶可以拖動畫布(代碼方式,這是有效的),但在視覺上它不顯示任何平移和鼠標釋放,畫布被重繪在其原始位置,所以似乎沒有任何事情發生。

JS:

$(document).ready(function() { 
    var canvas = document.querySelector('canvas'); 
    var ctx = canvas.getContext("2d"); 
    var global = { 
     scale: 1, 
     offset: { 
      x: 0, 
      y: 0, 
     }, 
    }; 
    var panning = { 
     start: { 
      x: null, 
      y: null, 
     }, 
     offset: { 
      x: 0, 
      y: 0, 
     }, 
    }; 
    var systems = '../js/json/eveSystems.json'; 

    fitToContainer(canvas); 

    $.getJSON(systems, function(data) { 

     function draw() { 
      ctx.setTransform(1, 0, 0, 1, 0, 0); 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 

      data.forEach(function(systemData) { 
       var coordX = systemData.position.x/100000000000000; 
       var coordY = systemData.position.y/100000000000000; 

       ctx.beginPath(); 
       ctx.arc(coordX,coordY,20,0,2*Math.PI); 
       ctx.stroke(); 
      }); 
     } 

     draw(); 

     canvas.addEventListener("mousedown", startPan); 

     function pan() { 
      ctx.setTransform(1, 0, 0, 1, 0, 0); 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
      ctx.translate(panning.offset.x, panning.offset.y); 
      console.log(panning.offset.x); 
      draw(); 
     } 

     function startPan(e) { 
      window.addEventListener("mousemove", trackMouse); 
      window.addEventListener("mousemove", pan); 
      window.addEventListener("mouseup", endPan); 
      panning.start.x = e.clientX; 
      panning.start.y = e.clientY; 
     } 

     function endPan(e) { 
      window.removeEventListener("mousemove", trackMouse); 
      window.removeEventListener("mousemove", pan); 
      window.removeEventListener("mouseup", endPan); 
      panning.start.x = null; 
      panning.start.y = null; 
      global.offset.x = panning.offset.x; 
      global.offset.y = panning.offset.y; 
     } 

     function trackMouse(e) { 
      var offsetX = e.clientX - panning.start.x; 
      var offsetY = e.clientY - panning.start.y; 
      panning.offset.x = global.offset.x + offsetX; 
      panning.offset.y = global.offset.y + offsetY; 
     } 
    }); 

    function fitToContainer(canvas){ 
     canvas.style.width ='100%'; 
     canvas.style.height='100%'; 
     canvas.width = canvas.offsetWidth; 
     canvas.height = canvas.offsetHeight; 
    } 

}); 

回答

1

ctx.setTransform覆蓋(0,0)的重新映射點由ctx.translate()完成。所以你應該從draw()函數中刪除ctx.setTransform(1, 0, 0, 1, 0, 0);行。