<canvas id="canvas"></canvas>
html {
  height: 100%;
  background: #222222;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 800px;
  min-height: 800px;
}
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const canvasSize = 900;
const ratio = window.devicePixelRatio || 1;
canvas.width = canvasSize * ratio;
canvas.height = canvasSize * ratio;
canvas.style.width = canvasSize + "px";
canvas.style.height = canvasSize + "px";
ctx.scale(ratio, ratio);

const animationInterval = 400;
const canvasPadding = 100;

const colors = ["#FFC513", "#247AFD", "#FE46A5", "#47C072"];

let startX = randomCoord();
let startY = randomCoord();
let endX = randomCoord();
let endY = randomCoord();

let iterator = 0;
draw();

function draw() {
  if (iterator % 2 == 0) {
    endX = randomCoord();
  }

  if (iterator % 2 == 1 || iterator % 4 == 0) {
    endY = randomCoord();
  }

  ctx.beginPath();
  ctx.moveTo(startX, startY);
  ctx.lineTo(endX, endY);
  ctx.lineWidth = 5;
  ctx.strokeStyle = colors[0];
  ctx.stroke();

  startX = endX;
  startY = endY;
  ++iterator;

  let lastColor = colors.pop();
  colors.unshift(lastColor);
  setTimeout(() => requestAnimationFrame(draw), animationInterval);
}

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

function randomCoord() {
  return randomNum(canvasPadding, canvasSize - canvasPadding);
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.