最终效果
一个Canvas,里面有个矩形一直在移动。
点击它,它会暂停or继续。
1,实现画布
先摆一个元素。
<canvas id="app"></canvas>
给点样式。
#app {
outline: solid pink .2px;
}
新建一个类,然后创建其实例。
class Game {
constructor(id, width, height, interval) {
//参数绑定
this.element = document.getElementById(id);
this.element.width = this.width = width;
this.element.height = this.height = height;
this.interval = interval;
}
}
let app = new Game("app", 400, 400, 40);
参数分别为:
- 容器ID
- 容器的宽,高
- 刷新频率
这个时候,元素已经有了大小。
2,添加元素
初始化以下参数:
pen:canvas的画笔。
items:元素数组。
constructor(id, width, height, interval) {
//....
this.pen = this.element.getContext("2d");
this.items = [];
}
开启定时器,关闭定时器。
start = () => {
this.timer = setInterval(() => {
//清除上次画的
this.pen.clearRect(0, 0, this.width, this.height);
//画这次的
this.items.forEach(obj => {
obj.draw(this.pen, this.width, this.height);
})
}, this.interval);
}
end = () => {
clearInterval(this.timer);
}
定义一个元素。
data:元素的状态。
draw:元素的绘制方法。
let rect = {
data: {
x: 0, y: 0, direction: 1
},
draw(pen, width, height) {
pen.fillStyle = "red";
pen.fillRect(this.data.x, this.data.y, 100, 100);
if (this.data.x + 100 >= width || this.data.y + 100 >= height) {
this.data.direction = -1;
} else if (this.data.x <= 0 || this.data.y <= 0) {
this.data.direction = 1;
}
if (this.data.direction === 1) {
this.data.x += 10
this.data.y += 10
} else if (this.data.direction === -1) {
this.data.x -= 10
this.data.y -= 10
}
}
}
定义添加方法。
addItem = (obj) => {
this.items.push(obj);
}
添加,开始游戏。
app.addItem(rect)
app.start();
效果:
3,事件处理
在开启定时器之后,添加点击事件。
start = () => {
this.timer = setInterval(() => {
this.pen.clearRect(0, 0, this.width, this.height);
this.items.forEach(obj => {
obj.draw(this.pen, this.width, this.height);
})
}, this.interval);
this.element.addEventListener('click', e => {
this.items.forEach(obj => {
obj.click(e.offsetX, e.offsetY);
})
})
}
定义元素的点击处理。
click(x, y) {
if (x >= this.data.x && x <= this.data.x + 100 && y >= this.data.y && y <= this.data.y + 100) {
console.log(1);
this.data.active = !this.data.active;
}
}
添加暂停状态,和暂停判断。
data: {
x: 0, y: 0, direction: 1, active: true
},
draw(pen, width, height) {
pen.fillStyle = "red";
pen.fillRect(this.data.x, this.data.y, 100, 100);
if (this.data.active) {
if (this.data.x + 100 >= width || this.data.y + 100 >= height) {
this.data.direction = -1;
} else if (this.data.x <= 0 || this.data.y <= 0) {
this.data.direction = 1;
}
if (this.data.direction === 1) {
this.data.x += 10
this.data.y += 10
} else if (this.data.direction === -1) {
this.data.x -= 10
this.data.y -= 10
}
}
}
达成效果!