如何让CSS变换-原点缩放和平移很好地协同工作?

问题描述 投票:0回答:1

我正在尝试制作一个可以拖动和缩放的画布元素。我有一个 html 范围输入元素来处理缩放。

我在使缩放和翻译协同工作方面遇到问题。当我缩放时,我将变换原点更改为鼠标拖动时的最后位置,使其缩放,同时聚焦于应该相对靠近视图中间的点。当我在缩放后开始拖动元素时,它在拖动开始时结结巴巴,我假设这是由于变换原点现在位于不同的位置?我不太确定。这是我的代码

inputElement =  document.getElementById("input");
inputElement.addEventListener("change",handleFiles, false);
canvas1 = document.getElementById('canvas1');
ctx1 = canvas1.getContext('2d');

const scrollBox = document.getElementById('scroll-box');
canvas1.style.transformOrigin = 'center center';

const zoomSlider = document.getElementById('zoomSlider');
let scale = 1;
let startX = 0;
let startY = 0;
let translateX = 0;
let translateY = 0;
let isDragging = false;
let lastX = 0;
let lastY = 0;


scrollBox.addEventListener('mousedown', (e) => {
    isDragging = true;
    startX = e.clientX;
    startY = e.clientY;
    scrollBox.style.cursor = 'grabbing';
});

scrollBox.addEventListener('mousemove', (e) => {
    if (isDragging) {
        const deltaX = (e.clientX - startX) / scale;
        const deltaY = (e.clientY - startY) / scale;
        translateX += deltaX;
        translateY += deltaY;
        startX = e.clientX;
        startY = e.clientY;
        applyTransform();
    }
});

scrollBox.addEventListener('mouseup', (e) => {
    isDragging = false;
    lastX = startX;
    lastY = startY;
    scrollBox.style.cursor = 'grab';
});

scrollBox.addEventListener('mouseleave', () => {
    isDragging = false;
    scrollBox.style.cursor = 'grab';
});

zoomSlider.addEventListener('input', (e) => {
    
    scale = Math.max(((e.target.value) / 100) * 2, 0.02);

    applyTransform();
});

function applyTransform() {
    canvas1.style.transformOrigin = `${lastX / 2}px ${lastY}px`;

    document.getElementById('canvas1').style.transform = `scale(${scale}, ${scale}) translate(${translateX}px, ${translateY}px)`;
    
}

我尝试在缩放时调整“translateX”和“translateY”变量以使其保持在中间,但我无法做到这一点。

javascript css transform
1个回答
0
投票

解决办法是搬家

canvas1.style.transformOrigin = 
${lastX / 2}px ${lastY}px
;
进入缩放输入事件处理程序。

© www.soinside.com 2019 - 2024. All rights reserved.