728x90
[Project][SVG] Text를 그려보자!
SVG 에는 text 태그를 이용해 원하는 text를 표현할 수 있습니다.
x,y 속성을 통해서 위치를 정하고, textAnchor 나 alignmentBaseline 등으로 text를 좌표기준 정렬 시킬수 있습니다.
https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text
전체 코드
// src\project\s\svg\components\text.js
// modules
import React, { useRef, forwardRef, useEffect, useState } from "react";
const Text = forwardRef(({ x, y, children, config = {} }, ref) => {
const textRef = ref || useRef();
const [options, setOptions] = useState({
textAnchor: "middle",
alignmentBaseline: "middle",
});
useEffect(() => {
setOptions((p) => ({ ...p, ...config }));
}, [config]);
return (
<text x={x} y={y} {...options} ref={textRef}>
{children}
</text>
);
});
export default Text;
Arc를 그릴때와 마찬가지로 forwardRef
를 통해 부모 컴포넌트에서 tex 컴포넌트를 접근할 수 있도록합니다.
Arc 그리지 → https://twentytwentyone.tistory.com/122
이번에는 props
로 넘어온 options
을 text에 spread operator
로 넘겨주어 따로 props 값을 지정해주는 수고를 덜었습니다.
데모는 아래의 링크에서 확인할 수 있습니다.
728x90
'project > svg' 카테고리의 다른 글
[Project][SVG] Arc 를 그려보자! (0) | 2022.07.06 |
---|