我正在学习使用react-native构建应用程序,以下是正在使用的组件代码。问题是 - 当我模拟这个应用程序时 - 它会在几秒钟内崩溃。我无法理解造成这个问题的原因。有人可以建议。 我正在尝试使用此组件中的requestAnimationFrame为画布圈设置动画。
谢谢..
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Dimensions
} from 'react-native';
import Canvas from 'react-native-canvas';
export default class ThreeDiscs extends Component{
constructor(props){
super(props);
this.state = {
context: null,
screen: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
},
a: 0,
b: 0,
c: 100,
d: 100
};
this.coordinates = {
a: 0,
b: 0,
c: 100,
d: 100
};
this.directions = {
increment: 5,
direction: 0
};
this.discs = [
{
x: 150,
y: 250,
lastX: 150,
lastY: 250,
velocityX: -3.2,
velocityY: 3.5,
radius: 10,
innerColor: 'rgba(255,255,0,1)',
middleColor: 'rgba(255,255,0,0.7)',
outerColor: 'rgba(255,255,0,0.5)',
strokeStyle: 'gray',
}
];
this.numDiscs = this.discs.length;
}
rendercanvas = (canvas) => {
canvas.width = this.state.screen.width;
canvas.height = this.state.screen.height;
const context = canvas.getContext('2d');
this.setState({context: context});
context.fillStyle = 'purple';
context.fillRect(0,0,100,100);
this.drawBackground(context);
this.update(context);
this.draw(context);
this.animatecanvas(context);
}
drawBackground(context) {
var STEP_Y = 12,
i = this.state.screen.height;
context.strokeStyle = 'lightgray';
context.lineWidth = 0.5;
while(i > STEP_Y*4) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(context.canvas.width, i);
context.stroke();
i -= STEP_Y;
}
context.save();
context.strokeStyle = 'rgba(100,0,0,0.3)';
context.lineWidth = 1;
context.beginPath();
context.moveTo(35,0);
context.lineTo(35,context.canvas.height);
context.stroke();
context.restore();
}
update(context) {
var disc = null;
for(var i=0; i < this.numDiscs; ++i) {
disc = this.discs[i];
if (disc.x + disc.velocityX + disc.radius > context.canvas.width ||
disc.x + disc.velocityX - disc.radius < 0)
disc.velocityX = -disc.velocityX;
if (disc.y + disc.velocityY + disc.radius > context.canvas.height ||
disc.y + disc.velocityY - disc.radius < 0)
disc.velocityY= -disc.velocityY;
disc.x += disc.velocityX;
disc.y += disc.velocityY;
}
}
draw(context) {
var disc = this.discs[i];
for(var i=0; i < this.numDiscs; ++i) {
disc = this.discs[i];
context.save();
context.beginPath();
context.arc(disc.x, disc.y, disc.radius, 0, Math.PI*2, false);
context.fillStyle = '#000';
context.strokeStyle = disc.strokeStyle;
context.fill();
context.stroke();
context.restore();
}
}
animatecanvas(context){
context.clearRect(0,0,this.state.screen.width,this.state.screen.height);
this.drawBackground(context);
this.update(context);
this.draw(context);
requestAnimationFrame(() => {this.animatecanvas(context)});
}
render(){
return(
<Canvas ref={this.rendercanvas} />
);
}
}