Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas id="canvas"></canvas>
              
            
!

CSS

              
                html,
body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    touch-action: none;
    cursor: none;
}

              
            
!

JS

              
                function randomGauss(mu = 0, sigma = 1, nsamples = 6) {
    // http://stackoverflow.com/a/33567961
    var run_total = 0;
    for (var i = 0; i < nsamples; i++) {
        run_total += Math.random();
    }

    return sigma * (run_total - nsamples / 2) / (nsamples / 2) + mu;
}

function cycle(value, total) {
    return (value % total + total) % total;
}

function clip(x, min, max) {
    if (min > max) {
        return x;
    } else if (x < min) {
        return min;
    } else if (x > max) {
        return max;
    } else {
        return x;
    }
}

function getRandomFloat(min, max) {
    return Math.random() * (max - min) + min;
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Point
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    get position() {
        return [this.x, this.y];
    }

    clone() {
        return new Point(this.x, this.y);
    }

    delta(point) {
        return [this.x - point.x, this.y - point.y];
    }

    distance(point) {
        const dx = point.x - this.x;
        const dy = point.y - this.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    moveTo(x, y) {
        this.x = x;
        this.y = y;
        return this;
    }

    moveAtAngle(angle, distance) {
        this.x += Math.cos(angle) * distance;
        this.y += Math.sin(angle) * distance;
        return this;
    }

    applyVelocity(velocity) {
        this.x += velocity.vx;
        this.y += velocity.vy;
        return this;
    }

    angleRadians(point) {
        // radians = atan2(deltaY, deltaX)
        const y = point.y - this.y;
        const x = point.x - this.x;
        return Math.atan2(y, x);
    }

    angleDeg(point) {
        // degrees = atan2(deltaY, deltaX) * (180 / PI)
        const y = point.y - this.y;
        const x = point.x - this.x;
        return Math.atan2(y, x) * (180 / Math.PI);
    }

    rotate(origin, radians) {
        // rotate the point around a given origin point
        const cos = Math.cos(radians);
        const sin = Math.sin(radians);
        this.x =
            cos * (this.x - origin.x) + sin * (this.y - origin.y) + origin.x;
        this.y =
            cos * (this.y - origin.y) - sin * (this.x - origin.x) + origin.y;
        return this;
    }
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Bounds
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Bounds {
    constructor(x, y, w, h) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        const hw = w / 2;
        const hh = h / 2;
        this.center = new Point(hw, hh);
        this.position = new Point(x, y);
    }

    get params() {
        return [this.x, this.y, this.w, this.h];
    }

    offsetOuter(offset) {
        const [x, y, w, h] = this.params;
        return new Bounds(
            x - offset,
            y - offset,
            w + offset * 2,
            h + offset * 2
        );
    }

    offsetInner(offset) {
        const [x, y, w, h] = this.params;
        return new Bounds(
            x + offset,
            y + offset,
            w - offset * 2,
            h - offset * 2
        );
    }
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Entity
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Entity {
    dpr = window.devicePixelRatio || 1;
    toValue = value => value * this.dpr;
    draw = () => {};
    update = () => {};
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Canvas
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Canvas {
    constructor({ canvas, entities = [], pointer }) {
        // setup a canvas
        this.canvas = canvas;
        this.dpr = window.devicePixelRatio || 1;
        this.ctx = canvas.getContext('2d');
        this.ctx.scale(this.dpr, this.dpr);

        // tick counter
        this.tick = 0;

        // entities to be drawn on the canvas
        this.entities = entities;

        // track mouse/touch movement
        this.pointer = pointer || null;

        // setup and run
        this.setCanvasSize();
        this.setupListeners();
        this.render();

        // demo pointer
        this.pointer.addPointerModifier((pointer, tick) => {
            const cx = window.innerWidth / 2 * this.dpr;
            const cy = window.innerHeight / 2 * this.dpr;

            const dx = window.innerWidth / 3 * this.dpr;
            const dy = window.innerHeight / 8 * this.dpr;

            const offX = cx + Math.sin(tick / 20) * dx;
            const offY = cy + Math.cos(-tick / 20) * dy;

            pointer.lastPosition.moveTo(pointer.position.x, pointer.position.y);
            pointer.position.moveTo(offX, offY);
        });
    }

    setupListeners() {
        window.addEventListener('resize', this.setCanvasSize);
    }

    setCanvasSize = () => {
        const { innerWidth: w, innerHeight: h } = window;
        const w2 = w * this.dpr;
        const h2 = h * this.dpr;
        this.canvas.width = w2;
        this.canvas.height = h2;
        this.canvas.style.width = w + 'px';
        this.canvas.style.height = h + 'px';
        this.bounds = new Bounds(0, 0, w2, h2);
    };

    addEntity = newEntity => {
        this.entities = [...this.entities, newEntity];
        return this.entities.length - 1;
    };

    removeEntity(deleteIndex) {
        this.entities = this.entities.filter((el, i) => i !== deleteIndex);
        return this.entities;
    }

    removeDead() {
        this.entities = this.entities.filter(({ dead = false }) => !dead);
    }

    render = () => {
        // Main loop

        // Draw and Update items here.
        this.entities.forEach(({ draw, update }) => {
            draw(this);
            update(this);
        });

        // update pointer for demos
        this.pointer.update(this);

        // Cleanup "dead" entities
        this.removeDead();

        ++this.tick;
        window.requestAnimationFrame(this.render);
    };
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Cursor
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Cursor extends Entity {
    constructor(radius) {
        super();
        this.radius = this.toValue(radius);
        this.pi2 = Math.PI * 2;
        this.lineWidth = this.toValue(2);
        this.strokeStyle = '#fff';
    }

    draw = ({ ctx, pointer }) => {
        ctx.strokeStyle = this.strokeStyle;
        ctx.lineWidth = this.lineWidth;
        ctx.beginPath();
        ctx.arc(
            pointer.position.x,
            pointer.position.y,
            this.radius,
            0,
            this.pi2,
            true
        );
        ctx.closePath();
        ctx.stroke();
    };
}


//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Background
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Background extends Entity {
    drawText({ ctx, canvas }) {
        const ms = Math.max(canvas.width, canvas.height);
        const size = ms / 15;

        const copy = 'Canvas Starter';
        const x = canvas.width / 2;
        const y = canvas.height / 2 + size / 3;
        ctx.font = `700 italic ${size}px futura, sans-serif`;
        ctx.textAlign = 'center';
        ctx.fillStyle = '#fff';
        ctx.fillText(copy, x, y);
    }

    drawGradient({ ctx, canvas, bounds }) {
        ctx.fillStyle = '#252f3d';
        ctx.fillRect(...bounds.params);
    }

    draw = context => {
        this.drawGradient(context);
        // this.drawText(context);
    };
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Pointer
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class Pointer {
    constructor() {
        this.dpr = window.devicePixelRatio || 1;
        this.delta;
        this.lastPosition = new Point(0, 0);
        this.position = new Point(0, 0);
        this.addListeners();
    }

    delta() {
        return this.position.delta(this.lastPosition);
    }

    addListeners() {
        ['mousemove', 'touchmove'].forEach((event, touch) => {
            window.addEventListener(
                event,
                e => {
                    // move previous point
                    const { x: px, y: py } = this.position;

                    // disable the demo modifier if it's been added
                    if (this.modifier) {
                        this.modifier = null;
                    }

                    if (touch) {
                        e.preventDefault();
                        const x = e.targetTouches[0].clientX * this.dpr;
                        const y = e.targetTouches[0].clientY * this.dpr;
                        this.position.moveTo(x, y);
                        this.lastPosition.moveTo(px, py);
                    } else {
                        const x = e.clientX * this.dpr;
                        const y = e.clientY * this.dpr;
                        this.position.moveTo(x, y);
                        this.lastPosition.moveTo(px, py);
                    }
                },
                false
            );
        });
    }

    addPointerModifier(modifier) {
        this.modifier = modifier;
    }

    update = ({ tick }) => {
        this.modifier && this.modifier(this, tick);
    };
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// Spring
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

// defaults and constants
const ELASTICITY = 0.03; // elastic force toward the origin
const DAMPING = 0.75;
const MASS = 2;
const ADJACENT_SPRING_CONSTANT = 0.1;

const DPR = window.devicePixelRatio || 1;
const MOUSE_STRENGTH = 0.7; // 0 - 1
const MOUSE_RADIUS = 100 * DPR;

class Spring extends Point {
    constructor({
        x,
        y,
        isFixed,
        mass = MASS,
        elasticity = ELASTICITY,
        damping = DAMPING,
    }) {
        super(x, y);
        this.ox = x; // original origin x, never changes
        this.oy = y; // original origin y, never changes
        this.vx = 0; // velocity x
        this.vy = 0; // velocity y
        this.fx = 0; // force x
        this.fy = 0; // force y

        this.isFixed = isFixed; // indeicates whether this point can be moved

        // spring constants
        this.mass = mass;
        this.elasticity = elasticity;
        this.damping = damping;
    }

    applyForce(x, y) {
        this.fx += x;
        this.fy += y;
    }

    attractors = []; // just testing

    addAttractor(point) {
        this.attractors = [...this.attractors, point];
    }

    setForceFromAttractors() {
        // currently unused, was testing out an
        this.attractors.forEach((point, i) => {
            const { x, y } = point;

            const force = { x: 0, y: 0 }; // prev point force
            const { vx, vy } = point;

            force.y = ADJACENT_SPRING_CONSTANT * vy;
            force.x = ADJACENT_SPRING_CONSTANT * vx;

            // apply adjacent forces to current spring
            this.applyForce(force.x, force.y);
        });
    }

    applyForceFromMouse(pointer) {
        const { x, y } = pointer.position;

        const distance = this.distance(pointer.position);

        if (distance < MOUSE_RADIUS) {
            const [dx, dy] = pointer.delta();
            const power = (1 - distance / MOUSE_RADIUS) * MOUSE_STRENGTH;

            this.applyForce(dx * power, dy * power);
        }
    }

    setSpringForce() {
        // force to origin, difference multiplied by elasticity constant
        const fx = (this.ox - this.x) * this.elasticity;
        const fy = (this.oy - this.y) * this.elasticity;

        // sum forces
        this.fx += fx;
        this.fy += fy;
    }

    solveVelocity() {
        if (this.fx === 0 && this.fy === 0) return;

        // acceleration = force / mass;
        const ax = this.fx / this.mass;
        const ay = this.fy / this.mass;

        // velocity, apply damping then ad acceleration
        this.vx = this.damping * this.vx + ax;
        this.vy = this.damping * this.vy + ay;

        // add velocity to center and top/left
        this.x += this.vx;
        this.y += this.vy;

        // reset any applied forces
        this.fx = 0;
        this.fy = 0;
    }

    update = ({ pointer }) => {
        if (this.isFixed) return;
        this.setForceFromAttractors();
        this.applyForceFromMouse(pointer);
        this.setSpringForce();
        this.solveVelocity();
    };

    draw = ({ ctx }) => {
        // temporary, just to see what's happening
        // const { x, y } = this;
        // ctx.fillStyle = 'white';
        // ctx.lineWidth = 5;
        // ctx.fillRect(x - 2, y - 2, 4, 4);
        // ctx.beginPath();
        // ctx.arc(x, y, 4, 0, Math.PI * 2, true);
        // ctx.closePath();
        // ctx.stroke();
    };
}

//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡/
// PolyWave
//*‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡‡*/

class PolyWave extends Entity {
    constructor({ verts, color, elasticity, damping }) {
        super();
        this.verts = verts; // corners
        this.color = color;
        this.points = [];
        this.resolution = 20;
        this.elasticity = elasticity;
        this.damping = damping;

        this.constructPolyWave();
        this.setAttractors();
    }

    constructPolyWave() {
        let begin = true;

        for (let i = 0; i < this.verts.length; i++) {
            const p1 = this.verts[i];
            const p2 = this.verts[i + 1];

            if (p1 && p2) {
                const [dx, dy] = p1.delta(p2);
                const distance = p1.distance(p2);
                const amount = distance / this.resolution;
                const pointAmt = Math.round(amount);

                const offX = dx / pointAmt;
                const offY = dy / pointAmt;

                for (let k = 1; k <= pointAmt; k++) {
                    const x = p1.x - offX * k;
                    const y = p1.y - offY * k;
                    this.points.push(
                        new Spring({
                            x,
                            y,
                            elasticity: this.elasticity,
                            damping: this.damping,
                        })
                    );
                }

                begin = false;
            }
        }
    }

    setAttractors() {
        this.points.forEach((p, i) => {
            const isLast = i === this.points.length - 1;
            const isFirst = i === 0;
            if (isLast) {
                p.addAttractor(this.points[i - 1]);
                p.addAttractor(this.points[0]);
            } else if (isFirst) {
                p.addAttractor(this.points[this.points.length - 1]);
                p.addAttractor(this.points[i + 1]);
            } else {
                p.addAttractor(this.points[i - 1]);
                p.addAttractor(this.points[i + 1]);
            }
        });
    }

    draw = ({ ctx, bounds }) => {
        ctx.beginPath();

        this.points.forEach(point => {
            ctx.lineTo(point.x, point.y);
        });

        ctx.closePath();

        ctx.fillStyle = this.color;

        ctx.lineWidth = this.toValue(2);
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';

        ctx.fill();
    };

    update = context => {
        this.points.forEach(point => point.update(context));
    };
}

const colors = [
    '#d16060',
    '#edb07b',
    '#7bc4a2',
    '#343a5b',
    '#9b7bad',
    '#a05065',
];

function generatePolygon(ctrX, ctrY, aveRadius = 100, numVerts = 6) {
    // Ported from http://stackoverflow.com/a/25276331

    let irregularity = 0.1;
    let spikeyness = 0.2;

    irregularity = clip(irregularity, 0, 1) * 2 * Math.PI / numVerts;
    spikeyness = clip(spikeyness, 0, 1) * aveRadius;

    // generate n angle steps
    const angleSteps = [];
    const lower = 2 * Math.PI / numVerts - irregularity;
    const upper = 2 * Math.PI / numVerts + irregularity;

    let sum = 0;
    for (var i = 0; i < numVerts; i++) {
        const tmp = getRandomInt(lower, upper);
        angleSteps.push(tmp);
        sum = sum + tmp;
    }

    // normalize the steps so that point 0 and point n+1 are the same
    const k = sum / (2 * Math.PI);
    for (var i = 0; i < numVerts; i++) {
        angleSteps[i] = angleSteps[i] / k;
    }

    const points = [];

    let angle = getRandomInt(0, 2 * Math.PI);

    for (var i = 0; i < numVerts; i++) {
        const r_i = clip(randomGauss(aveRadius, spikeyness), 0, 2 * aveRadius);
        const x = ctrX + r_i * Math.cos(angle);
        const y = ctrY + r_i * Math.sin(angle);

        points.push(new Point(x, y));

        angle = angle + angleSteps[i];
    }

    return points;
}

const center = new Point(
    window.innerWidth / 2 * DPR,
    window.innerHeight / 2 * DPR
);

const createPolys = amount =>
    Array(amount)
        .fill(null)
        .map((_, i) => {
            const size = Math.min(window.innerWidth / 25, window.innerHeight / 25) * (amount - i) * DPR;
            const points = 6 + (amount - i);
            const verts = generatePolygon(center.x, center.y, size, points);
            const cdx = cycle(i, colors.length);
            return new PolyWave({
                verts: [...verts, verts[0]],
                elasticity: getRandomFloat(0.01, 0.03),
                damping: getRandomFloat(0.4, 0.7),
                color: colors[cdx],
            });
        });

// Kick off
const canvas = new Canvas({
    canvas: document.getElementById('canvas'),
    pointer: new Pointer(),
    entities: [new Background(), ...createPolys(10), new Cursor(10)],
});

              
            
!
999px

Console