Canvas experiment

by Richard Hunter

HTML

<h2 id="header">Hello world of HTML Canvas</h2>

CSS

h2 {
  font-size: 30px;
  line-height: 1.5;
  padding: 10px;
  position: relative;
}

JavaScript

const headerEl = document.querySelector('#header');

const height = headerEl.offsetHeight;
const width = headerEl.offsetWidth;

const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.style.position = 'absolute';
canvas.style.left = 0;
canvas.style.top = 0;
canvas.style.pointerEvents = 'none';
headerEl.append(canvas);

const ctx = canvas.getContext('2d');

headerEl.addEventListener('click', handleClick);

let flag = true;

function animateLine() {
  let x = 10;

  draw();

  function draw() {
    if (x < 160) {
      x += 1;
      ctx.clearRect(0, 0, width, height);
      ctx.beginPath();
      ctx.moveTo(10, 50);
      ctx.lineTo(x, 50);
      ctx.strokeStyle = 'red';
      ctx.stroke();
      requestAnimationFrame(draw);
    }
  }
}

function handleClick() {
  if (flag) {
    animateLine();
    flag = false;
  }
}