p5.js parent() | Uncaught (in promise) TypeError: Cannot read properties of null (reading 'appendChild')

p5.js parent() | Uncaught (in promise) TypeError: Cannot read properties of null (reading 'appendChild')

我完全按照图书馆文档做 here

我有一个错误

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'appendChild')

index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles/index.css" />
        <script src="libs/p5.min.js"></script>
        <script src="scripts/barcode.js"></script>
    </head>
    <body>
        <div class="container"></div>
    </body>
</html>

尝试延迟条形码脚本导入,并将其放在最后。

barcode.js

function setup() {
    let cnv = createCanvas(500, 500);
    cnv.parent("container");
}

试过了,没有任何改变

async function setup() {
        let cnv = await createCanvas(500, 500);
        cnv.parent("container");
}

感谢您的见解!

正如 p5 文档所说:

The parent() function is used to attach the element as a parent element.

This function accepts either a string ID, DOM node, or p5.Element Add

因此,向容器 div 添加一个 id 并将其传递给父级而不是 class 解决问题

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles/index.css" />
        <script src="libs/p5.min.js"></script>
        <script src="scripts/barcode.js"></script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>