如何始终关注画布? [英] How to keep the focus on a canvas always?

查看:62
本文介绍了如何始终关注画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 buttons, and inside each onclick event i write:

document.getElementById('canvas').focus();

这样可以解决问题,但我认为这不是最好的做法。有什么想法?

This does the trick, but i think is not the best practise. Any idea?

推荐答案

默认情况下,画布元素不可聚焦。首先需要为它设置 tabIndex

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>

然而,我真的看不出你需要什么理由强制关注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>

这篇关于如何始终关注画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆