要按顺序绘制动画线条,你可以使用P5.js库中的setup()
和draw()
函数来实现。下面是一个示例代码:
let lines = []; // 用于存储线条的数组
let currentLine = null; // 当前正在绘制的线条
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// 绘制所有已完成的线条
for (let line of lines) {
line.display();
}
// 绘制当前正在绘制的线条
if (currentLine) {
currentLine.display();
}
}
function mousePressed() {
// 创建新的线条,并将其设为当前线条
currentLine = new Line();
}
function mouseDragged() {
// 在当前线条上添加新的点
if (currentLine) {
currentLine.addPoint(mouseX, mouseY);
}
}
function mouseReleased() {
// 完成当前线条的绘制,并将其添加到线条数组中
if (currentLine) {
lines.push(currentLine);
currentLine = null;
}
}
class Line {
constructor() {
this.points = []; // 线条上的点的数组
}
addPoint(x, y) {
// 添加新的点到线条的点数组中
this.points.push(createVector(x, y));
}
display() {
// 绘制线条
beginShape();
for (let point of this.points) {
vertex(point.x, point.y);
}
endShape();
}
}
这段代码创建了一个画布,并使用mousePressed()
、mouseDragged()
和mouseReleased()
函数来捕捉鼠标的交互事件。当鼠标按下时,创建一个新的线条对象并将其设为当前线条;当鼠标拖动时,将鼠标的位置添加到当前线条的点数组中;当鼠标释放时,完成当前线条的绘制,并将其添加到线条数组中。
Line
类包含addPoint()
方法用于添加新的点,以及display()
方法用于绘制线条。在draw()
函数中,使用循环来绘制所有已完成的线条和当前正在绘制的线条。
你可以根据自己的需求对代码进行修改和扩展。
上一篇:按顺序合并以字符分隔的列