javascript - How to change focus to new HTML5 Canvas element? -
i have bunch of canvas elements in html file so:
<canvas id="one"></canvas> <canvas id="two"></canvas>
i'm using arrow keys move object around #one
, want have object "appear" in #two
when hits point on #one
, e.g. x=150
, y=55
. tried using jquery focus()
method when coordinate triggered, object stayed in #one
. suggestions?
to make canvas element focus-able, , therefor able capture key-strokes, add tabindex
attribute element:
now can tab between elements , bind event-listeners canvas element directly.
inside handler draw canvas want based on whatever criteria require.
example
var canvases = document.queryselectorall("canvas"), = 0; while(canvas = canvases[i++]) { canvas.width = 200; canvas.tabindex = 0; canvas.addeventlistener("keyup", process); } function process(e) { var ctx = this.getcontext("2d"); ctx.clearrect(0, 0, 200, 150); ctx.filltext("key here: " + e.keycode, 10, 10); }
canvas {border:1px solid #999;margin:0 2px 2px 0; display:inline-block}
<canvas></canvas> <canvas></canvas> <canvas></canvas> <canvas></canvas> <canvas></canvas> <canvas></canvas>
Comments
Post a Comment