如何将p5元素添加到html div?例如,我有一个函数,它像这样绘制正弦波:
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动态间隔,而不是用绝对位置。有人知道我应该怎么做吗?
发布于 2021-11-14 20:47:34
默认情况下,p5.js绘制到单个<canvas>
元素。您可以通过获取createCanvas
返回的p5.Renderer
并调用其parent
方法来控制此<canvas>
元素在DOM中的位置:
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。
https://stackoverflow.com/questions/69965341
复制相似问题