我一直在这个论坛上寻找解决方案,但还没有找到。无论我在页面上的哪个位置单击,我都需要始终将注意力集中在 Canvas 元素上。我有几个按钮,在我写的每个 onclick 事件中:
document.getElementById('canvas').focus();
这确实有效,但我认为这不是最佳做法。有什么想法吗?
最佳答案
Canvas 元素默认是不可聚焦的。您需要先为其设置一个tabIndex
。
例子
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>
但是,我真的看不出有任何理由需要强制关注 Canvas 元素。
如果你想捕捉鼠标和按键事件,有更好的方法,例如防止事件冒泡。强制聚焦还会阻止输入字段工作、可访问性等。
这是一种捕捉鼠标移动和按键事件并将它们重定向到 Canvas 使用的方法:
“劫持”事件示例
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>
关于javascript - 如何始终将焦点保持在 Canvas 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29992688/