본문 바로가기
자바스크립트

[Canvas] text 랜덤으로 나오다가 하나씩 나타나도록 하기

by 곰돌찌 2020. 8. 10.

아래는 요런 느낌으로!

random text가 좀더 다양한 캐릭터가 들어가면 이쁠거같음!

 

이건 react로 canvas 와 같이 구현해봄

import React, { useRef, useState, useEffect } from 'react';

const randomText = '~!@#$%^&*()_+`-={}[];":,./<>?qwertyuiopasdfghjklzxcvbnm';
function Canvas1() {
  const canvasRef = useRef<any>();
  const [context, setContext] = useState<any>(null);
  const text = '얘들아 안녕!';
  const textArr = text.split('');
  let textIndex = -1;
  let rafId = undefined as any;
  let str = Date.now();

  useEffect(() => {
    setContext(canvasRef.current.getContext('2d'));
  }, []);

  const draw = () => {
    if (canvasRef && context) {
      context.clearRect(
        0,
        0,
        canvasRef.current.width,
        canvasRef.current.height
      );
      context.beginPath();
      context.fillStyle = '#E2ABFF';
      context.fillRect(
        canvasRef.current.width / 2 - 400 / 2,
        canvasRef.current.height / 2 - 200 / 2,
        400,
        200
      );
      context.fillStyle = 'black';
      context.font = '25px bold';
      context.textAlign = 'center';

      const restText = textArr.map((str, index) => {
        if (index > textIndex) {
          return randomText[Math.floor(Math.random() * text.length)];
        }
        return '';
      });
      context.fillText(
        text.substr(0, textIndex) + restText.join(''),
        canvasRef.current.width / 2,
        canvasRef.current.height / 2
      );

      if (Date.now() >= str) {
        textIndex++;
        str = Date.now() + Math.random() * 200;
      }
    }

    rafId = window.requestAnimationFrame(draw);

    if (textArr.length < textIndex) {
      window.cancelAnimationFrame(rafId);
    }
  };

  draw();

  return (
    <div>
      <canvas ref={canvasRef} width="800" height="400" />
    </div>
  );
}

export default Canvas1;

댓글