liveBook · Manning

L2 norm

As explained in Math for Web Design

Magnitude is the scalar length or size of a vector, representing the straight-line distance it covers.

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

How Math for Web Design covers it

How deep it goes
Defines magnitude with a 2D formula and implements it in JavaScript, including its use in normalization.
Examples
Uses a Vector2 class with magnitude(), normalize(), and a CSS translation method.
What it assumes
Builds from 2D coordinates and vector offsets before using the Pythagorean formula.
What you can do after
Apply it via JavaScript to measure a 2D offset and normalize it for directional movement.
How it connects
Connects vector coordinates, the Pythagorean formula, unit vectors, and CSS translations.

Also explained in

Compare how 4 books explain l2 norm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Math for Web Design. The section links point to the parts of the book it draws on.