p5.js example
by Corentin THOMASSET

A genetic algorithm I made using p5.js can be found here.

More examples from p5.js can be found here.

"use strict";

let snake = {
    x: [],
    y: [],
    numberOfSegment: 20,
    lengthOfSegment: 22
};

// Initialization of all segments
for (let i = 0; i < snake.numberOfSegment; ++i) {
    snake.x[i] = 0;
    snake.y[i] = 0;
}

// This function is called once
function setup() {
    createCanvas(500, 500);

    // Configuration of the aspect of the snake
    strokeWeight(12);
    stroke(92, 184, 92, 200);
}

// This one is called 60 times by second
function draw() {
    background(255);
    dragSegment(0, mouseX, mouseY);
    for (let i = 0; i < snake.numberOfSegment - 1; i++) {
        dragSegment(i + 1, snake.x[i], snake.y[i]);
    }
}

function dragSegment(i, xin, yin) {
    let dx = xin - snake.x[i];
    let dy = yin - snake.y[i];
    let angle = atan2(dy, dx);
    snake.x[i] = xin - cos(angle) * snake.lengthOfSegment;
    snake.y[i] = yin - sin(angle) * snake.lengthOfSegment;
    segment(snake.x[i], snake.y[i], angle);
}

function segment(x, y, a) {
    push();
    translate(x, y);
    rotate(a);
    line(0, 0, snake.lengthOfSegment, 0);
    pop();
}