动态动画元素css



所以,我正在编写一个横向旋转的轮盘(从右到左(,我想知道是否有任何方法可以动态使用@keyframes,这样我就可以使用translateX((,根据圆形结果使用值(轮盘在背景图像中(。E.g:四舍五入的结果是5。客户端从服务器接收结果,轮盘将X个像素转换为相应的数字。

这是轮盘代码:

import React, { useState, useEffect } from "react";
import { socket } from "../../App.js";
import "./roulette.css";
export default class Roulette extends React.Component {
constructor(props) {
super(props);
this.socket = socket;
this.roulette = React.createRef();
this.state = {
result: null,
};
}
componentDidMount() {
this.setState({
backgroundPositionX: (this.roulette.current.offsetWidth - 78) / 2
});
this.socket.on("roulette.roll", position => {
//TODO: Retrieve from the server how much pixels should be translated  
});
}
render() {
return (
<div className="main-r flex items-center justify-center">
<div ref={this.roulette} className="roulette relative">
<div
style={{backgroundPosition: this.state.backgroundPositionX + "px" + "0"}
className="roulette-bg h-full w-full" //The roulette background image, that is suposed to translate when the result is give is in this div
></div>
<div className="roulette-marker absolute"></div>
</div>
</div>
);
}
}

您可以在componentDidMount()中设置它,如下所示:

export default class Roulette extends React.Component {
constructor(props) {
super(props);
this.socket = socket;
this.roulette = React.createRef();
this.state = {
result: null,
backgroundPositionX: null
};
}
componentDidMount() {
this.setState({
backgroundPositionX: (this.roulette.current.offsetWidth - 78) / 2
});
this.socket.on("roulette.roll", position => {
this.setState({
backgroundPositionX: position
});
//TODO: Retrieve from the server how much pixels should be translated  
});
}
render() {
return (
<div className="main-r flex items-center justify-center">
<div ref={this.roulette} className="roulette relative">
<div
style={{backgroundPosition: this.state.backgroundPositionX + "px"}
className="roulette-bg h-full w-full" //The roulette background image, that is suposed to translate when the result is give is in this div
></div>
<div className="roulette-marker absolute"></div>
</div>
</div>
);
}
}

或者您可以使用js来使用ElementCSSInlineStyle功能设置页面上元素的样式。这里已经讨论过了。

我相信你会把这样的东西放在你的componentDidMount()中(使用像@yuri gor提到的翻译(:

const bgElement = window.document.querySelector('.roulette-bg');
bgElement.style.transform = 'translateX(42px)';

如果我正确地理解了您的需求,那么您需要CSS转换,而不是关键帧。

transition: transform 5s;
element.style.transform = 'translateX(42px)';

请注意,最好通过更改变换来设置动画,这样会渲染得更平滑。

最新更新