React中如何让SVG元素绕自身中心旋转?
问题描述
我想要实现SVG元素绕自身中心旋转的功能,但在React中无法生效。尝试了多种方法都没有进展:
- 使用
transform rotate(deg, cx, cy)时元素会乱跑甚至隐藏; - 尝试用
transform3d方法时元素完全不动。
我的代码
React组件代码
import React, { useState, useRef } from "react"; // import SVGStyles from "./SVGStyles"; function SVGComponent() { const svgRef = useRef(null); const [rotate, setRotate] = useState(45); const [viewBox, setviewBox] = useState("0 0 24 24"); function handleChange(event) { setRotate(event.target.value); } function rotateSvg() { if (svgRef.current) { const bbox = svgRef.current.getBBox(); const cx = bbox.x + bbox.width / 2; const cy = bbox.y + bbox.height / 2; // setviewBox([bbox.x, bbox.y, bbox.width, bbox.height].join(" ")); svgRef.current.style.setProperty("--r", `${rotate}deg`); // svgRef.current.setAttribute( // "transform", // `rotate(${rotate}), ${cx}, ${cy}` // ); } } return ( <> <svg ref={svgRef}> <Triangle viewBox={viewBox} style={{ border: "1px solid red" }} /> </svg> <br /> <br /> <br /> <br /> <label> Angle: <input type="range" min="0" max="360" value={rotate} onChange={handleChange} /> {rotate}° </label> <button onClick={rotateSvg}>Rotate</button> </> ); } const Triangle = (props) => ( <svg height="100%" viewBox={props.viewBox} fill="none" xmlns="http://www.w3.org/2000/svg" style={props.style} > <path fillRule="evenodd" clipRule="evenodd" d="m13.789 1.578 9.764 19.528A2 2 0 0 1 21.763 24H2.237a2 2 0 0 1-1.789-2.894l9.764-19.528a2 2 0 0 1 3.578 0Z" fill="#758CA3" /> </svg> ); export default SVGComponent;
CSS代码
svg { transform-origin: 50% 50%; transform-box: fill-box; transform: translate3d(25px, 25px, 0) rotate(var(--r, 0deg)); border: 1px dotted red; }
内容的提问来源于stack exchange,提问作者Spencer Trinh
相关产品推荐
相关产品推荐

