我得到了一个元素(画布)在鼠标滚轮上点击你可以移动它,在ctrl+scroll u上缩放它,为了使元素的移动更平滑我计算了鼠标相对于元素的距离,所以鼠标不只是去了元素的左上角,这个距离在缩放后计算错误,我尝试了不同的方法乘以或除以规模的距离,但仍然没有什么工作。以下是代码:
var scale = 1;
window.addEventListener("wheel", function(event) {
if (event.ctrlKey) {
event.preventDefault();
if(event.deltaY<0){
if(scale<5)
scale+=0.2;
}else{
if(scale>=0.8)
scale-=0.2;
}
canvas.style.transform = `scale(${scale})`;
}
}, { passive: false });
var canvasX,canvasY,movingCanvas = false;
document.addEventListener('mousedown',function(event){
if(event.button === 1)
{
//here somewting needs to be changed according to the scale
canvasX = (event.clientX- canvas.getBoundingClientRect().left);
canvasY = (event.clientY- canvas.getBoundingClientRect().top);
movingCanvas = true;
}
});
canvas = document.getElementById('canvas');
document.onmousemove = function(event){
if(movingCanvas){
canvas.style.top = (event.clientY-canvasY) +'px';
canvas.style.left=(event.clientX-canvasX) + 'px';
}
};
document.addEventListener('mouseup',function(e){
if(movingCanvas)
movingCanvas = false;
});
1条答案
按热度按时间zzwlnbp81#
发现问题了,代码没问题,不需要修改,问题是:缩放后,顶部和左侧保持在未缩放元素的相同位置,以修复它我添加了属性:css中的
transform-origin: top left;