var lineList = new Array();
function setup() {
// 创建居中画布
var centerDiv = createDiv();
centerDiv.id('centerDiv');
centerDiv.style('text-align', 'center');
centerDiv.parent('app');
// 画布大小定义为 500x500 px
var app = createCanvas(500, 500);
app.parent('centerDiv');
// 设置画布背景颜色
background(200);
// draw函数需要循环
// noLoop();
// for循环的使用方式
for(var i =1; i <= 10; i++) {
// 横线
lineList.push(new HorizontalLine(i*50));
// 竖线
lineList.push(new VerticalLine(i*50));
}
}
function draw(){
// 每次循环的时候,需要刷新页面,否则上一次绘制的线段会保留在画布上
background(200);
// forEach循环的使用方式
lineList.forEach(function(eachLine) {
eachLine.update();
eachLine.display();
});
}
// 抽象:会移动的线段
function BackgroundLine(initPosition) {
this.position = 0;
this.dir = 1; // 线段移动方向
this.initPosition = initPosition; // 初始位置
// 前面的案例中,线段的移动速度是1点,此次我们让这个速度在线段被创建的时候,随机取值
// 请各位同学们回顾一下之前线段的实现方法,如果不采用面向对象的编程方式,如果不抽象BackgroundLine,你需要如何修改这一需求?
this.speed = random(0.5, 2);
}
BackgroundLine.prototype.update = function() {
if(this.initPosition+this.position >= 500 || this.initPosition+this.position <= 0) {
this.dir = -this.dir;
}
this.position = this.position + this.dir*this.speed;
}
BackgroundLine.prototype.display = function() {
// 由于不同的线段在画布中显示的方式不一样(横/竖),因此没必要在此处写实现
}
// 定义横线
function HorizontalLine(init_yPosition) {
// 继承父类属性和方法
BackgroundLine.call(this, init_yPosition);
}
// 继承自BackgroundLine
HorizontalLine.prototype = Object.create(BackgroundLine.prototype);
HorizontalLine.prototype.display = function() {
line(0, this.initPosition+this.position, 500, this.initPosition+this.position);
}
// 定义竖线
function VerticalLine(init_xPosition) {
// 继承父类属性和方法
BackgroundLine.call(this, init_xPosition);
}
// 继承自BackgroundLine
VerticalLine.prototype = Object.create(BackgroundLine.prototype);
// BackgroundLine 父类中定义了display这个方法,只是没有写实现过程,因此,即使VerticalLine并没有提供display这一函数,在程序中调用display方法也不会报错,只不过程序没有任何反应而已!
VerticalLine.prototype.display = function() {
line(this.initPosition+this.position, 0, this.initPosition+this.position, 500);
}
new p5();
对战游戏教程实例
p5.js | 对战小游戏