我有一个SVG圆和一些线对象,它们制作了一个简单的十字光标,我正试图用带样式的组件来设置该光标的动画。当光标悬停在某些对象上时,我希望光标内的直线元素围绕组成光标的圆元素的原点旋转。redux useSelector钩子允许访问悬停在其上的组件的鼠标悬停/鼠标出状态。此部分工作良好,因为使用此方法可以引发简单的笔画颜色更改
const Cursor = (props) => {
const hoverState = useSelector(state => state.gameState.targetHovered);
// ...
return (
<Crosshair isHovering={hoverState} position={props.position}>
<circle
cx={cursorCoordinates.cx}
cy={cursorCoordinates.cy}
r={cursorCoordinates.outerRadius}
style={cursorStyle}
/>
<circle
cx={cursorCoordinates.cx}
cy={cursorCoordinates.cy}
r={cursorCoordinates.innerRadius}
style={cursorStyle}
/>
<line
id="top"
x1={cursorCoordinates.cx - cursorCoordinates.outerRadius}
y1={cursorCoordinates.cy}
x2={cursorCoordinates.cx - cursorCoordinates.innerRadius}
y2={cursorCoordinates.cy}
style={crossHairStyle}
/>
<line
id="bottom"
x1={cursorCoordinates.cx + cursorCoordinates.innerRadius}
y1={cursorCoordinates.cy}
x2={cursorCoordinates.cx + cursorCoordinates.outerRadius}
y2={cursorCoordinates.cy}
style={crossHairStyle}
/>
</Crosshair>
);以及样式化组件的代码...
const lockOn = (x, y) => keyframes`
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(90deg);
}
`;
const Crosshair = styled.g`
transform-origin: ${props => props.position.x} ${props => props.position.y};
animation: ${props => props.isHovering ? lockOn : 'none'} 1s linear;
`;我尝试过用许多不同的方式来表示关键帧,但是每次,当光标悬停在目标对象上时,动画不是旋转样式组组件中的元素,而是将其抛向右侧,就好像变换原点不正确一样。从十字准线中移除变换原点表现出相同的行为
我确信我犯了一个简单的语法错误。有什么想法吗?
发布于 2021-07-05 16:49:57
正如@RobertLongson在评论中指出的那样,解决方案是添加
transform-box: fill-box;在styled.g组件内部,否则转换原点是SVG对象的中心。有关MDN文档的更多详细信息,请访问:https://developer.mozilla.org/en-US/docs/Web/CSS/transform-box
添加一个转换原点也是必要的。注意动画中的“前进”是为了防止光标悬停在对象上时重置。
const lockOn = (x, y) => keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(90deg);
}
`;
const Crosshair = styled.g`
transform-origin: 50% 50%;
transform-box: fill-box;
animation: ${props => props.isHovering ? lockOn : 'none'} 0.3s linear forwards;
`;https://stackoverflow.com/questions/68247213
复制相似问题