In my class, there is a parameter called values that stores the points representing shapes on a canvas. I want to be able to drag these shapes around by adjusting each point based on how much they have been dragged.
To achieve this functionality, I came up with a plan. When I start dragging (by triggering the mousedown event), I save the initial values of my points in a variable called startValues. Then, as I move the mouse around, I update the values using the startValues and the distance between the starting point and the current mouse position.
However, I encountered an issue where this.startValues keeps getting changed to match this.values every time the cursor moves, and I can't figure out why. Am I overlooking something simple?
Since I store my points as values rather than coordinates (which helps with panning and zooming on the canvas), I convert the values to positions, modify the positions, and then convert them back to values. Below you can see the parent class, Grf, which includes the methods for converting values to positions and vice versa.
Class with the problems
class Test {
constructor(grf){
this.grf = grf;
this.values = [];
this.startValues = [];
}
startMove(p0){
const {grf} = this;
this.startValues = [...this.values];
this.p0 = p0;
grf.canvas.addEventListener('mousemove',this.move);
grf.canvas.addEventListener('mouseup', this.endMove);
}
move = (evt) => {
const {grf, p0, values, startValues} = this;
const coords = grf.canvas.getBoundingClientRect();
const px = evt.clientX - coords.left;
const py = evt.clientY - coords.top;
for (let i = 0, iMax = this.values.length; i < iMax; i++){
values[i][0] = grf.valX(grf.posX(startValues[0]) - (p0[0] - px));
values[i][1] = grf.valY(grf.posY(startValues[1]) - (p0[1] - py));
}
console.log(this.startValues);
}
endMove = (evt) => {
const {grf} = this;
grf.canvas.removeEventListener('mousemove',this.move);
grf.canvas.removeEventListener('mouseup', this.endMove);
}
}
The other class
class Grf {
constructor(canvas){
this.translateX = 1000;
this.translateY = 1000;
this.scaleY = 10.7;
this.scaleX = 11.2;
this.canvas = canvas;
}
posX (value){
return (value-this.translateX)*this.scaleX;
}
posY (value){
return (this.canvas.height-(100*(value))-this.translateY)*this.scaleY;
};
valX(pos){
return (pos/this.scaleX) + this.translateX
}
valY(pos){
return (-1)*((pos/this.scaleY) + this.translateY - this.canvas.height)/100
}
}