拍摄视频时内存中的移动Safari内存不足

las*_*fin 5 javascript mobile-safari html5-canvas webrtc react-native

我有两个主要元素的React类。画布和视频。我得到视频流并将其以30fps的速度渲染到画布上。

class GetImage extends Component {

  constructor() {
    super();
    this.constraints = {
      video: {
        width: { ideal: 2048 },
        height: { ideal: 1080 },
        facingMode: {
          exact: 'environment'
        }
      }
    }
  }

  componentDidMount() {
    setVideo(this.video, this.constraints, this.readyToPlayVideo)
  }

  capture = () => {
    const { video } = this
    let canvas = document.createElement('canvas')
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight

    let context = canvas.getContext('2d')
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(this.video, 0, 0, canvas.width, canvas.height)
    this.setState({ capture: canvas.toDataURL('image/jpeg') })
    stopVideo()
  }


  readyToPlayVideo = () => {
    const { canvas, video }  = this
    const { offsetHeight, offsetWidth } = video
    const ctx = canvas.getContext('2d')
    ctx.canvas.setAttribute('height', offsetHeight)
    ctx.canvas.setAttribute('width', offsetWidth)

    const timeout = 1000 / 30 // drawing at 30fps

    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    let _listener = () => {
      (function loop() {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.drawImage(video, 0, 0)
        setTimeout(loop, timeout)
      })()
    }

    _listener();
  }


  retake = () =>
    this.setState({ capture: null },
      () => {
        setVideo(this.video, this.constraints, this.readyToPlayVideo, this.handleError)
      }
    )

  render() {
    return (
        <div>
          <video
            style={{ visibility: 'hidden'}}
            ref={video => (this.video = video)}
            playsInline
            autoPlay
          />
          <canvas ref={canvas => (this.canvas = canvas)}/>
        </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好。但是我遇到了移动Safari的问题。看起来它会将曾经创建的每个Canvas对象都保留在内存中。

拍摄了几张照片后,Safari崩溃并显示“内存不足”。在渲染新图像之前,我已经做过clearRect,但这无济于事。

Rac*_*len 2

这里有几个问题需要解决。首先,你的函数中似乎有循环引用loop;您正在函数内调用该函数。

因此,自动播放视频(渲染时)不会停止..导致“内存不足”错误。

另外,我认为最佳实践是创建一个componentDidUnmount销毁视频的函数(当不再需要时)。用于.dispose销毁视频。

希望这可以帮助