1,Game.js
class Game {
constructor(id, width, height) {
//参数绑定
this.element = document.getElementById(id);
this.width = this.element.width = width;
this.height = this.element.height = height;
this.pen = this.element.getContext("2d");
this.items = [];
this.data = {
};
this.data.keys = [];
}
addItem(obj) {
this.items.push(obj);
}
/*计时器开始,清除*/
start = (interval) => {
this.timer = setInterval(() => {
this.repaint()
}, interval);
}
end() {
clearInterval(this.timer);
}
repaint() {
//清除上次画的
this.pen.clearRect(0, 0, this.width, this.height);
//画这次的
this.items.forEach(obj => {
if (obj.repaint) {
obj.repaint(this.pen, this.width, this.height, this.data);
}
})
}
bindClick() {
this.element.addEventListener('click', e => {
e.preventDefault()
this.items.forEach(obj => {
if (obj.click) {
obj.click(e.offsetX, e.offsetY);
}
})
})
}
bindKey() {
document.addEventListener('keydown', e => {
e.preventDefault()
if (this.data.keys.indexOf(e.key) === -1) {
this.data.keys.push(e.key);
}
})
document.addEventListener('keyup', e => {
e.preventDefault()
this.data.keys.splice(this.data.keys.indexOf(e.key), 1);
})
}
}
2,主要逻辑
class Rect {
constructor(data0) {
this.data = data0
}
repaint(pen, width, height, context) {
if (this.data.y + this.data.size < height) {
this.data.dy += 1
} else {
this.data.dy = 0
}
if (this.data.y + this.data.size < height) {
if (this.data.y + this.data.size + this.data.dy >= height) {
this.data.y = height - this.data.size
} else {
this.data.y += this.data.dy;
}
}
//绘制
pen.fillStyle = this.data.color;
pen.fillRect(this.data.x, this.data.y, this.data.size, this.data.size);
}
click(x, y) {
this.data.x = x - this.data.size / 2;
this.data.y = y - this.data.size / 2;
this.data.dy = 0;
}
}
let r1 = new Rect({
x: 0, y: 0, dy: 0, size: 100, color: "red"
})
const app = new Game("app", 800, 800);
app.addItem(r1)
app.bindKey()
app.bindClick()
app.start(24);
点击事件:赋值坐标,重置速度。
重绘:更新速度,没越界的话更新坐标。
效果: