为了让 P5 与 React 一起工作,我使用了P5Wrapper导入。
我有一个简单的星空动画来处理我的磁贴,但性能是一个问题。动画在 512 个“星”对象时缓慢爬行,因此我将其缩放回 128。然而,即使在 128 时,FPS 似乎也太低,平均低于 30 FPS。我正在寻找在 React 中加速 P5 性能的方法,以便动画可以运行接近 60 FPS。
P5代码:
function sketch (p) {
const star = () => {
const x = p.random(-TILE_SIZE/2, TILE_SIZE/2)
const y = p.random(-TILE_SIZE/2, TILE_SIZE/2)
const z = p.random(TILE_SIZE)
return { x, y, z }
}
const stars = new Array(128)
p.setup = () => {
p.createCanvas(TILE_SIZE, TILE_SIZE)
for (let i = 0; i < stars.length; i++) {
stars[i] = star()
}
}
const update = (coord) => {
const { z } = coord
let newZ = z - 8
if (newZ < 1) {
newZ = p.random(TILE_SIZE)
}
return { ...coord, z: newZ }
}
const show = (coord) => {
const { x, y, z } = coord
p.fill(255)
p.noStroke()
const sx = p.map(x / z, 0, 1, 0, TILE_SIZE)
const sy = p.map(y / z, 0, 1, 0, TILE_SIZE)
const r = p.map(z, 0, TILE_SIZE, 4, 0)
p.ellipse(sx, sy, r, r)
}
p.draw = () => {
p.background(0)
p.translate(TILE_SIZE/2, TILE_SIZE/2)
for (let i = 0; i < stars.length; i++) {
stars[i] = update(stars[i])
show(stars[i])
}
}
}
如何使用 P5Wrapper:
import P5Wrapper from 'react-p5-wrapper'
...
render (
<ItemContainer key={uuidv4()}>
<header>
{name}
<p>{description}</p>
</header>
<P5Wrapper sketch={sketch} />
</ItemContainer>
)
星空图块的实际外观(2 个图块)。
我计划根据性能添加更多动画。或者切换到 SVG。
Resolved the frame-rate issue without changing the actual animation logic. There could still be plenty of performance optimization that is still needed.
I noticed that the animation gets progressively slower as I un-mount and re-mount the component. Digging into the Github issue results in this post about performance degradation. The poster provided a PR and commit that was never merged and the repository haven't been updated for over a year.
Instead, it's better to remove the package and just create your own component following the poster's update:
import React from 'react'
import p5 from 'p5'
export default class P5Wrapper extends React.Component {
componentDidMount() {
this.canvas = new p5(this.props.sketch, this.wrapper)
if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) {
this.canvas.myCustomRedrawAccordingToNewPropsHandler(this.props)
}
}
componentWillReceiveProps(newprops) {
if(this.props.sketch !== newprops.sketch){
this.canvas.remove()
this.canvas = new p5(newprops.sketch, this.wrapper)
}
if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) {
this.canvas.myCustomRedrawAccordingToNewPropsHandler(newprops)
}
}
componentWillUnmount() {
this.canvas.remove()
}
render() {
return <div ref={wrapper => this.wrapper = wrapper}></div>
}
}
这至少解决了安装和卸载组件的性能下降问题。此外,我的帧数从低于 30 FPS 跃升至近 60 FPS。这可能是因为我也导入了最新的 P5 包,因为我不再依赖 react-p5-wrapper 来进行导入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句