小能豆

放大时图像未正确拖动

js

我在使用下面提供的功能时遇到问题。当放大图像时,可以将其拖动到其边界之外。此问题会导致图像与其容器之间存在间隙,并且该间隙随着图像比例的增大而增大。

看来该getBoundingClientRect方法在图像缩放时准确地捕获了图像的更新尺寸。尽管如此,问题的原因仍然存在。

对此问题的任何建议将不胜感激。

dragMove(event) {
    if (this.isDragging && this.imageScale > this.minZoom) {
        const containerRect = this.$refs.croquisContainer.getBoundingClientRect();
        const imageRect = this.$refs.croquisImage.getBoundingClientRect();

        const maxOffsetX = (imageRect.width - containerRect.width) / 2;
        const maxOffsetY = (imageRect.height - containerRect.height) / 2;

        const deltaX = event.clientX - this.lastX;
        const deltaY = event.clientY - this.lastY;

        const newOffsetX = this.offsetX + deltaX;
        const newOffsetY = this.offsetY + deltaY;

        this.offsetX = Math.max(Math.min(newOffsetX, maxOffsetX), -maxOffsetX);
        this.offsetY = Math.max(Math.min(newOffsetY, maxOffsetY), -maxOffsetY);

        this.lastX = event.clientX;
        this.lastY = event.clientY;
    }
}

JSFiddle: https://jsfiddle.net/n4d7txwy/


阅读 203

收藏
2024-02-23

共1个答案

小能豆

问题似乎是在图像放大后,由于偏移量未及时更新,因此允许将图像拖动到容器边界之外。为了解决这个问题,您可以在放大图像后更新偏移量,并根据新的图像尺寸和容器尺寸来限制拖动范围。

以下是一个可能的解决方案,您可以尝试将其应用到您的代码中:

dragMove(event) {
    if (this.isDragging && this.imageScale > this.minZoom) {
        const containerRect = this.$refs.croquisContainer.getBoundingClientRect();
        const imageRect = this.$refs.croquisImage.getBoundingClientRect();

        // 更新容器和图像的尺寸和位置
        const containerWidth = containerRect.width;
        const containerHeight = containerRect.height;
        const imageWidth = imageRect.width * this.imageScale;
        const imageHeight = imageRect.height * this.imageScale;

        // 计算最大偏移量
        const maxOffsetX = (imageWidth - containerWidth) / 2;
        const maxOffsetY = (imageHeight - containerHeight) / 2;

        // 计算鼠标移动距离
        const deltaX = event.clientX - this.lastX;
        const deltaY = event.clientY - this.lastY;

        // 更新偏移量
        let newOffsetX = this.offsetX + deltaX;
        let newOffsetY = this.offsetY + deltaY;

        // 限制偏移量在容器边界内
        newOffsetX = Math.max(Math.min(newOffsetX, maxOffsetX), -maxOffsetX);
        newOffsetY = Math.max(Math.min(newOffsetY, maxOffsetY), -maxOffsetY);

        // 更新偏移量
        this.offsetX = newOffsetX;
        this.offsetY = newOffsetY;

        // 更新上次鼠标位置
        this.lastX = event.clientX;
        this.lastY = event.clientY;
    }
}

此解决方案中,我们在每次拖动时都更新了容器和图像的尺寸和位置,并根据新的尺寸计算了最大偏移量。然后,我们根据这些最大偏移量来限制偏移量,并确保图像始终在容器边界内。希望这可以解决您遇到的问题。

2024-02-23