Gravity with Canvas
by bc_rikko
HTML
<form>
<button type="button" id="start">start</button>
<button type="button" id="stop">stop</button>
<button type="button" id="jump">jump</button>
</form>
<canvas id="gravity" width="180" height="500"></canvas>
CSS
#gravity {
background-color: white;
}
JavaScript
class Game {
constructor(el) {
this.canvas = document.querySelector(el);
this.items = [];
}
add(item) {
this.items.push(item);
}
remove(item) {
const i = this.items.findIndex(a => a === item);
this.items.splice(i, 1);
}
start() {
this.canvasCtx = this.canvas.getContext('2d');
this.req = window.requestAnimationFrame(this.updateArea.bind(this));
}
stop() {
if (this.req) {
window.cancelAnimationFrame(this.req);
this.req = null;
}
}
clear() {
if(this.canvasCtx) {
this.canvasCtx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
draw(ctx) {
this.items.forEach(a => a.update(ctx));
}
updateArea() {
this.clear();
this.draw(this.canvas);
this.req = window.requestAnimationFrame(this.updateArea.bind(this));
}
}
class ItemComponent {
constructor(opt) {
this.width = opt.width || 64;
this.height = opt.height || 64;
this.xPos = opt.x || 0;
this.yPos = opt.y || 0;
this.speedX = 0;
this.speedY = 0;
this.gravity = opt.gravity || 0.1;
this.gravitySpeed = 0;
}
update(canvas) {
this.move();
this.hit(canvas)
this.draw(canvas.getContext('2d'));
}
move() {
this.gravitySpeed += this.gravity;
this.xPos += this.speedX;
this.yPos += this.speedY + this.gravitySpeed;
}
draw(ctx) {
ctx.save();
ctx.fillStyle = '#F00';
ctx.fillRect(this.xPos, this.yPos, this.width, this.height);
ctx.restore();
}
// 当たり判定
hit(canvas) {
const bottom = canvas.height - this.height;
if (this.yPos > bottom) {
this.yPos = bottom;
this.gravitySpeed = 0;
}
}
// 加速度
accelerate(val) {
this.gravity = val;
}
}
// main
const game = new Game('#gravity');
let item;
document.getElementById('start').addEventListener('click', () => {
item = new ItemComponent({
x: 30,
y: 0,
width: 30,
height: 30
});
...