JSFiddle - React, Tailwind, and code Playground

by farazshaikh

HTML

<canvas width="400px" height="400px"></canvas>

CSS

body {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: #121212;
}

canvas {
  border: 1px solid white;
}

JavaScript

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

const drawGrid = function() {
  const gridDimentions = {
    width: 50,
    height: 50,
  };

  ctx.beginPath();
  ctx.save();

  for (var x = 0; x <= canvas.width; x += gridDimentions.width) {
    ctx.moveTo(0.5 + x, 0);
    ctx.lineTo(0.5 + x, canvas.height);
  }

  for (var x = 0; x <= canvas.height; x += gridDimentions.height) {
    ctx.moveTo(0, 0.5 + x);
    ctx.lineTo(canvas.width, 0.5 + x);
  }

  ctx.strokeStyle = '#606060';
  ctx.lineWidth = 1;
  ctx.stroke();

  ctx.beginPath();
  ctx.moveTo(gridDimentions.width * 3, canvas.height - gridDimentions.height * 3);
  ctx.lineTo(canvas.width - gridDimentions.width * 3, gridDimentions.height * 3);

  ctx.strokeStyle = '#d35d6e';
  ctx.lineWidth = 1;
  ctx.stroke();
}

const clear = function() {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
}

let smoothX = 0
let smoothY = 0
let smoothS = 0

const animate = function(dt) {
  clear()
  const theta = (Math.PI / 4) + dt * 0.001
  const scaleFac = 1.5 + (Math.sin(dt * 0.001) ** 2) * 0.5

  let scale = {
    x: Math.cos(theta) * scaleFac,
    y: Math.cos(theta) * scaleFac
  }


  let skew = {
    x: -Math.sin(theta) * scaleFac,
    y: Math.sin(theta) * scaleFac,

  }

  const translationFactor = {
    x: Math.sin(dt * 0.001) * 50,
    y: -Math.cos(dt * 0.001) * 50
  }

  const origin = {
    x: (canvas.width / 2),
    y: (canvas.height / 2)
  }

  const offset = {
    x: ((1 - scale.x) - skew.y) * origin.x,
    y: ((1 - scale.y) - skew.x) * origin.y
  }


  const translateVec = {
    x: translationFactor.x + offset.x,
    y: translationFactor.y + offset.y,
  }




  const mat_transform = new DOMMatrix([
    scale.x, skew.x, //  Sx  Qx
    skew.y, scale.y, //  Qy  Sy
    translateVec.x, translateVec.y, //  Tx  Ty
  ])
  ctx.setTransform(mat_transform)
  drawGrid()
  ctx.setTransform(1, 0, 0, 1, 0, 0)
  window.requestAnimationFrame(animate)

}

animate()