我使用svg.js
调用g.scale(4)之后,然后g.translate(x,y)会移到错误的位置,那我该怎么办呢?
有一个小提琴:https://jsfiddle.net/87gqz3no/34/
使用鼠标滚轮放大画布,然后拖动以移动它。但位置错误。
拖动白色背景。可以。
然后使用鼠标滚轮放大整个画布。然后拖动背景...放大...,拖动...,背景(根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>
答案 0 :(得分:1)
要复制回答问题的评论:
为什么要重新发明轮子? svg.panzoom.js用于平移/缩放问题,svg.draggable.js用于拖动元素
let canvas = SVG('idOfDiv').panZoom()
let rect = canvas.rect(100, 100).draggable()