You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用react-p5-wrapper调用createCapture报错:Cannot read property 'push' of undefined

Fixing "TypeError: Cannot read property 'push' of undefined" with createCapture() in react-p5-wrapper

Hey there! Let's break down why you're hitting this error and how to fix it.

What's Causing the Error?

The main issue is how you're calling createCapture(): using p5.prototype.createCapture() skips the proper initialization of p5's internal state. When you call methods directly on the prototype instead of the provided p5 instance (p), p5 can't set up the necessary structures (like the array where it stores DOM elements), which leads to the "push of undefined" error.

Fixed Code Example

Here's the corrected version of your sketch, with explanations of the key changes:

import p5 from "p5";
import "p5/lib/addons/p5.dom";

export default function sketch(p) {
  let capture; // Store the video capture object for later use

  p.setup = function() {
    p.createCanvas(400, 300, p.WEBGL);
    // Call createCapture on the p5 instance, not the prototype
    // Pass p.VIDEO to specify we want camera input
    capture = p.createCapture(p.VIDEO);
    
    // Match the capture size to our canvas and hide the default DOM element
    capture.size(400, 300);
    capture.hide(); // Prevents a duplicate video from showing up outside the canvas
  };

  p.draw = function() {
    p.background(100);

    // Optional: Draw the captured video to the WEBGL canvas
    p.push();
    p.translate(-200, -150); // Adjust position since WEBGL origin is at canvas center
    p.image(capture, 0, 0, 400, 300);
    p.pop();

    // Your existing drawing code
    p.stroke("rgb(0,255,0)");
    p.strokeWeight(4);
    p.line(-400, -50, 0, 400, -50);
    p.stroke(200);
  };
}

Key Fixes Explained

  1. Use the p5 instance instead of the prototype: Always call methods like createCapture() on the p object provided to the sketch function. This ensures p5 initializes all necessary internal state correctly.
  2. Pass a parameter to createCapture(): You need to specify what to capture (e.g., p.VIDEO for camera input, or a video URL). Without this, p5 doesn't know what resource to access.
  3. Handle the capture object: Storing the result of createCapture() lets you control the video element—like hiding it (so it doesn't appear outside your canvas) or drawing it directly to the canvas.
  4. WEBGL position adjustment: Since WEBGL uses the canvas center as the origin, we use translate() to shift the video to the top-left corner of the canvas.

内容的提问来源于stack exchange,提问作者Kunanan Tassuwan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:09:39