Add keyboard event listeners

This commit is contained in:
Cauli Tomaz 2019-07-29 20:22:49 +02:00
parent 7d153fb3f1
commit eaf5976e75
No known key found for this signature in database
GPG Key ID: 2B8B1D29D9CCC99B
3 changed files with 44 additions and 0 deletions

View File

@ -88,6 +88,24 @@ function Ronin () {
this.surface.drawGuide(shape) this.surface.drawGuide(shape)
} }
this.onKeyPress = (e, id = 'key-press') => {
if (this.bindings[id]) {
this.bindings[id](e)
}
}
this.onKeyUp = (e, id = 'key-up') => {
if (this.bindings[id]) {
this.bindings[id](e)
}
}
this.onKeyDown = (e, id = 'key-down') => {
if (this.bindings[id]) {
this.bindings[id](e)
}
}
this.onMouseMove = (e, id = 'mouse-move') => { this.onMouseMove = (e, id = 'mouse-move') => {
const pos = { x: e.offsetX * ronin.surface.ratio, y: e.offsetY * ronin.surface.ratio } const pos = { x: e.offsetX * ronin.surface.ratio, y: e.offsetY * ronin.surface.ratio }
const shape = this.mouseShape(pos, id) const shape = this.mouseShape(pos, id)

View File

@ -3,6 +3,7 @@ function Surface (ronin) {
this.el.id = 'surface' this.el.id = 'surface'
this._guide = document.createElement('canvas') this._guide = document.createElement('canvas')
this._guide.id = 'guide' this._guide.id = 'guide'
this._guide.setAttribute('tabindex', '1'); // focus is necessary to capture keyboard events
this.ratio = window.devicePixelRatio this.ratio = window.devicePixelRatio
// Contexts // Contexts
this.context = this.el.getContext('2d') this.context = this.el.getContext('2d')
@ -17,6 +18,9 @@ function Surface (ronin) {
this._guide.addEventListener('mouseup', ronin.onMouseUp, false) this._guide.addEventListener('mouseup', ronin.onMouseUp, false)
this._guide.addEventListener('mouseover', ronin.onMouseOver, false) this._guide.addEventListener('mouseover', ronin.onMouseOver, false)
this._guide.addEventListener('mouseout', ronin.onMouseOut, false) this._guide.addEventListener('mouseout', ronin.onMouseOut, false)
this._guide.addEventListener('keydown', ronin.onKeyDown, false)
this._guide.addEventListener('keyup', ronin.onKeyUp, false)
this._guide.addEventListener('keypress', ronin.onKeyPress, false)
} }
this.start = function () { this.start = function () {

View File

@ -0,0 +1,22 @@
; this demo shows how to use the key events.
;
(clear)
;
(defn draw-title
()
(fill
(text 30 80 50 "press key") "grey" 2))
;
(defn show-letter
(e)
(a
(clear)
(draw-title)
(fill
(text 30 170 50 (concat e:key " — " e:type)) "orange" 2)))
;
(draw-title)
;
(on "key-down" show-letter)
(on "key-up" show-letter)
(on "key-press" show-letter)