如何始终关注画布?

Rok*_*oll 8 javascript canvas

我一直在寻找这个论坛的解决方案,但还没有找到.无论我在哪里点击页面,我都需要始终关注画布元素.我有几个按钮,在我写的每个onclick事件中:

document.getElementById('canvas').focus();
Run Code Online (Sandbox Code Playgroud)

这样做,但我认为这不是最好的做法.任何的想法?

小智 11

默认情况下,Canvas元素不可聚焦.你需要先设置一个tabIndex.

document.querySelector("canvas").onblur = function() {
    var me = this;
    me.style.background = "red";
    setTimeout(function() {
        me.style.background = "transparent";
        me.focus();
    }, 500);
}
Run Code Online (Sandbox Code Playgroud)
canvas {border:1px solid #000}
Run Code Online (Sandbox Code Playgroud)
Click on canvas then outside - a blur event will be thrown coloring the background red for half a second:<br>
<canvas tabindex=0 ></canvas>
Run Code Online (Sandbox Code Playgroud)

但是,我真的没有理由为什么你需要强制关注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);
});
Run Code Online (Sandbox Code Playgroud)
html, body {width:100%;height:100%;margin:0;overflow:hidden}
canvas {border:1px solid #000}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)