首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将p5元素添加到html目录

将p5元素添加到html目录
EN

Stack Overflow用户
提问于 2021-11-14 17:08:33
回答 1查看 47关注 0票数 0

如何将p5元素添加到html div?例如,我有一个函数,它像这样绘制正弦波:

代码语言:javascript
运行
复制
            let theta = 0.0; // Start angle at 0
            let amplitude = this.circlesArray[i].radius / 2; // Height of wave
            let period = this.circlesArray[i].rotationSpeed * 500; // How many pixels before the wave repeats
            let dx = (TWO_PI / period) * this.xspacing;

            theta += 0.02;

            // For every x value, calculate a y value with sine function
            let x = theta;
            for (let i = 0; i < this.yvalues.length; i++) {
                this.yvalues[i] = sin(x) * amplitude;
                x += dx;
            }

            stroke(255);
            beginShape();

            for (let x = 0; x < this.yvalues.length; x++) {
                curveVertex(x * this.xspacing / 10, height / 2 + this.yvalues[x])
            }
            endShape();
        }

这将使用p5 beginShape();curveVertex();endShape();函数绘制正弦波,这些函数共同构成一条表示正弦波的连续线。问题是,我想把这些正弦波放在html div中,这样它们就可以用flex-box动态间隔,而不是用绝对位置。有人知道我应该怎么做吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-14 20:47:34

默认情况下,p5.js绘制到单个<canvas>元素。您可以通过获取createCanvas返回的p5.Renderer并调用其parent方法来控制此<canvas>元素在DOM中的位置:

代码语言:javascript
运行
复制
function setup() {
  let c = createCanvas(200, 200);
  c.parent('id_of_div');
}

还有一个名为p5.js-svg的p5.js库,它可以从一组绘图指令生成SVG文件,这在这个场景中可能也很有用。

注意:如果您想让多个p5.js在DOM中的不同位置创建图形,则需要使用"instance mode"。有关详细信息,请参阅this answer

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69965341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档