【发布时间】:2018-08-21 22:02:34
【问题描述】:
已解决 - 问题是使用“/about”和“/portfolio”路径渲染的容器中的 setInterval 方法 - 它使动画滞后
https://github.com/kaczmarekm/portfolio - 完整的应用代码
http://users.pja.edu.pl/~s17335/portfolio/ - 应用程序 - 通过单击导航按钮查看粒子动画如何在更改页面后开始滞后、减慢和停止 - 它会在几秒钟后发生,而且它并没有完全死掉 - 由于 SetParticleColor() 函数,它会改变颜色,但是有很大的延迟,就像间隔设置的时间比 10ms 长得多
问题是我不知道为什么会这样,所以希望有人能找到源头。
代码:
App.js
export default class App extends Component {
constructor(){
super();
this.state = {
particleInterval: null
}
}
componentWillMount() {
InitCanvas();
Paint();
}
componentDidMount(){
this.setState({
particleInterval: setInterval(() =>
requestAnimationFrame(Particles), 10)
})
}
render() {
return (
<Router>
<div>
<NavigationContainer/>
<Switch>
<Route path="/home" component={HomeContainer}/>
<Route path="/about" component={AboutContainer}/>
<Route path="/portfolio" component={PortfolioContainer}/>
<Route path="/contact" component={ContactContainer}/>
<Route path="*" component={EntryPageContainer}/>
</Switch>
</div>
</Router>
);
}
}
InitCanvas.js
export function InitCanvas() {
const rootWidth = window.innerWidth;
const rootHeight = window.innerHeight;
const canvas = document.createElement('canvas');
canvas.id = 'canvas';
canvas.width = rootWidth;
canvas.height = rootHeight;
canvas.style.zIndex = '-1';
canvas.style.position = 'absolute';
canvas.style.margin = '0';
canvas.style.padding = '0';
canvas.style.display = 'block';
const root = document.getElementById('root');
root.appendChild(canvas);
}
粒子.js
import { ParticleArray } from "../../Constants/ParticleArray";
import { SetParticleColor } from "./SetParticleColor";
const rootWidth = window.innerWidth;
const rootHeight = window.innerHeight;
for (let i = 0; i < 500; i++) {
let moveX = Math.random() - 0.5;
let moveY = Math.random() - 0.5;
ParticleArray[i] = Math.random()*rootWidth, Math.random()*rootWidth,
moveX,moveY];
}
export function Particles() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, rootWidth, rootHeight);
for (let i = 0; i < 500; i++) {
let centerX = ParticleArray[i][0];
let centerY = ParticleArray[i][1];
let moveX = ParticleArray[i][2];
let moveY = ParticleArray[i][3];
let radius = 2;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = SetParticleColor();
ctx.fill();
centerX += moveX;
centerY += moveY;
if(centerX >= rootWidth || centerX <= 0 || centerY >= rootHeight ||
centerY <= 0){
centerX = Math.random() * rootWidth;
centerY = Math.random() * rootHeight;
}
ParticleArray[i] = [centerX, centerY, ParticleArray[i][2],
ParticleArray[i][3]];
}
}
【问题讨论】:
标签: javascript reactjs react-router setinterval particles