I\'ve been looking for a solution in this forum, but not found yet. I need to keep the focus on a canvas element always, no matter where i click on the page. I have several
Canvas elements are not focusable by default. You need to set a tabIndex
for it first.
document.querySelector("canvas").onblur = function() {
var me = this;
me.style.background = "red";
setTimeout(function() {
me.style.background = "transparent";
me.focus();
}, 500);
}
canvas {border:1px solid #000}
Click on canvas then outside - a blur event will be thrown coloring the background red for half a second:<br>
<canvas tabindex=0 ></canvas>
However, I cannot really see any reason why you would need to force focus on the canvas element.
If you want to catch mouse and key events there are better ways to do it by for example prevent an event from bubbling up. Forcing focus will also prevent input fields from working, accessibility and so forth.
Here is one way you can catch mouse moves and key down events and redirect them to canvas use:
var ctx = document.querySelector("canvas").getContext("2d");
// redirect events
window.addEventListener("mousemove", function(e) {
var rect = ctx.canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
ctx.fillRect(x-2, y-2, 4, 4);
});
window.addEventListener("keydown", function(e) {
e.preventDefault();
ctx.fillText(e.keyCode, Math.random() * 300, Math.random() * 150);
});
html, body {width:100%;height:100%;margin:0;overflow:hidden}
canvas {border:1px solid #000}
<h1>Demo</h1>
<p>Active this window by clicking in it, then hit some keys and move mouse around</p>
<canvas tabindex=0></canvas>
<h2>End</h2>
<button>Test button</button>
using jQuery , you can use trigger()
$("#canvas").trigger("click");
What about this (using jQuery):
$('#canvas').focus().blur(function() {
$('#canvas').focus();
});
The idea is to give it the focus back every time it loses it (blur).
I made an example (with a textbox which is basically the same) here: http://jsfiddle.net/thepeak/j02vyryf/