Avoid Excessive Use of Math.floor
One issue in this problem stems from frequently calling the Math.floor
function. Repeatedly using Math.floor
can lead to reduced accuracy in subsequent calculations.
To maintain accuracy, it is advisable to round numbers only at the end of your calculation sequence or specifically where the variable is being utilized. For instance:
transform: function() {
const translateX = Math.floor(this.translateX)
const translateY = Math.floor(this.translateY)
return `scale(${this.zoomLevel}) translateX(${translateX}px) translateY(${translateY}px)`;
}
Adjusting Scaling Factor
However, there seems to be a discrepancy in the speed of image movement compared to mouse movements.
This imbalance can be corrected by dividing the value being added to the translation by the scale factor determined by the zoomLevel
, as illustrated below:
if (translate.left >= 0 && translate.right <= 0) {
this.translateX += move.x / this.zoomLevel
}
if (translate.top >= 0 && translate.bottom <= 0) {
this.translateY += move.y / this.zoomLevel
}
Adjusting Scaling Factor for Viewport
The viewport may still exhibit issues due to scaling effects. To address this, adjust the translation values based on the scale of the viewport stored in this.viewportScale
. By combining solutions, consider the following code snippet:
if (translate.left >= 0 && translate.right <= 0) {
if (viewport) {
this.translateX += move.x / this.viewportScale
} else {
this.translateX += move.x / this.zoomLevel
}
}
if (translate.top >= 0 && translate.bottom <= 0) {
if (viewport) {
this.translateY += move.y / this.viewportScale
} else {
this.translateY += move.y / this.zoomLevel
}
}
Addressing Value Reversal
There appears to be redundant reversal of values when clicking and dragging within the viewport.
To streamline the code and avoid unnecessary value reversals, consider implementing separate inner translate functions that cater to different input sources (viewport or image). This approach results in cleaner code organization and facilitates future enhancements specific to each feature. You could structure your function as follows:
translate (positions, element, zooming, viewport) {
positions = positions || {
x: this.startX,
y: this.startY
}
if (viewport) {
this._translateFromViewport(positions, element, zooming)
} else {
this._translateFromImage(positions, element, zooming)
}
this.startX = positions.x
this.startY = positions.y
}
The _translateFromViewport
and _translateFromImage
functions can contain feature-specific logic.