아래는 요런 느낌으로!
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;
'자바스크립트' 카테고리의 다른 글
[Javascript] this 할당하기 (2) | 2021.05.27 |
---|---|
[Javascript] 브라우저 저장소 (2) | 2021.05.27 |
[Canvas] Canvas로 비내리는 화면 만들기 (0) | 2020.08.10 |
[JavaScript공부 - 12] Logical operators(논리 연산자) (0) | 2019.02.27 |
[JavaScript공부 - 11] 조건 연산자 : if, '?' (0) | 2019.02.18 |
댓글