canvas game event listener
testing function call on keydown event and interruptions
by trentHarlem
HTML
<!-- <pre>open console</pre> -->
<canvas id='can'></canvas>
CSS
* {
box-sizing: border-box;
margin: 0px;
padding: 0px;
}
#can {
background: blueviolet;
width: 100%;
min-width: 490px;/* for fiddle */
max-width: 545px;
height: auto;
}
JavaScript
const L = console.log
const CAN = document.getElementById('can')
const C = CAN.getContext('2d')
const CANW = window.innerWidth
const CANH = window.innerHeight
/* L(can) */
const PersistantKeyState = {};
let gun
let keys = []
let bullets = []
let repeat = 50 // Key re-Trigger Speed
let lastRenderTime = 0 // to control rAF speed
const FPS = 60
// weapon class
class Weapon {
constructor(x, y, radius) {
this.x = x
this.y = y
this.radius = radius
this.color = 'yellow'
this.angle = 0
this.triggerDelay = 100
this.isShooting = false
this.speed = 8
}
Update() {
}
Draw() {
C.strokeStyle = this.color
C.lineWidth = 3
C.beginPath()
C.moveTo(this.x, this.y - this.radius)
C.lineTo(this.x + this.radius, this.y + this.radius)
C.lineTo(this.x - this.radius, this.y + this.radius)
C.closePath()
C.stroke()
}
Shoot(key, delay) {
if (key === 32) {
bullets.push(new Bullet(weapon.x, weapon.y - weapon.radius))
// delay=weapon.triggerDelay
}
// delay--
// L('shoot()', weapon.x, weapon.y)
}
Move(key) {
if (key === 37) this.x -= this.speed
if (key === 39) this.x += this.speed
}
}
class Bullet {
constructor(x, y) {
this.visible = true
/* this.x = weapon.turretX */
/* this.y = weapon.turretY */
// this.angle = angle
this.x = x
this.y = y
this.height = 2
this.width = 2
this.speed = 3
}
Update() {
/* this.x -= 1 * this.speed */
this.y -= 1 * this.speed
}
Draw() {
C.fillStyle = 'orange'
C.fillRect(this.x, this.y, 2, 2)
}
}
/*
document.body.addEventListener(
'keydown',
e => {
e.preventDefault()
if (e.key === ' ') {
keydown(e)
let key = e.which;
keys[e.key] = true
L('autofire ON')
weapon.isShooting = true
weapon.Shoot(key)
}
},
false
)
document.body.addEventListener(
'keyup',
e => {
if (e.key === ' ') {
keys[e.key] = false
...