如何使用p5.js绘制简单的动画
动画是一种方法,它将一组图像以特定的方式组合和处理,使它们看起来像是移动的图像。构建动画使得屏幕上的对象似乎是活的。
在本文中,我们将学习如何使用p5.js制作一个简单的房子动画,其中使用线条、矩形和椭圆来制作房子的各个部分。
步骤:
- 创建一个列表来存储房子的所有顶点。
- 声明两个变量iter和counter。
- 设置函数setup(),其中设置输出窗口的大小、颜色和背景,将iter和counter的值初始化为1,并初始化顶点列表。
- 设置函数draw,添加笔触和笔触宽度。
- 添加一个if条件来检查iter是否在范围内,如果是,则将counter增加0.05,并将counter的ceil值作为iter,如果不是,则退出循环。
- 编写函数addVertices(),将房子的起始点和终点作为线的顶点加入。
- 现在编写绘制房子各个部分的函数:
- 编写函数来绘制房子的垂直和水平线。
- 编写函数来绘制方形窗户。
- 编写函数来绘制大门。
- 编写函数来绘制圆形窗户。
- 编写函数来绘制烟囱。
- 完成以上所有步骤后,创建一个switch语句,逐步添加房子的所有部分。
下面是以上方法的实现代码:
JavaScript
// List to store all the vertices
let vertices = [];
// Variable declared
var iter;
var counter;
// Function to set up output window
function setup() {
// Size of output window
createCanvas(600, 600);
// Fill the color
fill(31);
// Background of output window
background(31);
// Put the value of variables as 1
iter = 1;
counter = 1;
// Initialize the list of vertices
addVertices();
}
// Set the draw function
function draw() {
stroke(255);
strokeWeight(4);
step();
// Condition to check within bound
if (iter < 11) {
// Increase counter everytime
counter += 0.05;
// Set the iter variable to the
// floor value of counter
iter = floor(counter);
}
else {
// If iter increases by 11 then
// stop the loop
noLoop();
}
}
// Function to add vertices of house giving
// start and end point of line
function addVertices() {
vertices.push(new p5.Vector(100, 300));
vertices.push(new p5.Vector(340, 300));
vertices.push(new p5.Vector(40, 380));
vertices.push(new p5.Vector(160, 380));
vertices.push(new p5.Vector(400, 380));
vertices.push(new p5.Vector(40, 550));
vertices.push(new p5.Vector(160, 550));
vertices.push(new p5.Vector(400, 550));
}
// Function to draw lines in house
function drawLine(a, b) {
line(vertices[a].x, vertices[a].y,
vertices[b].x, vertices[b].y);
}
// Function to draw gate
function addGate() {
rectMode(CENTER);
rect(100, 500, 70, 100);
}
// Function to draw window
function addWindow() {
rect(280, 430, 40, 30);
}
// Function to add circular window
function addOculus() {
ellipse(100, 340, 20, 20);
}
// Function to add Chimney
function addChimney() {
rect(320, 295, 16, 20);
ellipse(320, 285, 16, 10);
}
// Function to draw parts of
// house step by step
function step() {
switch (iter) {
case 1:
drawLine(5, 6);
break;
case 2:
drawLine(6, 7);
break;
case 3:
drawLine(2, 5);
drawLine(3, 6);
break;
case 4:
drawLine(4, 7);
break;
case 5:
drawLine(2, 3);
drawLine(3, 4);
break;
case 6:
drawLine(0, 2);
drawLine(0, 3);
drawLine(1, 4);
break;
case 7:
drawLine(0, 1);
break;
case 8:
addGate();
break;
case 9:
addWindow();
break;
case 10:
addOculus();
break;
case 11:
addChimney();
break;
}
}
输出: