用户SVG.js缩放,然后平移会使位置错误

User SVG.js to scale, then translate will make it wrong position

我用svg.js

我调用g.scale(4)后,g.translate(x, y)会跑到错误的位置,那怎么办好呢?

有一个fiddle:https://jsfiddle.net/87gqz3no/34/

使用鼠标滚轮放大 canvas,然后拖动以移动它。但是它走错了位置。

拖动白色背景。没问题。

然后使用鼠标滚轮放大整个canvas。然后拖背景...放大...,拖...,背景(根g元素)的位置出错了

F12查看控制台,设置和获取。

var $canvas = $('#mycanvas')
var g = SVG('mycanvas').size('100%', '100%').group()
// draw a rect
g.rect(200, 40).translate(100, 100).fill('red')


var click = {};  // click pos of screen 
var g_pos = {};  // click pos of container element `g`
var scale = 1;  // scale of container element `g`


// mouse down to record the position
$canvas.on('mousedown', function(e) {
  click = {x: e.pageX, y: e.pageY};
  g_pos = {x: g.x(), y: g.y()};
  scale = g.transform().scaleX;
  
  // when mousedown, add event listener
  $canvas.on('mousemove', move);
  $canvas.on('mouseup', up);
})


// set the new position of the g
function move(e) {
  // delta pos of mouse move
  var delta = {
    x: e.pageX - click.x,
    y: e.pageY - click.y
  };
  
  // calculate the new position of g
  // even if I force set scale to 1, also not work.
  // scale = 1;
  var x = g_pos.x + delta.x / scale;
  var y = g_pos.y + delta.y / scale;
  
  console.log("set pos of g:", x, y, "delta:", delta, 'scale:', scale);
  g.move(x, y);
  console.log("get pos of g:", g.x(), g.y());
}


// when mouseup, remove event listener
function up(e) {
  $canvas.off('mousemove', move);
  $canvas.off('mouseup', up);
}


// mousewheel to zoom
$canvas.on('mousewheel DOMMouseScroll', function(e) {
      var delta, diff, last_scale, max_scale, min_scale, per;
      delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));  // delta position of mouse wheel
      last_scale = g.transform().scaleX;
      per = .1;
      min_scale = .5;  // min scale
      max_scale = 8.6;  // max scale
      diff = delta > 0 ? per : -per;
      return g.scale(Math.min(Math.max(last_scale + diff, min_scale), max_scale));
    })
html,
body,
#mycanvas {
  width: 99%;
  height: 99%;
  padding: 0;
  margin: 0;
}

#mycanvas {
  border: 1px solid red;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.5/svg.min.js"></script>
<div id="mycanvas"></div>

复制回答问题的评论:

为什么要重新发明轮子?有svg.panzoom.js for your pan/zoom problem and svg.draggable.js用于拖动元素

let canvas = SVG('idOfDiv').panZoom()

let rect = canvas.rect(100, 100).draggable()