添加 p5 元素到 html div
Add p5 element to html div
如何将 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 动态间隔而不是绝对位置。有谁知道我应该怎么做?
默认情况下 p5.js 绘制到单个 <canvas>
元素。您可以通过获取 createCanvas
返回的 p5.Renderer
并调用其 parent
方法来控制此 <canvas>
元素在 DOM 中的位置:
function setup() {
let c = createCanvas(200, 200);
c.parent('id_of_div');
}
p5.js 还有一个名为 p5.js-svg 的库,可以从一组绘图指令生成 SVG 文件,这在这种情况下也很有用。
注意:如果您想在 DOM 中的不同点创建多个 p5.js 图形,则需要使用 "instance mode". See 获取更多信息。
如何将 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 动态间隔而不是绝对位置。有谁知道我应该怎么做?
默认情况下 p5.js 绘制到单个 <canvas>
元素。您可以通过获取 createCanvas
返回的 p5.Renderer
并调用其 parent
方法来控制此 <canvas>
元素在 DOM 中的位置:
function setup() {
let c = createCanvas(200, 200);
c.parent('id_of_div');
}
p5.js 还有一个名为 p5.js-svg 的库,可以从一组绘图指令生成 SVG 文件,这在这种情况下也很有用。
注意:如果您想在 DOM 中的不同点创建多个 p5.js 图形,则需要使用 "instance mode". See