To move an element toward a target at a consistent speed, you need to know how long the movement vector is. The L2 norm, called magnitude here, is that straight-line length. For a 2D vector [x, y], magnitude = √(x² + y²). The vector gives both direction and distance; its magnitude gives only distance. section 10.6 section 10.3.1
Right three pixels, up four
A movement of [3, −4] has magnitude √(3² + (−4)²) = 5 pixels. The signs tell you which way to move in browser coordinates; the magnitude tells you how far. This is a vector offset, not a point’s location. section 10.1 section 10.6
class Vector2 {
constructor(x = 0, y = 0) { #1
this.x = x;
this.y = y;
}
add(vector) {
return new Vector2(this.x + vector.x, this.y + vector.y);
}
subtract(vector) {
return new Vector2(this.x - vector.x, this.y - vector.y);
}
multiply(scalar) {
return new Vector2(this.x * scalar, this.y * scalar);
}
magnitude() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
normalize() { #2
const mag = this.magnitude();
return mag > 0 ? new Vector2(this.x / mag, this.y / mag) :
new Vector2(0, 0);
}
clone() {
return new Vector2(this.x, this.y);
}
toCSSTranslate() {
return `translate(${this.x}px, ${this.y}px)`; #3
}
}
The JavaScript Vector2 class calculates magnitude with Math.sqrt(x*x + y*y). Its normalize() method divides each component by that magnitude to keep the direction while making the length 1; it handles a zero-length vector separately. The resulting vector can be converted to a CSS translation. section 10.3.1



