HTML Canvas boiler template

Ming Sun

Ming Sun / May 08, 2023

2 min read––– views

React component

The following code will create a boiler template for HTML canvas.

import { useEffect } from "react";

const CanvasBoilerTemplate = () => {
  useEffect(() => {
    let canvasParent = document.getElementById("canvasParent");
    let canvas = document.getElementById("canvas1");
    canvas.style.background = "black";
    let ctx = canvas.getContext("2d");
    canvas.width = canvasParent.offsetWidth;
    canvas.height = 400;

    let mouse = { x: undefined, y: undefined };

    canvas.addEventListener("mousemove", function (event) {
      mouse.x = event.offsetX;
      mouse.y = event.offsetY;
    });

    function animate() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      //   ctx.fillStyle = "rgb(0,0,0)";
      //   ctx.fillRect(0, 0, canvas.width, canvas.height);

      ctx.fillStyle = "#fff";
      ctx.beginPath();
      ctx.arc(canvas.width / 2, canvas.height / 2, 100, 0, Math.PI * 2);
      ctx.closePath();
      ctx.fill();

      requestAnimationFrame(animate);
    }

    animate();
  }, []);

  return (
    <div id="canvasParent" className="w-full">
      <canvas id="canvas1"></canvas>
    </div>
  );
};

export default CanvasBoilerTemplate;

References and downloads

[1] HTML5 Canvas CRASH COURSE for Beginners


HomeWikis
SnippetsAbout
Google ScholarLinkedIn